anki/ts/components/WithDropdownMenu.svelte

48 lines
1.4 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 Dropdown from "bootstrap/js/dist/dropdown";
2021-03-31 03:34:08 +02:00
2021-04-28 22:15:24 +02:00
import { setContext } from "svelte";
import { dropdownKey } from "./contextKeys";
setContext(dropdownKey, {
dropdown: true,
"data-bs-toggle": "dropdown",
"aria-expanded": "false",
2021-04-28 22:15:24 +02:00
});
2021-03-31 03:34:08 +02:00
2021-04-28 22:15:24 +02:00
const menuId = Math.random().toString(36).substring(2);
2021-05-18 18:55:22 +02:00
let dropdown: Dropdown;
function activateDropdown(_event: MouseEvent): void {
dropdown.toggle();
}
2021-03-31 03:34:08 +02:00
2021-04-28 22:15:24 +02:00
/* Normally dropdown and trigger are associated with a
/* common ancestor with .dropdown class */
2021-04-30 20:01:40 +02:00
function createDropdown(event: CustomEvent): void {
const button: HTMLButtonElement = event.detail.button;
2021-03-31 03:34:08 +02:00
/* Prevent focus on menu activation */
const noop = () => {};
Object.defineProperty(button, "focus", { value: noop });
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.`);
2021-04-30 20:01:40 +02:00
} else {
2021-05-18 18:55:22 +02:00
dropdown = new Dropdown(button);
2021-03-31 03:34:08 +02:00
2021-04-30 20:01:40 +02:00
/* Set custom menu without using common element with .dropdown */
(dropdown as any)._menu = menu;
}
2021-03-31 03:34:08 +02:00
}
</script>
2021-05-18 18:55:22 +02:00
<slot {createDropdown} {activateDropdown} {menuId} />