@nustackdev/ui-core 0.2.2 → 0.2.4
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 +107 -28
- package/src/tree.ts +99 -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];
|
|
@@ -73,6 +74,18 @@ describe("write", () => {
|
|
|
73
74
|
expect(segments(store.getState().getIn(["sec"]))).toEqual(["t", "u"]);
|
|
74
75
|
});
|
|
75
76
|
|
|
77
|
+
it("keeps the declared props as the node's seed, untouched by later writes", () => {
|
|
78
|
+
const store = createTreeStore();
|
|
79
|
+
store.getState().write([step("f", "Form"), step("title", "InputRef", { value: "seed" })]);
|
|
80
|
+
store.getState().setProps(["f", "title"], { value: "typed" });
|
|
81
|
+
store.getState().write([step("f", "Form"), step("title", "InputRef", { value: "seed" })], {
|
|
82
|
+
value: "written",
|
|
83
|
+
});
|
|
84
|
+
const node = store.getState().getIn(["f", "title"]);
|
|
85
|
+
expect(node?.props.value).toBe("written");
|
|
86
|
+
expect(node?.seed).toEqual({ value: "seed" });
|
|
87
|
+
});
|
|
88
|
+
|
|
76
89
|
it("keeps a prop set at runtime when a deep write rides through", () => {
|
|
77
90
|
const store = createTreeStore();
|
|
78
91
|
const chain = [
|
|
@@ -97,25 +110,45 @@ describe("write", () => {
|
|
|
97
110
|
expect(store.getState().getIn(["sec", "t"])?.props).toEqual({ value: "x" });
|
|
98
111
|
});
|
|
99
112
|
|
|
100
|
-
it("
|
|
101
|
-
const
|
|
102
|
-
const
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
113
|
+
it("refuses a write naming another kind for a node already there", () => {
|
|
114
|
+
const errors: [string, string[]][] = [];
|
|
115
|
+
const dispose = vi.fn();
|
|
116
|
+
const store = createTreeStore({
|
|
117
|
+
resolve: () => ({ dispose }),
|
|
118
|
+
onError: (message, path) => errors.push([message, path]),
|
|
119
|
+
});
|
|
107
120
|
store.getState().write([step("sec", "Card", { title: "One" }), step("t", "TextRef")]);
|
|
108
|
-
store.getState().
|
|
121
|
+
const before = store.getState().root;
|
|
109
122
|
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
expect(store.getState().
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
123
|
+
const applied = store.getState().write([step("sec", "Modal", { open: true })], { open: true });
|
|
124
|
+
|
|
125
|
+
expect(applied).toBe(false);
|
|
126
|
+
// Nothing of the refused write lands, and nothing is torn down.
|
|
127
|
+
expect(store.getState().root).toBe(before);
|
|
128
|
+
expect(dispose).not.toHaveBeenCalled();
|
|
129
|
+
expect(errors).toHaveLength(1);
|
|
130
|
+
expect(errors[0][0]).toContain("kind mismatch at sec: the node is Card, the write names Modal");
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
it("refuses a mismatch above a leaf that is already there", () => {
|
|
134
|
+
const errors: string[] = [];
|
|
135
|
+
const store = createTreeStore({ onError: (message) => errors.push(message) });
|
|
136
|
+
store.getState().write([step("a", "Card"), step("t", "TextRef", { value: "x" })]);
|
|
137
|
+
|
|
138
|
+
const applied = store.getState().write([step("a", "Grid"), step("t", "TextRef")], { value: "y" });
|
|
139
|
+
|
|
140
|
+
expect(applied).toBe(false);
|
|
141
|
+
expect(store.getState().getIn(["a", "t"])?.props).toEqual({ value: "x" });
|
|
142
|
+
expect(errors[0]).toContain("kind mismatch at a: the node is Card, the write names Grid");
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
it("puts another kind at an address once the old node is removed", () => {
|
|
146
|
+
const store = createTreeStore({ onError: () => {} });
|
|
147
|
+
store.getState().write([step("a", "TextRef"), step("x", "TextRef")]);
|
|
148
|
+
store.getState().write([step("b", "TextRef")]);
|
|
149
|
+
store.getState().remove(["a"]);
|
|
150
|
+
expect(store.getState().write([step("a", "Card")])).toBe(true);
|
|
151
|
+
expect(store.getState().getIn(["a"])?.type).toBe("Card");
|
|
119
152
|
});
|
|
120
153
|
|
|
121
154
|
it("keeps a node whose write does not name a type", () => {
|
|
@@ -126,6 +159,7 @@ describe("write", () => {
|
|
|
126
159
|
type: "InputRef",
|
|
127
160
|
props: { value: "y" },
|
|
128
161
|
children: new Map(),
|
|
162
|
+
seed: { value: "x" },
|
|
129
163
|
});
|
|
130
164
|
});
|
|
131
165
|
|
|
@@ -147,14 +181,6 @@ describe("write", () => {
|
|
|
147
181
|
expect(segments(store.getState().getIn(["box"]))).toEqual(["z", "0", "a", "1"]);
|
|
148
182
|
});
|
|
149
183
|
|
|
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
184
|
it("writes into the root with an empty chain", () => {
|
|
159
185
|
const store = createTreeStore();
|
|
160
186
|
store.getState().write([], { title: "root" });
|
|
@@ -260,7 +286,7 @@ describe("dispatch", () => {
|
|
|
260
286
|
|
|
261
287
|
it("lands a list payload on value rather than spreading it", () => {
|
|
262
288
|
const store = createTreeStore();
|
|
263
|
-
store.getState().dispatch(frame(OPS.write, ["a"], [1, 2, 3], [step("a", "
|
|
289
|
+
store.getState().dispatch(frame(OPS.write, ["a"], [1, 2, 3], [step("a", "DataTableRef")]));
|
|
264
290
|
expect(store.getState().getIn(["a"])?.props).toEqual({ value: [1, 2, 3] });
|
|
265
291
|
});
|
|
266
292
|
|
|
@@ -283,12 +309,13 @@ describe("dispatch", () => {
|
|
|
283
309
|
type: "InputRef",
|
|
284
310
|
props: { label: "L", value: "typed" },
|
|
285
311
|
children: new Map(),
|
|
312
|
+
seed: { label: "L" },
|
|
286
313
|
});
|
|
287
314
|
});
|
|
288
315
|
|
|
289
316
|
it("routes an op to the handler for the node's type", () => {
|
|
290
317
|
const behaviours: Record<string, Behaviour> = {
|
|
291
|
-
|
|
318
|
+
DataTableRef: {
|
|
292
319
|
handlers: {
|
|
293
320
|
append: (ctx, payload) =>
|
|
294
321
|
ctx.update((props) => {
|
|
@@ -298,7 +325,7 @@ describe("dispatch", () => {
|
|
|
298
325
|
},
|
|
299
326
|
};
|
|
300
327
|
const store = createTreeStore({ resolve: (t) => behaviours[t] });
|
|
301
|
-
store.getState().write([step("t", "
|
|
328
|
+
store.getState().write([step("t", "DataTableRef", { rows: [] })]);
|
|
302
329
|
store.getState().dispatch(frame("append", ["t"], { id: 1 }));
|
|
303
330
|
store.getState().dispatch(frame("append", ["t"], { id: 2 }));
|
|
304
331
|
expect(store.getState().getIn(["t"])?.props.rows).toEqual([{ id: 1 }, { id: 2 }]);
|
|
@@ -492,6 +519,58 @@ describe("visibility", () => {
|
|
|
492
519
|
});
|
|
493
520
|
});
|
|
494
521
|
|
|
522
|
+
describe("kind mismatch", () => {
|
|
523
|
+
it("answers a refused write with an error frame and runs no handler", () => {
|
|
524
|
+
const sent: TreeFrame[] = [];
|
|
525
|
+
const handler = vi.fn();
|
|
526
|
+
const store = createTreeStore({
|
|
527
|
+
resolve: (t) => (t === "Modal" ? { handlers: { write: handler } } : undefined),
|
|
528
|
+
onError: () => {},
|
|
529
|
+
});
|
|
530
|
+
store.getState().setSender((f) => sent.push(f));
|
|
531
|
+
store.getState().dispatch(frame(OPS.write, ["a"], "x", [step("a", "TextRef")]));
|
|
532
|
+
|
|
533
|
+
store.getState().dispatch(frame(OPS.write, ["a"], { open: true }, [step("a", "Modal")]));
|
|
534
|
+
|
|
535
|
+
expect(handler).not.toHaveBeenCalled();
|
|
536
|
+
expect(store.getState().getIn(["a"])).toEqual({
|
|
537
|
+
type: "TextRef",
|
|
538
|
+
props: { value: "x" },
|
|
539
|
+
children: new Map(),
|
|
540
|
+
});
|
|
541
|
+
expect(sent).toHaveLength(1);
|
|
542
|
+
expect(sent[0].op).toBe(OP_ERROR);
|
|
543
|
+
expect(sent[0].ref).toEqual(["a"]);
|
|
544
|
+
expect(sent[0].payload).toMatchObject({ code: "kind_mismatch" });
|
|
545
|
+
expect((sent[0].payload as { message: string }).message).toContain(
|
|
546
|
+
"the node is TextRef, the write names Modal",
|
|
547
|
+
);
|
|
548
|
+
});
|
|
549
|
+
|
|
550
|
+
it("refuses init, hide and custom ops the same way", () => {
|
|
551
|
+
const sent: TreeFrame[] = [];
|
|
552
|
+
const store = createTreeStore({ onError: () => {} });
|
|
553
|
+
store.getState().setSender((f) => sent.push(f));
|
|
554
|
+
store.getState().write([step("a", "Card")]);
|
|
555
|
+
|
|
556
|
+
store.getState().dispatch(frame(OPS.init, ["a"], null, [step("a", "Grid")]));
|
|
557
|
+
store.getState().dispatch(frame(OPS.hide, ["a"], null, [step("a", "Grid")]));
|
|
558
|
+
store.getState().dispatch(frame("set_span", ["a", "c"], [2, 1], [step("a", "Grid"), step("c")]));
|
|
559
|
+
|
|
560
|
+
expect(sent.map((f) => f.op)).toEqual([OP_ERROR, OP_ERROR, OP_ERROR]);
|
|
561
|
+
expect(store.getState().getIn(["a"])?.type).toBe("Card");
|
|
562
|
+
expect(store.getState().getIn(["a"])?.hidden).toBeUndefined();
|
|
563
|
+
expect(store.getState().getIn(["a", "c"])).toBeNull();
|
|
564
|
+
});
|
|
565
|
+
|
|
566
|
+
it("hands an inbound error frame to onError", () => {
|
|
567
|
+
const errors: [string, string[]][] = [];
|
|
568
|
+
const store = createTreeStore({ onError: (message, path) => errors.push([message, path]) });
|
|
569
|
+
store.getState().dispatch(frame(OP_ERROR, ["a"], { code: "internal", message: "boom" }));
|
|
570
|
+
expect(errors).toEqual([["server: boom", ["a"]]]);
|
|
571
|
+
});
|
|
572
|
+
});
|
|
573
|
+
|
|
495
574
|
describe("send", () => {
|
|
496
575
|
it("drops frames until a sender is set, then delivers", () => {
|
|
497
576
|
const sent: TreeFrame[] = [];
|
package/src/tree.ts
CHANGED
|
@@ -12,14 +12,19 @@
|
|
|
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";
|
|
21
|
-
import { createStore, type StoreApi } from "zustand/vanilla";
|
|
22
25
|
import { immer } from "zustand/middleware/immer";
|
|
26
|
+
import { createStore, type StoreApi } from "zustand/vanilla";
|
|
27
|
+
import { type ChainLevel, type ErrorPayload, type Frame, OP_ERROR } from "./protocol";
|
|
23
28
|
|
|
24
29
|
// `children` is a Map, and immer only drafts those once this is on.
|
|
25
30
|
enableMapSet();
|
|
@@ -40,6 +45,10 @@ export type Node = {
|
|
|
40
45
|
props: Props;
|
|
41
46
|
children: Map<string, Node>;
|
|
42
47
|
hidden?: boolean;
|
|
48
|
+
// The props the node's slot declared, as they came on the chain that
|
|
49
|
+
// created it. Never written after that, so a reset (an input back to its
|
|
50
|
+
// declared value) has something to go back to once the live props moved.
|
|
51
|
+
seed?: Props;
|
|
43
52
|
};
|
|
44
53
|
|
|
45
54
|
/** Alias for consumers where the DOM's `Node` is also in scope. */
|
|
@@ -104,8 +113,12 @@ export type Resolve = (type: string) => Behaviour | undefined;
|
|
|
104
113
|
export type TreeState = { root: Node };
|
|
105
114
|
|
|
106
115
|
export type TreeActions = {
|
|
107
|
-
/**
|
|
108
|
-
|
|
116
|
+
/**
|
|
117
|
+
* Walk the chain, creating what is missing, then merge `props` into the leaf.
|
|
118
|
+
* False when the chain names a kind other than a node's already there: the
|
|
119
|
+
* write is refused whole and `onError` has it.
|
|
120
|
+
*/
|
|
121
|
+
write: (chain: ChainStep[], props?: Props) => boolean;
|
|
109
122
|
/** Drop a subtree, running dispose down the branch. Server-driven only. */
|
|
110
123
|
remove: (path: Path) => void;
|
|
111
124
|
getIn: (path: Path) => Node | null;
|
|
@@ -149,6 +162,35 @@ export function frameChain(frame: TreeFrame): ChainStep[] {
|
|
|
149
162
|
return frame.ref.map((segment) => [segment, null] as ChainStep);
|
|
150
163
|
}
|
|
151
164
|
|
|
165
|
+
/** Where `chain` names a type other than the node already there has, or null. */
|
|
166
|
+
export function kindConflict(
|
|
167
|
+
root: Node,
|
|
168
|
+
chain: ChainStep[],
|
|
169
|
+
): { path: Path; have: string; want: string } | null {
|
|
170
|
+
let node: Node = root;
|
|
171
|
+
const here: Path = [];
|
|
172
|
+
for (const [segment, rawType] of chain) {
|
|
173
|
+
const child = node.children.get(segment);
|
|
174
|
+
if (!child) return null;
|
|
175
|
+
here.push(segment);
|
|
176
|
+
const want = rawType ?? null;
|
|
177
|
+
// An untyped side on either end is no claim: a synthesized chain names
|
|
178
|
+
// no type, and an autovivified level takes the first one named.
|
|
179
|
+
if (want !== null && child.type !== null && child.type !== want) {
|
|
180
|
+
return { path: [...here], have: child.type, want };
|
|
181
|
+
}
|
|
182
|
+
node = child;
|
|
183
|
+
}
|
|
184
|
+
return null;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function mismatch(conflict: { path: Path; have: string; want: string }): string {
|
|
188
|
+
return (
|
|
189
|
+
`kind mismatch at ${conflict.path.join(" / ")}: the node is ${conflict.have}, ` +
|
|
190
|
+
`the write names ${conflict.want}; remove it first to put another kind there`
|
|
191
|
+
);
|
|
192
|
+
}
|
|
193
|
+
|
|
152
194
|
/** Pure lookup, handy for selectors over a state snapshot. */
|
|
153
195
|
export function getNode(root: Node, path: Path): Node | null {
|
|
154
196
|
let node: Node = root;
|
|
@@ -204,14 +246,20 @@ export function createTreeStore(options: TreeStoreOptions = {}): TreeStore {
|
|
|
204
246
|
|
|
205
247
|
write: (chain, props) => {
|
|
206
248
|
const path = chain.map((step) => step[0]);
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
249
|
+
const conflict = kindConflict(get().root, chain);
|
|
250
|
+
if (conflict) {
|
|
251
|
+
onError(mismatch(conflict), path);
|
|
252
|
+
return false;
|
|
253
|
+
}
|
|
254
|
+
// When the leaf is already there, the conflict walk has seen every
|
|
255
|
+
// level above it agree, so only the payload lands.
|
|
210
256
|
const existing = getNode(get().root, path);
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
if (
|
|
214
|
-
|
|
257
|
+
if (existing) {
|
|
258
|
+
const leafType = chain.length ? (chain[chain.length - 1][1] ?? null) : null;
|
|
259
|
+
if (leafType === null || existing.type !== null) {
|
|
260
|
+
if (props && Object.keys(props).length) get().setProps(path, props);
|
|
261
|
+
return true;
|
|
262
|
+
}
|
|
215
263
|
}
|
|
216
264
|
set((draft) => {
|
|
217
265
|
let node = draft.root as Node;
|
|
@@ -220,24 +268,22 @@ export function createTreeStore(options: TreeStoreOptions = {}): TreeStore {
|
|
|
220
268
|
here.push(segment);
|
|
221
269
|
const type = rawType ?? null;
|
|
222
270
|
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
271
|
if (!child) {
|
|
230
272
|
child = emptyNode(type);
|
|
231
|
-
if (stepProps)
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
273
|
+
if (stepProps) {
|
|
274
|
+
Object.assign(child.props, stepProps);
|
|
275
|
+
child.seed = { ...stepProps };
|
|
276
|
+
}
|
|
277
|
+
node.children.set(segment, child);
|
|
235
278
|
} else if (child.type === null && type !== null) {
|
|
236
279
|
// Autovivified earlier by something below it, so it
|
|
237
280
|
// never got its declared props. This write names its
|
|
238
281
|
// type, which is when it really comes into being.
|
|
239
282
|
child.type = type;
|
|
240
|
-
if (stepProps)
|
|
283
|
+
if (stepProps) {
|
|
284
|
+
Object.assign(child.props, stepProps);
|
|
285
|
+
child.seed = { ...stepProps };
|
|
286
|
+
}
|
|
241
287
|
}
|
|
242
288
|
// Otherwise: the level is already there with the right
|
|
243
289
|
// type. The chain says nothing new about it.
|
|
@@ -245,7 +291,7 @@ export function createTreeStore(options: TreeStoreOptions = {}): TreeStore {
|
|
|
245
291
|
}
|
|
246
292
|
if (props) Object.assign(node.props, props);
|
|
247
293
|
});
|
|
248
|
-
|
|
294
|
+
return true;
|
|
249
295
|
},
|
|
250
296
|
|
|
251
297
|
remove: (path) => {
|
|
@@ -303,6 +349,23 @@ export function createTreeStore(options: TreeStoreOptions = {}): TreeStore {
|
|
|
303
349
|
|
|
304
350
|
dispatch: (frame) => {
|
|
305
351
|
const api = get();
|
|
352
|
+
if (frame.op === OP_ERROR) {
|
|
353
|
+
const payload = (frame.payload ?? {}) as Partial<ErrorPayload>;
|
|
354
|
+
onError(`server: ${payload.message ?? payload.code ?? "error"}`, frame.ref);
|
|
355
|
+
return;
|
|
356
|
+
}
|
|
357
|
+
// A chain the store refused never reaches a handler; the server
|
|
358
|
+
// hears why, since the write it sent did not land.
|
|
359
|
+
const refuse = () => {
|
|
360
|
+
const conflict = kindConflict(api.root, frameChain(frame));
|
|
361
|
+
const message = conflict ? mismatch(conflict) : "write refused";
|
|
362
|
+
api.send({
|
|
363
|
+
op: OP_ERROR,
|
|
364
|
+
ref: frame.ref,
|
|
365
|
+
payload: { code: "kind_mismatch", message } satisfies ErrorPayload,
|
|
366
|
+
id: frame.id,
|
|
367
|
+
});
|
|
368
|
+
};
|
|
306
369
|
if (frame.op === OPS.remove) {
|
|
307
370
|
api.remove(frame.ref);
|
|
308
371
|
return;
|
|
@@ -311,13 +374,16 @@ export function createTreeStore(options: TreeStoreOptions = {}): TreeStore {
|
|
|
311
374
|
if (frame.op === OPS.init) {
|
|
312
375
|
// Structure and nothing else. An init carries no payload, so
|
|
313
376
|
// it never touches a value the program already set.
|
|
314
|
-
api.write(chain);
|
|
377
|
+
if (!api.write(chain)) refuse();
|
|
315
378
|
return;
|
|
316
379
|
}
|
|
317
380
|
if (frame.op === OPS.hide || frame.op === OPS.display) {
|
|
318
381
|
// Structure first (the node may not exist yet), then the
|
|
319
382
|
// flag. Generic for every type, never a handler's call.
|
|
320
|
-
api.write(chain)
|
|
383
|
+
if (!api.write(chain)) {
|
|
384
|
+
refuse();
|
|
385
|
+
return;
|
|
386
|
+
}
|
|
321
387
|
api.setHidden(frame.ref, frame.op === OPS.hide);
|
|
322
388
|
return;
|
|
323
389
|
}
|
|
@@ -328,7 +394,10 @@ export function createTreeStore(options: TreeStoreOptions = {}): TreeStore {
|
|
|
328
394
|
if (frame.op === OPS.write) {
|
|
329
395
|
// Structure first, always: the node may not exist yet, so
|
|
330
396
|
// the chain runs before anything can be looked up by type.
|
|
331
|
-
api.write(chain)
|
|
397
|
+
if (!api.write(chain)) {
|
|
398
|
+
refuse();
|
|
399
|
+
return;
|
|
400
|
+
}
|
|
332
401
|
const written = api.getIn(frame.ref);
|
|
333
402
|
if (!written) return;
|
|
334
403
|
const custom = handlerFor(written);
|
|
@@ -346,7 +415,10 @@ export function createTreeStore(options: TreeStoreOptions = {}): TreeStore {
|
|
|
346
415
|
// first, the same way a write does: a Card's `set_title` may be
|
|
347
416
|
// the first frame that ever names that Card. A frame with no
|
|
348
417
|
// chain is addressed at a node that should already be there.
|
|
349
|
-
if (frame.chain
|
|
418
|
+
if (frame.chain && !api.write(chain)) {
|
|
419
|
+
refuse();
|
|
420
|
+
return;
|
|
421
|
+
}
|
|
350
422
|
const node = api.getIn(frame.ref);
|
|
351
423
|
if (!node) {
|
|
352
424
|
onError(`no node for op "${frame.op}"`, frame.ref);
|