flotilla/src/app/modal.ts

83 lines
2.1 KiB
TypeScript
Raw Normal View History

2025-02-03 23:01:42 +00:00
import type {Component} from "svelte"
import {randomId, last, Emitter} from "@welshman/lib"
import {goto, pushState, replaceState} from "$app/navigation"
import {page} from "$app/state"
import type {DialogSize} from "@lib/components/Dialog.svelte"
export type ModalOptions = {
drawer?: boolean
nested?: boolean
noEscape?: boolean
fullscreen?: boolean
size?: DialogSize
replaceState?: boolean
path?: string
}
export type Modal = {
id: string
component: Component
props: Record<string, any>
options: ModalOptions
}
2024-10-15 22:52:30 +00:00
export const emitter = new Emitter()
const modals: Record<string, Modal> = {}
// Open modal ids live in SvelteKit page state (shallow routing): each modal owns a history entry
// without a navigation, and any `goto` that does not pass `state` along closes them.
export const getModalStack = () => (page.state.modals ?? []).map(id => modals[id]).filter(Boolean)
export const getModal = () => last(getModalStack())
export type NavigateOptions = Parameters<typeof goto>[1] & {keepModal?: boolean}
2026-09-10 15:44:21 +00:00
// An open modal owns the current history entry, so a navigation that drops it takes that entry over
export const navigate = (path: string, {keepModal, ...options}: NavigateOptions = {}) => {
const ids = page.state.modals ?? []
if (keepModal && ids.length > 0) {
return goto(path, {...options, state: {modals: ids}, replaceState: true})
}
return goto(path, {...options, replaceState: options.replaceState || ids.length > 0})
}
2024-10-08 18:39:16 +00:00
export const pushModal = (
2025-02-03 23:40:00 +00:00
component: Component<any>,
2024-10-08 18:39:16 +00:00
props: Record<string, any> = {},
options: ModalOptions = {},
) => {
2024-08-06 20:10:10 +00:00
const id = randomId()
const ids = options.nested ? [...(page.state.modals ?? []), id] : [id]
2024-08-06 20:10:10 +00:00
modals[id] = {id, component, props, options}
2024-10-11 22:29:54 +00:00
if (options.replaceState) {
replaceState("", {modals: ids})
} else {
pushState("", {modals: ids})
}
2024-08-06 20:10:10 +00:00
return id
}
2026-03-11 23:29:24 +00:00
export const popModal = () => {
const ids = page.state.modals ?? []
2026-03-11 23:29:24 +00:00
if (ids.length > 0) {
replaceState("", {modals: ids.slice(0, -1)})
2026-03-11 23:29:24 +00:00
}
}
2024-10-15 22:52:30 +00:00
export const clearModals = () => {
replaceState("", {})
for (const id of Object.keys(modals)) {
delete modals[id]
}
2024-08-16 17:50:38 +00:00
emitter.emit("close")
2024-08-09 23:22:09 +00:00
}