flotilla/src/app/components/ModalContainer.svelte

84 lines
2.2 KiB
Svelte
Raw Normal View History

<script lang="ts">
import type {Component, ComponentProps} from "svelte"
import {mount, unmount, untrack} from "svelte"
import Drawer from "@lib/components/Drawer.svelte"
2024-10-15 22:52:30 +00:00
import Dialog from "@lib/components/Dialog.svelte"
import {getModal, getModalStack, popModal} from "@app/modal"
2026-03-11 23:29:24 +00:00
const closeModal = () => {
const modal = getModal()
if (modal && !modal.options.noEscape) {
2026-03-11 23:29:24 +00:00
popModal()
}
}
2026-09-07 17:04:54 +00:00
const onKeyDown = (event: KeyboardEvent) => {
const target = event.target
if (
!event.defaultPrevented &&
2026-09-07 17:04:54 +00:00
event.code === "Escape" &&
target instanceof Element &&
!target.closest("input, textarea, [contenteditable]")
) {
2026-03-11 23:29:24 +00:00
closeModal()
}
}
2025-10-24 17:26:54 +00:00
let element: HTMLElement
type WrapperProps = ComponentProps<typeof Dialog>
const instances: Record<string, {instance: ReturnType<typeof mount>; props: WrapperProps}> = {}
2025-10-24 17:26:54 +00:00
$effect(() => {
const stack = getModalStack()
untrack(() => {
const ids = stack.map(({id}) => id)
const activeId = ids.at(-1)
for (const [id, {instance, props}] of Object.entries(instances)) {
props.active = id === activeId
2026-03-11 23:29:24 +00:00
if (!ids.includes(id)) {
props.restoreFocus = !activeId || Boolean(instances[activeId])
2026-03-11 23:29:24 +00:00
unmount(instance, {outro: true})
delete instances[id]
}
2025-10-24 17:26:54 +00:00
}
for (const item of stack) {
2026-03-11 23:29:24 +00:00
if (instances[item.id]) {
continue
}
const {options, component, props} = item
2025-10-24 17:26:54 +00:00
const wrapper = options.drawer ? Drawer : Dialog
const wrapperProps = $state({
active: item.id === activeId,
onClose: closeModal,
label: options.label,
restoreFocus: true,
size: options.size,
noEscape: options.noEscape,
fullscreen: options.fullscreen,
children: {component, props},
2025-10-24 17:26:54 +00:00
})
instances[item.id] = {
instance: mount(wrapper as Component, {
target: element,
props: wrapperProps,
}),
props: wrapperProps,
}
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
<div bind:this={element} data-sveltekit-replacestate="true"></div>