flotilla/src/app/state.ts

69 lines
1.5 KiB
TypeScript
Raw Normal View History

2024-08-05 22:28:46 +00:00
import type {ComponentType} from "svelte"
import {readable, writable} from "svelte/store"
import type {FlyParams} from "svelte/transition"
import {fly as baseFly} from "svelte/transition"
import {randomId} from "@welshman/lib"
import {pushState} from "$app/navigation"
2024-08-05 21:45:16 +00:00
// Animations
2024-08-05 22:28:46 +00:00
export const fly = (node: Element, params?: FlyParams | undefined) =>
baseFly(node, {y: 20, ...params})
2024-08-05 21:45:16 +00:00
// Toast
2024-08-05 22:25:04 +00:00
export type Toast = {
id: number
message: string
options: ToastOptions
}
export type ToastOptions = {
timeout?: number
}
export const toast = writable<Toast | null>(null)
2024-08-05 22:28:46 +00:00
export const pushToast = (
{message = "", id = Math.random()}: Partial<Toast>,
options: ToastOptions,
) => {
2024-08-05 22:25:04 +00:00
toast.set({id, message, options})
setTimeout(() => popToast(id), options.timeout || 5000)
return id
}
2024-08-05 22:28:46 +00:00
export const popToast = (id: number) => toast.update($t => ($t?.id === id ? null : $t))
2024-08-05 21:45:16 +00:00
// Modals
export const modals = new Map()
2024-08-05 22:25:04 +00:00
export const pushModal = (component: ComponentType, props: Record<string, any>) => {
const id = randomId()
2024-08-05 21:45:16 +00:00
2024-08-05 22:25:04 +00:00
// TODO: fix memory leak here by listening to history somehow
2024-08-05 21:45:16 +00:00
modals.set(id, {component, props})
2024-08-05 22:28:46 +00:00
pushState("", {modal: id})
2024-08-05 21:45:16 +00:00
return id
}
2024-08-05 22:25:04 +00:00
export const popModal = (id: string) => {
modals.delete(id)
history.back()
}
2024-08-05 21:45:16 +00:00
// App state
export const spaces = readable([
{
2024-08-05 22:28:46 +00:00
id: "test",
2024-08-05 21:45:16 +00:00
name: "Test",
2024-08-05 22:28:46 +00:00
picture:
"https://images.unsplash.com/photo-1721853046219-209921be684e?w=800&auto=format&fit=crop&q=60&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxmZWF0dXJlZC1waG90b3MtZmVlZHw0fHx8ZW58MHx8fHx8",
},
2024-08-05 21:45:16 +00:00
])