// Copyright: Ankitects Pty Ltd and contributors // License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html /* eslint @typescript-eslint/no-non-null-assertion: "off", */ import type { Writable, Subscriber, Unsubscriber, Updater } from "svelte/store"; import { noop } from "../lib/functional"; export interface NodeStore extends Writable { setUnprocessed(node: T): void; } export function nodeStore( node?: T, preprocess: (node: T) => void = noop, ): NodeStore { const subscribers: Set> = new Set(); function setUnprocessed(newNode: T): void { if (!node || !node.isEqualNode(newNode)) { node = newNode; for (const subscriber of subscribers) { subscriber(node); } } } function set(newNode: T): void { preprocess(newNode); setUnprocessed(newNode); } function update(fn: Updater): void { set(fn(node!)); } function subscribe(subscriber: Subscriber): Unsubscriber { subscribers.add(subscriber); if (node) { subscriber(node); } return () => subscribers.delete(subscriber); } return { set, setUnprocessed, update, subscribe }; } export default nodeStore;