@nustackdev/ui-core 0.2.1 → 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 +1 -1
- package/src/index.ts +1 -0
- package/src/order.test.ts +226 -0
- package/src/order.ts +229 -0
- package/src/protocol.ts +5 -2
- package/src/tree.test.ts +177 -28
- package/src/tree.ts +119 -27
package/package.json
CHANGED
package/src/index.ts
CHANGED
|
@@ -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`
|
|
7
|
-
//
|
|
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("
|
|
101
|
-
const
|
|
102
|
-
const
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
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().
|
|
109
|
+
const before = store.getState().root;
|
|
109
110
|
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
expect(store.getState().
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
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", "
|
|
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
|
-
|
|
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", "
|
|
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 }]);
|
|
@@ -408,6 +421,142 @@ describe("dispatch", () => {
|
|
|
408
421
|
});
|
|
409
422
|
});
|
|
410
423
|
|
|
424
|
+
describe("visibility", () => {
|
|
425
|
+
it("hides a node and keeps its props and children", () => {
|
|
426
|
+
const store = createTreeStore();
|
|
427
|
+
store.getState().write([step("a", "Card", { title: "T" }), step("b", "TextRef")], { value: "x" });
|
|
428
|
+
store.getState().dispatch(frame(OPS.hide, ["a"], null, [step("a", "Card", { title: "T" })]));
|
|
429
|
+
const a = store.getState().getIn(["a"]);
|
|
430
|
+
expect(a?.hidden).toBe(true);
|
|
431
|
+
expect(a?.props).toEqual({ title: "T" });
|
|
432
|
+
expect(store.getState().getIn(["a", "b"])?.props).toEqual({ value: "x" });
|
|
433
|
+
});
|
|
434
|
+
|
|
435
|
+
it("shows it again on display", () => {
|
|
436
|
+
const store = createTreeStore();
|
|
437
|
+
store.getState().write([step("a", "TextRef")]);
|
|
438
|
+
store.getState().dispatch(frame(OPS.hide, ["a"], null, [step("a", "TextRef")]));
|
|
439
|
+
store.getState().dispatch(frame(OPS.display, ["a"], null, [step("a", "TextRef")]));
|
|
440
|
+
expect(store.getState().getIn(["a"])?.hidden).toBeUndefined();
|
|
441
|
+
});
|
|
442
|
+
|
|
443
|
+
it("brings a node into being hidden when the hide is the first frame", () => {
|
|
444
|
+
const store = createTreeStore();
|
|
445
|
+
store.getState().dispatch(
|
|
446
|
+
frame(OPS.hide, ["a", "b"], null, [step("a", "Column"), step("b", "TextRef", { value: "seed" })]),
|
|
447
|
+
);
|
|
448
|
+
const b = store.getState().getIn(["a", "b"]);
|
|
449
|
+
expect(b?.type).toBe("TextRef");
|
|
450
|
+
expect(b?.props).toEqual({ value: "seed" });
|
|
451
|
+
expect(b?.hidden).toBe(true);
|
|
452
|
+
expect(store.getState().getIn(["a"])?.hidden).toBeUndefined();
|
|
453
|
+
});
|
|
454
|
+
|
|
455
|
+
it("keeps the flag through prop merges and a type's own write handler", () => {
|
|
456
|
+
const behaviours: Record<string, Behaviour> = {
|
|
457
|
+
HeadingRef: {
|
|
458
|
+
handlers: {
|
|
459
|
+
write: (ctx, payload) =>
|
|
460
|
+
ctx.update((props) => {
|
|
461
|
+
props.label = String(payload);
|
|
462
|
+
}),
|
|
463
|
+
},
|
|
464
|
+
},
|
|
465
|
+
};
|
|
466
|
+
const store = createTreeStore({ resolve: (t) => behaviours[t] });
|
|
467
|
+
store.getState().write([step("h", "HeadingRef"), step("t", "TextRef")]);
|
|
468
|
+
store.getState().dispatch(frame(OPS.hide, ["h"], null, [step("h", "HeadingRef")]));
|
|
469
|
+
store.getState().dispatch(frame(OPS.hide, ["h", "t"], null, [step("h", "HeadingRef"), step("t", "TextRef")]));
|
|
470
|
+
store.getState().dispatch(frame(OPS.write, ["h"], "hello", [step("h", "HeadingRef")]));
|
|
471
|
+
store.getState().dispatch(
|
|
472
|
+
frame(OPS.write, ["h", "t"], { value: 1, hidden: false }, [step("h", "HeadingRef"), step("t", "TextRef")]),
|
|
473
|
+
);
|
|
474
|
+
expect(store.getState().getIn(["h"])?.hidden).toBe(true);
|
|
475
|
+
expect(store.getState().getIn(["h"])?.props.label).toBe("hello");
|
|
476
|
+
expect(store.getState().getIn(["h", "t"])?.hidden).toBe(true);
|
|
477
|
+
});
|
|
478
|
+
|
|
479
|
+
it("never asks a type's handlers", () => {
|
|
480
|
+
const errors: string[] = [];
|
|
481
|
+
const hide = vi.fn();
|
|
482
|
+
const behaviours: Record<string, Behaviour> = { TextRef: { handlers: { hide } } };
|
|
483
|
+
const store = createTreeStore({ resolve: (t) => behaviours[t], onError: (m) => errors.push(m) });
|
|
484
|
+
store.getState().write([step("a", "TextRef")]);
|
|
485
|
+
store.getState().dispatch(frame(OPS.hide, ["a"], null, [step("a", "TextRef")]));
|
|
486
|
+
expect(hide).not.toHaveBeenCalled();
|
|
487
|
+
expect(errors).toEqual([]);
|
|
488
|
+
});
|
|
489
|
+
|
|
490
|
+
it("leaves an untouched node's identity alone on a repeat", () => {
|
|
491
|
+
const store = createTreeStore();
|
|
492
|
+
store.getState().write([step("a", "TextRef")]);
|
|
493
|
+
store.getState().dispatch(frame(OPS.hide, ["a"], null, [step("a", "TextRef")]));
|
|
494
|
+
const root = store.getState().root;
|
|
495
|
+
store.getState().dispatch(frame(OPS.hide, ["a"], null, [step("a", "TextRef")]));
|
|
496
|
+
expect(store.getState().root).toBe(root);
|
|
497
|
+
});
|
|
498
|
+
|
|
499
|
+
it("still removes a hidden node", () => {
|
|
500
|
+
const store = createTreeStore();
|
|
501
|
+
store.getState().write([step("a", "TextRef")]);
|
|
502
|
+
store.getState().dispatch(frame(OPS.hide, ["a"], null, [step("a", "TextRef")]));
|
|
503
|
+
store.getState().dispatch(frame(OPS.remove, ["a"]));
|
|
504
|
+
expect(store.getState().getIn(["a"])).toBeNull();
|
|
505
|
+
});
|
|
506
|
+
});
|
|
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
|
+
|
|
411
560
|
describe("send", () => {
|
|
412
561
|
it("drops frames until a sender is set, then delivers", () => {
|
|
413
562
|
const sent: TreeFrame[] = [];
|
package/src/tree.ts
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
// The browser store, as a tree.
|
|
2
2
|
//
|
|
3
|
-
// One node is
|
|
4
|
-
// keyed by segment
|
|
5
|
-
//
|
|
6
|
-
// own -- a node's current value
|
|
3
|
+
// One node is three things: a `type`, a bag of `props`, and `children`
|
|
4
|
+
// keyed by segment (plus the `hidden` flag the visibility ops set). `type` is
|
|
5
|
+
// null for a node that exists only because something below it was written.
|
|
6
|
+
// `value` is just a prop, not a field of its own -- a node's current value
|
|
7
|
+
// lives at `props.value` like everything else.
|
|
7
8
|
//
|
|
8
9
|
// Writes autovivify. A frame carries a `chain`, root-first, one triple per
|
|
9
10
|
// level, so a write to `a.b.c` creates `a` and `b` with the type and props
|
|
@@ -11,12 +12,17 @@
|
|
|
11
12
|
// mounted ahead of time and there is no fields list. Chain props are a seed
|
|
12
13
|
// for a level being created, never an update to one already there.
|
|
13
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
|
+
//
|
|
14
20
|
// React-free on purpose: this is zustand's vanilla store, so core stays usable
|
|
15
21
|
// from a worker, a test, or anywhere else with no DOM. The React bindings and
|
|
16
22
|
// the component registry live in the kit.
|
|
17
23
|
|
|
18
24
|
import { current, enableMapSet, isDraft } from "immer";
|
|
19
|
-
import type
|
|
25
|
+
import { type ChainLevel, type ErrorPayload, type Frame, OP_ERROR } from "./protocol";
|
|
20
26
|
import { createStore, type StoreApi } from "zustand/vanilla";
|
|
21
27
|
import { immer } from "zustand/middleware/immer";
|
|
22
28
|
|
|
@@ -31,10 +37,14 @@ export type Props = Record<string, unknown>;
|
|
|
31
37
|
// A Map and not a plain object: render order is insertion order, and an
|
|
32
38
|
// object hoists integer-like keys to the front, so a segment like "0" or an
|
|
33
39
|
// index from a dynamic ref would silently jump the queue.
|
|
40
|
+
//
|
|
41
|
+
// `hidden` lives on the node and not in its props, so no prop merge and no
|
|
42
|
+
// type's own write handler can clobber it. Unset means shown.
|
|
34
43
|
export type Node = {
|
|
35
44
|
type: string | null;
|
|
36
45
|
props: Props;
|
|
37
46
|
children: Map<string, Node>;
|
|
47
|
+
hidden?: boolean;
|
|
38
48
|
};
|
|
39
49
|
|
|
40
50
|
/** Alias for consumers where the DOM's `Node` is also in scope. */
|
|
@@ -63,6 +73,11 @@ export const OPS = {
|
|
|
63
73
|
// write to it. What a boot batch is made of.
|
|
64
74
|
init: "init",
|
|
65
75
|
remove: "remove",
|
|
76
|
+
// Chain only, no payload, like init. Hide keeps the node, its props and
|
|
77
|
+
// its children (state survives, the browser just draws nothing); display
|
|
78
|
+
// shows it again. Every type takes them, none handles them.
|
|
79
|
+
hide: "hide",
|
|
80
|
+
display: "display",
|
|
66
81
|
read: "read",
|
|
67
82
|
notify: "notify",
|
|
68
83
|
} as const;
|
|
@@ -94,13 +109,19 @@ export type Resolve = (type: string) => Behaviour | undefined;
|
|
|
94
109
|
export type TreeState = { root: Node };
|
|
95
110
|
|
|
96
111
|
export type TreeActions = {
|
|
97
|
-
/**
|
|
98
|
-
|
|
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;
|
|
99
118
|
/** Drop a subtree, running dispose down the branch. Server-driven only. */
|
|
100
119
|
remove: (path: Path) => void;
|
|
101
120
|
getIn: (path: Path) => Node | null;
|
|
102
121
|
/** Merge props into an existing node. No-op when the node is not there. */
|
|
103
122
|
setProps: (path: Path, props: Props) => void;
|
|
123
|
+
/** Hide or show an existing node. No-op when the node is not there. */
|
|
124
|
+
setHidden: (path: Path, hidden: boolean) => void;
|
|
104
125
|
/** Route an inbound frame to its node, by node type and frame op. */
|
|
105
126
|
dispatch: (frame: TreeFrame) => void;
|
|
106
127
|
/** Outbound. No-op until a sender is set. */
|
|
@@ -137,6 +158,35 @@ export function frameChain(frame: TreeFrame): ChainStep[] {
|
|
|
137
158
|
return frame.ref.map((segment) => [segment, null] as ChainStep);
|
|
138
159
|
}
|
|
139
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
|
+
|
|
140
190
|
/** Pure lookup, handy for selectors over a state snapshot. */
|
|
141
191
|
export function getNode(root: Node, path: Path): Node | null {
|
|
142
192
|
let node: Node = root;
|
|
@@ -192,14 +242,20 @@ export function createTreeStore(options: TreeStoreOptions = {}): TreeStore {
|
|
|
192
242
|
|
|
193
243
|
write: (chain, props) => {
|
|
194
244
|
const path = chain.map((step) => step[0]);
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
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.
|
|
198
252
|
const existing = getNode(get().root, path);
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
if (
|
|
202
|
-
|
|
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
|
+
}
|
|
203
259
|
}
|
|
204
260
|
set((draft) => {
|
|
205
261
|
let node = draft.root as Node;
|
|
@@ -208,18 +264,10 @@ export function createTreeStore(options: TreeStoreOptions = {}): TreeStore {
|
|
|
208
264
|
here.push(segment);
|
|
209
265
|
const type = rawType ?? null;
|
|
210
266
|
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
267
|
if (!child) {
|
|
218
268
|
child = emptyNode(type);
|
|
219
269
|
if (stepProps) Object.assign(child.props, stepProps);
|
|
220
|
-
|
|
221
|
-
// rebuilt level does not jump to the end.
|
|
222
|
-
node.children.set(segment, child);
|
|
270
|
+
node.children.set(segment, child);
|
|
223
271
|
} else if (child.type === null && type !== null) {
|
|
224
272
|
// Autovivified earlier by something below it, so it
|
|
225
273
|
// never got its declared props. This write names its
|
|
@@ -233,7 +281,7 @@ export function createTreeStore(options: TreeStoreOptions = {}): TreeStore {
|
|
|
233
281
|
}
|
|
234
282
|
if (props) Object.assign(node.props, props);
|
|
235
283
|
});
|
|
236
|
-
|
|
284
|
+
return true;
|
|
237
285
|
},
|
|
238
286
|
|
|
239
287
|
remove: (path) => {
|
|
@@ -266,6 +314,17 @@ export function createTreeStore(options: TreeStoreOptions = {}): TreeStore {
|
|
|
266
314
|
Object.assign(node.props, props);
|
|
267
315
|
}),
|
|
268
316
|
|
|
317
|
+
setHidden: (path, hidden) => {
|
|
318
|
+
const node = getNode(get().root, path);
|
|
319
|
+
if (!node || Boolean(node.hidden) === hidden) return;
|
|
320
|
+
set((draft) => {
|
|
321
|
+
const target = getNode(draft.root as Node, path);
|
|
322
|
+
if (!target) return;
|
|
323
|
+
if (hidden) target.hidden = true;
|
|
324
|
+
else delete target.hidden;
|
|
325
|
+
});
|
|
326
|
+
},
|
|
327
|
+
|
|
269
328
|
send: (frame) => {
|
|
270
329
|
if (outbound) outbound(frame);
|
|
271
330
|
},
|
|
@@ -280,6 +339,23 @@ export function createTreeStore(options: TreeStoreOptions = {}): TreeStore {
|
|
|
280
339
|
|
|
281
340
|
dispatch: (frame) => {
|
|
282
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
|
+
};
|
|
283
359
|
if (frame.op === OPS.remove) {
|
|
284
360
|
api.remove(frame.ref);
|
|
285
361
|
return;
|
|
@@ -288,7 +364,17 @@ export function createTreeStore(options: TreeStoreOptions = {}): TreeStore {
|
|
|
288
364
|
if (frame.op === OPS.init) {
|
|
289
365
|
// Structure and nothing else. An init carries no payload, so
|
|
290
366
|
// it never touches a value the program already set.
|
|
291
|
-
api.write(chain);
|
|
367
|
+
if (!api.write(chain)) refuse();
|
|
368
|
+
return;
|
|
369
|
+
}
|
|
370
|
+
if (frame.op === OPS.hide || frame.op === OPS.display) {
|
|
371
|
+
// Structure first (the node may not exist yet), then the
|
|
372
|
+
// flag. Generic for every type, never a handler's call.
|
|
373
|
+
if (!api.write(chain)) {
|
|
374
|
+
refuse();
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
377
|
+
api.setHidden(frame.ref, frame.op === OPS.hide);
|
|
292
378
|
return;
|
|
293
379
|
}
|
|
294
380
|
const handlerFor = (node: Node | null) => {
|
|
@@ -298,7 +384,10 @@ export function createTreeStore(options: TreeStoreOptions = {}): TreeStore {
|
|
|
298
384
|
if (frame.op === OPS.write) {
|
|
299
385
|
// Structure first, always: the node may not exist yet, so
|
|
300
386
|
// the chain runs before anything can be looked up by type.
|
|
301
|
-
api.write(chain)
|
|
387
|
+
if (!api.write(chain)) {
|
|
388
|
+
refuse();
|
|
389
|
+
return;
|
|
390
|
+
}
|
|
302
391
|
const written = api.getIn(frame.ref);
|
|
303
392
|
if (!written) return;
|
|
304
393
|
const custom = handlerFor(written);
|
|
@@ -316,7 +405,10 @@ export function createTreeStore(options: TreeStoreOptions = {}): TreeStore {
|
|
|
316
405
|
// first, the same way a write does: a Card's `set_title` may be
|
|
317
406
|
// the first frame that ever names that Card. A frame with no
|
|
318
407
|
// chain is addressed at a node that should already be there.
|
|
319
|
-
if (frame.chain
|
|
408
|
+
if (frame.chain && !api.write(chain)) {
|
|
409
|
+
refuse();
|
|
410
|
+
return;
|
|
411
|
+
}
|
|
320
412
|
const node = api.getIn(frame.ref);
|
|
321
413
|
if (!node) {
|
|
322
414
|
onError(`no node for op "${frame.op}"`, frame.ref);
|