anki/ts/editor-toolbar/WithShortcuts.svelte

50 lines
1.4 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";
import { onDestroy } from "svelte";
import { registerShortcut, getPlatformString } from "anki/shortcuts";
2021-04-21 16:05:08 +02:00
export let button: ToolbarItem;
2021-04-22 03:25:31 +02:00
export let shortcuts: string[];
2021-04-21 16:05:08 +02:00
function extend({
tooltip,
...rest
}: DynamicSvelteComponent): DynamicSvelteComponent {
const platformShortcut = getPlatformString(shortcuts[0]);
if (tooltip) {
tooltip = `${tooltip} (${platformShortcut})`;
}
2021-04-21 16:05:08 +02:00
return {
tooltip,
2021-04-21 16:05:08 +02:00
...rest,
};
}
2021-04-22 03:25:31 +02:00
let deregister: (() => void)[];
2021-04-21 16:05:08 +02:00
function createShortcut({ detail }: CustomEvent): void {
const mounted: HTMLButtonElement = detail.button;
2021-04-22 03:25:31 +02:00
deregisters = shortcuts.map((shortcut: string): (() => void) =>
registerShortcut((event) => {
mounted.dispatchEvent(new MouseEvent("click"));
event.preventDefault();
}, shortcut)
);
2021-04-21 16:05:08 +02:00
}
2021-04-22 03:25:31 +02:00
onDestroy(() => deregisters.map((dereg) => dereg()));
2021-04-21 16:05:08 +02:00
</script>
<svelte:component
this={button.component}
{...extend(button)}
on:mount={createShortcut} />