Use sveltekits' push/pop state helpers for modals

This commit is contained in:
Jon Staab 2026-09-10 09:26:54 -07:00
parent 246bdfcf7b
commit 6b49ef498d
4 changed files with 45 additions and 76 deletions

2
src/app.d.ts vendored
View file

@ -9,7 +9,7 @@ declare global {
// interface Locals {} // interface Locals {}
// interface PageData {} // interface PageData {}
interface PageState { interface PageState {
modal?: string modals?: string[]
} }
// interface Platform {} // interface Platform {}
} }

View file

@ -11,9 +11,15 @@ w.plausible =
;(w.plausible.q = w.plausible.q || []).push(arguments) ;(w.plausible.q = w.plausible.q || []).push(arguments)
} }
export const setupAnalytics = () => // Modals live in page state, so the page store also emits when one opens or closes
page.subscribe($page => { export const setupAnalytics = () => {
if ($page.route && getSetting("report_usage")) { let prevHref: string | undefined
return page.subscribe($page => {
if ($page.route && getSetting("report_usage") && $page.url.href !== prevHref) {
prevHref = $page.url.href
w.plausible("pageview", {u: $page.route.id}) w.plausible("pageview", {u: $page.route.id})
} }
}) })
}

View file

@ -1,8 +1,8 @@
import type {Component} from "svelte" import type {Component} from "svelte"
import {get, writable} from "svelte/store" import {get, writable} from "svelte/store"
import {randomId, last, call, always, assoc, Emitter} from "@welshman/lib" import {randomId, last, always, assoc, Emitter} from "@welshman/lib"
import {deriveDeduplicated} from "@welshman/store" import {deriveDeduplicated} from "@welshman/store"
import {goto} from "$app/navigation" import {goto, pushState, replaceState} from "$app/navigation"
import {page} from "$app/stores" import {page} from "$app/stores"
import type {DialogSize} from "@lib/components/Dialog.svelte" import type {DialogSize} from "@lib/components/Dialog.svelte"
@ -27,58 +27,41 @@ export const emitter = new Emitter()
export const modals = writable<Record<string, Modal>>({}) export const modals = writable<Record<string, Modal>>({})
export const getIdsFromHash = (hash: string) => hash.slice(1).split(",").filter(Boolean) // Open modal ids live in SvelteKit's page state (shallow routing): each modal owns a history entry
// without a navigation, and any `goto` that doesn't pass `state` along closes them.
export const modalHash = writable("") export const modalStack = deriveDeduplicated([page, modals], ([$page, $modals]) =>
($page.state?.modals ?? []).map(id => $modals[id]).filter(Boolean),
export const modalStack = deriveDeduplicated([modalHash, modals], ([$hash, $modals]) => { )
return getIdsFromHash($hash)
.map(id => $modals[id])
.filter(Boolean)
})
export const modal = deriveDeduplicated(modalStack, last) export const modal = deriveDeduplicated(modalStack, last)
// Base push which handles both modals and paths export type NavigateOptions = Parameters<typeof goto>[1] & {keepModal?: boolean}
export type PushParams = { // An open modal owns the current history entry, so a navigation that drops it takes that entry over
pathname?: string export const navigate = (path: string, {keepModal, ...options}: NavigateOptions = {}) => {
search?: string const {state} = get(page)
hash?: string const modalIsOpen = Boolean(state.modals?.length)
if (keepModal && modalIsOpen) {
return goto(path, {...options, state, replaceState: true})
} }
export type PushOptions = Parameters<typeof goto>[1] return goto(path, {...options, replaceState: options.replaceState || modalIsOpen})
export const push = (params: PushParams, options: PushOptions) => {
const $page = get(page)
const $pathname = params.pathname ?? $page.url.pathname
const $search = params.search ?? $page.url.search
const $hash = params.hash ?? $page.url.hash
const url = $pathname + $search + $hash
if (params.pathname !== $page.url.pathname) {
goto(url, options)
} else if (options.replaceState) {
history.replaceState(history.state, "", url)
} else {
history.pushState(history.state, "", url)
}
} }
export const pop = () => history.back() export const pop = () => history.back()
// push/pop path, for navigations that clear modals and query params
export const pushPath = (pathname: string, options: PushOptions) =>
push({pathname, search: "", hash: ""}, options)
export const popPath = async () => { export const popPath = async () => {
while (get(modal)) { while (get(modal)) {
await history.back() const popped = new Promise(resolve =>
} window.addEventListener("popstate", resolve, {once: true}),
} )
// push/pop/clear modal history.back()
await popped
}
}
export const pushModal = ( export const pushModal = (
component: Component<any>, component: Component<any>,
@ -86,45 +69,30 @@ export const pushModal = (
options: ModalOptions = {}, options: ModalOptions = {},
) => { ) => {
const id = randomId() const id = randomId()
const existingIds = getIdsFromHash(get(modalHash)) const existingIds = get(page).state.modals ?? []
const ids = options.nested ? [...existingIds, id] : [id] const ids = options.nested ? [...existingIds, id] : [id]
modals.update(assoc(id, {id, component, props, options})) modals.update(assoc(id, {id, component, props, options}))
push({ if (options.replaceState) {
hash: "#" + ids.join(","), replaceState("", {modals: ids})
}, { } else {
replaceState: Boolean(options.replaceState), pushState("", {modals: ids})
}) }
return id return id
} }
export const popModal = () => { export const popModal = () => {
const ids = getIdsFromHash(get(modalHash)) const ids = get(page).state.modals ?? []
if (ids.length === 0) { if (ids.length > 0) {
return replaceState("", {modals: ids.slice(0, -1)})
} }
const next = ids.slice(0, -1).join(",")
push({
hash: next ? `#${next}` : "",
}, {
replaceState: true,
})
} }
export const clearModals = () => { export const clearModals = () => {
push({hash: ""}, {replaceState: true}) replaceState("", {})
modals.update(always({})) modals.update(always({}))
emitter.emit("close") emitter.emit("close")
} }
// Sync window history with the current hash directly. Svelte's navigation stuff
// is buggy, and results in double-mounted pages in dev.
call(() => {
window.addEventListener("popstate", () => modalHash.set(location.hash))
page.subscribe($page => modalHash.set($page.url?.hash ?? ""))
})

View file

@ -1,4 +1,3 @@
import theme from "tailwindcss/defaultTheme"
import {get, writable} from "svelte/store" import {get, writable} from "svelte/store"
import * as nip19 from "nostr-tools/nip19" import * as nip19 from "nostr-tools/nip19"
import {page} from "$app/stores" import {page} from "$app/stores"
@ -110,13 +109,9 @@ export const goToMovedSpace = (oldUrl: string, newUrl: string) =>
navigate(get(page).url.pathname.replace(encodeRelay(oldUrl), encodeRelay(newUrl))) navigate(get(page).url.pathname.replace(encodeRelay(oldUrl), encodeRelay(newUrl)))
export const goToHome = () => { export const goToHome = () => {
if (PLATFORM_RELAYS.length > 0) { const path = PLATFORM_RELAYS.length > 0 ? makeSpaceEntryPath(PLATFORM_RELAYS[0]) : "/home"
return navigate(makeSpaceEntryPath(PLATFORM_RELAYS[0]) + get(page).url.hash, {
replaceState: true,
})
}
return navigate("/home" + get(page).url.hash) return navigate(path, {keepModal: true, replaceState: true})
} }
// Content types, events // Content types, events