@nustackdev/ui-core 0.1.0 → 0.2.1
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 +14 -4
- package/src/index.ts +2 -1
- package/src/protocol.ts +24 -27
- package/src/tree.test.ts +435 -0
- package/src/tree.ts +364 -0
package/package.json
CHANGED
|
@@ -1,7 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nustackdev/ui-core",
|
|
3
3
|
"description": "Wire protocol for the Nu.",
|
|
4
|
-
"
|
|
4
|
+
"repository": {
|
|
5
|
+
"type": "git",
|
|
6
|
+
"url": "git+https://github.com/nustackdev/nu.git",
|
|
7
|
+
"directory": "pkgs/ts/ui-core"
|
|
8
|
+
},
|
|
9
|
+
"version": "0.2.1",
|
|
5
10
|
"type": "module",
|
|
6
11
|
"main": "./src/index.ts",
|
|
7
12
|
"types": "./src/index.ts",
|
|
@@ -16,13 +21,18 @@
|
|
|
16
21
|
],
|
|
17
22
|
"scripts": {
|
|
18
23
|
"typecheck": "tsc --noEmit",
|
|
19
|
-
"check": "biome check ."
|
|
24
|
+
"check": "biome check .",
|
|
25
|
+
"test": "vitest run",
|
|
26
|
+
"test:watch": "vitest"
|
|
20
27
|
},
|
|
21
28
|
"dependencies": {
|
|
22
|
-
"@msgpack/msgpack": "^3.1.3"
|
|
29
|
+
"@msgpack/msgpack": "^3.1.3",
|
|
30
|
+
"immer": "^11.1.8",
|
|
31
|
+
"zustand": "^5.0.13"
|
|
23
32
|
},
|
|
24
33
|
"devDependencies": {
|
|
25
34
|
"typescript": "~5.9.3",
|
|
26
|
-
"@biomejs/biome": "^2.3.15"
|
|
35
|
+
"@biomejs/biome": "^2.3.15",
|
|
36
|
+
"vitest": "^3.2.7"
|
|
27
37
|
}
|
|
28
38
|
}
|
package/src/index.ts
CHANGED
package/src/protocol.ts
CHANGED
|
@@ -3,44 +3,40 @@
|
|
|
3
3
|
|
|
4
4
|
import { decode as mpDecode, encode as mpEncode } from "@msgpack/msgpack";
|
|
5
5
|
|
|
6
|
-
|
|
7
|
-
|
|
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.
|
|
8
8
|
export const OP_ERROR = "error";
|
|
9
|
-
|
|
10
|
-
|
|
9
|
+
|
|
10
|
+
// A ref's address: the Ref chain's segments, root-first. Stays a list end
|
|
11
|
+
// to end -- a segment may contain any character, dots included, so there is
|
|
12
|
+
// no separator that could take it apart again.
|
|
13
|
+
export type RefPath = string[];
|
|
14
|
+
|
|
15
|
+
// One level of a ref chain: its segment, the type the browser renders it
|
|
16
|
+
// with, and the props its slot declared (empty object when it declared none).
|
|
17
|
+
// One level of a write's chain. The server always sends all three, but a chain
|
|
18
|
+
// synthesized locally from a bare `ref` has no type and no props to give, so the
|
|
19
|
+
// tail is optional. One type for both, or the two ends stop agreeing.
|
|
20
|
+
export type ChainLevel = [
|
|
21
|
+
segment: string,
|
|
22
|
+
type?: string | null,
|
|
23
|
+
props?: Record<string, unknown>,
|
|
24
|
+
];
|
|
11
25
|
|
|
12
26
|
export type Frame = {
|
|
13
27
|
op: string;
|
|
14
|
-
ref:
|
|
28
|
+
ref: RefPath;
|
|
15
29
|
payload: unknown;
|
|
16
30
|
id?: string;
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
path: string;
|
|
21
|
-
type: string;
|
|
22
|
-
// Optional class-level defaults for the Ref or Section. When present,
|
|
23
|
-
// the slice factory seeds its state from these values.
|
|
24
|
-
props?: Record<string, unknown>;
|
|
25
|
-
// Optional nested fields. Layout entries (Row, Column, Container) carry
|
|
26
|
-
// their child entries here. Leaf Ref entries omit this key. The browser
|
|
27
|
-
// walks the tree recursively to register slices for every leaf.
|
|
28
|
-
fields?: MountField[];
|
|
29
|
-
};
|
|
30
|
-
export type MountPage = { route: string; name: string; fields: MountField[] };
|
|
31
|
-
// `name` is the Index class name; `fields` are Index-level structural
|
|
32
|
-
// slots (TitleRef, NavRef, ...); `pages` lists Page subtrees by route.
|
|
33
|
-
export type MountPayload = {
|
|
34
|
-
name: string;
|
|
35
|
-
fields: MountField[];
|
|
36
|
-
pages?: MountPage[];
|
|
31
|
+
// The `ref` path annotated, root-first. Present on writes; absent on
|
|
32
|
+
// frames that carry no chain, so treat a missing one as empty.
|
|
33
|
+
chain?: ChainLevel[];
|
|
37
34
|
};
|
|
38
35
|
|
|
39
36
|
export type ErrorCode =
|
|
40
37
|
| "ref_not_found"
|
|
41
38
|
| "op_not_allowed"
|
|
42
39
|
| "payload_invalid"
|
|
43
|
-
| "not_mounted"
|
|
44
40
|
| "internal";
|
|
45
41
|
|
|
46
42
|
export type ErrorPayload = { code: ErrorCode; message: string };
|
|
@@ -54,8 +50,9 @@ export function decode(raw: ArrayBuffer | Uint8Array): Frame {
|
|
|
54
50
|
const d = mpDecode(bytes) as Partial<Frame> & { op: string };
|
|
55
51
|
return {
|
|
56
52
|
op: d.op,
|
|
57
|
-
ref: d.ref ??
|
|
53
|
+
ref: d.ref ?? [],
|
|
58
54
|
payload: d.payload,
|
|
59
55
|
id: d.id,
|
|
56
|
+
...(d.chain ? { chain: d.chain } : {}),
|
|
60
57
|
};
|
|
61
58
|
}
|
package/src/tree.test.ts
ADDED
|
@@ -0,0 +1,435 @@
|
|
|
1
|
+
// The tree store, tested in isolation: no React, no socket, no server.
|
|
2
|
+
// Everything below is a plain frame in and a plain node out.
|
|
3
|
+
|
|
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
|
+
|
|
13
|
+
function step(segment: string, type: string | null = null, props?: Record<string, unknown>): ChainStep {
|
|
14
|
+
return props ? [segment, type, props] : [segment, type];
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Child segments in order. The whole point of the Map, so read it directly. */
|
|
18
|
+
function segments(node: { children: Map<string, unknown> } | null): string[] {
|
|
19
|
+
return node ? [...node.children.keys()] : [];
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function frame(op: string, ref: string[], payload?: unknown, chain?: ChainStep[]): TreeFrame {
|
|
23
|
+
return { op, ref, payload, chain };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
describe("write", () => {
|
|
27
|
+
it("autovivifies every level in one go", () => {
|
|
28
|
+
const store = createTreeStore();
|
|
29
|
+
store.getState().write([step("page", "Page"), step("form", "Form"), step("inp", "InputRef")], {
|
|
30
|
+
value: "hi",
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
const root = store.getState().root;
|
|
34
|
+
expect(segments(root)).toEqual(["page"]);
|
|
35
|
+
const page = root.children.get("page");
|
|
36
|
+
expect(page?.type).toBe("Page");
|
|
37
|
+
expect(page?.children.get("form")?.type).toBe("Form");
|
|
38
|
+
const inp = store.getState().getIn(["page", "form", "inp"]);
|
|
39
|
+
expect(inp).toEqual({ type: "InputRef", props: { value: "hi" }, children: new Map() });
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it("leaves a level untyped when the chain does not name a type", () => {
|
|
43
|
+
const store = createTreeStore();
|
|
44
|
+
store.getState().write([step("a"), step("b", "TextRef")], { value: 1 });
|
|
45
|
+
expect(store.getState().getIn(["a"])?.type).toBeNull();
|
|
46
|
+
expect(store.getState().getIn(["b"])).toBeNull();
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
it("claims an untyped level when a later write names its type", () => {
|
|
50
|
+
const store = createTreeStore();
|
|
51
|
+
store.getState().write([step("a"), step("b", "TextRef")]);
|
|
52
|
+
store.getState().write([step("a", "Column", { gap: 2 })]);
|
|
53
|
+
expect(store.getState().getIn(["a"])?.type).toBe("Column");
|
|
54
|
+
// The child that caused the autovivify is still there.
|
|
55
|
+
expect(store.getState().getIn(["a", "b"])?.type).toBe("TextRef");
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it("merges the payload into a level that already exists", () => {
|
|
59
|
+
const store = createTreeStore();
|
|
60
|
+
store.getState().write([step("a", "InputRef", { label: "Name", value: "" })]);
|
|
61
|
+
store.getState().write([step("a", "InputRef")], { value: "gor" });
|
|
62
|
+
expect(store.getState().getIn(["a"])?.props).toEqual({ label: "Name", value: "gor" });
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
it("seeds chain props on creation only, never as an update", () => {
|
|
66
|
+
const store = createTreeStore();
|
|
67
|
+
store.getState().write([step("sec", "Card", { title: "One" }), step("t", "TextRef")]);
|
|
68
|
+
// Same chain, same declared props, new child below it. The declared
|
|
69
|
+
// title must not come back and overwrite a runtime one.
|
|
70
|
+
store.getState().setProps(["sec"], { title: "Live" });
|
|
71
|
+
store.getState().write([step("sec", "Card", { title: "One" }), step("u", "TextRef")]);
|
|
72
|
+
expect(store.getState().getIn(["sec"])?.props).toEqual({ title: "Live" });
|
|
73
|
+
expect(segments(store.getState().getIn(["sec"]))).toEqual(["t", "u"]);
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it("keeps a prop set at runtime when a deep write rides through", () => {
|
|
77
|
+
const store = createTreeStore();
|
|
78
|
+
const chain = [
|
|
79
|
+
step("page", "Page", { title: "Page" }),
|
|
80
|
+
step("sec", "Section", { variant: "plain" }),
|
|
81
|
+
step("t", "TextRef", { value: "" }),
|
|
82
|
+
];
|
|
83
|
+
store.getState().write(chain);
|
|
84
|
+
store.getState().setProps(["page", "sec"], { variant: "auto-scroll" });
|
|
85
|
+
store.getState().write(chain, { value: "tick" });
|
|
86
|
+
expect(store.getState().getIn(["page", "sec"])?.props).toEqual({ variant: "auto-scroll" });
|
|
87
|
+
expect(store.getState().getIn(["page", "sec", "t"])?.props.value).toBe("tick");
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
it("skips the walk when the leaf is already there", () => {
|
|
91
|
+
const store = createTreeStore();
|
|
92
|
+
store.getState().write([step("sec", "Card", { title: "One" }), step("t", "TextRef")]);
|
|
93
|
+
store.getState().write([step("sec", "Card", { title: "Two" }), step("t", "TextRef")], {
|
|
94
|
+
value: "x",
|
|
95
|
+
});
|
|
96
|
+
expect(store.getState().getIn(["sec"])?.props).toEqual({ title: "One" });
|
|
97
|
+
expect(store.getState().getIn(["sec", "t"])?.props).toEqual({ value: "x" });
|
|
98
|
+
});
|
|
99
|
+
|
|
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] });
|
|
107
|
+
store.getState().write([step("sec", "Card", { title: "One" }), step("t", "TextRef")]);
|
|
108
|
+
store.getState().write([step("sec", "Modal", { open: true })]);
|
|
109
|
+
|
|
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
|
+
});
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
it("keeps a node whose write does not name a type", () => {
|
|
122
|
+
const store = createTreeStore();
|
|
123
|
+
store.getState().write([step("a", "InputRef", { value: "x" })]);
|
|
124
|
+
store.getState().write([step("a")], { value: "y" });
|
|
125
|
+
expect(store.getState().getIn(["a"])).toEqual({
|
|
126
|
+
type: "InputRef",
|
|
127
|
+
props: { value: "y" },
|
|
128
|
+
children: new Map(),
|
|
129
|
+
});
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
it("treats a segment with a dot as one segment", () => {
|
|
133
|
+
const store = createTreeStore();
|
|
134
|
+
store.getState().write([step("a.b", "Card"), step("c.d", "TextRef", { value: 1 })]);
|
|
135
|
+
expect(store.getState().getIn(["a.b", "c.d"])?.props).toEqual({ value: 1 });
|
|
136
|
+
expect(store.getState().getIn(["a", "b", "c", "d"])).toBeNull();
|
|
137
|
+
expect(segments(store.getState().root)).toEqual(["a.b"]);
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
it("keeps a numeric-looking segment where it was written", () => {
|
|
141
|
+
// A plain object hoists "0" and "1" to the front no matter when they
|
|
142
|
+
// went in. Render order is insertion order, so they must not move.
|
|
143
|
+
const store = createTreeStore();
|
|
144
|
+
for (const seg of ["z", "0", "a", "1"]) {
|
|
145
|
+
store.getState().write([step("box", "Column"), step(seg, "TextRef", { value: seg })]);
|
|
146
|
+
}
|
|
147
|
+
expect(segments(store.getState().getIn(["box"]))).toEqual(["z", "0", "a", "1"]);
|
|
148
|
+
});
|
|
149
|
+
|
|
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
|
+
it("writes into the root with an empty chain", () => {
|
|
159
|
+
const store = createTreeStore();
|
|
160
|
+
store.getState().write([], { title: "root" });
|
|
161
|
+
expect(store.getState().root.props).toEqual({ title: "root" });
|
|
162
|
+
});
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
describe("getIn", () => {
|
|
166
|
+
it("returns null for a path that is not there", () => {
|
|
167
|
+
const store = createTreeStore();
|
|
168
|
+
store.getState().write([step("a", "Card")]);
|
|
169
|
+
expect(store.getState().getIn(["a", "nope"])).toBeNull();
|
|
170
|
+
expect(store.getState().getIn(["nope"])).toBeNull();
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
it("returns the root for an empty path", () => {
|
|
174
|
+
const store = createTreeStore();
|
|
175
|
+
expect(store.getState().getIn([])).toBe(store.getState().root);
|
|
176
|
+
});
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
describe("remove", () => {
|
|
180
|
+
it("drops the subtree and disposes descendants first", () => {
|
|
181
|
+
const gone: string[][] = [];
|
|
182
|
+
const dispose = (ctx: { path: string[] }) => gone.push(ctx.path);
|
|
183
|
+
const behaviours: Record<string, Behaviour> = {
|
|
184
|
+
Card: { dispose },
|
|
185
|
+
Column: { dispose },
|
|
186
|
+
TextRef: { dispose },
|
|
187
|
+
};
|
|
188
|
+
const store = createTreeStore({ resolve: (t) => behaviours[t] });
|
|
189
|
+
store
|
|
190
|
+
.getState()
|
|
191
|
+
.write([step("sec", "Card"), step("col", "Column"), step("t", "TextRef", { value: 1 })]);
|
|
192
|
+
store.getState().write([step("other", "TextRef")]);
|
|
193
|
+
|
|
194
|
+
store.getState().remove(["sec"]);
|
|
195
|
+
|
|
196
|
+
expect(gone).toEqual([
|
|
197
|
+
["sec", "col", "t"],
|
|
198
|
+
["sec", "col"],
|
|
199
|
+
["sec"],
|
|
200
|
+
]);
|
|
201
|
+
expect(store.getState().getIn(["sec"])).toBeNull();
|
|
202
|
+
expect(store.getState().getIn(["other"])?.type).toBe("TextRef");
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
it("hands dispose a live snapshot, not a dead draft", () => {
|
|
206
|
+
const seen: unknown[] = [];
|
|
207
|
+
const store = createTreeStore({
|
|
208
|
+
resolve: () => ({ dispose: (ctx) => seen.push(ctx.node.props.value) }),
|
|
209
|
+
});
|
|
210
|
+
store.getState().write([step("a", "TextRef", { value: "keep" })]);
|
|
211
|
+
store.getState().remove(["a"]);
|
|
212
|
+
expect(seen).toEqual(["keep"]);
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
it("skips untyped nodes when disposing", () => {
|
|
216
|
+
const dispose = vi.fn();
|
|
217
|
+
const store = createTreeStore({ resolve: () => ({ dispose }) });
|
|
218
|
+
store.getState().write([step("a"), step("b")]);
|
|
219
|
+
store.getState().remove(["a"]);
|
|
220
|
+
expect(dispose).not.toHaveBeenCalled();
|
|
221
|
+
});
|
|
222
|
+
|
|
223
|
+
it("is a no-op for a path that is not there", () => {
|
|
224
|
+
const store = createTreeStore();
|
|
225
|
+
store.getState().write([step("a", "Card")]);
|
|
226
|
+
store.getState().remove(["nope", "deeper"]);
|
|
227
|
+
expect(store.getState().getIn(["a"])?.type).toBe("Card");
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
it("clears everything for an empty path", () => {
|
|
231
|
+
const store = createTreeStore();
|
|
232
|
+
store.getState().write([step("a", "Card"), step("b", "TextRef")]);
|
|
233
|
+
store.getState().remove([]);
|
|
234
|
+
expect(store.getState().root).toEqual({ type: null, props: {}, children: new Map() });
|
|
235
|
+
});
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
describe("dispatch", () => {
|
|
239
|
+
it("creates the node on the first write it sees", () => {
|
|
240
|
+
const store = createTreeStore();
|
|
241
|
+
store
|
|
242
|
+
.getState()
|
|
243
|
+
.dispatch(
|
|
244
|
+
frame(OPS.write, ["page", "inp"], "hello", [step("page", "Page"), step("inp", "InputRef")]),
|
|
245
|
+
);
|
|
246
|
+
expect(store.getState().getIn(["page", "inp"])).toEqual({
|
|
247
|
+
type: "InputRef",
|
|
248
|
+
props: { value: "hello" },
|
|
249
|
+
children: new Map(),
|
|
250
|
+
});
|
|
251
|
+
});
|
|
252
|
+
|
|
253
|
+
it("merges an object payload as props", () => {
|
|
254
|
+
const store = createTreeStore();
|
|
255
|
+
store
|
|
256
|
+
.getState()
|
|
257
|
+
.dispatch(frame(OPS.write, ["a"], { label: "L", value: 2 }, [step("a", "InputRef")]));
|
|
258
|
+
expect(store.getState().getIn(["a"])?.props).toEqual({ label: "L", value: 2 });
|
|
259
|
+
});
|
|
260
|
+
|
|
261
|
+
it("lands a list payload on value rather than spreading it", () => {
|
|
262
|
+
const store = createTreeStore();
|
|
263
|
+
store.getState().dispatch(frame(OPS.write, ["a"], [1, 2, 3], [step("a", "TableRef")]));
|
|
264
|
+
expect(store.getState().getIn(["a"])?.props).toEqual({ value: [1, 2, 3] });
|
|
265
|
+
});
|
|
266
|
+
|
|
267
|
+
it("walks the ref untyped when a frame arrives with no chain", () => {
|
|
268
|
+
const store = createTreeStore();
|
|
269
|
+
store.getState().dispatch(frame(OPS.write, ["a", "b"], "x"));
|
|
270
|
+
expect(store.getState().getIn(["a"])?.type).toBeNull();
|
|
271
|
+
expect(store.getState().getIn(["a", "b"])).toEqual({
|
|
272
|
+
type: null,
|
|
273
|
+
props: { value: "x" },
|
|
274
|
+
children: new Map(),
|
|
275
|
+
});
|
|
276
|
+
});
|
|
277
|
+
|
|
278
|
+
it("keeps a typed node's type when a chainless write lands on it", () => {
|
|
279
|
+
const store = createTreeStore();
|
|
280
|
+
store.getState().write([step("a", "InputRef", { label: "L" })]);
|
|
281
|
+
store.getState().dispatch(frame(OPS.write, ["a"], "typed"));
|
|
282
|
+
expect(store.getState().getIn(["a"])).toEqual({
|
|
283
|
+
type: "InputRef",
|
|
284
|
+
props: { label: "L", value: "typed" },
|
|
285
|
+
children: new Map(),
|
|
286
|
+
});
|
|
287
|
+
});
|
|
288
|
+
|
|
289
|
+
it("routes an op to the handler for the node's type", () => {
|
|
290
|
+
const behaviours: Record<string, Behaviour> = {
|
|
291
|
+
TableRef: {
|
|
292
|
+
handlers: {
|
|
293
|
+
append: (ctx, payload) =>
|
|
294
|
+
ctx.update((props) => {
|
|
295
|
+
props.rows = [...((props.rows as unknown[]) ?? []), payload];
|
|
296
|
+
}),
|
|
297
|
+
},
|
|
298
|
+
},
|
|
299
|
+
};
|
|
300
|
+
const store = createTreeStore({ resolve: (t) => behaviours[t] });
|
|
301
|
+
store.getState().write([step("t", "TableRef", { rows: [] })]);
|
|
302
|
+
store.getState().dispatch(frame("append", ["t"], { id: 1 }));
|
|
303
|
+
store.getState().dispatch(frame("append", ["t"], { id: 2 }));
|
|
304
|
+
expect(store.getState().getIn(["t"])?.props.rows).toEqual([{ id: 1 }, { id: 2 }]);
|
|
305
|
+
});
|
|
306
|
+
|
|
307
|
+
it("creates the node from a custom op's chain, then runs its handler", () => {
|
|
308
|
+
const behaviours: Record<string, Behaviour> = {
|
|
309
|
+
Card: {
|
|
310
|
+
handlers: {
|
|
311
|
+
set_title: (ctx, payload) =>
|
|
312
|
+
ctx.update((props) => {
|
|
313
|
+
props.title = String(payload);
|
|
314
|
+
}),
|
|
315
|
+
},
|
|
316
|
+
},
|
|
317
|
+
};
|
|
318
|
+
const store = createTreeStore({ resolve: (t) => behaviours[t] });
|
|
319
|
+
store
|
|
320
|
+
.getState()
|
|
321
|
+
.dispatch(
|
|
322
|
+
frame("set_title", ["col", "card"], "Hi", [
|
|
323
|
+
step("col", "Column"),
|
|
324
|
+
step("card", "Card", { title: "", footer: "" }),
|
|
325
|
+
]),
|
|
326
|
+
);
|
|
327
|
+
expect(store.getState().getIn(["col"])?.type).toBe("Column");
|
|
328
|
+
expect(store.getState().getIn(["col", "card"])?.props).toEqual({ title: "Hi", footer: "" });
|
|
329
|
+
});
|
|
330
|
+
|
|
331
|
+
it("still reports a custom op with no chain on a missing node", () => {
|
|
332
|
+
const onError = vi.fn();
|
|
333
|
+
const store = createTreeStore({ onError });
|
|
334
|
+
store.getState().dispatch(frame("set_title", ["nope"], "Hi"));
|
|
335
|
+
expect(onError).toHaveBeenCalledOnce();
|
|
336
|
+
expect(store.getState().getIn(["nope"])).toBeNull();
|
|
337
|
+
});
|
|
338
|
+
|
|
339
|
+
it("gives a type's own write handler the raw payload", () => {
|
|
340
|
+
const behaviours: Record<string, Behaviour> = {
|
|
341
|
+
InputRef: {
|
|
342
|
+
handlers: {
|
|
343
|
+
// A null write must not make the input uncontrolled.
|
|
344
|
+
write: (ctx, payload) =>
|
|
345
|
+
ctx.update((props) => {
|
|
346
|
+
props.value = payload == null ? "" : String(payload);
|
|
347
|
+
}),
|
|
348
|
+
},
|
|
349
|
+
},
|
|
350
|
+
};
|
|
351
|
+
const store = createTreeStore({ resolve: (t) => behaviours[t] });
|
|
352
|
+
store.getState().dispatch(frame(OPS.write, ["i"], null, [step("i", "InputRef")]));
|
|
353
|
+
expect(store.getState().getIn(["i"])?.props).toEqual({ value: "" });
|
|
354
|
+
});
|
|
355
|
+
|
|
356
|
+
it("builds structure from an init and touches no value", () => {
|
|
357
|
+
const store = createTreeStore();
|
|
358
|
+
store.getState().write([step("a", "InputRef", { label: "L" })], { value: "typed" });
|
|
359
|
+
store.getState().dispatch(frame(OPS.init, ["a"], null, [step("a", "InputRef", { label: "L" })]));
|
|
360
|
+
store.getState().dispatch(frame(OPS.init, ["b"], null, [step("b", "TextRef", { value: "" })]));
|
|
361
|
+
expect(store.getState().getIn(["a"])?.props).toEqual({ label: "L", value: "typed" });
|
|
362
|
+
expect(store.getState().getIn(["b"])?.type).toBe("TextRef");
|
|
363
|
+
});
|
|
364
|
+
|
|
365
|
+
it("removes on a remove frame", () => {
|
|
366
|
+
const store = createTreeStore();
|
|
367
|
+
store.getState().write([step("a", "Card"), step("b", "TextRef")]);
|
|
368
|
+
store.getState().dispatch(frame(OPS.remove, ["a"]));
|
|
369
|
+
expect(store.getState().getIn(["a"])).toBeNull();
|
|
370
|
+
});
|
|
371
|
+
|
|
372
|
+
it("answers a read with the node's value and the same id", () => {
|
|
373
|
+
const sent: TreeFrame[] = [];
|
|
374
|
+
const store = createTreeStore({ send: (f) => sent.push(f) });
|
|
375
|
+
store.getState().write([step("a", "InputRef", { value: "gor" })]);
|
|
376
|
+
store.getState().dispatch({ op: OPS.read, ref: ["a"], payload: null, id: "f1" });
|
|
377
|
+
expect(sent).toEqual([{ op: OPS.read, ref: ["a"], payload: "gor", id: "f1" }]);
|
|
378
|
+
});
|
|
379
|
+
|
|
380
|
+
it("lets a type answer a read itself", () => {
|
|
381
|
+
const sent: TreeFrame[] = [];
|
|
382
|
+
const behaviours: Record<string, Behaviour> = {
|
|
383
|
+
MarkdownRef: {
|
|
384
|
+
handlers: {
|
|
385
|
+
read: (ctx) => ctx.send(OPS.read, `md:${ctx.node.props.value}`, ctx.frame.id),
|
|
386
|
+
},
|
|
387
|
+
},
|
|
388
|
+
};
|
|
389
|
+
const store = createTreeStore({ send: (f) => sent.push(f), resolve: (t) => behaviours[t] });
|
|
390
|
+
store.getState().write([step("p", "MarkdownRef", { value: "hi" })]);
|
|
391
|
+
store.getState().dispatch({ op: OPS.read, ref: ["p"], payload: null, id: "f2" });
|
|
392
|
+
expect(sent).toEqual([{ op: OPS.read, ref: ["p"], payload: "md:hi", id: "f2" }]);
|
|
393
|
+
});
|
|
394
|
+
|
|
395
|
+
it("reports an op on a node that is not there", () => {
|
|
396
|
+
const errors: string[] = [];
|
|
397
|
+
const store = createTreeStore({ onError: (m) => errors.push(m) });
|
|
398
|
+
store.getState().dispatch(frame("append", ["nope"], 1));
|
|
399
|
+
expect(errors).toHaveLength(1);
|
|
400
|
+
});
|
|
401
|
+
|
|
402
|
+
it("reports an op the node's type does not support", () => {
|
|
403
|
+
const errors: string[] = [];
|
|
404
|
+
const store = createTreeStore({ onError: (m) => errors.push(m) });
|
|
405
|
+
store.getState().write([step("a", "TextRef")]);
|
|
406
|
+
store.getState().dispatch(frame("append", ["a"], 1));
|
|
407
|
+
expect(errors).toHaveLength(1);
|
|
408
|
+
});
|
|
409
|
+
});
|
|
410
|
+
|
|
411
|
+
describe("send", () => {
|
|
412
|
+
it("drops frames until a sender is set, then delivers", () => {
|
|
413
|
+
const sent: TreeFrame[] = [];
|
|
414
|
+
const store = createTreeStore();
|
|
415
|
+
store.getState().send({ op: OPS.notify, ref: ["a"], payload: null });
|
|
416
|
+
store.getState().setSender((f) => sent.push(f));
|
|
417
|
+
store.getState().send({ op: OPS.notify, ref: ["a"], payload: null });
|
|
418
|
+
expect(sent).toHaveLength(1);
|
|
419
|
+
});
|
|
420
|
+
});
|
|
421
|
+
|
|
422
|
+
describe("subscription", () => {
|
|
423
|
+
it("shares structure so an untouched branch keeps its identity", () => {
|
|
424
|
+
const store = createTreeStore();
|
|
425
|
+
store.getState().write([step("left", "Card"), step("t", "TextRef", { value: 1 })]);
|
|
426
|
+
store.getState().write([step("right", "Card"), step("t", "TextRef", { value: 1 })]);
|
|
427
|
+
const leftBefore = store.getState().getIn(["left"]);
|
|
428
|
+
|
|
429
|
+
store.getState().write([step("right", "Card"), step("t", "TextRef")], { value: 2 });
|
|
430
|
+
|
|
431
|
+
expect(store.getState().getIn(["left"])).toBe(leftBefore);
|
|
432
|
+
expect(store.getState().getIn(["right"])).not.toBe(undefined);
|
|
433
|
+
expect(store.getState().getIn(["right", "t"])?.props.value).toBe(2);
|
|
434
|
+
});
|
|
435
|
+
});
|
package/src/tree.ts
ADDED
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
// The browser store, as a tree.
|
|
2
|
+
//
|
|
3
|
+
// One node is exactly three things: a `type`, a bag of `props`, and `children`
|
|
4
|
+
// keyed by segment. `type` is null for a node that exists only because
|
|
5
|
+
// something below it was written. `value` is just a prop, not a field of its
|
|
6
|
+
// own -- a node's current value lives at `props.value` like everything else.
|
|
7
|
+
//
|
|
8
|
+
// Writes autovivify. A frame carries a `chain`, root-first, one triple per
|
|
9
|
+
// level, so a write to `a.b.c` creates `a` and `b` with the type and props
|
|
10
|
+
// each was annotated with, exactly like a kv set on a nested path. Nothing is
|
|
11
|
+
// mounted ahead of time and there is no fields list. Chain props are a seed
|
|
12
|
+
// for a level being created, never an update to one already there.
|
|
13
|
+
//
|
|
14
|
+
// React-free on purpose: this is zustand's vanilla store, so core stays usable
|
|
15
|
+
// from a worker, a test, or anywhere else with no DOM. The React bindings and
|
|
16
|
+
// the component registry live in the kit.
|
|
17
|
+
|
|
18
|
+
import { current, enableMapSet, isDraft } from "immer";
|
|
19
|
+
import type { ChainLevel, Frame } from "./protocol";
|
|
20
|
+
import { createStore, type StoreApi } from "zustand/vanilla";
|
|
21
|
+
import { immer } from "zustand/middleware/immer";
|
|
22
|
+
|
|
23
|
+
// `children` is a Map, and immer only drafts those once this is on.
|
|
24
|
+
enableMapSet();
|
|
25
|
+
|
|
26
|
+
/** A node's address: segments, root-first. A segment may contain any character. */
|
|
27
|
+
export type Path = string[];
|
|
28
|
+
|
|
29
|
+
export type Props = Record<string, unknown>;
|
|
30
|
+
|
|
31
|
+
// A Map and not a plain object: render order is insertion order, and an
|
|
32
|
+
// object hoists integer-like keys to the front, so a segment like "0" or an
|
|
33
|
+
// index from a dynamic ref would silently jump the queue.
|
|
34
|
+
export type Node = {
|
|
35
|
+
type: string | null;
|
|
36
|
+
props: Props;
|
|
37
|
+
children: Map<string, Node>;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
/** Alias for consumers where the DOM's `Node` is also in scope. */
|
|
41
|
+
export type TreeNode = Node;
|
|
42
|
+
|
|
43
|
+
// One level of a write's chain: the segment, the type the level should have,
|
|
44
|
+
// and the props its slot declared. This is the wire `ChainLevel`: a frame
|
|
45
|
+
// that arrives with no chain gets one synthesized from its ref, and those
|
|
46
|
+
// levels know neither type nor props.
|
|
47
|
+
//
|
|
48
|
+
// Chain props are a create-time seed and nothing else. The same chain rides
|
|
49
|
+
// along on every write to anything below that level, carrying the declared
|
|
50
|
+
// defaults, so merging them into a level that already exists would stomp on
|
|
51
|
+
// whatever the program set at runtime. An existing level is compared by type
|
|
52
|
+
// and otherwise left alone.
|
|
53
|
+
export type ChainStep = ChainLevel;
|
|
54
|
+
|
|
55
|
+
// A frame as it arrives. The chain is the wire type, so this is `Frame`; the
|
|
56
|
+
// alias stays because the store talks about frames it may have synthesized.
|
|
57
|
+
export type TreeFrame = Frame;
|
|
58
|
+
|
|
59
|
+
/** The op vocabulary. There is no mount and no unmount. */
|
|
60
|
+
export const OPS = {
|
|
61
|
+
write: "write",
|
|
62
|
+
// Chain only, no payload: brings a node into being ahead of the first
|
|
63
|
+
// write to it. What a boot batch is made of.
|
|
64
|
+
init: "init",
|
|
65
|
+
remove: "remove",
|
|
66
|
+
read: "read",
|
|
67
|
+
notify: "notify",
|
|
68
|
+
} as const;
|
|
69
|
+
|
|
70
|
+
export type NodeCtx = {
|
|
71
|
+
path: Path;
|
|
72
|
+
/** Snapshot of the node at dispatch time. */
|
|
73
|
+
node: Node;
|
|
74
|
+
/** Mutate this node's own props. */
|
|
75
|
+
update: (mutate: (props: Props) => void) => void;
|
|
76
|
+
/** Send a frame rooted at this node. */
|
|
77
|
+
send: (op: string, payload: unknown, id?: string) => void;
|
|
78
|
+
store: TreeStore;
|
|
79
|
+
frame: TreeFrame;
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
export type NodeHandler = (ctx: NodeCtx, payload: unknown) => void;
|
|
83
|
+
|
|
84
|
+
export type DisposeCtx = { path: Path; node: Node };
|
|
85
|
+
|
|
86
|
+
/** What a type contributes to the store: inbound ops and teardown. */
|
|
87
|
+
export type Behaviour = {
|
|
88
|
+
handlers?: Record<string, NodeHandler>;
|
|
89
|
+
dispose?: (ctx: DisposeCtx) => void;
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
export type Resolve = (type: string) => Behaviour | undefined;
|
|
93
|
+
|
|
94
|
+
export type TreeState = { root: Node };
|
|
95
|
+
|
|
96
|
+
export type TreeActions = {
|
|
97
|
+
/** Walk the chain, creating what is missing, then merge `props` into the leaf. */
|
|
98
|
+
write: (chain: ChainStep[], props?: Props) => void;
|
|
99
|
+
/** Drop a subtree, running dispose down the branch. Server-driven only. */
|
|
100
|
+
remove: (path: Path) => void;
|
|
101
|
+
getIn: (path: Path) => Node | null;
|
|
102
|
+
/** Merge props into an existing node. No-op when the node is not there. */
|
|
103
|
+
setProps: (path: Path, props: Props) => void;
|
|
104
|
+
/** Route an inbound frame to its node, by node type and frame op. */
|
|
105
|
+
dispatch: (frame: TreeFrame) => void;
|
|
106
|
+
/** Outbound. No-op until a sender is set. */
|
|
107
|
+
send: (frame: TreeFrame) => void;
|
|
108
|
+
setSender: (send: ((frame: TreeFrame) => void) | null) => void;
|
|
109
|
+
setResolve: (resolve: Resolve) => void;
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
export type TreeStore = StoreApi<TreeState & TreeActions>;
|
|
113
|
+
|
|
114
|
+
export type TreeStoreOptions = {
|
|
115
|
+
/** Behaviour lookup by type name. The kit registry supplies this. */
|
|
116
|
+
resolve?: Resolve;
|
|
117
|
+
send?: (frame: TreeFrame) => void;
|
|
118
|
+
onError?: (message: string, path: Path) => void;
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
export function emptyNode(type: string | null = null): Node {
|
|
122
|
+
return { type, props: {}, children: new Map() };
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function isPlainProps(v: unknown): v is Props {
|
|
126
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** A write payload as props: an object merges, anything else lands on `value`. */
|
|
130
|
+
export function asProps(payload: unknown): Props {
|
|
131
|
+
return isPlainProps(payload) ? payload : { value: payload };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** The chain a frame carries, or an untyped one built from its ref. */
|
|
135
|
+
export function frameChain(frame: TreeFrame): ChainStep[] {
|
|
136
|
+
if (frame.chain) return frame.chain;
|
|
137
|
+
return frame.ref.map((segment) => [segment, null] as ChainStep);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Pure lookup, handy for selectors over a state snapshot. */
|
|
141
|
+
export function getNode(root: Node, path: Path): Node | null {
|
|
142
|
+
let node: Node = root;
|
|
143
|
+
for (const segment of path) {
|
|
144
|
+
const next = node.children.get(segment);
|
|
145
|
+
if (!next) return null;
|
|
146
|
+
node = next;
|
|
147
|
+
}
|
|
148
|
+
return node;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// Post-order: a child tears down before its parent. The node is snapshotted
|
|
152
|
+
// out of the draft first -- disposals run after the set returns, by which
|
|
153
|
+
// point a draft proxy is dead.
|
|
154
|
+
function collectDispose(draftNode: Node, path: Path, out: DisposeCtx[]): void {
|
|
155
|
+
walkDispose(isDraft(draftNode) ? (current(draftNode) as Node) : draftNode, path, out);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function walkDispose(node: Node, path: Path, out: DisposeCtx[]): void {
|
|
159
|
+
for (const [segment, child] of node.children) {
|
|
160
|
+
walkDispose(child, [...path, segment], out);
|
|
161
|
+
}
|
|
162
|
+
if (node.type !== null) out.push({ path, node });
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export function createTreeStore(options: TreeStoreOptions = {}): TreeStore {
|
|
166
|
+
let resolve: Resolve = options.resolve ?? (() => undefined);
|
|
167
|
+
let outbound = options.send ?? null;
|
|
168
|
+
const onError =
|
|
169
|
+
options.onError ??
|
|
170
|
+
((message: string, path: Path) => console.error(`nu.ui [${path.join(" / ")}]: ${message}`));
|
|
171
|
+
|
|
172
|
+
// Disposals are collected inside a draft and run after the set returns, so
|
|
173
|
+
// a dispose is free to touch the store without writing into a dead draft.
|
|
174
|
+
let pending: DisposeCtx[] = [];
|
|
175
|
+
const flushDispose = () => {
|
|
176
|
+
const batch = pending;
|
|
177
|
+
pending = [];
|
|
178
|
+
for (const ctx of batch) {
|
|
179
|
+
const behaviour = ctx.node.type ? resolve(ctx.node.type) : undefined;
|
|
180
|
+
if (!behaviour?.dispose) continue;
|
|
181
|
+
try {
|
|
182
|
+
behaviour.dispose(ctx);
|
|
183
|
+
} catch (err) {
|
|
184
|
+
console.warn(`nu.ui: dispose threw for ${ctx.path.join(" / ")}`, err);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
const store: TreeStore = createStore<TreeState & TreeActions>()(
|
|
190
|
+
immer((set, get) => ({
|
|
191
|
+
root: emptyNode(),
|
|
192
|
+
|
|
193
|
+
write: (chain, props) => {
|
|
194
|
+
const path = chain.map((step) => step[0]);
|
|
195
|
+
// One existence probe first. When the leaf is already there with
|
|
196
|
+
// the right type, everything above it is too, so the walk is
|
|
197
|
+
// skipped and only the payload lands.
|
|
198
|
+
const existing = getNode(get().root, path);
|
|
199
|
+
const leafType = chain.length ? (chain[chain.length - 1][1] ?? null) : null;
|
|
200
|
+
if (existing && (leafType === null || existing.type === leafType)) {
|
|
201
|
+
if (props && Object.keys(props).length) get().setProps(path, props);
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
set((draft) => {
|
|
205
|
+
let node = draft.root as Node;
|
|
206
|
+
const here: Path = [];
|
|
207
|
+
for (const [segment, rawType, stepProps] of chain) {
|
|
208
|
+
here.push(segment);
|
|
209
|
+
const type = rawType ?? null;
|
|
210
|
+
let child: Node | undefined = node.children.get(segment);
|
|
211
|
+
// A level whose type changes is rebuilt, not patched:
|
|
212
|
+
// its old props and children go, and the branch disposes.
|
|
213
|
+
if (child && type !== null && child.type !== null && child.type !== type) {
|
|
214
|
+
collectDispose(child, [...here], pending);
|
|
215
|
+
child = undefined;
|
|
216
|
+
}
|
|
217
|
+
if (!child) {
|
|
218
|
+
child = emptyNode(type);
|
|
219
|
+
if (stepProps) Object.assign(child.props, stepProps);
|
|
220
|
+
// `set` on a key already there keeps its slot, so a
|
|
221
|
+
// rebuilt level does not jump to the end.
|
|
222
|
+
node.children.set(segment, child);
|
|
223
|
+
} else if (child.type === null && type !== null) {
|
|
224
|
+
// Autovivified earlier by something below it, so it
|
|
225
|
+
// never got its declared props. This write names its
|
|
226
|
+
// type, which is when it really comes into being.
|
|
227
|
+
child.type = type;
|
|
228
|
+
if (stepProps) Object.assign(child.props, stepProps);
|
|
229
|
+
}
|
|
230
|
+
// Otherwise: the level is already there with the right
|
|
231
|
+
// type. The chain says nothing new about it.
|
|
232
|
+
node = child;
|
|
233
|
+
}
|
|
234
|
+
if (props) Object.assign(node.props, props);
|
|
235
|
+
});
|
|
236
|
+
flushDispose();
|
|
237
|
+
},
|
|
238
|
+
|
|
239
|
+
remove: (path) => {
|
|
240
|
+
if (!path.length) {
|
|
241
|
+
set((draft) => {
|
|
242
|
+
collectDispose(draft.root as Node, [], pending);
|
|
243
|
+
draft.root = emptyNode();
|
|
244
|
+
});
|
|
245
|
+
flushDispose();
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
const parentPath = path.slice(0, -1);
|
|
249
|
+
const segment = path[path.length - 1];
|
|
250
|
+
set((draft) => {
|
|
251
|
+
const parent = getNode(draft.root as Node, parentPath);
|
|
252
|
+
const node = parent?.children.get(segment);
|
|
253
|
+
if (!parent || !node) return;
|
|
254
|
+
collectDispose(node, path, pending);
|
|
255
|
+
parent.children.delete(segment);
|
|
256
|
+
});
|
|
257
|
+
flushDispose();
|
|
258
|
+
},
|
|
259
|
+
|
|
260
|
+
getIn: (path) => getNode(get().root, path),
|
|
261
|
+
|
|
262
|
+
setProps: (path, props) =>
|
|
263
|
+
set((draft) => {
|
|
264
|
+
const node = getNode(draft.root as Node, path);
|
|
265
|
+
if (!node) return;
|
|
266
|
+
Object.assign(node.props, props);
|
|
267
|
+
}),
|
|
268
|
+
|
|
269
|
+
send: (frame) => {
|
|
270
|
+
if (outbound) outbound(frame);
|
|
271
|
+
},
|
|
272
|
+
|
|
273
|
+
setSender: (sender) => {
|
|
274
|
+
outbound = sender;
|
|
275
|
+
},
|
|
276
|
+
|
|
277
|
+
setResolve: (next) => {
|
|
278
|
+
resolve = next;
|
|
279
|
+
},
|
|
280
|
+
|
|
281
|
+
dispatch: (frame) => {
|
|
282
|
+
const api = get();
|
|
283
|
+
if (frame.op === OPS.remove) {
|
|
284
|
+
api.remove(frame.ref);
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
const chain = frameChain(frame);
|
|
288
|
+
if (frame.op === OPS.init) {
|
|
289
|
+
// Structure and nothing else. An init carries no payload, so
|
|
290
|
+
// it never touches a value the program already set.
|
|
291
|
+
api.write(chain);
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
const handlerFor = (node: Node | null) => {
|
|
295
|
+
const behaviour = node?.type ? resolve(node.type) : undefined;
|
|
296
|
+
return behaviour?.handlers?.[frame.op];
|
|
297
|
+
};
|
|
298
|
+
if (frame.op === OPS.write) {
|
|
299
|
+
// Structure first, always: the node may not exist yet, so
|
|
300
|
+
// the chain runs before anything can be looked up by type.
|
|
301
|
+
api.write(chain);
|
|
302
|
+
const written = api.getIn(frame.ref);
|
|
303
|
+
if (!written) return;
|
|
304
|
+
const custom = handlerFor(written);
|
|
305
|
+
if (custom) {
|
|
306
|
+
// The type owns what its payload means.
|
|
307
|
+
custom(makeCtx(store, frame, written), frame.payload);
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
if (frame.payload !== undefined) {
|
|
311
|
+
api.setProps(frame.ref, asProps(frame.payload));
|
|
312
|
+
}
|
|
313
|
+
return;
|
|
314
|
+
}
|
|
315
|
+
// Any other op that carries a chain brings its node into being
|
|
316
|
+
// first, the same way a write does: a Card's `set_title` may be
|
|
317
|
+
// the first frame that ever names that Card. A frame with no
|
|
318
|
+
// chain is addressed at a node that should already be there.
|
|
319
|
+
if (frame.chain) api.write(chain);
|
|
320
|
+
const node = api.getIn(frame.ref);
|
|
321
|
+
if (!node) {
|
|
322
|
+
onError(`no node for op "${frame.op}"`, frame.ref);
|
|
323
|
+
return;
|
|
324
|
+
}
|
|
325
|
+
const handler = handlerFor(node);
|
|
326
|
+
if (handler) {
|
|
327
|
+
handler(makeCtx(store, frame, node), frame.payload);
|
|
328
|
+
return;
|
|
329
|
+
}
|
|
330
|
+
if (frame.op === OPS.read) {
|
|
331
|
+
// The server is asking for our current value. Same id back
|
|
332
|
+
// so its future resolves.
|
|
333
|
+
api.send({
|
|
334
|
+
op: OPS.read,
|
|
335
|
+
ref: frame.ref,
|
|
336
|
+
payload: node.props.value ?? null,
|
|
337
|
+
id: frame.id,
|
|
338
|
+
});
|
|
339
|
+
return;
|
|
340
|
+
}
|
|
341
|
+
onError(`op "${frame.op}" not supported by ${node.type ?? "untyped node"}`, frame.ref);
|
|
342
|
+
},
|
|
343
|
+
})),
|
|
344
|
+
);
|
|
345
|
+
|
|
346
|
+
return store;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
function makeCtx(store: TreeStore, frame: TreeFrame, node: Node): NodeCtx {
|
|
350
|
+
const path = frame.ref;
|
|
351
|
+
return {
|
|
352
|
+
path,
|
|
353
|
+
node,
|
|
354
|
+
frame,
|
|
355
|
+
store,
|
|
356
|
+
update: (mutate) => {
|
|
357
|
+
const current = store.getState().getIn(path);
|
|
358
|
+
const next: Props = { ...(current?.props ?? node.props) };
|
|
359
|
+
mutate(next);
|
|
360
|
+
store.getState().setProps(path, next);
|
|
361
|
+
},
|
|
362
|
+
send: (op, payload, id) => store.getState().send({ op, ref: path, payload, id }),
|
|
363
|
+
};
|
|
364
|
+
}
|