@nustackdev/ui-core 0.2.4 → 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.4",
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
 
@@ -135,7 +133,9 @@ describe("write", () => {
135
133
  const store = createTreeStore({ onError: (message) => errors.push(message) });
136
134
  store.getState().write([step("a", "Card"), step("t", "TextRef", { value: "x" })]);
137
135
 
138
- 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" });
139
139
 
140
140
  expect(applied).toBe(false);
141
141
  expect(store.getState().getIn(["a", "t"])?.props).toEqual({ value: "x" });
@@ -219,11 +219,7 @@ describe("remove", () => {
219
219
 
220
220
  store.getState().remove(["sec"]);
221
221
 
222
- expect(gone).toEqual([
223
- ["sec", "col", "t"],
224
- ["sec", "col"],
225
- ["sec"],
226
- ]);
222
+ expect(gone).toEqual([["sec", "col", "t"], ["sec", "col"], ["sec"]]);
227
223
  expect(store.getState().getIn(["sec"])).toBeNull();
228
224
  expect(store.getState().getIn(["other"])?.type).toBe("TextRef");
229
225
  });
@@ -383,7 +379,9 @@ describe("dispatch", () => {
383
379
  it("builds structure from an init and touches no value", () => {
384
380
  const store = createTreeStore();
385
381
  store.getState().write([step("a", "InputRef", { label: "L" })], { value: "typed" });
386
- 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" })]));
387
385
  store.getState().dispatch(frame(OPS.init, ["b"], null, [step("b", "TextRef", { value: "" })]));
388
386
  expect(store.getState().getIn(["a"])?.props).toEqual({ label: "L", value: "typed" });
389
387
  expect(store.getState().getIn(["b"])?.type).toBe("TextRef");
@@ -419,6 +417,40 @@ describe("dispatch", () => {
419
417
  expect(sent).toEqual([{ op: OPS.read, ref: ["p"], payload: "md:hi", id: "f2" }]);
420
418
  });
421
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
+
422
454
  it("reports an op on a node that is not there", () => {
423
455
  const errors: string[] = [];
424
456
  const store = createTreeStore({ onError: (m) => errors.push(m) });
@@ -438,7 +470,9 @@ describe("dispatch", () => {
438
470
  describe("visibility", () => {
439
471
  it("hides a node and keeps its props and children", () => {
440
472
  const store = createTreeStore();
441
- 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" });
442
476
  store.getState().dispatch(frame(OPS.hide, ["a"], null, [step("a", "Card", { title: "T" })]));
443
477
  const a = store.getState().getIn(["a"]);
444
478
  expect(a?.hidden).toBe(true);
@@ -456,9 +490,14 @@ describe("visibility", () => {
456
490
 
457
491
  it("brings a node into being hidden when the hide is the first frame", () => {
458
492
  const store = createTreeStore();
459
- store.getState().dispatch(
460
- frame(OPS.hide, ["a", "b"], null, [step("a", "Column"), step("b", "TextRef", { value: "seed" })]),
461
- );
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
+ );
462
501
  const b = store.getState().getIn(["a", "b"]);
463
502
  expect(b?.type).toBe("TextRef");
464
503
  expect(b?.props).toEqual({ value: "seed" });
@@ -480,11 +519,18 @@ describe("visibility", () => {
480
519
  const store = createTreeStore({ resolve: (t) => behaviours[t] });
481
520
  store.getState().write([step("h", "HeadingRef"), step("t", "TextRef")]);
482
521
  store.getState().dispatch(frame(OPS.hide, ["h"], null, [step("h", "HeadingRef")]));
483
- 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")]));
484
525
  store.getState().dispatch(frame(OPS.write, ["h"], "hello", [step("h", "HeadingRef")]));
485
- store.getState().dispatch(
486
- frame(OPS.write, ["h", "t"], { value: 1, hidden: false }, [step("h", "HeadingRef"), step("t", "TextRef")]),
487
- );
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
+ );
488
534
  expect(store.getState().getIn(["h"])?.hidden).toBe(true);
489
535
  expect(store.getState().getIn(["h"])?.props.label).toBe("hello");
490
536
  expect(store.getState().getIn(["h", "t"])?.hidden).toBe(true);
@@ -494,7 +540,10 @@ describe("visibility", () => {
494
540
  const errors: string[] = [];
495
541
  const hide = vi.fn();
496
542
  const behaviours: Record<string, Behaviour> = { TextRef: { handlers: { hide } } };
497
- 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
+ });
498
547
  store.getState().write([step("a", "TextRef")]);
499
548
  store.getState().dispatch(frame(OPS.hide, ["a"], null, [step("a", "TextRef")]));
500
549
  expect(hide).not.toHaveBeenCalled();
@@ -555,7 +604,9 @@ describe("kind mismatch", () => {
555
604
 
556
605
  store.getState().dispatch(frame(OPS.init, ["a"], null, [step("a", "Grid")]));
557
606
  store.getState().dispatch(frame(OPS.hide, ["a"], null, [step("a", "Grid")]));
558
- 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")]));
559
610
 
560
611
  expect(sent.map((f) => f.op)).toEqual([OP_ERROR, OP_ERROR, OP_ERROR]);
561
612
  expect(store.getState().getIn(["a"])?.type).toBe("Card");
package/src/tree.ts CHANGED
@@ -82,8 +82,18 @@ export const OPS = {
82
82
  // shows it again. Every type takes them, none handles them.
83
83
  hide: "hide",
84
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`.
85
87
  read: "read",
86
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",
87
97
  } as const;
88
98
 
89
99
  export type NodeCtx = {
@@ -102,12 +112,54 @@ export type NodeHandler = (ctx: NodeCtx, payload: unknown) => void;
102
112
 
103
113
  export type DisposeCtx = { path: Path; node: Node };
104
114
 
105
- /** 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. */
106
124
  export type Behaviour = {
107
125
  handlers?: Record<string, NodeHandler>;
126
+ reads?: Reads;
108
127
  dispose?: (ctx: DisposeCtx) => void;
109
128
  };
110
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
+
111
163
  export type Resolve = (type: string) => Behaviour | undefined;
112
164
 
113
165
  export type TreeState = { root: Node };
@@ -126,6 +178,22 @@ export type TreeActions = {
126
178
  setProps: (path: Path, props: Props) => void;
127
179
  /** Hide or show an existing node. No-op when the node is not there. */
128
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;
129
197
  /** Route an inbound frame to its node, by node type and frame op. */
130
198
  dispatch: (frame: TreeFrame) => void;
131
199
  /** Outbound. No-op until a sender is set. */
@@ -226,6 +294,17 @@ export function createTreeStore(options: TreeStoreOptions = {}): TreeStore {
226
294
  // Disposals are collected inside a draft and run after the set returns, so
227
295
  // a dispose is free to touch the store without writing into a dead draft.
228
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);
229
308
  const flushDispose = () => {
230
309
  const batch = pending;
231
310
  pending = [];
@@ -335,6 +414,38 @@ export function createTreeStore(options: TreeStoreOptions = {}): TreeStore {
335
414
  });
336
415
  },
337
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
+
338
449
  send: (frame) => {
339
450
  if (outbound) outbound(frame);
340
451
  },
@@ -366,7 +477,21 @@ export function createTreeStore(options: TreeStoreOptions = {}): TreeStore {
366
477
  id: frame.id,
367
478
  });
368
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
+ }
369
492
  if (frame.op === OPS.remove) {
493
+ // Watches stay: they belong to the path, and the node may
494
+ // be drawn there again.
370
495
  api.remove(frame.ref);
371
496
  return;
372
497
  }
@@ -430,12 +555,24 @@ export function createTreeStore(options: TreeStoreOptions = {}): TreeStore {
430
555
  return;
431
556
  }
432
557
  if (frame.op === OPS.read) {
433
- // The server is asking for our current value. Same id back
434
- // 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
+ }
435
569
  api.send({
436
- op: OPS.read,
570
+ op: OP_ERROR,
437
571
  ref: frame.ref,
438
- payload: node.props.value ?? null,
572
+ payload: {
573
+ code: "payload_invalid",
574
+ message: `${node.type ?? "untyped node"} has no read "${field}"`,
575
+ } satisfies ErrorPayload,
439
576
  id: frame.id,
440
577
  });
441
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
+ });