anki/ts/editor-toolbar/WithDropdownMenu.svelte

54 lines
1.6 KiB
Svelte
Raw Normal View History

2021-04-15 15:59:52 +02:00
<!--
Copyright: Ankitects Pty Ltd and contributors
License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
-->
2021-03-31 03:34:08 +02:00
<script lang="typescript">
import type { DynamicSvelteComponent } from "sveltelib/dynamicComponent";
import type { ToolbarItem } from "./types";
import Dropdown from "bootstrap/js/dist/dropdown";
2021-03-31 03:34:08 +02:00
/* Bootstrap dropdown are normally declared alongside the associated button
* However we cannot do that, as the menus cannot be declared in sticky-positioned elements
*/
export let button: ToolbarItem;
2021-03-31 03:34:08 +02:00
export let menuId: string;
function extend({
className,
...rest
}: DynamicSvelteComponent): DynamicSvelteComponent {
2021-03-31 03:34:08 +02:00
return {
dropdownToggle: true,
2021-03-31 03:34:08 +02:00
...rest,
};
}
function createDropdown({ detail }: CustomEvent): void {
const button: HTMLButtonElement = detail.button;
/* Prevent focus on menu activation */
const noop = () => {};
Object.defineProperty(button, "focus", { value: noop });
/* Set custom menu without using .dropdown
* Rendering the menu here would cause the menu to
* be displayed outside of the visible area
*/
const dropdown = new Dropdown(button);
2021-04-15 14:58:13 +02:00
const menu = (button.getRootNode() as Document) /* or shadow root */
.getElementById(menuId);
2021-03-31 03:34:08 +02:00
if (!menu) {
console.log(`Could not find menu "${menuId}" for dropdown menu.`);
}
(dropdown as any)._menu = menu;
2021-03-31 03:34:08 +02:00
}
</script>
<svelte:component
this={button.component}
{...extend(button)}
on:mount={createDropdown} />