import { createContext, useContext, type ParentProps, Show } from "solid-js" import { createStore } from "solid-js/store" import { useTheme } from "@tui/context/theme" import { SplitBorder } from "../component/border" import { TextAttributes } from "@opentui/core" import z from "zod" import { TuiEvent } from "../event" export type ToastOptions = z.infer export function Toast() { const toast = useToast() const { theme } = useTheme() return ( {(current) => ( {current().title} {current().message} )} ) } function init() { const [store, setStore] = createStore({ currentToast: null as ToastOptions | null, }) let timeoutHandle: NodeJS.Timeout | null = null const toast = { show(options: ToastOptions) { const parsedOptions = TuiEvent.ToastShow.properties.parse(options) const { duration, ...currentToast } = parsedOptions setStore("currentToast", currentToast) if (timeoutHandle) clearTimeout(timeoutHandle) timeoutHandle = setTimeout(() => { setStore("currentToast", null) }, duration).unref() }, error: (err: any) => { if (err instanceof Error) return toast.show({ variant: "error", message: err.message, }) toast.show({ variant: "error", message: "An unknown error has occurred", }) }, get currentToast(): ToastOptions | null { return store.currentToast }, } return toast } export type ToastContext = ReturnType const ctx = createContext() export function ToastProvider(props: ParentProps) { const value = init() return {props.children} } export function useToast() { const value = useContext(ctx) if (!value) { throw new Error("useToast must be used within a ToastProvider") } return value }