anki/ts/editor-toolbar/WithShortcut.svelte

47 lines
1.3 KiB
Svelte
Raw Normal View History

2021-04-21 16:05:08 +02:00
<!--
Copyright: Ankitects Pty Ltd and contributors
License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
-->
<script lang="typescript">
import type { DynamicSvelteComponent } from "sveltelib/dynamicComponent";
import type { ToolbarItem } from "./types";
2021-04-23 02:16:40 +02:00
import type { Modifier } from "lib/shortcuts";
2021-04-21 16:05:08 +02:00
import { onDestroy } from "svelte";
2021-04-23 02:16:40 +02:00
import { registerShortcut, getPlatformString } from "lib/shortcuts";
2021-04-21 16:05:08 +02:00
export let button: ToolbarItem;
export let shortcut: string;
export let optionalModifiers: Modifier[];
2021-04-21 16:05:08 +02:00
function extend({ ...rest }: DynamicSvelteComponent): DynamicSvelteComponent {
const shortcutLabel = getPlatformString(shortcut);
2021-04-21 16:05:08 +02:00
return {
shortcutLabel,
2021-04-21 16:05:08 +02:00
...rest,
};
}
let deregister: () => void;
2021-04-21 16:05:08 +02:00
function createShortcut({ detail }: CustomEvent): void {
const mounted: HTMLButtonElement = detail.button;
deregister = registerShortcut(
(event: KeyboardEvent) => {
mounted.dispatchEvent(new KeyboardEvent("click", event));
2021-04-22 03:25:31 +02:00
event.preventDefault();
},
shortcut,
optionalModifiers
2021-04-22 03:25:31 +02:00
);
2021-04-21 16:05:08 +02:00
}
onDestroy(() => deregister());
2021-04-21 16:05:08 +02:00
</script>
<svelte:component
this={button.component}
{...extend(button)}
on:mount={createShortcut} />