@nustackdev/ui-core 0.2.3 → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -6,7 +6,7 @@
6
6
  "url": "git+https://github.com/nustackdev/nu.git",
7
7
  "directory": "pkgs/ts/ui-core"
8
8
  },
9
- "version": "0.2.3",
9
+ "version": "0.2.5",
10
10
  "type": "module",
11
11
  "main": "./src/index.ts",
12
12
  "types": "./src/index.ts",
package/src/protocol.ts CHANGED
@@ -19,11 +19,7 @@ export type RefPath = string[];
19
19
  // One level of a write's chain. The server always sends all three, but a chain
20
20
  // synthesized locally from a bare `ref` has no type and no props to give, so the
21
21
  // tail is optional. One type for both, or the two ends stop agreeing.
22
- export type ChainLevel = [
23
- segment: string,
24
- type?: string | null,
25
- props?: Record<string, unknown>,
26
- ];
22
+ export type ChainLevel = [segment: string, type?: string | null, props?: Record<string, unknown>];
27
23
 
28
24
  export type Frame = {
29
25
  op: string;
package/src/tree.test.ts CHANGED
@@ -2,16 +2,14 @@
2
2
  // Everything below is a plain frame in and a plain node out.
3
3
 
4
4
  import { describe, expect, it, vi } from "vitest";
5
- import {
6
- type Behaviour,
7
- type ChainStep,
8
- OPS,
9
- type TreeFrame,
10
- createTreeStore,
11
- } from "./tree";
12
5
  import { OP_ERROR } from "./protocol";
6
+ import { type Behaviour, type ChainStep, createTreeStore, OPS, type TreeFrame } from "./tree";
13
7
 
14
- function step(segment: string, type: string | null = null, props?: Record<string, unknown>): ChainStep {
8
+ function step(
9
+ segment: string,
10
+ type: string | null = null,
11
+ props?: Record<string, unknown>,
12
+ ): ChainStep {
15
13
  return props ? [segment, type, props] : [segment, type];
16
14
  }
17
15
 
@@ -74,6 +72,18 @@ describe("write", () => {
74
72
  expect(segments(store.getState().getIn(["sec"]))).toEqual(["t", "u"]);
75
73
  });
76
74
 
75
+ it("keeps the declared props as the node's seed, untouched by later writes", () => {
76
+ const store = createTreeStore();
77
+ store.getState().write([step("f", "Form"), step("title", "InputRef", { value: "seed" })]);
78
+ store.getState().setProps(["f", "title"], { value: "typed" });
79
+ store.getState().write([step("f", "Form"), step("title", "InputRef", { value: "seed" })], {
80
+ value: "written",
81
+ });
82
+ const node = store.getState().getIn(["f", "title"]);
83
+ expect(node?.props.value).toBe("written");
84
+ expect(node?.seed).toEqual({ value: "seed" });
85
+ });
86
+
77
87
  it("keeps a prop set at runtime when a deep write rides through", () => {
78
88
  const store = createTreeStore();
79
89
  const chain = [
@@ -123,7 +133,9 @@ describe("write", () => {
123
133
  const store = createTreeStore({ onError: (message) => errors.push(message) });
124
134
  store.getState().write([step("a", "Card"), step("t", "TextRef", { value: "x" })]);
125
135
 
126
- const applied = store.getState().write([step("a", "Grid"), step("t", "TextRef")], { value: "y" });
136
+ const applied = store
137
+ .getState()
138
+ .write([step("a", "Grid"), step("t", "TextRef")], { value: "y" });
127
139
 
128
140
  expect(applied).toBe(false);
129
141
  expect(store.getState().getIn(["a", "t"])?.props).toEqual({ value: "x" });
@@ -147,6 +159,7 @@ describe("write", () => {
147
159
  type: "InputRef",
148
160
  props: { value: "y" },
149
161
  children: new Map(),
162
+ seed: { value: "x" },
150
163
  });
151
164
  });
152
165
 
@@ -206,11 +219,7 @@ describe("remove", () => {
206
219
 
207
220
  store.getState().remove(["sec"]);
208
221
 
209
- expect(gone).toEqual([
210
- ["sec", "col", "t"],
211
- ["sec", "col"],
212
- ["sec"],
213
- ]);
222
+ expect(gone).toEqual([["sec", "col", "t"], ["sec", "col"], ["sec"]]);
214
223
  expect(store.getState().getIn(["sec"])).toBeNull();
215
224
  expect(store.getState().getIn(["other"])?.type).toBe("TextRef");
216
225
  });
@@ -296,6 +305,7 @@ describe("dispatch", () => {
296
305
  type: "InputRef",
297
306
  props: { label: "L", value: "typed" },
298
307
  children: new Map(),
308
+ seed: { label: "L" },
299
309
  });
300
310
  });
301
311
 
@@ -369,7 +379,9 @@ describe("dispatch", () => {
369
379
  it("builds structure from an init and touches no value", () => {
370
380
  const store = createTreeStore();
371
381
  store.getState().write([step("a", "InputRef", { label: "L" })], { value: "typed" });
372
- store.getState().dispatch(frame(OPS.init, ["a"], null, [step("a", "InputRef", { label: "L" })]));
382
+ store
383
+ .getState()
384
+ .dispatch(frame(OPS.init, ["a"], null, [step("a", "InputRef", { label: "L" })]));
373
385
  store.getState().dispatch(frame(OPS.init, ["b"], null, [step("b", "TextRef", { value: "" })]));
374
386
  expect(store.getState().getIn(["a"])?.props).toEqual({ label: "L", value: "typed" });
375
387
  expect(store.getState().getIn(["b"])?.type).toBe("TextRef");
@@ -405,6 +417,40 @@ describe("dispatch", () => {
405
417
  expect(sent).toEqual([{ op: OPS.read, ref: ["p"], payload: "md:hi", id: "f2" }]);
406
418
  });
407
419
 
420
+ it("answers a read through the type's reads, per field", () => {
421
+ const sent: TreeFrame[] = [];
422
+ const behaviours: Record<string, Behaviour> = {
423
+ TreeRef: {
424
+ reads: {
425
+ "": (p) => p.selected ?? null,
426
+ expanded: (p) => p.expanded ?? [],
427
+ },
428
+ },
429
+ };
430
+ const store = createTreeStore({ send: (f) => sent.push(f), resolve: (t) => behaviours[t] });
431
+ store.getState().write([step("t", "TreeRef", { selected: "x", expanded: ["a"] })]);
432
+ store.getState().dispatch({ op: OPS.read, ref: ["t"], payload: null, id: "r1" });
433
+ store.getState().dispatch({ op: OPS.read, ref: ["t"], payload: { field: "" }, id: "r2" });
434
+ store
435
+ .getState()
436
+ .dispatch({ op: OPS.read, ref: ["t"], payload: { field: "expanded" }, id: "r3" });
437
+ expect(sent).toEqual([
438
+ { op: OPS.read, ref: ["t"], payload: "x", id: "r1" },
439
+ { op: OPS.read, ref: ["t"], payload: "x", id: "r2" },
440
+ { op: OPS.read, ref: ["t"], payload: ["a"], id: "r3" },
441
+ ]);
442
+ });
443
+
444
+ it("answers a read of a field the type does not declare with an error", () => {
445
+ const sent: TreeFrame[] = [];
446
+ const store = createTreeStore({ send: (f) => sent.push(f) });
447
+ store.getState().write([step("a", "InputRef", { value: "gor" })]);
448
+ store.getState().dispatch({ op: OPS.read, ref: ["a"], payload: { field: "nope" }, id: "f3" });
449
+ expect(sent).toHaveLength(1);
450
+ expect(sent[0]).toMatchObject({ op: OP_ERROR, ref: ["a"], id: "f3" });
451
+ expect((sent[0].payload as { code: string }).code).toBe("payload_invalid");
452
+ });
453
+
408
454
  it("reports an op on a node that is not there", () => {
409
455
  const errors: string[] = [];
410
456
  const store = createTreeStore({ onError: (m) => errors.push(m) });
@@ -424,7 +470,9 @@ describe("dispatch", () => {
424
470
  describe("visibility", () => {
425
471
  it("hides a node and keeps its props and children", () => {
426
472
  const store = createTreeStore();
427
- store.getState().write([step("a", "Card", { title: "T" }), step("b", "TextRef")], { value: "x" });
473
+ store
474
+ .getState()
475
+ .write([step("a", "Card", { title: "T" }), step("b", "TextRef")], { value: "x" });
428
476
  store.getState().dispatch(frame(OPS.hide, ["a"], null, [step("a", "Card", { title: "T" })]));
429
477
  const a = store.getState().getIn(["a"]);
430
478
  expect(a?.hidden).toBe(true);
@@ -442,9 +490,14 @@ describe("visibility", () => {
442
490
 
443
491
  it("brings a node into being hidden when the hide is the first frame", () => {
444
492
  const store = createTreeStore();
445
- store.getState().dispatch(
446
- frame(OPS.hide, ["a", "b"], null, [step("a", "Column"), step("b", "TextRef", { value: "seed" })]),
447
- );
493
+ store
494
+ .getState()
495
+ .dispatch(
496
+ frame(OPS.hide, ["a", "b"], null, [
497
+ step("a", "Column"),
498
+ step("b", "TextRef", { value: "seed" }),
499
+ ]),
500
+ );
448
501
  const b = store.getState().getIn(["a", "b"]);
449
502
  expect(b?.type).toBe("TextRef");
450
503
  expect(b?.props).toEqual({ value: "seed" });
@@ -466,11 +519,18 @@ describe("visibility", () => {
466
519
  const store = createTreeStore({ resolve: (t) => behaviours[t] });
467
520
  store.getState().write([step("h", "HeadingRef"), step("t", "TextRef")]);
468
521
  store.getState().dispatch(frame(OPS.hide, ["h"], null, [step("h", "HeadingRef")]));
469
- store.getState().dispatch(frame(OPS.hide, ["h", "t"], null, [step("h", "HeadingRef"), step("t", "TextRef")]));
522
+ store
523
+ .getState()
524
+ .dispatch(frame(OPS.hide, ["h", "t"], null, [step("h", "HeadingRef"), step("t", "TextRef")]));
470
525
  store.getState().dispatch(frame(OPS.write, ["h"], "hello", [step("h", "HeadingRef")]));
471
- store.getState().dispatch(
472
- frame(OPS.write, ["h", "t"], { value: 1, hidden: false }, [step("h", "HeadingRef"), step("t", "TextRef")]),
473
- );
526
+ store
527
+ .getState()
528
+ .dispatch(
529
+ frame(OPS.write, ["h", "t"], { value: 1, hidden: false }, [
530
+ step("h", "HeadingRef"),
531
+ step("t", "TextRef"),
532
+ ]),
533
+ );
474
534
  expect(store.getState().getIn(["h"])?.hidden).toBe(true);
475
535
  expect(store.getState().getIn(["h"])?.props.label).toBe("hello");
476
536
  expect(store.getState().getIn(["h", "t"])?.hidden).toBe(true);
@@ -480,7 +540,10 @@ describe("visibility", () => {
480
540
  const errors: string[] = [];
481
541
  const hide = vi.fn();
482
542
  const behaviours: Record<string, Behaviour> = { TextRef: { handlers: { hide } } };
483
- const store = createTreeStore({ resolve: (t) => behaviours[t], onError: (m) => errors.push(m) });
543
+ const store = createTreeStore({
544
+ resolve: (t) => behaviours[t],
545
+ onError: (m) => errors.push(m),
546
+ });
484
547
  store.getState().write([step("a", "TextRef")]);
485
548
  store.getState().dispatch(frame(OPS.hide, ["a"], null, [step("a", "TextRef")]));
486
549
  expect(hide).not.toHaveBeenCalled();
@@ -541,7 +604,9 @@ describe("kind mismatch", () => {
541
604
 
542
605
  store.getState().dispatch(frame(OPS.init, ["a"], null, [step("a", "Grid")]));
543
606
  store.getState().dispatch(frame(OPS.hide, ["a"], null, [step("a", "Grid")]));
544
- store.getState().dispatch(frame("set_span", ["a", "c"], [2, 1], [step("a", "Grid"), step("c")]));
607
+ store
608
+ .getState()
609
+ .dispatch(frame("set_span", ["a", "c"], [2, 1], [step("a", "Grid"), step("c")]));
545
610
 
546
611
  expect(sent.map((f) => f.op)).toEqual([OP_ERROR, OP_ERROR, OP_ERROR]);
547
612
  expect(store.getState().getIn(["a"])?.type).toBe("Card");
package/src/tree.ts CHANGED
@@ -22,9 +22,9 @@
22
22
  // the component registry live in the kit.
23
23
 
24
24
  import { current, enableMapSet, isDraft } from "immer";
25
- import { type ChainLevel, type ErrorPayload, type Frame, OP_ERROR } from "./protocol";
26
- import { createStore, type StoreApi } from "zustand/vanilla";
27
25
  import { immer } from "zustand/middleware/immer";
26
+ import { createStore, type StoreApi } from "zustand/vanilla";
27
+ import { type ChainLevel, type ErrorPayload, type Frame, OP_ERROR } from "./protocol";
28
28
 
29
29
  // `children` is a Map, and immer only drafts those once this is on.
30
30
  enableMapSet();
@@ -45,6 +45,10 @@ export type Node = {
45
45
  props: Props;
46
46
  children: Map<string, Node>;
47
47
  hidden?: boolean;
48
+ // The props the node's slot declared, as they came on the chain that
49
+ // created it. Never written after that, so a reset (an input back to its
50
+ // declared value) has something to go back to once the live props moved.
51
+ seed?: Props;
48
52
  };
49
53
 
50
54
  /** Alias for consumers where the DOM's `Node` is also in scope. */
@@ -78,8 +82,18 @@ export const OPS = {
78
82
  // shows it again. Every type takes them, none handles them.
79
83
  hide: "hide",
80
84
  display: "display",
85
+ // Payload `{field}` or null. Null (or no field) asks for the node's main
86
+ // read; a field names one of its other reads. See `Reads`.
81
87
  read: "read",
82
88
  notify: "notify",
89
+ // Server to browser, plain path, payload `{event}`: someone on the
90
+ // server listens for `event` on this ref (`*` for every event), or
91
+ // stopped listening. Kept by path, apart from the nodes: see `isWatched`.
92
+ watch: "watch",
93
+ unwatch: "unwatch",
94
+ // Browser to server, payload a list of `[ref, payload]` pairs in order:
95
+ // several notifies in one frame.
96
+ batch: "batch",
83
97
  } as const;
84
98
 
85
99
  export type NodeCtx = {
@@ -98,12 +112,54 @@ export type NodeHandler = (ctx: NodeCtx, payload: unknown) => void;
98
112
 
99
113
  export type DisposeCtx = { path: Path; node: Node };
100
114
 
101
- /** What a type contributes to the store: inbound ops and teardown. */
115
+ /**
116
+ * What a read answers, per field, from the node's props. `""` is the main
117
+ * read (the ref itself on the server); any other key is a named read
118
+ * (`tree.expanded()` asks for `expanded`). A type with no `""` entry answers
119
+ * its main read with `props.value`.
120
+ */
121
+ export type Reads = Record<string, (props: Props) => unknown>;
122
+
123
+ /** What a type contributes to the store: inbound ops, reads and teardown. */
102
124
  export type Behaviour = {
103
125
  handlers?: Record<string, NodeHandler>;
126
+ reads?: Reads;
104
127
  dispose?: (ctx: DisposeCtx) => void;
105
128
  };
106
129
 
130
+ /** The event a watch matching every event names. */
131
+ export const ANY_EVENT = "*";
132
+
133
+ /** The event a `watch` / `unwatch` frame names, or null when it names none. */
134
+ export function watchEvent(payload: unknown): string | null {
135
+ if (!isPlainProps(payload)) return null;
136
+ const event = payload.event;
137
+ return typeof event === "string" && event !== "" ? event : null;
138
+ }
139
+
140
+ /** The field a read frame asks for: `""` for the main read. */
141
+ export function readField(payload: unknown): string {
142
+ if (!isPlainProps(payload)) return "";
143
+ const field = payload.field;
144
+ return typeof field === "string" ? field : "";
145
+ }
146
+
147
+ /**
148
+ * One field of a node, through its type's `reads`. Undefined when the type
149
+ * declares no such field; the main read always answers (`props.value`, or
150
+ * null, when the type declares none).
151
+ */
152
+ export function readNode(
153
+ behaviour: Behaviour | undefined,
154
+ props: Props,
155
+ field = "",
156
+ ): { value: unknown } | undefined {
157
+ const reader = behaviour?.reads?.[field];
158
+ if (reader) return { value: reader(props) };
159
+ if (field === "") return { value: props.value ?? null };
160
+ return undefined;
161
+ }
162
+
107
163
  export type Resolve = (type: string) => Behaviour | undefined;
108
164
 
109
165
  export type TreeState = { root: Node };
@@ -122,6 +178,22 @@ export type TreeActions = {
122
178
  setProps: (path: Path, props: Props) => void;
123
179
  /** Hide or show an existing node. No-op when the node is not there. */
124
180
  setHidden: (path: Path, hidden: boolean) => void;
181
+ /**
182
+ * Whether the server listens for `event` on the node at `path`: a watch on
183
+ * that event or on `*`. A node sends only the events this answers true for.
184
+ */
185
+ isWatched: (path: Path, event: string) => boolean;
186
+ /** Start sending `event` from `path`; what a `watch` frame does. */
187
+ watch: (path: Path, event: string) => void;
188
+ /** Stop sending `event` from `path`; what an `unwatch` frame does. */
189
+ unwatch: (path: Path, event: string) => void;
190
+ /** Forget every watch: a new connection's session watches afresh. */
191
+ unwatchAll: () => void;
192
+ /**
193
+ * Count every event as watched, whatever the table holds. For a host whose
194
+ * server sends no watches, and for tests that drive nodes with no server.
195
+ */
196
+ setWatchAll: (on: boolean) => void;
125
197
  /** Route an inbound frame to its node, by node type and frame op. */
126
198
  dispatch: (frame: TreeFrame) => void;
127
199
  /** Outbound. No-op until a sender is set. */
@@ -222,6 +294,17 @@ export function createTreeStore(options: TreeStoreOptions = {}): TreeStore {
222
294
  // Disposals are collected inside a draft and run after the set returns, so
223
295
  // a dispose is free to touch the store without writing into a dead draft.
224
296
  let pending: DisposeCtx[] = [];
297
+
298
+ // What the server listens to, per path: event names, `*` for all of them.
299
+ // Kept out of the node tree and out of the store state on purpose. A watch
300
+ // may land before the node is drawn, and survives a remove and a redraw at
301
+ // the same path: the server's subscription is to the address, not to one
302
+ // incarnation of the node. Nothing renders from it, so no state, no
303
+ // re-render. The server counts its listeners and sends one watch and one
304
+ // unwatch per (path, event), so a set is enough here.
305
+ const watches = new Map<string, Set<string>>();
306
+ let watchAll = false;
307
+ const watchKey = (path: Path) => JSON.stringify(path);
225
308
  const flushDispose = () => {
226
309
  const batch = pending;
227
310
  pending = [];
@@ -266,14 +349,20 @@ export function createTreeStore(options: TreeStoreOptions = {}): TreeStore {
266
349
  let child: Node | undefined = node.children.get(segment);
267
350
  if (!child) {
268
351
  child = emptyNode(type);
269
- if (stepProps) Object.assign(child.props, stepProps);
352
+ if (stepProps) {
353
+ Object.assign(child.props, stepProps);
354
+ child.seed = { ...stepProps };
355
+ }
270
356
  node.children.set(segment, child);
271
357
  } else if (child.type === null && type !== null) {
272
358
  // Autovivified earlier by something below it, so it
273
359
  // never got its declared props. This write names its
274
360
  // type, which is when it really comes into being.
275
361
  child.type = type;
276
- if (stepProps) Object.assign(child.props, stepProps);
362
+ if (stepProps) {
363
+ Object.assign(child.props, stepProps);
364
+ child.seed = { ...stepProps };
365
+ }
277
366
  }
278
367
  // Otherwise: the level is already there with the right
279
368
  // type. The chain says nothing new about it.
@@ -325,6 +414,38 @@ export function createTreeStore(options: TreeStoreOptions = {}): TreeStore {
325
414
  });
326
415
  },
327
416
 
417
+ isWatched: (path, event) => {
418
+ if (watchAll) return true;
419
+ const events = watches.get(watchKey(path));
420
+ return events !== undefined && (events.has(event) || events.has(ANY_EVENT));
421
+ },
422
+
423
+ watch: (path, event) => {
424
+ const key = watchKey(path);
425
+ let events = watches.get(key);
426
+ if (!events) {
427
+ events = new Set();
428
+ watches.set(key, events);
429
+ }
430
+ events.add(event);
431
+ },
432
+
433
+ unwatch: (path, event) => {
434
+ const key = watchKey(path);
435
+ const events = watches.get(key);
436
+ if (!events) return;
437
+ events.delete(event);
438
+ if (events.size === 0) watches.delete(key);
439
+ },
440
+
441
+ unwatchAll: () => {
442
+ watches.clear();
443
+ },
444
+
445
+ setWatchAll: (on) => {
446
+ watchAll = on;
447
+ },
448
+
328
449
  send: (frame) => {
329
450
  if (outbound) outbound(frame);
330
451
  },
@@ -356,7 +477,21 @@ export function createTreeStore(options: TreeStoreOptions = {}): TreeStore {
356
477
  id: frame.id,
357
478
  });
358
479
  };
480
+ if (frame.op === OPS.watch || frame.op === OPS.unwatch) {
481
+ // Generic for every type, and no node needed: the table is
482
+ // keyed by path, so a watch may come before the node does.
483
+ const event = watchEvent(frame.payload);
484
+ if (event === null) {
485
+ onError(`${frame.op} names no event`, frame.ref);
486
+ return;
487
+ }
488
+ if (frame.op === OPS.watch) api.watch(frame.ref, event);
489
+ else api.unwatch(frame.ref, event);
490
+ return;
491
+ }
359
492
  if (frame.op === OPS.remove) {
493
+ // Watches stay: they belong to the path, and the node may
494
+ // be drawn there again.
360
495
  api.remove(frame.ref);
361
496
  return;
362
497
  }
@@ -420,12 +555,24 @@ export function createTreeStore(options: TreeStoreOptions = {}): TreeStore {
420
555
  return;
421
556
  }
422
557
  if (frame.op === OPS.read) {
423
- // The server is asking for our current value. Same id back
424
- // so its future resolves.
558
+ // The server is asking for one field of the node, the main
559
+ // read when it names none. Same id back so its future
560
+ // resolves, a value or an error. A type whose read needs
561
+ // more than its props (a Form gathers its children) keeps a
562
+ // `read` handler, which answered above.
563
+ const field = readField(frame.payload);
564
+ const found = readNode(node.type ? resolve(node.type) : undefined, node.props, field);
565
+ if (found) {
566
+ api.send({ op: OPS.read, ref: frame.ref, payload: found.value, id: frame.id });
567
+ return;
568
+ }
425
569
  api.send({
426
- op: OPS.read,
570
+ op: OP_ERROR,
427
571
  ref: frame.ref,
428
- payload: node.props.value ?? null,
572
+ payload: {
573
+ code: "payload_invalid",
574
+ message: `${node.type ?? "untyped node"} has no read "${field}"`,
575
+ } satisfies ErrorPayload,
429
576
  id: frame.id,
430
577
  });
431
578
  return;
@@ -0,0 +1,95 @@
1
+ // The watch table: what the server listens to, per path. Plain frames in,
2
+ // `isWatched` out; no React, no socket.
3
+
4
+ import { describe, expect, it, vi } from "vitest";
5
+ import { createTreeStore, OPS, type TreeFrame } from "./tree";
6
+
7
+ function frame(op: string, ref: string[], payload?: unknown): TreeFrame {
8
+ return { op, ref, payload };
9
+ }
10
+
11
+ describe("watch", () => {
12
+ it("watches nothing until the server asks", () => {
13
+ const store = createTreeStore();
14
+ expect(store.getState().isWatched(["s"], "change")).toBe(false);
15
+ });
16
+
17
+ it("watches one event on one path", () => {
18
+ const store = createTreeStore();
19
+ store.getState().dispatch(frame(OPS.watch, ["p", "s"], { event: "change" }));
20
+ expect(store.getState().isWatched(["p", "s"], "change")).toBe(true);
21
+ expect(store.getState().isWatched(["p", "s"], "input")).toBe(false);
22
+ expect(store.getState().isWatched(["p"], "change")).toBe(false);
23
+ expect(store.getState().isWatched(["p", "t"], "change")).toBe(false);
24
+ });
25
+
26
+ it("takes * as every event", () => {
27
+ const store = createTreeStore();
28
+ store.getState().dispatch(frame(OPS.watch, ["t"], { event: "*" }));
29
+ expect(store.getState().isWatched(["t"], "select")).toBe(true);
30
+ expect(store.getState().isWatched(["t"], "toggle")).toBe(true);
31
+ });
32
+
33
+ it("unwatch stops that event only", () => {
34
+ const store = createTreeStore();
35
+ store.getState().dispatch(frame(OPS.watch, ["s"], { event: "change" }));
36
+ store.getState().dispatch(frame(OPS.watch, ["s"], { event: "input" }));
37
+ store.getState().dispatch(frame(OPS.unwatch, ["s"], { event: "change" }));
38
+ expect(store.getState().isWatched(["s"], "change")).toBe(false);
39
+ expect(store.getState().isWatched(["s"], "input")).toBe(true);
40
+ store.getState().dispatch(frame(OPS.unwatch, ["s"], { event: "input" }));
41
+ expect(store.getState().isWatched(["s"], "input")).toBe(false);
42
+ });
43
+
44
+ it("lands before the node is drawn and creates nothing", () => {
45
+ const store = createTreeStore();
46
+ store.getState().dispatch(frame(OPS.watch, ["page", "s"], { event: "change" }));
47
+ expect(store.getState().getIn(["page"])).toBeNull();
48
+ store.getState().write([
49
+ ["page", "Page"],
50
+ ["s", "Slider"],
51
+ ]);
52
+ expect(store.getState().isWatched(["page", "s"], "change")).toBe(true);
53
+ });
54
+
55
+ it("survives a remove and a clear of the node", () => {
56
+ const store = createTreeStore();
57
+ store.getState().write([["s", "Slider"]]);
58
+ store.getState().dispatch(frame(OPS.watch, ["s"], { event: "change" }));
59
+ store.getState().dispatch(frame(OPS.remove, ["s"]));
60
+ expect(store.getState().isWatched(["s"], "change")).toBe(true);
61
+ store.getState().dispatch(frame(OPS.remove, []));
62
+ expect(store.getState().isWatched(["s"], "change")).toBe(true);
63
+ });
64
+
65
+ it("keeps segments apart that a joined key would merge", () => {
66
+ const store = createTreeStore();
67
+ store.getState().dispatch(frame(OPS.watch, ["a.b"], { event: "change" }));
68
+ expect(store.getState().isWatched(["a", "b"], "change")).toBe(false);
69
+ });
70
+
71
+ it("unwatchAll forgets every watch", () => {
72
+ const store = createTreeStore();
73
+ store.getState().dispatch(frame(OPS.watch, ["s"], { event: "*" }));
74
+ store.getState().unwatchAll();
75
+ expect(store.getState().isWatched(["s"], "change")).toBe(false);
76
+ });
77
+
78
+ it("setWatchAll counts every event as watched", () => {
79
+ const store = createTreeStore();
80
+ store.getState().setWatchAll(true);
81
+ expect(store.getState().isWatched(["any"], "input")).toBe(true);
82
+ store.getState().setWatchAll(false);
83
+ expect(store.getState().isWatched(["any"], "input")).toBe(false);
84
+ });
85
+
86
+ it("reports a watch that names no event, and sends nothing", () => {
87
+ const onError = vi.fn();
88
+ const send = vi.fn();
89
+ const store = createTreeStore({ onError, send });
90
+ store.getState().dispatch(frame(OPS.watch, ["s"], null));
91
+ expect(onError).toHaveBeenCalledOnce();
92
+ expect(send).not.toHaveBeenCalled();
93
+ expect(store.getState().isWatched(["s"], "change")).toBe(false);
94
+ });
95
+ });