anki/ts/editor/HandleSelection.svelte

69 lines
2.0 KiB
Svelte
Raw Normal View History

2021-08-04 22:25:05 +02:00
<!--
Copyright: Ankitects Pty Ltd and contributors
License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
-->
2021-08-05 22:48:36 +02:00
<script lang="ts">
2021-08-06 02:19:36 +02:00
import { onMount, createEventDispatcher } from "svelte";
2021-08-05 22:48:36 +02:00
export let container: HTMLElement;
2021-08-06 02:19:36 +02:00
export let image: HTMLImageElement;
2021-08-05 22:48:36 +02:00
2021-08-06 00:16:15 +02:00
export let offsetX = 0;
export let offsetY = 0;
2021-08-05 22:48:36 +02:00
let left: number;
let top: number;
let width: number;
let height: number;
function setSelection(_selection?: HTMLDivElement): void {
2021-08-05 22:48:36 +02:00
const containerRect = container.getBoundingClientRect();
2021-08-06 02:19:36 +02:00
const imageRect = image!.getBoundingClientRect();
2021-08-05 22:48:36 +02:00
const containerLeft = containerRect.left;
const containerTop = containerRect.top;
left = imageRect!.left - containerLeft;
top = imageRect!.top - containerTop;
2021-08-06 02:19:36 +02:00
width = image!.clientWidth;
height = image!.clientHeight;
2021-08-05 22:48:36 +02:00
}
export function updateSelection(): Promise<void> {
let updateResolve: () => void;
const afterUpdate: Promise<void> = new Promise((resolve) => {
updateResolve = resolve;
});
setSelection();
setTimeout(() => updateResolve());
return afterUpdate;
}
2021-08-06 02:19:36 +02:00
const dispatch = createEventDispatcher();
let selection: HTMLDivElement;
2021-08-05 22:48:36 +02:00
2021-08-06 02:19:36 +02:00
onMount(() => dispatch("mount", { selection }));
2021-08-05 22:48:36 +02:00
</script>
<div
2021-08-06 02:19:36 +02:00
bind:this={selection}
use:setSelection
2021-09-02 21:01:29 +02:00
on:click={(event) =>
/* prevent triggering Bootstrap dropdown */ event.stopImmediatePropagation()}
2021-08-06 00:16:15 +02:00
style="--left: {left}px; --top: {top}px; --width: {width}px; --height: {height}px; --offsetX: {offsetX}px; --offsetY: {offsetY}px;"
2021-08-05 22:48:36 +02:00
>
2021-08-04 22:25:05 +02:00
<slot />
</div>
<style lang="scss">
div {
position: absolute;
2021-08-06 00:16:15 +02:00
left: calc(var(--left, 0px) - var(--offsetX, 0px));
top: calc(var(--top, 0px) - var(--offsetY, 0px));
width: calc(var(--width) + 2 * var(--offsetX, 0px));
height: calc(var(--height) + 2 * var(--offsetY, 0px));
2021-08-04 22:25:05 +02:00
}
</style>