flotilla/src/app/components/ModalContainer.svelte

58 lines
1.4 KiB
Svelte
Raw Normal View History

<script lang="ts">
import {onMount, mount, unmount} from "svelte"
import Drawer from "@lib/components/Drawer.svelte"
2024-10-15 22:52:30 +00:00
import Dialog from "@lib/components/Dialog.svelte"
2026-06-08 21:14:40 +00:00
import {modal, modalStack, popModal} from "@app/modal"
2026-03-11 23:29:24 +00:00
const closeModal = () => {
if ($modal && !$modal.options.noEscape) {
2026-03-11 23:29:24 +00:00
popModal()
}
}
2024-10-15 22:52:30 +00:00
const onKeyDown = (e: any) => {
if (e.code === "Escape" && e.target === document.body) {
2026-03-11 23:29:24 +00:00
closeModal()
}
}
2025-10-24 17:26:54 +00:00
let element: HTMLElement
2026-03-11 23:29:24 +00:00
const instances: Record<string, any> = {}
2025-10-24 17:26:54 +00:00
onMount(() => {
2026-03-11 23:29:24 +00:00
return modalStack.subscribe($modalStack => {
const ids = $modalStack.map(({id}) => id)
for (const [id, instance] of Object.entries(instances)) {
if (!ids.includes(id)) {
unmount(instance, {outro: true})
delete instances[id]
}
2025-10-24 17:26:54 +00:00
}
2026-03-11 23:29:24 +00:00
for (const item of $modalStack) {
if (instances[item.id]) {
continue
}
const {options, component, props} = item
2025-10-24 17:26:54 +00:00
const wrapper = options.drawer ? Drawer : Dialog
2026-03-11 23:29:24 +00:00
instances[item.id] = mount(wrapper as any, {
2025-10-24 17:26:54 +00:00
target: element,
props: {
2026-03-11 23:29:24 +00:00
onClose: closeModal,
noEscape: options.noEscape,
fullscreen: options.fullscreen,
2026-01-30 22:14:12 +00:00
children: {component, props},
2025-10-24 17:26:54 +00:00
},
})
}
})
})
</script>
2025-02-04 00:37:14 +00:00
<svelte:window onkeydown={onKeyDown} />
2024-10-15 22:52:30 +00:00
2025-10-24 17:26:54 +00:00
<div bind:this={element}></div>