UNPKG

shelving

Version:

Toolkit for using data in JavaScript.

44 lines (43 loc) 1.88 kB
import { jsx as _jsx } from "react/jsx-runtime"; import { createContext, use } from "react"; import { useInstance } from "../../react/useInstance.js"; import { useStore } from "../../react/useStore.js"; import { ArrayStore } from "../../store/ArrayStore.js"; import { getRandomKey } from "../../util/random.js"; import { Dialog } from "./Dialog.js"; /** How long before a hidden dialogs are removed from the DOM (allow time for animates to complete). */ const REMOVE_DELAY = 500; /** Store a list of dialogs. */ export class DialogsStore extends ArrayStore { /** Show a new dialog. */ show(children) { const dialog = (_jsx(Dialog // Add a `key=""` so dialogs can be rendered directly and added/removed in any order. , { // When the `<dialog>` is closed, wait for the animation to finish then remove the dialog from the list. onClose: () => { setTimeout(() => this.delete(dialog), REMOVE_DELAY); }, children: children }, getRandomKey())); this.add(dialog); } /** Hide all currently visible dialogs. */ hideAll() { this.delete(...this.value); } } /** Context to get the current `DialogsStore` created by a `<DialogsWrapper>`. */ const _DialogsContext = createContext(new DialogsStore()); _DialogsContext.displayName = "DialogsContext"; /** Return the current dialogs context. */ export function requireDialogs() { return use(_DialogsContext); } /** Create a new `<DialogsStore>` for a set of elements. */ export function DialogsContext({ children }) { return _jsx(_DialogsContext, { value: useInstance(DialogsStore), children: children }); } /** Output the list of dialogs from a `DialogsStore` in the current `DialogsContext`. */ export function Dialogs() { const dialogs = useStore(requireDialogs()); return dialogs ? dialogs.value : null; }