@nustackdev/ui-core 0.2.2 → 0.2.3

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.2",
9
+ "version": "0.2.3",
10
10
  "type": "module",
11
11
  "main": "./src/index.ts",
12
12
  "types": "./src/index.ts",
package/src/index.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  // Public entry point for @nustackdev/ui-core.
2
2
  // Consumers import wire types + msgpack codec + the tree store from here.
3
3
 
4
+ export * from "./order";
4
5
  export * from "./protocol";
5
6
  export * from "./tree";
@@ -0,0 +1,226 @@
1
+ // Keyed order: the pure op math, and the handlers over a real store.
2
+
3
+ import { describe, expect, it } from "vitest";
4
+ import {
5
+ applyOrderOp,
6
+ indexedOrder,
7
+ keyedOrder,
8
+ ORDER_OPS,
9
+ ORDER_PROP,
10
+ OrderError,
11
+ orderHandlers,
12
+ places,
13
+ } from "./order";
14
+ import { type Behaviour, createTreeStore, type TreeFrame } from "./tree";
15
+
16
+ const op = (name: string, payload: unknown, order: string[] | undefined, present: string[]) =>
17
+ applyOrderOp(name, payload, order, present);
18
+
19
+ describe("default order", () => {
20
+ it("sorts indices by number and keeps names where written", () => {
21
+ expect(indexedOrder(["2", "a", "0", "b", "1"])).toEqual(["0", "a", "1", "b", "2"]);
22
+ });
23
+
24
+ it("is what draws until an order is kept", () => {
25
+ expect(keyedOrder(undefined, ["10", "2"])).toEqual(["2", "10"]);
26
+ });
27
+
28
+ it("puts children with no place after the placed ones", () => {
29
+ expect(keyedOrder(["b", "a"], ["a", "b", "3", "c", "1"])).toEqual(["b", "a", "1", "c", "3"]);
30
+ });
31
+
32
+ it("draws nothing for a place with no child", () => {
33
+ expect(keyedOrder(["x", "a"], ["a"])).toEqual(["a"]);
34
+ expect(places(["x", "a"], ["a"])).toEqual(["x", "a"]);
35
+ });
36
+ });
37
+
38
+ describe("insert_item", () => {
39
+ it("appends by default and writes the drawn order down first", () => {
40
+ expect(op(ORDER_OPS.insert, { key: "n" }, undefined, ["1", "0"])).toEqual({
41
+ order: ["0", "1", "n"],
42
+ drop: [],
43
+ });
44
+ });
45
+
46
+ it("places at a position, clamped", () => {
47
+ expect(op(ORDER_OPS.insert, { key: "n", at: 1 }, ["a", "b"], [])?.order).toEqual([
48
+ "a",
49
+ "n",
50
+ "b",
51
+ ]);
52
+ expect(op(ORDER_OPS.insert, { key: "n", at: 99 }, ["a"], [])?.order).toEqual(["a", "n"]);
53
+ });
54
+
55
+ it("places before and after a key", () => {
56
+ expect(op(ORDER_OPS.insert, { key: "n", before: "b" }, ["a", "b"], [])?.order).toEqual([
57
+ "a",
58
+ "n",
59
+ "b",
60
+ ]);
61
+ expect(op(ORDER_OPS.insert, { key: "n", after: "a" }, ["a", "b"], [])?.order).toEqual([
62
+ "a",
63
+ "n",
64
+ "b",
65
+ ]);
66
+ });
67
+
68
+ it("moves a key already placed", () => {
69
+ expect(op(ORDER_OPS.insert, { key: "b", at: 0 }, ["a", "b"], ["a", "b"])?.order).toEqual([
70
+ "b",
71
+ "a",
72
+ ]);
73
+ });
74
+
75
+ it("refuses an anchor with no place", () => {
76
+ expect(() => op(ORDER_OPS.insert, { key: "n", before: "zz" }, ["a"], ["a"])).toThrow(
77
+ OrderError,
78
+ );
79
+ });
80
+ });
81
+
82
+ describe("move_item", () => {
83
+ it("moves one place, the rest keep theirs", () => {
84
+ expect(op(ORDER_OPS.move, { key: "2", at: 0 }, undefined, ["0", "1", "2"])).toEqual({
85
+ order: ["2", "0", "1"],
86
+ drop: [],
87
+ });
88
+ expect(op(ORDER_OPS.move, { key: "0" }, undefined, ["0", "1", "2"])?.order).toEqual([
89
+ "1",
90
+ "2",
91
+ "0",
92
+ ]);
93
+ });
94
+
95
+ it("refuses a key with no place", () => {
96
+ expect(() => op(ORDER_OPS.move, { key: "q" }, undefined, ["a"])).toThrow(OrderError);
97
+ });
98
+ });
99
+
100
+ describe("remove, truncate, keep", () => {
101
+ it("removes one child and its place, a missing key is a no-op", () => {
102
+ expect(op(ORDER_OPS.remove, { key: "b" }, ["a", "b", "c"], ["a", "b", "c"])).toEqual({
103
+ order: ["a", "c"],
104
+ drop: ["b"],
105
+ });
106
+ expect(op(ORDER_OPS.remove, { key: "q" }, ["a"], ["a"])).toEqual({ order: ["a"], drop: [] });
107
+ });
108
+
109
+ it("truncates to the first places", () => {
110
+ expect(op(ORDER_OPS.truncate, { count: 2 }, undefined, ["2", "0", "1", "3"])).toEqual({
111
+ order: ["0", "1"],
112
+ drop: ["2", "3"],
113
+ });
114
+ expect(op(ORDER_OPS.truncate, { count: 0 }, ["a"], ["a"])).toEqual({ order: [], drop: ["a"] });
115
+ });
116
+
117
+ it("keeps the keys named, where they are", () => {
118
+ expect(
119
+ op(ORDER_OPS.keep, { keys: ["c", "a", "zz"] }, ["a", "b", "c"], ["a", "b", "c"]),
120
+ ).toEqual({
121
+ order: ["a", "c"],
122
+ drop: ["b"],
123
+ });
124
+ });
125
+
126
+ it("refuses a bad payload", () => {
127
+ expect(() => op(ORDER_OPS.truncate, { count: -1 }, [], [])).toThrow(OrderError);
128
+ expect(() => op(ORDER_OPS.keep, { keys: "a" }, [], [])).toThrow(OrderError);
129
+ expect(() => op(ORDER_OPS.remove, {}, [], [])).toThrow(OrderError);
130
+ });
131
+ });
132
+
133
+ describe("order_items", () => {
134
+ it("puts the named first, the rest keep theirs after", () => {
135
+ expect(
136
+ op(ORDER_OPS.order, { keys: ["c", "zz", "a"] }, undefined, ["a", "b", "c", "d"])?.order,
137
+ ).toEqual(["c", "a", "b", "d"]);
138
+ });
139
+
140
+ it("is not one of the ops for anything else", () => {
141
+ expect(op("write", {}, undefined, [])).toBeNull();
142
+ });
143
+ });
144
+
145
+ describe("handlers over a store", () => {
146
+ const frame = (opName: string, payload: unknown, id?: string): TreeFrame => ({
147
+ op: opName,
148
+ ref: ["l"],
149
+ payload,
150
+ id,
151
+ });
152
+
153
+ function setup() {
154
+ const disposed: string[] = [];
155
+ const sent: TreeFrame[] = [];
156
+ const behaviours: Record<string, Behaviour> = {
157
+ L: { handlers: orderHandlers() },
158
+ T: { dispose: ({ path }) => disposed.push(path.join("/")) },
159
+ };
160
+ const store = createTreeStore({ resolve: (t) => behaviours[t], send: (f) => sent.push(f) });
161
+ store.getState().write([["l", "L", {}]]);
162
+ for (const k of ["0", "1", "2"])
163
+ store.getState().write([
164
+ ["l", "L", {}],
165
+ [k, "T", {}],
166
+ ]);
167
+ const kids = () => [...(store.getState().getIn(["l"])?.children.keys() ?? [])];
168
+ const order = () => store.getState().getIn(["l"])?.props[ORDER_PROP];
169
+ return { store, disposed, sent, kids, order };
170
+ }
171
+
172
+ it("keeps the order on the node and rewrites no child", () => {
173
+ const { store, kids, order } = setup();
174
+ const child = store.getState().getIn(["l", "1"]);
175
+ store.getState().dispatch(frame(ORDER_OPS.move, { key: "2", at: 0 }));
176
+ expect(order()).toEqual(["2", "0", "1"]);
177
+ expect(kids()).toEqual(["0", "1", "2"]);
178
+ expect(store.getState().getIn(["l", "1"])).toBe(child);
179
+ });
180
+
181
+ it("drops children through the store, dispose included", () => {
182
+ const { store, disposed, kids, order } = setup();
183
+ store.getState().dispatch(frame(ORDER_OPS.truncate, { count: 1 }));
184
+ expect(kids()).toEqual(["0"]);
185
+ expect(order()).toEqual(["0"]);
186
+ expect(disposed.sort()).toEqual(["l/1", "l/2"]);
187
+ });
188
+
189
+ it("draws a child written into an inserted place there", () => {
190
+ const { store, order } = setup();
191
+ store.getState().dispatch(frame(ORDER_OPS.insert, { key: "n", at: 0 }));
192
+ store.getState().write([
193
+ ["l", "L", {}],
194
+ ["n", "T", {}],
195
+ ]);
196
+ const node = store.getState().getIn(["l"]);
197
+ const present = [...(node?.children.keys() ?? [])];
198
+ expect(keyedOrder(order() as string[], present)).toEqual(["n", "0", "1", "2"]);
199
+ });
200
+
201
+ it("answers a payload it cannot apply with an error, changing nothing", () => {
202
+ const { store, sent, order } = setup();
203
+ store.getState().dispatch(frame(ORDER_OPS.move, { key: "q" }, "7"));
204
+ expect(order()).toBeUndefined();
205
+ expect(sent).toHaveLength(1);
206
+ expect(sent[0]).toMatchObject({ op: "error", ref: ["l"], id: "7" });
207
+ expect((sent[0].payload as { code: string }).code).toBe("payload_invalid");
208
+ });
209
+
210
+ it("turns an op down when the node refuses it, changing nothing", () => {
211
+ const sent: TreeFrame[] = [];
212
+ const behaviours: Record<string, Behaviour> = {
213
+ G: {
214
+ handlers: orderHandlers((props) =>
215
+ props.cols ? "a placed grid keeps no order" : undefined,
216
+ ),
217
+ },
218
+ };
219
+ const store = createTreeStore({ resolve: (t) => behaviours[t], send: (f) => sent.push(f) });
220
+ store.getState().write([["l", "G", { cols: "2fr 1fr" }]]);
221
+ store.getState().dispatch(frame(ORDER_OPS.remove, { key: "0" }, "9"));
222
+ expect(store.getState().getIn(["l"])?.props[ORDER_PROP]).toBeUndefined();
223
+ expect(sent[0]).toMatchObject({ op: "error", ref: ["l"], id: "9" });
224
+ expect((sent[0].payload as { message: string }).message).toContain("placed grid");
225
+ });
226
+ });
package/src/order.ts ADDED
@@ -0,0 +1,229 @@
1
+ // Keyed order: where the children of an ordered collection draw (Row,
2
+ // Column, a flowing Grid, List).
3
+ //
4
+ // A child's segment is its key, its identity; where it draws is a place in
5
+ // the collection's order. The order is the collection's own prop
6
+ // (`props.order`, a list of segments) and the browser is the only one that
7
+ // holds it: the server never knows which children are there, so each op
8
+ // names keys and positions and the store works out the rest here.
9
+ //
10
+ // - No order yet: children draw in the default order, `indexedOrder`
11
+ // (index segments by number, named ones where first written).
12
+ // - The first op writes the order down as drawn, every child placed. From
13
+ // then on a child with no place (written after) draws after the placed
14
+ // ones, in the default order among themselves.
15
+ // - A place may hold no child: `insert` before the child is written, or a
16
+ // child erased on its own (`remove` on its path). A child written there
17
+ // later shows in that place. Places with no child draw nothing.
18
+ // - insert / move edit one place and rewrite no child. remove / truncate /
19
+ // keep drop children and their places together.
20
+ //
21
+ // Ops (payload, keys as segment text):
22
+ // insert_item {key, at? | before? | after?} none of them: the end
23
+ // move_item {key, at? | before? | after?} the key must be there
24
+ // remove_item {key} missing key: no-op
25
+ // truncate_items {count} keep the first count places
26
+ // keep_items {keys} drop every other child
27
+ // order_items {keys} these first, the rest after
28
+
29
+ import { OP_ERROR } from "./protocol";
30
+ import type { NodeCtx, NodeHandler, Path } from "./tree";
31
+
32
+ /** The prop an ordered collection keeps its order in. */
33
+ export const ORDER_PROP = "order";
34
+
35
+ /** The child ops of an ordered collection, by wire name. */
36
+ export const ORDER_OPS = {
37
+ insert: "insert_item",
38
+ move: "move_item",
39
+ remove: "remove_item",
40
+ truncate: "truncate_items",
41
+ keep: "keep_items",
42
+ order: "order_items",
43
+ } as const;
44
+
45
+ const isIndex = (s: string) => /^\d+$/.test(s);
46
+
47
+ /**
48
+ * The default order: segments that are indices ("0", "1", ...) sort by
49
+ * number among the places indexed children hold; named segments keep their
50
+ * place in write order. So `[2]` written before `[0]` still draws 0 before 2.
51
+ */
52
+ export function indexedOrder(segments: readonly string[]): string[] {
53
+ const indexed = segments.filter(isIndex).sort((a, b) => Number(a) - Number(b));
54
+ let next = 0;
55
+ return segments.map((s) => (isIndex(s) ? indexed[next++] : s));
56
+ }
57
+
58
+ /** `raw` as an order, or undefined when it is not a list (no order kept yet). */
59
+ export function asOrder(raw: unknown): string[] | undefined {
60
+ if (!Array.isArray(raw)) return undefined;
61
+ return raw.map(String);
62
+ }
63
+
64
+ /**
65
+ * Every place, in order: the kept order (empty places included), then each
66
+ * child that has no place, in the default order. With no order kept yet,
67
+ * just the default order.
68
+ */
69
+ export function places(order: readonly string[] | undefined, present: readonly string[]): string[] {
70
+ if (!order) return indexedOrder(present);
71
+ const placed = new Set(order);
72
+ return [...order, ...indexedOrder(present.filter((s) => !placed.has(s)))];
73
+ }
74
+
75
+ /** The order children draw in: every place that holds one of `present`. */
76
+ export function keyedOrder(
77
+ order: readonly string[] | undefined,
78
+ present: readonly string[],
79
+ ): string[] {
80
+ if (!order) return indexedOrder(present);
81
+ const here = new Set(present);
82
+ return places(order, present).filter((s) => here.has(s));
83
+ }
84
+
85
+ /** What an op does: the order to keep, and the children to drop. */
86
+ export type OrderEdit = { order: string[]; drop: string[] };
87
+
88
+ /** Why an op could not apply: the frame is refused and nothing changes. */
89
+ export class OrderError extends Error {}
90
+
91
+ type Payload = Record<string, unknown>;
92
+
93
+ function keyOf(payload: Payload, field = "key"): string {
94
+ const raw = payload[field];
95
+ if (typeof raw === "string" && raw) return raw;
96
+ if (typeof raw === "number" && Number.isInteger(raw) && raw >= 0) return String(raw);
97
+ throw new OrderError(`${field} must be a key, got ${JSON.stringify(raw)}`);
98
+ }
99
+
100
+ function keysOf(payload: Payload): string[] {
101
+ const raw = payload.keys;
102
+ if (!Array.isArray(raw)) throw new OrderError(`keys must be a list, got ${JSON.stringify(raw)}`);
103
+ return raw.map(String);
104
+ }
105
+
106
+ // Where `key` goes in `rest` (the places without it): an index into `rest`.
107
+ function slotIn(rest: string[], payload: Payload): number {
108
+ if (payload.at != null) {
109
+ const at = Number(payload.at);
110
+ if (!Number.isInteger(at) || at < 0) {
111
+ throw new OrderError(`at must be a position >= 0, got ${JSON.stringify(payload.at)}`);
112
+ }
113
+ return Math.min(at, rest.length);
114
+ }
115
+ for (const side of ["before", "after"] as const) {
116
+ if (payload[side] == null) continue;
117
+ const anchor = keyOf(payload, side);
118
+ const i = rest.indexOf(anchor);
119
+ if (i < 0) throw new OrderError(`${side} names ${anchor}, which has no place here`);
120
+ return side === "before" ? i : i + 1;
121
+ }
122
+ return rest.length;
123
+ }
124
+
125
+ function place(all: string[], key: string, payload: Payload): string[] {
126
+ const rest = all.filter((s) => s !== key);
127
+ const at = slotIn(rest, payload);
128
+ return [...rest.slice(0, at), key, ...rest.slice(at)];
129
+ }
130
+
131
+ /**
132
+ * Apply one op to an order. `order` is the kept one (undefined before the
133
+ * first op), `present` the segments of the children there. Throws
134
+ * `OrderError` for a payload it cannot apply; returns null for an op that
135
+ * is not one of `ORDER_OPS`.
136
+ */
137
+ export function applyOrderOp(
138
+ op: string,
139
+ rawPayload: unknown,
140
+ order: readonly string[] | undefined,
141
+ present: readonly string[],
142
+ ): OrderEdit | null {
143
+ const payload: Payload =
144
+ typeof rawPayload === "object" && rawPayload !== null && !Array.isArray(rawPayload)
145
+ ? (rawPayload as Payload)
146
+ : {};
147
+ const all = places(order, present);
148
+ const here = new Set(present);
149
+ switch (op) {
150
+ case ORDER_OPS.insert:
151
+ return { order: place(all, keyOf(payload), payload), drop: [] };
152
+ case ORDER_OPS.move: {
153
+ const key = keyOf(payload);
154
+ if (!all.includes(key)) throw new OrderError(`no child at ${key} to move`);
155
+ return { order: place(all, key, payload), drop: [] };
156
+ }
157
+ case ORDER_OPS.remove: {
158
+ const key = keyOf(payload);
159
+ return { order: all.filter((s) => s !== key), drop: here.has(key) ? [key] : [] };
160
+ }
161
+ case ORDER_OPS.truncate: {
162
+ const count = Number(payload.count);
163
+ if (!Number.isInteger(count) || count < 0) {
164
+ throw new OrderError(`count must be >= 0, got ${JSON.stringify(payload.count)}`);
165
+ }
166
+ const gone = all.slice(count);
167
+ return { order: all.slice(0, count), drop: gone.filter((s) => here.has(s)) };
168
+ }
169
+ case ORDER_OPS.keep: {
170
+ const kept = new Set(keysOf(payload));
171
+ return {
172
+ order: all.filter((s) => kept.has(s)),
173
+ drop: all.filter((s) => !kept.has(s) && here.has(s)),
174
+ };
175
+ }
176
+ case ORDER_OPS.order: {
177
+ const first = [...new Set(keysOf(payload))].filter((s) => all.includes(s));
178
+ const named = new Set(first);
179
+ return { order: [...first, ...all.filter((s) => !named.has(s))], drop: [] };
180
+ }
181
+ default:
182
+ return null;
183
+ }
184
+ }
185
+
186
+ /** Why a container takes no order op right now (a placed grid), or undefined when it does. */
187
+ export type OrderRefusal = (props: Record<string, unknown>) => string | undefined;
188
+
189
+ /**
190
+ * Handlers that make a type an ordered collection: one per op in
191
+ * `ORDER_OPS`, keeping the order in `props.order` and dropping children
192
+ * through the store (so their dispose runs). A payload that cannot apply,
193
+ * or an op `refuse` turns down, changes nothing and goes back to the server
194
+ * as a `payload_invalid` error.
195
+ */
196
+ export function orderHandlers(refuse?: OrderRefusal): Record<string, NodeHandler> {
197
+ return Object.fromEntries(
198
+ Object.values(ORDER_OPS).map((op) => [
199
+ op,
200
+ (ctx: NodeCtx, payload: unknown) => applyTo(ctx, op, payload, refuse),
201
+ ]),
202
+ );
203
+ }
204
+
205
+ function applyTo(ctx: NodeCtx, op: string, payload: unknown, refuse?: OrderRefusal): void {
206
+ const api = ctx.store.getState();
207
+ const node = api.getIn(ctx.path) ?? ctx.node;
208
+ let edit: OrderEdit | null;
209
+ try {
210
+ const why = refuse?.(node.props);
211
+ if (why) throw new OrderError(why);
212
+ edit = applyOrderOp(op, payload, asOrder(node.props[ORDER_PROP]), [...node.children.keys()]);
213
+ } catch (err) {
214
+ if (!(err instanceof OrderError)) throw err;
215
+ api.send({
216
+ op: OP_ERROR,
217
+ ref: ctx.path,
218
+ payload: { code: "payload_invalid", message: `${op}: ${err.message}` },
219
+ id: ctx.frame.id,
220
+ });
221
+ return;
222
+ }
223
+ if (!edit) return;
224
+ const { order, drop } = edit;
225
+ ctx.update((props) => {
226
+ props[ORDER_PROP] = order;
227
+ });
228
+ for (const segment of drop) api.remove([...ctx.path, segment] as Path);
229
+ }
package/src/protocol.ts CHANGED
@@ -3,8 +3,10 @@
3
3
 
