flotilla/src/app/modal.ts

59 lines
1.5 KiB
TypeScript
Raw Normal View History

2025-02-03 23:01:42 +00:00
import type {Component} from "svelte"
import {randomId, Emitter} from "@welshman/lib"
import {goto, pushState, replaceState} from "$app/navigation"
import {page} from "$app/state"
import {modals, type ModalOptions} from "@app/modal.svelte"
2024-10-15 22:52:30 +00:00
export const emitter = new Emitter()
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 ?? []
const modalIsOpen = ids.length > 0
if (keepModal && modalIsOpen) {
return goto(path, {...options, state: {modals: ids}, replaceState: true})
}
return goto(path, {...options, replaceState: options.replaceState || modalIsOpen})
}
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
}