flotilla/src/app/toast.ts

43 lines
915 B
TypeScript
Raw Normal View History

import type {Component} from "svelte"
2024-08-06 20:10:10 +00:00
import {writable} from "svelte/store"
2026-07-15 16:30:17 +00:00
import type {Maybe} from "@welshman/lib"
2024-08-06 20:10:10 +00:00
import {randomId} from "@welshman/lib"
2024-08-16 17:50:38 +00:00
import {copyToClipboard} from "@lib/html"
2024-08-06 20:10:10 +00:00
2024-08-09 23:22:09 +00:00
export type ToastParams = {
message?: string
2024-08-09 23:22:09 +00:00
timeout?: number
theme?: "error"
children?: {
component: Component<any>
props: Record<string, any>
}
2025-07-30 22:54:10 +00:00
action?: {
message: string
onclick: () => void
}
2024-08-06 20:10:10 +00:00
}
2024-08-09 23:22:09 +00:00
export type Toast = ToastParams & {
id: string
2024-08-06 20:10:10 +00:00
}
2026-07-15 16:30:17 +00:00
export const toast = writable<Maybe<Toast>>()
2024-08-06 20:10:10 +00:00
2024-08-09 23:22:09 +00:00
export const pushToast = (params: ToastParams) => {
const id = randomId()
toast.set({id, ...params})
2024-08-06 20:10:10 +00:00
2024-08-09 23:22:09 +00:00
setTimeout(() => popToast(id), params.timeout || 5000)
2024-08-06 20:10:10 +00:00
return id
}
2026-07-15 16:30:17 +00:00
export const popToast = (id: string) => toast.update($t => ($t?.id === id ? undefined : $t))
2024-08-08 23:32:46 +00:00
export const clip = (value: string) => {
copyToClipboard(value)
pushToast({message: "Copied to clipboard!"})
}