Allow nested modals
This commit is contained in:
+33
-3
@@ -1,5 +1,5 @@
|
||||
import type {Component} from "svelte"
|
||||
import {writable} from "svelte/store"
|
||||
import {get, writable} from "svelte/store"
|
||||
import {randomId, always, assoc, Emitter} from "@welshman/lib"
|
||||
import {deriveDeduplicated} from "@welshman/store"
|
||||
import {goto} from "$app/navigation"
|
||||
@@ -7,6 +7,7 @@ import {page} from "$app/stores"
|
||||
|
||||
export type ModalOptions = {
|
||||
drawer?: boolean
|
||||
nested?: boolean
|
||||
noEscape?: boolean
|
||||
fullscreen?: boolean
|
||||
replaceState?: boolean
|
||||
@@ -24,8 +25,18 @@ export const emitter = new Emitter()
|
||||
|
||||
export const modals = writable<Record<string, Modal>>({})
|
||||
|
||||
const getIdsFromHash = (hash: string) => hash.slice(1).split(",").filter(Boolean)
|
||||
|
||||
export const modalStack = deriveDeduplicated([page, modals], ([$page, $modals]) => {
|
||||
return getIdsFromHash($page.url.hash)
|
||||
.map(id => $modals[id])
|
||||
.filter(Boolean)
|
||||
})
|
||||
|
||||
export const modal = deriveDeduplicated([page, modals], ([$page, $modals]) => {
|
||||
return $modals[$page.url.hash.slice(1)]
|
||||
const ids = getIdsFromHash($page.url.hash)
|
||||
|
||||
return $modals[ids.at(-1) || ""]
|
||||
})
|
||||
|
||||
export const pushModal = (
|
||||
@@ -35,10 +46,12 @@ export const pushModal = (
|
||||
) => {
|
||||
const id = randomId()
|
||||
const path = options.path || ""
|
||||
const existingIds = getIdsFromHash(get(page).url.hash)
|
||||
const ids = options.nested ? [...existingIds, id] : [id]
|
||||
|
||||
modals.update(assoc(id, {id, component, props, options}))
|
||||
|
||||
goto(path + "#" + id, {replaceState: options.replaceState})
|
||||
goto(path + "#" + ids.join(","), {replaceState: options.replaceState})
|
||||
|
||||
return id
|
||||
}
|
||||
@@ -49,7 +62,24 @@ export const pushDrawer = (
|
||||
options: ModalOptions = {},
|
||||
) => pushModal(component, props, {...options, drawer: true})
|
||||
|
||||
export const popModal = () => {
|
||||
const url = get(page).url
|
||||
const ids = getIdsFromHash(url.hash)
|
||||
|
||||
if (ids.length === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
const next = ids.slice(0, -1).join(",")
|
||||
const hash = next ? `#${next}` : ""
|
||||
|
||||
goto(url.pathname + url.search + hash, {replaceState: true})
|
||||
}
|
||||
|
||||
export const clearModals = () => {
|
||||
const url = get(page).url
|
||||
|
||||
goto(url.pathname + url.search, {replaceState: true})
|
||||
modals.update(always({}))
|
||||
emitter.emit("close")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user