anki/ts/sveltelib/node-store.ts
Henrik Giesel 30bbbaf00b
Use eslint for sorting our imports (#1637)
* Make eslint sort our imports

* fix missing deps in eslint rule (dae)

Caught on Linux due to the stricter sandboxing

* Remove exports-last eslint rule (for now?)

* Adjust browserslist settings

- We use ResizeObserver which is not supported in browsers like KaiOS,
  Baidu or Android UC

* Raise minimum iOS version 13.4

- It's the first version that supports ResizeObserver

* Apply new eslint rules to sort imports
2022-02-04 18:36:34 +10:00

52 lines
1.2 KiB
TypeScript

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