4
4
  import { decode as mpDecode, encode as mpEncode } from "@msgpack/msgpack";
5
5
 
6
- // The op vocabulary lives in OPS (tree.ts). `error` is the one op the tree
7
- // store has no member for -- nothing on this side handles one yet.
6
+ // The op vocabulary lives in OPS (tree.ts). `error` goes either way: a frame
7
+ // the far end refused, payload `ErrorPayload`. The tree store sends
8
+ // `kind_mismatch` for a write naming a kind other than the node's, and hands
9
+ // an inbound one to its `onError`.
8
10
  export const OP_ERROR = "error";
9
11
 
10
12
  // A ref's address: the Ref chain's segments, root-first. Stays a list end
@@ -34,6 +36,7 @@ export type Frame = {
34
36
  };
35
37
 
36
38
  export type ErrorCode =
39
+ | "kind_mismatch"
37
40
  | "ref_not_found"
38
41
  | "op_not_allowed"
39
42
  | "payload_invalid"
package/src/tree.test.ts CHANGED
@@ -9,6 +9,7 @@ import {
9
9
  type TreeFrame,
10
10
  createTreeStore,
11
11
  } from "./tree";
12
+ import { OP_ERROR } from "./protocol";
12
13
 
13
14
  function step(segment: string, type: string | null = null, props?: Record<string, unknown>): ChainStep {
14
15
  return props ? [segment, type, props] : [segment, type];
@@ -97,25 +98,45 @@ describe("write", () => {
97
98
  expect(store.getState().getIn(["sec", "t"])?.props).toEqual({ value: "x" });
98
99
  });
99
100
 
100
- it("rebuilds a node whose type changed and disposes the old branch", () => {
101
- const gone: string[][] = [];
102
- const behaviours: Record<string, Behaviour> = {
103
- Card: { dispose: (ctx) => gone.push(ctx.path) },
104
- TextRef: { dispose: (ctx) => gone.push(ctx.path) },
105
- };
106
- const store = createTreeStore({ resolve: (t) => behaviours[t] });
101
+ it("refuses a write naming another kind for a node already there", () => {
102
+ const errors: [string, string[]][] = [];
103
+ const dispose = vi.fn();
104
+ const store = createTreeStore({
105
+ resolve: () => ({ dispose }),
106
+ onError: (message, path) => errors.push([message, path]),
107
+ });
107
108
  store.getState().write([step("sec", "Card", { title: "One" }), step("t", "TextRef")]);
108
- store.getState().write([step("sec", "Modal", { open: true })]);
109
+ const before = store.getState().root;
109
110
 
110
- expect(gone).toEqual([
111
- ["sec", "t"],
112
- ["sec"],
113
- ]);
114
- expect(store.getState().getIn(["sec"])).toEqual({
115
- type: "Modal",
116
- props: { open: true },
117
- children: new Map(),
118
- });
111
+ const applied = store.getState().write([step("sec", "Modal", { open: true })], { open: true });
112
+
113
+ expect(applied).toBe(false);
114
+ // Nothing of the refused write lands, and nothing is torn down.
115
+ expect(store.getState().root).toBe(before);
116
+ expect(dispose).not.toHaveBeenCalled();
117
+ expect(errors).toHaveLength(1);
118
+ expect(errors[0][0]).toContain("kind mismatch at sec: the node is Card, the write names Modal");
119
+ });
120
+
121
+ it("refuses a mismatch above a leaf that is already there", () => {
122
+ const errors: string[] = [];
123
+ const store = createTreeStore({ onError: (message) => errors.push(message) });
124
+ store.getState().write([step("a", "Card"), step("t", "TextRef", { value: "x" })]);
125
+
126
+ const applied = store.getState().write([step("a", "Grid"), step("t", "TextRef")], { value: "y" });
127
+
128
+ expect(applied).toBe(false);
129
+ expect(store.getState().getIn(["a", "t"])?.props).toEqual({ value: "x" });
130
+ expect(errors[0]).toContain("kind mismatch at a: the node is Card, the write names Grid");
131
+ });
132
+
133
+ it("puts another kind at an address once the old node is removed", () => {
134
+ const store = createTreeStore({ onError: () => {} });
135
+ store.getState().write([step("a", "TextRef"), step("x", "TextRef")]);
136
+ store.getState().write([step("b", "TextRef")]);
137
+ store.getState().remove(["a"]);
138
+ expect(store.getState().write([step("a", "Card")])).toBe(true);
139
+ expect(store.getState().getIn(["a"])?.type).toBe("Card");
119
140
  });
120
141
 
121
142
  it("keeps a node whose write does not name a type", () => {
@@ -147,14 +168,6 @@ describe("write", () => {
147
168
  expect(segments(store.getState().getIn(["box"]))).toEqual(["z", "0", "a", "1"]);
148
169
  });
149
170
 
150
- it("keeps a rebuilt level in its original slot", () => {
151
- const store = createTreeStore();
152
- store.getState().write([step("a", "TextRef"), step("x", "TextRef")]);
153
- store.getState().write([step("b", "TextRef")]);
154
- store.getState().write([step("a", "Card")]);
155
- expect(segments(store.getState().root)).toEqual(["a", "b"]);
156
- });
157
-
158
171
  it("writes into the root with an empty chain", () => {
159
172
  const store = createTreeStore();
160
173
  store.getState().write([], { title: "root" });
@@ -260,7 +273,7 @@ describe("dispatch", () => {
260
273
 
261
274
  it("lands a list payload on value rather than spreading it", () => {
262
275
  const store = createTreeStore();
263
- store.getState().dispatch(frame(OPS.write, ["a"], [1, 2, 3], [step("a", "TableRef")]));
276
+ store.getState().dispatch(frame(OPS.write, ["a"], [1, 2, 3], [step("a", "DataTableRef")]));
264
277
  expect(store.getState().getIn(["a"])?.props).toEqual({ value: [1, 2, 3] });
265
278
  });
266
279
 
@@ -288,7 +301,7 @@ describe("dispatch", () => {
288
301
 
289
302
  it("routes an op to the handler for the node's type", () => {
290
303
  const behaviours: Record<string, Behaviour> = {
291
- TableRef: {
304
+ DataTableRef: {
292
305
  handlers: {
293
306
  append: (ctx, payload) =>
294
307
  ctx.update((props) => {
@@ -298,7 +311,7 @@ describe("dispatch", () => {
298
311
  },
299
312
  };
300
313
  const store = createTreeStore({ resolve: (t) => behaviours[t] });
301
- store.getState().write([step("t", "TableRef", { rows: [] })]);
314
+ store.getState().write([step("t", "DataTableRef", { rows: [] })]);
302
315
  store.getState().dispatch(frame("append", ["t"], { id: 1 }));
303
316
  store.getState().dispatch(frame("append", ["t"], { id: 2 }));
304
317
  expect(store.getState().getIn(["t"])?.props.rows).toEqual([{ id: 1 }, { id: 2 }]);
@@ -492,6 +505,58 @@ describe("visibility", () => {
492
505
  });
493
506
  });
494
507
 
508
+ describe("kind mismatch", () => {
509
+ it("answers a refused write with an error frame and runs no handler", () => {
510
+ const sent: TreeFrame[] = [];
511
+ const handler = vi.fn();
512
+ const store = createTreeStore({
513
+ resolve: (t) => (t === "Modal" ? { handlers: { write: handler } } : undefined),
514
+ onError: () => {},
515
+ });
516
+ store.getState().setSender((f) => sent.push(f));
517
+ store.getState().dispatch(frame(OPS.write, ["a"], "x", [step("a", "TextRef")]));
518
+
519
+ store.getState().dispatch(frame(OPS.write, ["a"], { open: true }, [step("a", "Modal")]));
520
+
521
+ expect(handler).not.toHaveBeenCalled();
522
+ expect(store.getState().getIn(["a"])).toEqual({
523
+ type: "TextRef",
524
+ props: { value: "x" },
525
+ children: new Map(),
526
+ });
527
+ expect(sent).toHaveLength(1);
528
+ expect(sent[0].op).toBe(OP_ERROR);
529
+ expect(sent[0].ref).toEqual(["a"]);
530
+ expect(sent[0].payload).toMatchObject({ code: "kind_mismatch" });
531
+ expect((sent[0].payload as { message: string }).message).toContain(
532
+ "the node is TextRef, the write names Modal",
533
+ );
534
+ });
535
+
536
+ it("refuses init, hide and custom ops the same way", () => {
537
+ const sent: TreeFrame[] = [];
538
+ const store = createTreeStore({ onError: () => {} });
539
+ store.getState().setSender((f) => sent.push(f));
540
+ store.getState().write([step("a", "Card")]);
541
+
542
+ store.getState().dispatch(frame(OPS.init, ["a"], null, [step("a", "Grid")]));
543
+ 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")]));
545
+
546
+ expect(sent.map((f) => f.op)).toEqual([OP_ERROR, OP_ERROR, OP_ERROR]);
547
+ expect(store.getState().getIn(["a"])?.type).toBe("Card");
548
+ expect(store.getState().getIn(["a"])?.hidden).toBeUndefined();
549
+ expect(store.getState().getIn(["a", "c"])).toBeNull();
550
+ });
551
+
552
+ it("hands an inbound error frame to onError", () => {
553
+ const errors: [string, string[]][] = [];
554
+ const store = createTreeStore({ onError: (message, path) => errors.push([message, path]) });
555
+ store.getState().dispatch(frame(OP_ERROR, ["a"], { code: "internal", message: "boom" }));
556
+ expect(errors).toEqual([["server: boom", ["a"]]]);
557
+ });
558
+ });
559
+
495
560
  describe("send", () => {
496
561
  it("drops frames until a sender is set, then delivers", () => {
497
562
  const sent: TreeFrame[] = [];
package/src/tree.ts CHANGED
@@ -12,12 +12,17 @@
12
12
  // mounted ahead of time and there is no fields list. Chain props are a seed
13
13
  // for a level being created, never an update to one already there.
14
14
  //
15
+ // A node's type is fixed once named. A chain that names another type for a
16
+ // node already there is refused whole: nothing lands, `onError` reports it and
17
+ // a frame from the server gets an `error` frame back. Changing what sits at an
18
+ // address takes a `remove` first.
19
+ //
15
20
  // React-free on purpose: this is zustand's vanilla store, so core stays usable
16
21
  // from a worker, a test, or anywhere else with no DOM. The React bindings and
17
22
  // the component registry live in the kit.
18
23
 
19
24
  import { current, enableMapSet, isDraft } from "immer";
20
- import type { ChainLevel, Frame } from "./protocol";
25
+ import { type ChainLevel, type ErrorPayload, type Frame, OP_ERROR } from "./protocol";
21
26
  import { createStore, type StoreApi } from "zustand/vanilla";
22
27
  import { immer } from "zustand/middleware/immer";
23
28
 
@@ -104,8 +109,12 @@ export type Resolve = (type: string) => Behaviour | undefined;
104
109
  export type TreeState = { root: Node };
105
110
 
106
111
  export type TreeActions = {
107
- /** Walk the chain, creating what is missing, then merge `props` into the leaf. */
108
- write: (chain: ChainStep[], props?: Props) => void;
112
+ /**
113
+ * Walk the chain, creating what is missing, then merge `props` into the leaf.
114
+ * False when the chain names a kind other than a node's already there: the
115
+ * write is refused whole and `onError` has it.
116
+ */
117
+ write: (chain: ChainStep[], props?: Props) => boolean;
109
118
  /** Drop a subtree, running dispose down the branch. Server-driven only. */
110
119
  remove: (path: Path) => void;
111
120
  getIn: (path: Path) => Node | null;
@@ -149,6 +158,35 @@ export function frameChain(frame: TreeFrame): ChainStep[] {
149
158
  return frame.ref.map((segment) => [segment, null] as ChainStep);
150
159
  }
151
160
 
161
+ /** Where `chain` names a type other than the node already there has, or null. */
162
+ export function kindConflict(
163
+ root: Node,
164
+ chain: ChainStep[],
165
+ ): { path: Path; have: string; want: string } | null {
166
+ let node: Node = root;
167
+ const here: Path = [];
168
+ for (const [segment, rawType] of chain) {
169
+ const child = node.children.get(segment);
170
+ if (!child) return null;
171
+ here.push(segment);
172
+ const want = rawType ?? null;
173
+ // An untyped side on either end is no claim: a synthesized chain names
174
+ // no type, and an autovivified level takes the first one named.
175
+ if (want !== null && child.type !== null && child.type !== want) {
176
+ return { path: [...here], have: child.type, want };
177
+ }
178
+ node = child;
179
+ }
180
+ return null;
181
+ }
182
+
183
+ function mismatch(conflict: { path: Path; have: string; want: string }): string {
184
+ return (
185
+ `kind mismatch at ${conflict.path.join(" / ")}: the node is ${conflict.have}, ` +
186
+ `the write names ${conflict.want}; remove it first to put another kind there`
187
+ );
188
+ }
189
+
152
190
  /** Pure lookup, handy for selectors over a state snapshot. */
153
191
  export function getNode(root: Node, path: Path): Node | null {
154
192
  let node: Node = root;
@@ -204,14 +242,20 @@ export function createTreeStore(options: TreeStoreOptions = {}): TreeStore {
204
242
 
205
243
  write: (chain, props) => {
206
244
  const path = chain.map((step) => step[0]);
207
- // One existence probe first. When the leaf is already there with
208
- // the right type, everything above it is too, so the walk is
209
- // skipped and only the payload lands.
245
+ const conflict = kindConflict(get().root, chain);
246
+ if (conflict) {
247
+ onError(mismatch(conflict), path);
248
+ return false;
249
+ }
250
+ // When the leaf is already there, the conflict walk has seen every
251
+ // level above it agree, so only the payload lands.
210
252
  const existing = getNode(get().root, path);
211
- const leafType = chain.length ? (chain[chain.length - 1][1] ?? null) : null;
212
- if (existing && (leafType === null || existing.type === leafType)) {
213
- if (props && Object.keys(props).length) get().setProps(path, props);
214
- return;
253
+ if (existing) {
254
+ const leafType = chain.length ? (chain[chain.length - 1][1] ?? null) : null;
255
+ if (leafType === null || existing.type !== null) {
256
+ if (props && Object.keys(props).length) get().setProps(path, props);
257
+ return true;
258
+ }
215
259
  }
216
260
  set((draft) => {
217
261
  let node = draft.root as Node;
@@ -220,18 +264,10 @@ export function createTreeStore(options: TreeStoreOptions = {}): TreeStore {
220
264
  here.push(segment);
221
265
  const type = rawType ?? null;
222
266
  let child: Node | undefined = node.children.get(segment);
223
- // A level whose type changes is rebuilt, not patched:
224
- // its old props and children go, and the branch disposes.
225
- if (child && type !== null && child.type !== null && child.type !== type) {
226
- collectDispose(child, [...here], pending);
227
- child = undefined;
228
- }
229
267
  if (!child) {
230
268
  child = emptyNode(type);
231
269
  if (stepProps) Object.assign(child.props, stepProps);
232
- // `set` on a key already there keeps its slot, so a
233
- // rebuilt level does not jump to the end.
234
- node.children.set(segment, child);
270
+ node.children.set(segment, child);
235
271
  } else if (child.type === null && type !== null) {
236
272
  // Autovivified earlier by something below it, so it
237
273
  // never got its declared props. This write names its
@@ -245,7 +281,7 @@ export function createTreeStore(options: TreeStoreOptions = {}): TreeStore {
245
281
  }
246
282
  if (props) Object.assign(node.props, props);
247
283
  });
248
- flushDispose();
284
+ return true;
249
285
  },
250
286
 
251
287
  remove: (path) => {
@@ -303,6 +339,23 @@ export function createTreeStore(options: TreeStoreOptions = {}): TreeStore {
303
339
 
304
340
  dispatch: (frame) => {
305
341
  const api = get();
342
+ if (frame.op === OP_ERROR) {
343
+ const payload = (frame.payload ?? {}) as Partial<ErrorPayload>;
344
+ onError(`server: ${payload.message ?? payload.code ?? "error"}`, frame.ref);
345
+ return;
346
+ }
347
+ // A chain the store refused never reaches a handler; the server
348
+ // hears why, since the write it sent did not land.
349
+ const refuse = () => {
350
+ const conflict = kindConflict(api.root, frameChain(frame));
351
+ const message = conflict ? mismatch(conflict) : "write refused";
352
+ api.send({
353
+ op: OP_ERROR,
354
+ ref: frame.ref,
355
+ payload: { code: "kind_mismatch", message } satisfies ErrorPayload,
356
+ id: frame.id,
357
+ });
358
+ };
306
359
  if (frame.op === OPS.remove) {
307
360
  api.remove(frame.ref);
308
361
  return;
@@ -311,13 +364,16 @@ export function createTreeStore(options: TreeStoreOptions = {}): TreeStore {
311
364
  if (frame.op === OPS.init) {
312
365
  // Structure and nothing else. An init carries no payload, so
313
366
  // it never touches a value the program already set.
314
- api.write(chain);
367
+ if (!api.write(chain)) refuse();
315
368
  return;
316
369
  }
317
370
  if (frame.op === OPS.hide || frame.op === OPS.display) {
318
371
  // Structure first (the node may not exist yet), then the
319
372
  // flag. Generic for every type, never a handler's call.
320
- api.write(chain);
373
+ if (!api.write(chain)) {
374
+ refuse();
375
+ return;
376
+ }
321
377
  api.setHidden(frame.ref, frame.op === OPS.hide);
322
378
  return;
323
379
  }
@@ -328,7 +384,10 @@ export function createTreeStore(options: TreeStoreOptions = {}): TreeStore {
328
384
  if (frame.op === OPS.write) {
329
385
  // Structure first, always: the node may not exist yet, so
330
386
  // the chain runs before anything can be looked up by type.
331
- api.write(chain);
387
+ if (!api.write(chain)) {
388
+ refuse();
389
+ return;
390
+ }
332
391
  const written = api.getIn(frame.ref);
333
392
  if (!written) return;
334
393
  const custom = handlerFor(written);
@@ -346,7 +405,10 @@ export function createTreeStore(options: TreeStoreOptions = {}): TreeStore {
346
405
  // first, the same way a write does: a Card's `set_title` may be
347
406
  // the first frame that ever names that Card. A frame with no
348
407
  // chain is addressed at a node that should already be there.
349
- if (frame.chain) api.write(chain);
408
+ if (frame.chain && !api.write(chain)) {
409
+ refuse();
410
+ return;
411
+ }
350
412
  const node = api.getIn(frame.ref);
351
413
  if (!node) {
352
414
  onError(`no node for op "${frame.op}"`, frame.ref);