flotilla/src/app/util/modal.ts

54 lines
1.2 KiB
TypeScript
Raw Normal View History

2025-02-03 23:01:42 +00:00
import type {Component} from "svelte"
import {derived, writable} from "svelte/store"
2024-10-15 22:52:30 +00:00
import {randomId, always, assoc, Emitter} from "@welshman/lib"
2024-08-09 00:22:17 +00:00
import {goto} from "$app/navigation"
import {page} from "$app/stores"
2024-08-06 20:10:10 +00:00
2024-10-01 18:47:21 +00:00
export type ModalOptions = {
drawer?: boolean
2024-10-17 22:02:03 +00:00
fullscreen?: boolean
replaceState?: boolean
2024-11-27 00:39:49 +00:00
path?: string
2024-10-01 18:47:21 +00:00
}
2024-10-15 22:52:30 +00:00
export type Modal = {
id: string
2025-02-03 23:01:42 +00:00
component: Component
2024-10-15 22:52:30 +00:00
props: Record<string, any>
options: ModalOptions
}
export const emitter = new Emitter()
export const modals = writable<Record<string, Modal>>({})
export const modal = derived([page, modals], ([$page, $modals]) => {
return $modals[$page.url.hash.slice(1)]
})
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()
2024-11-27 00:39:49 +00:00
const path = options.path || ""
2024-08-06 20:10:10 +00:00
2024-10-15 22:52:30 +00:00
modals.update(assoc(id, {id, component, props, options}))
2024-10-11 22:29:54 +00:00
2024-11-27 00:39:49 +00:00
goto(path + "#" + id, {replaceState: options.replaceState})
2024-08-06 20:10:10 +00:00
return id
}
2024-10-09 16:31:50 +00:00
export const pushDrawer = (
2025-02-03 23:40:00 +00:00
component: Component<any>,
2024-10-09 16:31:50 +00:00
props: Record<string, any> = {},
options: ModalOptions = {},
) => pushModal(component, props, {...options, drawer: true})
2024-10-15 22:52:30 +00:00
export const clearModals = () => {
modals.update(always({}))
2024-08-16 17:50:38 +00:00
emitter.emit("close")
2024-08-09 23:22:09 +00:00
}