@ewe-studios/foundation-wasm-ui 0.0.0-stage → 0.1.13
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/LICENSE +201 -0
- package/README.md +11 -2
- package/bundle.js +15565 -0
- package/bundle.min.js +2 -0
- package/foundation_wasm/runtime/foundation-wasm.js +2449 -0
- package/index.js +3 -0
- package/package.json +12 -4
- package/ui/runtimes/foundation-ui-actions.js +698 -0
- package/ui/runtimes/foundation-ui-behaviours.js +792 -0
- package/ui/runtimes/foundation-ui-bootstrap.js +13 -0
- package/ui/runtimes/foundation-ui-connections.js +99 -0
- package/ui/runtimes/foundation-ui-frames.js +1023 -0
- package/ui/runtimes/foundation-ui-live.js +186 -0
- package/ui/runtimes/foundation-ui-recovery.js +66 -0
- package/ui/runtimes/foundation-ui-vocab.js +262 -0
- package/ui/runtimes/foundation-ui-wire.js +1 -0
- package/ui/runtimes/foundation-wasm-ui.js +2164 -0
- package/ui/runtimes/platform-scheme-interceptor.js +124 -0
- package/ui/runtimes/runtime-entry.js +4 -0
|
@@ -0,0 +1,1023 @@
|
|
|
1
|
+
// Apply EWF1 message frames to the browser node registry.
|
|
2
|
+
import { ViewRecovery } from "./foundation-ui-recovery.js";
|
|
3
|
+
import { bindLiveMounts } from "./foundation-ui-live.js";
|
|
4
|
+
import * as wire from "./foundation-ui-wire.js";
|
|
5
|
+
import * as vocab from "./foundation-ui-vocab.js";
|
|
6
|
+
import * as registryBehaviours from "./foundation-ui-behaviours.js";
|
|
7
|
+
import { NodeRegistry, Patcher } from "./foundation-wasm-ui.js";
|
|
8
|
+
|
|
9
|
+
const asBytes = input => ArrayBuffer.isView(input)
|
|
10
|
+
? new Uint8Array(input.buffer, input.byteOffset, input.byteLength)
|
|
11
|
+
: new Uint8Array(input);
|
|
12
|
+
const utf8 = new TextDecoder("utf-8", { fatal: true });
|
|
13
|
+
const defaultFrameBytes = 4 * 1024 * 1024;
|
|
14
|
+
|
|
15
|
+
export function isFrame(input) {
|
|
16
|
+
const b = asBytes(input);
|
|
17
|
+
return b.length >= 8 && b[4] === 69 && b[5] === 87 && b[6] === 70 && b[7] === 49;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// Read length-prefixed frames without retaining consumed transport chunks.
|
|
21
|
+
class FrameSplitter {
|
|
22
|
+
constructor(limit) {
|
|
23
|
+
this.limit = limit;
|
|
24
|
+
this.prefix = new Uint8Array(4);
|
|
25
|
+
this.used = 0;
|
|
26
|
+
this.frame = null;
|
|
27
|
+
}
|
|
28
|
+
*push(input) {
|
|
29
|
+
const bytes = asBytes(input);
|
|
30
|
+
let cursor = 0;
|
|
31
|
+
while (cursor < bytes.length) {
|
|
32
|
+
const dest = this.frame ?? this.prefix;
|
|
33
|
+
const count = Math.min(dest.length - this.used, bytes.length - cursor);
|
|
34
|
+
dest.set(bytes.subarray(cursor, cursor + count), this.used);
|
|
35
|
+
this.used += count;
|
|
36
|
+
cursor += count;
|
|
37
|
+
if (this.used !== dest.length) continue;
|
|
38
|
+
this.used = 0;
|
|
39
|
+
if (this.frame) {
|
|
40
|
+
this.frame = null;
|
|
41
|
+
if (!isFrame(dest)) throw new Error("Invalid EWF1 identifier");
|
|
42
|
+
yield dest;
|
|
43
|
+
} else {
|
|
44
|
+
const size = new DataView(dest.buffer).getUint32(0, true);
|
|
45
|
+
if (size < 8 || size > this.limit) throw new RangeError("Invalid frame size");
|
|
46
|
+
this.frame = new Uint8Array(size);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
finish() {
|
|
51
|
+
if (this.frame || this.used) throw new Error("Truncated frame");
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function splitFrames(input, limit = defaultFrameBytes) {
|
|
56
|
+
const splitter = new FrameSplitter(limit);
|
|
57
|
+
const frames = Array.from(splitter.push(input));
|
|
58
|
+
splitter.finish();
|
|
59
|
+
return frames;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export async function* readFrames(body, limit = defaultFrameBytes) {
|
|
63
|
+
const splitter = new FrameSplitter(limit);
|
|
64
|
+
if (!body) throw new Error("Missing frame response body");
|
|
65
|
+
const reader = body.getReader();
|
|
66
|
+
let done = false;
|
|
67
|
+
try {
|
|
68
|
+
while (true) {
|
|
69
|
+
const chunk = await reader.read();
|
|
70
|
+
if (chunk.done) { splitter.finish(); done = true; break; }
|
|
71
|
+
yield* splitter.push(chunk.value);
|
|
72
|
+
}
|
|
73
|
+
} finally {
|
|
74
|
+
try { if (!done) await reader.cancel(); } finally { reader.releaseLock(); }
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// Raw initial responses use the HTTP message boundary. Action streams carry a length prefix.
|
|
79
|
+
export async function readViewResponse(response, limit = defaultFrameBytes) {
|
|
80
|
+
if (!response.ok) throw new Error("View request failed with HTTP " + response.status);
|
|
81
|
+
if (!response.body) throw new Error("Missing view response body");
|
|
82
|
+
const reader = response.body.getReader();
|
|
83
|
+
const chunks = [];
|
|
84
|
+
let size = 0, complete = false;
|
|
85
|
+
try {
|
|
86
|
+
while (true) {
|
|
87
|
+
const {done, value} = await reader.read();
|
|
88
|
+
if (done) { complete = true; break; }
|
|
89
|
+
size += value.byteLength;
|
|
90
|
+
if (size > limit) throw new RangeError("View exceeds frame limit");
|
|
91
|
+
chunks.push(value);
|
|
92
|
+
}
|
|
93
|
+
} finally {
|
|
94
|
+
try { if (!complete) await reader.cancel(); } finally { reader.releaseLock(); }
|
|
95
|
+
}
|
|
96
|
+
const frame = new Uint8Array(size);
|
|
97
|
+
let offset = 0;
|
|
98
|
+
for (const chunk of chunks) { frame.set(chunk, offset); offset += chunk.byteLength; }
|
|
99
|
+
if (!isFrame(frame)) throw new Error("Invalid view frame");
|
|
100
|
+
return frame;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function base64urlEncode(bytes) {
|
|
104
|
+
let binary = "";
|
|
105
|
+
for (const value of bytes) binary += String.fromCharCode(value);
|
|
106
|
+
return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function base64urlDecode(text) {
|
|
110
|
+
return Uint8Array.from(atob(text.replaceAll("-", "+").replaceAll("_", "/")), c => c.charCodeAt(0));
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// Generated readers normally trust their buffer. Bound vector lengths before walking them.
|
|
114
|
+
class CheckedBuffer extends wire.ByteBuffer {
|
|
115
|
+
check(pos, length) {
|
|
116
|
+
if (pos < 0 || length < 0 || pos + length > this.bytes().length) throw new Error("Truncated frame field");
|
|
117
|
+
}
|
|
118
|
+
readInt8(pos) { this.check(pos, 1); return super.readInt8(pos); }
|
|
119
|
+
readUint8(pos) { this.check(pos, 1); return super.readUint8(pos); }
|
|
120
|
+
readInt16(pos) { this.check(pos, 2); return super.readInt16(pos); }
|
|
121
|
+
readUint16(pos) { this.check(pos, 2); return super.readUint16(pos); }
|
|
122
|
+
readInt32(pos) { this.check(pos, 4); return super.readInt32(pos); }
|
|
123
|
+
readUint32(pos) { this.check(pos, 4); return super.readUint32(pos); }
|
|
124
|
+
__vector_len(pos) {
|
|
125
|
+
const len = super.__vector_len(pos);
|
|
126
|
+
this.check(super.__vector(pos), len);
|
|
127
|
+
return len;
|
|
128
|
+
}
|
|
129
|
+
__string(pos, encoding) {
|
|
130
|
+
const start = pos + this.readInt32(pos);
|
|
131
|
+
this.check(start + 4, this.readInt32(start));
|
|
132
|
+
return super.__string(pos, encoding);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function vector(table, field, vtableOffset, Type, stats) {
|
|
137
|
+
const count = table[field + "Length"]();
|
|
138
|
+
const bb = table.bb;
|
|
139
|
+
const offset = bb.__offset(table.bb_pos, vtableOffset);
|
|
140
|
+
if (!offset) return new Type();
|
|
141
|
+
const start = bb.__vector(table.bb_pos + offset);
|
|
142
|
+
bb.check(start, count * Type.BYTES_PER_ELEMENT);
|
|
143
|
+
if ((bb.bytes().byteOffset + start) % Type.BYTES_PER_ELEMENT === 0) {
|
|
144
|
+
if (stats) stats.zeroCopyColumns++;
|
|
145
|
+
return table[field + "Array"]?.() ?? new Type(bb.bytes().buffer, bb.bytes().byteOffset + start, count);
|
|
146
|
+
}
|
|
147
|
+
if (stats) stats.copiedColumns++;
|
|
148
|
+
return Type.from({ length: count }, (_, i) => table[field](i));
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function problem(code, fields = {}) {
|
|
152
|
+
return Object.assign(new Error(code), { report: { code, ...fields } });
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const utilityClasses = new WeakMap();
|
|
156
|
+
function applyClasses(node, classes) {
|
|
157
|
+
const previous = utilityClasses.get(node) ?? [];
|
|
158
|
+
for (const cls of previous) node.classList.remove(cls);
|
|
159
|
+
const words = (classes ?? "").split(/\s+/).filter(Boolean);
|
|
160
|
+
const shared = words.filter(word => !/^(ios|android|web)-/.test(word));
|
|
161
|
+
const overrides = words.filter(word => word.startsWith("web-")).map(word => word.slice(4));
|
|
162
|
+
const ordered = [...shared, ...overrides];
|
|
163
|
+
const applied = [];
|
|
164
|
+
for (const word of ordered) {
|
|
165
|
+
if (!node.classList.contains(word)) {
|
|
166
|
+
node.classList.add(word);
|
|
167
|
+
applied.push(word);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
node.setAttribute("data-ewe-themed", "");
|
|
171
|
+
for (const [prefix, categories, field] of [
|
|
172
|
+
["text-", ["color"], "color"], ["text-", ["font-size"], "font-size"],
|
|
173
|
+
["bg-", ["color"], "background"], ["p-", ["padding", "spacing"], "padding"],
|
|
174
|
+
]) {
|
|
175
|
+
let value = "";
|
|
176
|
+
for (const word of ordered) {
|
|
177
|
+
const name = word.slice(prefix.length);
|
|
178
|
+
if (!word.startsWith(prefix) || !/^[a-zA-Z0-9_-]+$/.test(name)) continue;
|
|
179
|
+
for (const category of categories) value = "var(--" + category + "-" + name + (value ? "," + value : "") + ")";
|
|
180
|
+
}
|
|
181
|
+
const property = "--ewe-utility-" + field;
|
|
182
|
+
if (value) node.style.setProperty?.(property, value);
|
|
183
|
+
else node.style.removeProperty?.(property);
|
|
184
|
+
}
|
|
185
|
+
utilityClasses.set(node, applied);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const propStyles = { PADDING: "padding", SPACING: "gap", WIDTH: "width", HEIGHT: "height" };
|
|
189
|
+
function applyProp(node, id, type, value) {
|
|
190
|
+
if (!value || wire.PropValue[type] !== vocab.PROP_KIND[id]) throw problem("BadFrame");
|
|
191
|
+
const prop = wire.PropId[id];
|
|
192
|
+
const v = value.v;
|
|
193
|
+
if (Object.hasOwn(propStyles, prop)) {
|
|
194
|
+
node.style[propStyles[prop]] = v.unit === wire.LengthUnit.Auto ? "auto" :
|
|
195
|
+
String(v.value) + (v.unit === wire.LengthUnit.Percent ? "%" : "px");
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
switch (prop) {
|
|
199
|
+
case "ID": node.setAttribute("id", v); break;
|
|
200
|
+
case "ALIGN": node.style.alignItems = ["flex-start", "center", "flex-end", "stretch"][v]; break;
|
|
201
|
+
case "AXIS": node.style.flexDirection = v === wire.Axis.Horizontal ? "row" : "column"; break;
|
|
202
|
+
case "FONT": node.style.font = "var(--ewe-font-" + value.id + ")"; break;
|
|
203
|
+
case "COLOR": case "BACKGROUND":
|
|
204
|
+
node.style[prop === "COLOR" ? "color" : "backgroundColor"] = "var(--ewe-color-" + value.id + ")"; break;
|
|
205
|
+
case "ENABLED": case "HIDDEN": {
|
|
206
|
+
const attr = prop === "HIDDEN" ? "hidden" : "disabled";
|
|
207
|
+
if (prop === "HIDDEN" ? v : !v) node.setAttribute(attr, "");
|
|
208
|
+
else node.removeAttribute(attr);
|
|
209
|
+
break;
|
|
210
|
+
}
|
|
211
|
+
case "UTILITY_CLASSES": applyClasses(node, v); break;
|
|
212
|
+
case "A11Y_LABEL": node.setAttribute("aria-label", v ?? ""); break;
|
|
213
|
+
case "SOURCE": node.setAttribute("src", v ?? ""); break;
|
|
214
|
+
case "PLACEHOLDER": node.setAttribute("placeholder", v ?? ""); break;
|
|
215
|
+
case "VALUE": node.value = v ?? ""; break;
|
|
216
|
+
case "CHECKED":
|
|
217
|
+
node.checked = v;
|
|
218
|
+
if (node.tagName === "BUTTON") node.setAttribute("aria-pressed", String(v));
|
|
219
|
+
break;
|
|
220
|
+
default: throw problem("UnknownOp");
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function dispatchEvent(target, name, detail) {
|
|
225
|
+
const EventType = target.ownerDocument?.defaultView?.CustomEvent ?? globalThis.CustomEvent;
|
|
226
|
+
target.dispatchEvent?.(EventType ? new EventType(name, { bubbles: true, detail }) : { type: name, detail, bubbles: true });
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// A submit button can use the value of one enabled sibling field.
|
|
230
|
+
export function sheetSubmitField(button) {
|
|
231
|
+
if (!button.classList?.contains("ewe-submit-button") || !button.closest?.(".ewe-bottom-sheet")) return null;
|
|
232
|
+
const fields = Array.from(button.parentElement.children).filter(node =>
|
|
233
|
+
node.tagName === "INPUT" && !node.disabled && !node.hidden && node.hasAttribute("primal:onsubmit"));
|
|
234
|
+
return fields.length === 1 ? fields[0] : null;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// A sheet forwards a submit gesture to the input that owns the action.
|
|
238
|
+
function wireBottomSheet(sheet, options) {
|
|
239
|
+
function submit(input) {
|
|
240
|
+
if (input && !input.disabled) {
|
|
241
|
+
const EventType = sheet.ownerDocument.defaultView.Event;
|
|
242
|
+
input.dispatchEvent(new EventType("submit", { cancelable: true }));
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
sheet.addEventListener("keydown", event => {
|
|
246
|
+
const input = event.target;
|
|
247
|
+
if (event.key !== "Enter" || event.isComposing || input.closest(".ewe-bottom-sheet") !== sheet) return;
|
|
248
|
+
if (input.tagName !== "INPUT" || !input.hasAttribute("primal:onsubmit")) return;
|
|
249
|
+
event.preventDefault();
|
|
250
|
+
if (!event.repeat) submit(input);
|
|
251
|
+
}, options);
|
|
252
|
+
sheet.addEventListener("click", event => {
|
|
253
|
+
const button = event.target.closest?.('button.ewe-submit-button');
|
|
254
|
+
if (!button || button.closest(".ewe-bottom-sheet") !== sheet || button.hasAttribute("primal:onclick")) return;
|
|
255
|
+
submit(sheetSubmitField(button));
|
|
256
|
+
}, options);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
export class FrameApplicator {
|
|
260
|
+
constructor(deps) {
|
|
261
|
+
this.deps = deps;
|
|
262
|
+
this.document = deps.document;
|
|
263
|
+
this.registry = deps.registry;
|
|
264
|
+
this.elementListeners = new WeakMap();
|
|
265
|
+
this.bindings = [];
|
|
266
|
+
this.layers = new Set();
|
|
267
|
+
this.containerEvents = new WeakMap();
|
|
268
|
+
this.maxFrameBytes = deps.maxFrameBytes ?? defaultFrameBytes;
|
|
269
|
+
this.gapTimeoutMs = deps.gapTimeoutMs ?? 1000;
|
|
270
|
+
this.maxPendingFrames = deps.maxPendingFrames ?? 128;
|
|
271
|
+
this.timer = deps.timer ?? { set: setTimeout, clear: clearTimeout };
|
|
272
|
+
this.schedule = deps.schedule ?? (run => {
|
|
273
|
+
if (this.document.visibilityState === "hidden" || !globalThis.requestAnimationFrame) queueMicrotask(run);
|
|
274
|
+
else globalThis.requestAnimationFrame(run);
|
|
275
|
+
});
|
|
276
|
+
this.stats = { frames: 0, rows: 0, reports: 0, copiedColumns: 0, zeroCopyColumns: 0 };
|
|
277
|
+
this.defaultView = { registry: deps.registry, cursors: new Map(), gaps: new Map() };
|
|
278
|
+
this.viewStates = new Map();
|
|
279
|
+
this.loaders = new Map();
|
|
280
|
+
this.queue = [];
|
|
281
|
+
this.scheduled = false;
|
|
282
|
+
this.cssInstalled = false;
|
|
283
|
+
this.nodeIds = new WeakMap();
|
|
284
|
+
this.origins = new WeakMap();
|
|
285
|
+
this.views = new Map();
|
|
286
|
+
this.sharedKinds = new WeakMap();
|
|
287
|
+
this.drawingTargets = [];
|
|
288
|
+
this.drawingJobs = new Map();
|
|
289
|
+
}
|
|
290
|
+
bindDrawing(canvas, nodeId) {
|
|
291
|
+
const graphics = this.deps.graphics;
|
|
292
|
+
if (!graphics || !canvas.isConnected) return;
|
|
293
|
+
const name = canvas.id || String(nodeId);
|
|
294
|
+
const host = this.document.defaultView;
|
|
295
|
+
let surface, removed = false, observer;
|
|
296
|
+
const enqueue = work => {
|
|
297
|
+
const previous = this.drawingJobs.get(name) ?? Promise.resolve();
|
|
298
|
+
const job = previous.then(work).catch(error => this.report("Graphics", {node:nodeId, detail:error.message}));
|
|
299
|
+
this.drawingJobs.set(name, job);
|
|
300
|
+
job.then(() => { if (this.drawingJobs.get(name) === job) this.drawingJobs.delete(name); });
|
|
301
|
+
};
|
|
302
|
+
const resize = () => {
|
|
303
|
+
if (removed) return;
|
|
304
|
+
const rect = canvas.getBoundingClientRect();
|
|
305
|
+
const scale = host.devicePixelRatio || 1;
|
|
306
|
+
const width = Math.round(rect.width * scale), height = Math.round(rect.height * scale);
|
|
307
|
+
if (canvas.width === width && canvas.height === height && surface) return;
|
|
308
|
+
if (canvas.width !== width) canvas.width = width;
|
|
309
|
+
if (canvas.height !== height) canvas.height = height;
|
|
310
|
+
enqueue(async () => {
|
|
311
|
+
if (removed) return;
|
|
312
|
+
if (surface) await surface.resize(width, height);
|
|
313
|
+
else surface = await graphics.attach(name, canvas);
|
|
314
|
+
});
|
|
315
|
+
};
|
|
316
|
+
resize();
|
|
317
|
+
if (host.ResizeObserver) {
|
|
318
|
+
observer = new host.ResizeObserver(resize);
|
|
319
|
+
observer.observe(canvas);
|
|
320
|
+
}
|
|
321
|
+
this.registerUnmount(canvas, () => {
|
|
322
|
+
removed = true;
|
|
323
|
+
observer?.disconnect();
|
|
324
|
+
enqueue(async () => { if (surface) await surface.remove(); });
|
|
325
|
+
});
|
|
326
|
+
}
|
|
327
|
+
viewOwner(mount) {
|
|
328
|
+
for (let node = mount; node; node = node.parentNode) {
|
|
329
|
+
if (this.viewStates.has(node)) return node;
|
|
330
|
+
}
|
|
331
|
+
return this.deps.viewMount ?? this;
|
|
332
|
+
}
|
|
333
|
+
viewState(mount) {
|
|
334
|
+
return this.viewStates.get(this.viewOwner(mount)) ?? this.defaultView;
|
|
335
|
+
}
|
|
336
|
+
cursor(stream, mount) { return this.viewState(mount).cursors.get(stream); }
|
|
337
|
+
setCursor(stream, sequence, mount) {
|
|
338
|
+
const {gaps, cursors} = this.viewState(mount);
|
|
339
|
+
const gap = gaps.get(stream);
|
|
340
|
+
if (gap) this.timer.clear(gap.timer);
|
|
341
|
+
gaps.delete(stream);
|
|
342
|
+
cursors.set(stream, sequence);
|
|
343
|
+
}
|
|
344
|
+
registerUnmount(node, hook) { Patcher.registerUnmount(node, hook); }
|
|
345
|
+
report(code, fields = {}) {
|
|
346
|
+
this.stats.reports++;
|
|
347
|
+
const report = { code, ...fields };
|
|
348
|
+
if (this.deps.onReport) this.deps.onReport(report);
|
|
349
|
+
else console.error("Frame operation failed", report);
|
|
350
|
+
}
|
|
351
|
+
receive(input, origin) {
|
|
352
|
+
try {
|
|
353
|
+
const bytes = asBytes(input);
|
|
354
|
+
if (bytes.length > this.maxFrameBytes) { this.report("TooLarge"); return false; }
|
|
355
|
+
if (!isFrame(bytes)) throw problem("BadFrame");
|
|
356
|
+
const frame = wire.Frame.getRootAsFrame(new CheckedBuffer(bytes));
|
|
357
|
+
if (frame.kindType() !== wire.FrameKind.FrameMessage) throw problem("BadFrame");
|
|
358
|
+
const msg = frame.kind(new wire.FrameMessage());
|
|
359
|
+
if (!msg) throw problem("BadFrame");
|
|
360
|
+
const count = msg.messagesLength();
|
|
361
|
+
if (count) {
|
|
362
|
+
const bb = msg.bb;
|
|
363
|
+
bb.check(bb.__vector(msg.bb_pos + bb.__offset(msg.bb_pos, 6)), count * 4);
|
|
364
|
+
}
|
|
365
|
+
const seq = frame.sequenceId();
|
|
366
|
+
const stream = frame.streamId();
|
|
367
|
+
if (origin) {
|
|
368
|
+
this.origins.set(msg, origin);
|
|
369
|
+
origin.observeStream?.(stream);
|
|
370
|
+
}
|
|
371
|
+
if (seq === 0n || msg.ack() !== 0n) this.enqueue(msg);
|
|
372
|
+
else this.order(stream, seq, msg);
|
|
373
|
+
return true;
|
|
374
|
+
} catch (error) { this.report("BadFrame", { detail: error.message }); return false; }
|
|
375
|
+
}
|
|
376
|
+
order(stream, seq, msg) {
|
|
377
|
+
const owner = this.viewOwner(this.origins.get(msg)?.viewMount);
|
|
378
|
+
const {cursors, gaps} = this.viewState(owner);
|
|
379
|
+
const cursor = cursors.get(stream);
|
|
380
|
+
if (cursor !== undefined && seq <= cursor) return;
|
|
381
|
+
let gap = gaps.get(stream);
|
|
382
|
+
if (cursor !== undefined && seq > cursor + 1n) {
|
|
383
|
+
if (!gap) {
|
|
384
|
+
gap = { held: new Map(), timer: this.timer.set(() => {
|
|
385
|
+
gaps.delete(stream);
|
|
386
|
+
this.deps.onGap?.({ streamId: stream, ...(this.viewStates.has(owner) ? {view: owner} : {}), resumeFrom: cursors.get(stream) });
|
|
387
|
+
}, this.gapTimeoutMs) };
|
|
388
|
+
gaps.set(stream, gap);
|
|
389
|
+
}
|
|
390
|
+
if (!gap.held.has(seq) && gap.held.size >= this.maxPendingFrames) {
|
|
391
|
+
this.timer.clear(gap.timer);
|
|
392
|
+
gaps.delete(stream);
|
|
393
|
+
this.deps.onGap?.({ streamId: stream, ...(this.viewStates.has(owner) ? {view: owner} : {}), resumeFrom: cursor });
|
|
394
|
+
} else gap.held.set(seq, msg);
|
|
395
|
+
return;
|
|
396
|
+
}
|
|
397
|
+
this.enqueue(msg);
|
|
398
|
+
while (gap?.held.has(seq + 1n)) {
|
|
399
|
+
seq++;
|
|
400
|
+
this.enqueue(gap.held.get(seq));
|
|
401
|
+
gap.held.delete(seq);
|
|
402
|
+
}
|
|
403
|
+
cursors.set(stream, seq);
|
|
404
|
+
if (gap && !gap.held.size) { this.timer.clear(gap.timer); gaps.delete(stream); }
|
|
405
|
+
}
|
|
406
|
+
enqueue(msg) {
|
|
407
|
+
this.queue.push(msg);
|
|
408
|
+
if (!this.scheduled) {
|
|
409
|
+
this.scheduled = true;
|
|
410
|
+
this.schedule(() => this.flush());
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
flush() {
|
|
414
|
+
this.scheduled = false;
|
|
415
|
+
for (const msg of this.queue.splice(0)) {
|
|
416
|
+
const previousOrigin = this.origin;
|
|
417
|
+
this.origin = this.origins.get(msg);
|
|
418
|
+
if (this.origin?.active && !this.origin.active()) { this.origin = previousOrigin; continue; }
|
|
419
|
+
const previousRegistry = this.registry;
|
|
420
|
+
this.registry = this.viewState(this.origin?.viewMount).registry;
|
|
421
|
+
this.stats.frames++;
|
|
422
|
+
for (let i = 0; i < msg.messagesLength(); i++) {
|
|
423
|
+
try {
|
|
424
|
+
const m = msg.messages(i);
|
|
425
|
+
if (m.operation()) this.applyUnit(m.operation(), i);
|
|
426
|
+
if (m.data()) this.applyData(m.data());
|
|
427
|
+
if (m.control()) this.applyControl(m.control());
|
|
428
|
+
} catch (e) { this.report(e.report?.code ?? "BadFrame", { unitIndex: i, ...(e.report ?? {}), detail: e.message }); }
|
|
429
|
+
}
|
|
430
|
+
for (const {node, id, index, name, args, shared, registry: nodeRegistry} of this.bindings.splice(0)) {
|
|
431
|
+
if (nodeRegistry.get(id) !== node) continue;
|
|
432
|
+
const registry = this.deps.behaviours ?? registryBehaviours;
|
|
433
|
+
try {
|
|
434
|
+
const applied = shared ? registry.applyBehaviour(node, name, args) : registry.applyWebBehaviour(node, name, args);
|
|
435
|
+
if (!applied) this.report("UnknownBehaviour", {unitIndex:index,node:id,name:String(name)});
|
|
436
|
+
} catch (error) { this.report("BadFrame",{unitIndex:index,node:id,detail:error.message}); }
|
|
437
|
+
}
|
|
438
|
+
for (const layer of this.layers) {
|
|
439
|
+
if (!layer.isConnected) continue;
|
|
440
|
+
const hidden = layer.closest("[hidden]") !== null;
|
|
441
|
+
if (layer.tagName === "DIALOG") {
|
|
442
|
+
if (hidden && layer.open) layer.close();
|
|
443
|
+
else if (!hidden && !layer.open) layer.showModal();
|
|
444
|
+
} else {
|
|
445
|
+
const open = layer.matches(":popover-open");
|
|
446
|
+
if (hidden && open) layer.hidePopover();
|
|
447
|
+
else if (!hidden && !open) layer.showPopover();
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
for (const [canvas, nodeId] of this.drawingTargets.splice(0)) this.bindDrawing(canvas, nodeId);
|
|
451
|
+
this.registry = previousRegistry;
|
|
452
|
+
this.origin = previousOrigin;
|
|
453
|
+
this.deps.onApplied?.();
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
node(id, staged = false) {
|
|
457
|
+
const n = this.registry.get(id);
|
|
458
|
+
if (n) return n;
|
|
459
|
+
if (staged && this.registry.pending.has(id)) return this.registry.expectOrStaged(id);
|
|
460
|
+
throw problem("UnknownNode", { node: id });
|
|
461
|
+
}
|
|
462
|
+
applyUnit(op, index) {
|
|
463
|
+
const read = (key, enumType, handler) => {
|
|
464
|
+
const id = op[key + "Type"]();
|
|
465
|
+
if (!id) return false;
|
|
466
|
+
const name = enumType[id];
|
|
467
|
+
if (!wire[name]) throw problem("UnknownOp", { field: key });
|
|
468
|
+
const reader = op[key](new wire[name]());
|
|
469
|
+
if (!reader) throw problem("BadFrame");
|
|
470
|
+
handler.call(this, name, reader, index);
|
|
471
|
+
this.stats.rows++;
|
|
472
|
+
return true;
|
|
473
|
+
};
|
|
474
|
+
const ui = read("ui", wire.UiOperation, this.applyUiReader);
|
|
475
|
+
const web = read("web", wire.WebOperation, this.applyWebReader);
|
|
476
|
+
if (op.columnar()) this.applyColumnar(op.columnar(), index);
|
|
477
|
+
if (op.mobileType()) this.report("UnsupportedPlatformOp", { unitIndex: index, field: "mobile" });
|
|
478
|
+
else if (!ui && !web && !op.columnar()) this.report("UnknownOp", { unitIndex: index });
|
|
479
|
+
}
|
|
480
|
+
applyUiReader(name, reader, index) {
|
|
481
|
+
if (name === "ReplaceSubtree") {
|
|
482
|
+
const root = this.node(reader.nodeId());
|
|
483
|
+
for (const child of Array.from(root.childNodes)) { this.discard(child); root.removeChild(child); }
|
|
484
|
+
this.applyNested(reader, index);
|
|
485
|
+
} else if (name === "Place") this.place(reader, index);
|
|
486
|
+
else this.applyUi(name, reader.unpack(), index);
|
|
487
|
+
}
|
|
488
|
+
applyNested(reader, index) {
|
|
489
|
+
for (let i = 0; i < reader.operationsLength(); i++) this.applyUnit(reader.operations(i), index);
|
|
490
|
+
}
|
|
491
|
+
discard(node) {
|
|
492
|
+
if (this.layers.delete(node)) {
|
|
493
|
+
if (node.tagName === "DIALOG" && node.open) node.close();
|
|
494
|
+
else if (node.hasAttribute("popover") && node.matches(":popover-open")) node.hidePopover();
|
|
495
|
+
}
|
|
496
|
+
this.containerEvents.get(node)?.abort();
|
|
497
|
+
this.containerEvents.delete(node);
|
|
498
|
+
for (const child of Array.from(node.childNodes ?? [])) this.discard(child);
|
|
499
|
+
Patcher.releaseScope(node);
|
|
500
|
+
registryBehaviours.disposeBehaviours(node);
|
|
501
|
+
this.deps.onUnmount?.(node);
|
|
502
|
+
(this.deps.dispatcher ?? this.deps.runtime?.dispatcher)?.off?.(node);
|
|
503
|
+
const id = this.nodeIds.get(node) ?? node.getAttribute?.("primal-id");
|
|
504
|
+
if (id != null && this.registry.get(Number(id)) === node) {
|
|
505
|
+
this.registry.unregister(Number(id));
|
|
506
|
+
}
|
|
507
|
+
for (const [name, handler] of this.elementListeners.get(node) ?? []) {
|
|
508
|
+
node.removeEventListener(name, handler);
|
|
509
|
+
}
|
|
510
|
+
this.elementListeners.delete(node);
|
|
511
|
+
this.nodeIds.delete(node);
|
|
512
|
+
}
|
|
513
|
+
selectorQuery(selector) {
|
|
514
|
+
const text = selector.text;
|
|
515
|
+
const escape = this.document.defaultView?.CSS?.escape ?? globalThis.CSS?.escape;
|
|
516
|
+
if (selector.kind === wire.SelectorKind.Id) return "#" + escape(text);
|
|
517
|
+
if (selector.kind === wire.SelectorKind.Class) return "." + escape(text);
|
|
518
|
+
if (selector.kind === wire.SelectorKind.Query) return text;
|
|
519
|
+
throw problem("UnknownOp");
|
|
520
|
+
}
|
|
521
|
+
resolve(selector) {
|
|
522
|
+
if (!selector) return null;
|
|
523
|
+
if (selector.kind === wire.SelectorKind.NodeId) return this.registry.get(selector.nodeId);
|
|
524
|
+
if (selector.kind === wire.SelectorKind.Id) return this.document.getElementById(selector.text);
|
|
525
|
+
return this.document.querySelector(this.selectorQuery(selector));
|
|
526
|
+
}
|
|
527
|
+
registerView(name, root) {
|
|
528
|
+
if (!/^[A-Za-z_][A-Za-z0-9_-]*$/.test(name) || !root || this.views.has(name) || [...this.views.values()].includes(root))
|
|
529
|
+
throw problem("DuplicateView", {detail: name});
|
|
530
|
+
const primary = root === this.deps.viewMount || (!this.deps.viewMount && this.views.size === 0);
|
|
531
|
+
const state = primary ? this.defaultView : {registry: new NodeRegistry(), cursors: new Map(), gaps: new Map()};
|
|
532
|
+
this.viewStates.set(root, state);
|
|
533
|
+
this.views.set(name, root);
|
|
534
|
+
return () => {
|
|
535
|
+
if (this.views.get(name) !== root) return;
|
|
536
|
+
const previous = this.registry;
|
|
537
|
+
this.registry = state.registry;
|
|
538
|
+
try {
|
|
539
|
+
for (const child of Array.from(root.childNodes)) { this.discard(child); child.remove(); }
|
|
540
|
+
} finally {
|
|
541
|
+
this.registry = previous;
|
|
542
|
+
for (const gap of state.gaps.values()) this.timer.clear(gap.timer);
|
|
543
|
+
state.gaps.clear();
|
|
544
|
+
state.cursors.clear();
|
|
545
|
+
this.loaders.get(root)?.close();
|
|
546
|
+
this.loaders.delete(root);
|
|
547
|
+
this.views.delete(name);
|
|
548
|
+
this.viewStates.delete(root);
|
|
549
|
+
}
|
|
550
|
+
};
|
|
551
|
+
}
|
|
552
|
+
registerLoader(root, load, options = {}) {
|
|
553
|
+
if (this.loaders.get(root)?.active) throw new Error("View already has a loader");
|
|
554
|
+
const recovery = new ViewRecovery(load, (bytes, expired) => {
|
|
555
|
+
if (!isFrame(bytes) || bytes.byteLength > this.maxFrameBytes) throw new Error("Invalid view snapshot");
|
|
556
|
+
const frame = wire.Frame.getRootAsFrame(new CheckedBuffer(asBytes(bytes)));
|
|
557
|
+
const body = frame.kindType() === wire.FrameKind.FrameMessage && frame.kind(new wire.FrameMessage());
|
|
558
|
+
if (!body || !body.messagesLength()) throw new Error("Expected a full view");
|
|
559
|
+
for (let index = 1; index < body.messagesLength(); index++) {
|
|
560
|
+
const message = body.messages(index);
|
|
561
|
+
if (!message.data() || message.operation() || message.control()) throw new Error("Expected snapshot data");
|
|
562
|
+
}
|
|
563
|
+
const operation = body.messages(0).operation();
|
|
564
|
+
const place = operation?.uiType() === wire.UiOperation.Place && operation.ui(new wire.Place());
|
|
565
|
+
if (!place || place.kind() !== wire.PlacementKind.FullView) throw new Error("Expected a full view");
|
|
566
|
+
const doc = this.deps.snapshotDocument?.() ?? this.document.implementation.createHTMLDocument("");
|
|
567
|
+
const detached = doc.createElement("main");
|
|
568
|
+
doc.body.appendChild(detached);
|
|
569
|
+
const issues = [];
|
|
570
|
+
const probe = new FrameApplicator({document:doc, registry:new NodeRegistry().seedDocument(doc),
|
|
571
|
+
viewMount:detached, schedule:run => run(), maxFrameBytes:this.maxFrameBytes, onReport:error => issues.push(error)});
|
|
572
|
+
if (!probe.receive(bytes) || issues.length) throw new Error("Invalid snapshot content");
|
|
573
|
+
const cursors = new Map();
|
|
574
|
+
for (let i = 0; i < place.operationsLength(); i++) {
|
|
575
|
+
const op = place.operations(i);
|
|
576
|
+
if (op.uiType() !== wire.UiOperation.LiveMount) continue;
|
|
577
|
+
const mount = op.ui(new wire.LiveMount());
|
|
578
|
+
if (mount.kind() !== wire.LiveKind.Stream || mount.transport() === wire.LiveTransport.Local ||
|
|
579
|
+
(mount.transport() === wire.LiveTransport.Sse && mount.sharing() === wire.ConnectionSharing.Shared)) continue;
|
|
580
|
+
if (cursors.has(mount.channelId()) && cursors.get(mount.channelId()) !== mount.resumeFrom()) throw new Error("Conflicting stream cursors");
|
|
581
|
+
cursors.set(mount.channelId(), mount.resumeFrom());
|
|
582
|
+
}
|
|
583
|
+
for (const stream of expired) if (!cursors.has(stream)) throw new Error("Snapshot is missing the expired stream");
|
|
584
|
+
const state = this.viewState(root);
|
|
585
|
+
for (const gap of state.gaps.values()) this.timer.clear(gap.timer);
|
|
586
|
+
state.gaps.clear();
|
|
587
|
+
state.cursors.clear();
|
|
588
|
+
for (const [stream, cursor] of cursors) this.setCursor(stream,cursor,root);
|
|
589
|
+
if (!this.receive(bytes, {viewMount:root})) throw new Error("Invalid view snapshot");
|
|
590
|
+
this.flush();
|
|
591
|
+
}, options);
|
|
592
|
+
this.loaders.set(root,recovery);
|
|
593
|
+
return recovery;
|
|
594
|
+
}
|
|
595
|
+
registerElement(name, tag, node) {
|
|
596
|
+
const valid = /^[A-Za-z_][A-Za-z0-9_-]*$/;
|
|
597
|
+
if (!valid.test(name) || !valid.test(tag) || tag.toLowerCase() === "view") throw problem("InvalidName");
|
|
598
|
+
let root = node;
|
|
599
|
+
while (root.parentNode && ![...this.views.values(),this.deps.viewMount].includes(root)) root = root.parentNode;
|
|
600
|
+
const other = this.namedElements(root).get(name);
|
|
601
|
+
if (other && other !== node) throw problem("DuplicateName", {detail:name});
|
|
602
|
+
node.setAttribute("id",name);
|
|
603
|
+
this.sharedKinds.set(node,tag);
|
|
604
|
+
}
|
|
605
|
+
receivingView(supplied = this.origin?.viewMount) {
|
|
606
|
+
if (supplied) {
|
|
607
|
+
for (let node = supplied; node; node = node.parentNode) {
|
|
608
|
+
if (node === this.deps.viewMount || [...this.views.values()].includes(node)) return node;
|
|
609
|
+
}
|
|
610
|
+
return supplied;
|
|
611
|
+
}
|
|
612
|
+
const roots = new Set(this.views.values());
|
|
613
|
+
if (this.deps.viewMount) roots.add(this.deps.viewMount);
|
|
614
|
+
if (roots.size > 1) throw problem("AmbiguousView");
|
|
615
|
+
return roots.values().next().value;
|
|
616
|
+
}
|
|
617
|
+
namedElements(root) {
|
|
618
|
+
const names = new Map(), pending = [root];
|
|
619
|
+
const otherViews = new Set(this.views.values());
|
|
620
|
+
while (pending.length) {
|
|
621
|
+
const node = pending.pop();
|
|
622
|
+
if (!node || (node !== root && otherViews.has(node))) continue;
|
|
623
|
+
const name = node.getAttribute?.("id");
|
|
624
|
+
if (name) {
|
|
625
|
+
if (names.has(name)) throw problem("DuplicateName", {detail:name});
|
|
626
|
+
names.set(name,node);
|
|
627
|
+
}
|
|
628
|
+
for (const child of node.children ?? []) pending.push(child);
|
|
629
|
+
}
|
|
630
|
+
return names;
|
|
631
|
+
}
|
|
632
|
+
placementTarget(selector, parent, scope) {
|
|
633
|
+
if (!selector) return null;
|
|
634
|
+
const kinds = wire.SelectorKind;
|
|
635
|
+
if (selector.kind === kinds.NodeId) {
|
|
636
|
+
const node = this.registry.get(selector.nodeId);
|
|
637
|
+
return node && (!parent || node.parentNode === parent) ? node : null;
|
|
638
|
+
}
|
|
639
|
+
if (selector.kind === kinds.View) return this.views.get(selector.text);
|
|
640
|
+
if (selector.kind === kinds.Receiving) return this.receivingView();
|
|
641
|
+
if (selector.kind === kinds.Id || selector.kind === kinds.TypedId) {
|
|
642
|
+
const typed = selector.kind === kinds.TypedId;
|
|
643
|
+
const parts = typed ? selector.text?.split("#") : [null,selector.text];
|
|
644
|
+
if (parts?.length !== 2 || (typed && !/^[A-Za-z_][A-Za-z0-9_-]*$/.test(parts[0]))) throw problem("InvalidName");
|
|
645
|
+
const [tag, name] = parts;
|
|
646
|
+
if (!/^[A-Za-z_][A-Za-z0-9_-]*$/.test(name)) throw problem("InvalidName");
|
|
647
|
+
const root = scope ?? this.receivingView() ?? this.document.body;
|
|
648
|
+
const node = this.namedElements(root).get(name);
|
|
649
|
+
if (!node || (parent && node.parentNode !== parent)) return null;
|
|
650
|
+
if (typed) {
|
|
651
|
+
const compact = text => text?.replace(/[-_]/g,"").toLowerCase();
|
|
652
|
+
const expected = compact(tag) === "sheet" ? "bottomsheet" : compact(tag);
|
|
653
|
+
if (compact(this.sharedKinds.get(node) ?? node.localName) !== expected)
|
|
654
|
+
throw problem("WrongTargetKind", {detail:selector.text});
|
|
655
|
+
}
|
|
656
|
+
return node;
|
|
657
|
+
}
|
|
658
|
+
const query = this.selectorQuery(selector);
|
|
659
|
+
const matches = parent ? Array.from(parent.children).filter(node => node.matches(query)) :
|
|
660
|
+
this.document.querySelectorAll(query);
|
|
661
|
+
return matches.length === 1 ? matches[0] : null;
|
|
662
|
+
}
|
|
663
|
+
validatePlacementNames(reader, scope, outgoing) {
|
|
664
|
+
const names = this.namedElements(scope);
|
|
665
|
+
for (const [name,node] of names) if (outgoing?.some(root => root === node || root.contains?.(node))) names.delete(name);
|
|
666
|
+
const check = name => {
|
|
667
|
+
if (!name || !/^[A-Za-z_][A-Za-z0-9_-]*$/.test(name)) throw problem("InvalidName");
|
|
668
|
+
if (names.has(name)) throw problem("DuplicateName", {detail:name});
|
|
669
|
+
names.set(name,true);
|
|
670
|
+
};
|
|
671
|
+
for (let i = 0; i < reader.operationsLength(); i++) {
|
|
672
|
+
const unit = reader.operations(i);
|
|
673
|
+
if (unit.uiType() === wire.UiOperation.SetProp) {
|
|
674
|
+
const prop = unit.ui(new wire.SetProp());
|
|
675
|
+
if (prop.prop() === wire.PropId.ID) check(prop.value(new wire.TextValue())?.v());
|
|
676
|
+
}
|
|
677
|
+
const batch = unit.columnar();
|
|
678
|
+
if (!batch) continue;
|
|
679
|
+
const bytes = batch.blobBytesArray() ?? new Uint8Array();
|
|
680
|
+
for (let row = 0; row < batch.opCodesLength(); row++) {
|
|
681
|
+
if (batch.opCodes(row) !== wire.UiOperation.SetProp || (batch.argA(row) & 0xffff) !== wire.PropId.ID) continue;
|
|
682
|
+
const start = batch.blobAOff(row), end = batch.blobAOff(row + 1);
|
|
683
|
+
if (start > end || end > bytes.length) throw problem("BadFrame");
|
|
684
|
+
check(utf8.decode(bytes.subarray(start,end)));
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
place(reader, index) {
|
|
689
|
+
const target = reader.target();
|
|
690
|
+
const root = target?.kind() === wire.SelectorKind.View ? this.views.get(target.text()) : this.origin?.viewMount;
|
|
691
|
+
const previous = this.registry;
|
|
692
|
+
this.registry = this.viewState(root).registry;
|
|
693
|
+
try { this.applyPlacement(reader, index); }
|
|
694
|
+
finally { this.registry = previous; }
|
|
695
|
+
}
|
|
696
|
+
applyPlacement(reader, index) {
|
|
697
|
+
const kind = wire.PlacementKind[reader.kind()];
|
|
698
|
+
if (kind === "FullView") {
|
|
699
|
+
const mount = this.receivingView();
|
|
700
|
+
if (!mount || mount.isConnected === false) throw problem("UnknownNode", { detail: "Missing receiving view mount" });
|
|
701
|
+
this.validatePlacementNames(reader, mount, Array.from(mount.childNodes));
|
|
702
|
+
for (const node of Array.from(mount.childNodes)) { this.discard(node); node.remove(); }
|
|
703
|
+
this.applyNested(reader, index);
|
|
704
|
+
mount.appendChild(this.node(reader.rootNode(), true));
|
|
705
|
+
return;
|
|
706
|
+
}
|
|
707
|
+
const selector = reader.target()?.unpack();
|
|
708
|
+
const scope = selector?.kind === wire.SelectorKind.View ? this.views.get(selector.text) : this.receivingView() ?? this.document.body;
|
|
709
|
+
const target = this.placementTarget(selector, null, scope);
|
|
710
|
+
const missing = value => [wire.SelectorKind.Id, wire.SelectorKind.View, wire.SelectorKind.TypedId, wire.SelectorKind.Receiving].includes(value?.kind)
|
|
711
|
+
? "MissingTarget" : "UnknownNode";
|
|
712
|
+
if (!target) throw problem(missing(selector), { detail: "Placement needs one target" });
|
|
713
|
+
const childSelector = reader.child()?.unpack();
|
|
714
|
+
const child = childSelector && this.placementTarget(childSelector, target, scope);
|
|
715
|
+
if (childSelector && (!child || child.parentNode !== target)) throw problem(missing(childSelector), { detail: "Placement child missing" });
|
|
716
|
+
this.validatePlacementNames(reader, scope, kind === "Swap" ? [target] : []);
|
|
717
|
+
if (kind === "Remove") { this.discard(target); target.remove(); return; }
|
|
718
|
+
if (kind === "Swap") this.discard(target);
|
|
719
|
+
this.applyNested(reader, index);
|
|
720
|
+
const root = this.node(reader.rootNode(), true);
|
|
721
|
+
switch (kind) {
|
|
722
|
+
case "Append": target.appendChild(root); break;
|
|
723
|
+
case "Swap": target.replaceWith(root); break;
|
|
724
|
+
case "Before": target.insertBefore(root, child ?? target.firstChild); break;
|
|
725
|
+
case "After": target.insertBefore(root, child?.nextSibling ?? null); break;
|
|
726
|
+
default: throw problem("UnknownOp");
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
applyUi(name, m, index) {
|
|
730
|
+
const d = this.document;
|
|
731
|
+
switch (name) {
|
|
732
|
+
case "CreateNode": {
|
|
733
|
+
if (!this.cssInstalled) {
|
|
734
|
+
const style = d.createElement("style"); style.setAttribute("data-ewe-core", "");
|
|
735
|
+
style.textContent = vocab.CORE_CSS; d.head.appendChild(style); this.cssInstalled = true;
|
|
736
|
+
}
|
|
737
|
+
const kind = vocab.WEB_KINDS[m.kind];
|
|
738
|
+
if (!kind) this.report("UnknownKind", { unitIndex: index, node: m.nodeId });
|
|
739
|
+
const el = d.createElement(kind?.tag ?? "div");
|
|
740
|
+
this.sharedKinds.set(el, wire.NodeKind[m.kind]);
|
|
741
|
+
el.className = kind?.cls ?? "ewe-unknown";
|
|
742
|
+
if (m.kind === wire.NodeKind.DRAWING_SURFACE) this.drawingTargets.push([el, m.nodeId]);
|
|
743
|
+
for (const [attr, value] of kind?.attrs ?? []) el.setAttribute(attr, value);
|
|
744
|
+
el.setAttribute("primal-id", String(m.nodeId));
|
|
745
|
+
if (m.kind === wire.NodeKind.OVERLAY && el.showPopover) {
|
|
746
|
+
el.setAttribute("popover", "manual");
|
|
747
|
+
this.layers.add(el);
|
|
748
|
+
}
|
|
749
|
+
if ([wire.NodeKind.MODAL, wire.NodeKind.CONFIRMATION_DIALOG, wire.NodeKind.BOTTOM_SHEET].includes(m.kind)) {
|
|
750
|
+
const Controller = d.defaultView?.AbortController ?? globalThis.AbortController;
|
|
751
|
+
const controller = new Controller();
|
|
752
|
+
this.containerEvents.set(el, controller);
|
|
753
|
+
const options = { signal: controller.signal };
|
|
754
|
+
if (m.kind !== wire.NodeKind.BOTTOM_SHEET) {
|
|
755
|
+
this.layers.add(el);
|
|
756
|
+
el.addEventListener("cancel", event => {
|
|
757
|
+
event.preventDefault();
|
|
758
|
+
const cancel = Array.from(el.querySelectorAll('.ewe-cancel-button'))
|
|
759
|
+
.find(node => node.closest("dialog") === el && !node.disabled && !node.closest("[hidden]")
|
|
760
|
+
&& node.hasAttribute("primal:onclick"));
|
|
761
|
+
cancel?.click();
|
|
762
|
+
}, options);
|
|
763
|
+
} else {
|
|
764
|
+
wireBottomSheet(el, options);
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
if (m.sharing !== wire.ConnectionSharing.TransportDefault) {
|
|
768
|
+
el.setAttribute("data-connection-shared", String(m.sharing === wire.ConnectionSharing.Shared));
|
|
769
|
+
}
|
|
770
|
+
if (m.keepAlive) el.setAttribute("data-connection-keep-alive", "true");
|
|
771
|
+
this.origin?.onMount?.(m.nodeId, el);
|
|
772
|
+
this.registry.register(m.nodeId, el);
|
|
773
|
+
break;
|
|
774
|
+
}
|
|
775
|
+
case "SetText": {
|
|
776
|
+
const node = this.node(m.nodeId);
|
|
777
|
+
for (const child of Array.from(node.childNodes)) this.discard(child);
|
|
778
|
+
node.textContent = m.text ?? ""; break;
|
|
779
|
+
}
|
|
780
|
+
case "SetProp": applyProp(this.node(m.nodeId), m.prop, m.valueType, m.value); break;
|
|
781
|
+
case "AppendChild": this.node(m.parentId).appendChild(this.node(m.childId, true)); break;
|
|
782
|
+
case "InsertBefore": {
|
|
783
|
+
const parent = this.node(m.parentId);
|
|
784
|
+
const before = this.node(m.beforeId);
|
|
785
|
+
parent.insertBefore(this.node(m.childId, true), before);
|
|
786
|
+
break;
|
|
787
|
+
}
|
|
788
|
+
case "Remove": { const node = this.node(m.nodeId); this.discard(node); node.remove(); this.registry.unregister(m.nodeId); break; }
|
|
789
|
+
case "BindAction": case "UnbindAction": {
|
|
790
|
+
const el = this.node(m.nodeId), event = vocab.WEB_EVENTS[m.event];
|
|
791
|
+
if (!event) throw problem("UnknownOp");
|
|
792
|
+
const attr = "primal:on" + event;
|
|
793
|
+
const dispatcher = this.deps.dispatcher ?? this.deps.runtime?.dispatcher;
|
|
794
|
+
if (name === "BindAction") { el.setAttribute(attr, m.action); dispatcher?.scanAndWire?.(el); }
|
|
795
|
+
else { el.removeAttribute(attr); dispatcher?.off?.(el, event); }
|
|
796
|
+
break;
|
|
797
|
+
}
|
|
798
|
+
case "AttachState": this.node(m.rootNode).setAttribute("primal::state", base64urlEncode(m.state ?? [])); break;
|
|
799
|
+
case "UiBehaviour":
|
|
800
|
+
this.bindings.push({registry: this.registry, node:this.node(m.nodeId),id:m.nodeId,index,name:m.behaviour,args:m.args,shared:true});
|
|
801
|
+
break;
|
|
802
|
+
case "LiveMount": {
|
|
803
|
+
const el = d.createElement(m.kind === wire.LiveKind.Stream ? "mount-stream" : "mount-data");
|
|
804
|
+
const transport = ["local", "sse", "websocket", "fetch"][m.transport];
|
|
805
|
+
for (const [key, value] of Object.entries({ api: m.endpoint, transport, protocol: "frame",
|
|
806
|
+
"data-channel-id": m.channelId, "data-resume-from": m.resumeFrom, "primal-id": m.nodeId })) el.setAttribute(key, String(value));
|
|
807
|
+
if (m.sharing !== wire.ConnectionSharing.TransportDefault) {
|
|
808
|
+
el.setAttribute("data-connection-shared", String(m.sharing === wire.ConnectionSharing.Shared));
|
|
809
|
+
}
|
|
810
|
+
if (m.keepAlive) el.setAttribute("data-connection-keep-alive", "true");
|
|
811
|
+
this.origin?.onMount?.(m.nodeId, el);
|
|
812
|
+
this.registry.register(m.nodeId, el); break;
|
|
813
|
+
}
|
|
814
|
+
default: throw problem("UnknownOp", { field: "ui" });
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
applyWebReader(name, reader, index) {
|
|
818
|
+
const m = reader.unpack();
|
|
819
|
+
const d = this.document;
|
|
820
|
+
const id = m.nodeId;
|
|
821
|
+
const resolveName = (id, custom, names) => {
|
|
822
|
+
const value = id ? names[id - 1] : custom;
|
|
823
|
+
if (!value) throw problem("BadFrame");
|
|
824
|
+
return value;
|
|
825
|
+
};
|
|
826
|
+
const property = () => resolveName(m.nameId, m.customName, vocab.ATTR_NAMES);
|
|
827
|
+
switch (name) {
|
|
828
|
+
case "WebElement": {
|
|
829
|
+
const el = d.createElement(resolveName(m.tagId, m.customTag, vocab.TAG_NAMES));
|
|
830
|
+
if (m.className) el.className = m.className;
|
|
831
|
+
this.origin?.onMount?.(id, el);
|
|
832
|
+
this.nodeIds.set(el, id); this.registry.stage(id, el); break;
|
|
833
|
+
}
|
|
834
|
+
case "WebText": {
|
|
835
|
+
const node = d.createTextNode(m.content ?? "");
|
|
836
|
+
this.origin?.onMount?.(id, node);
|
|
837
|
+
this.nodeIds.set(node, id); this.registry.stage(id, node); break;
|
|
838
|
+
}
|
|
839
|
+
case "WebRegisterNode": this.registry.applyRegister(id, d); break;
|
|
840
|
+
case "WebUnregisterNode": this.registry.unregister(id); break;
|
|
841
|
+
case "WebReplaceNode": {
|
|
842
|
+
const old = this.node(m.oldId), next = this.node(m.newId, true);
|
|
843
|
+
this.discard(old); old.replaceWith(next);
|
|
844
|
+
this.registry.unregister(m.oldId); this.registry.register(m.newId, next); break;
|
|
845
|
+
}
|
|
846
|
+
case "WebDetachChild": this.node(m.parentId).removeChild(this.node(m.childId)); break;
|
|
847
|
+
case "WebSetAttribute": case "WebRemoveAttribute": {
|
|
848
|
+
const attr = resolveName(m.attrId, m.customAttr, vocab.ATTR_NAMES);
|
|
849
|
+
if (attr.toLowerCase() === "primal::state") throw problem("BadFrame");
|
|
850
|
+
if (name === "WebSetAttribute") this.node(id).setAttribute(attr, m.value ?? "");
|
|
851
|
+
else this.node(id).removeAttribute(attr);
|
|
852
|
+
break;
|
|
853
|
+
}
|
|
854
|
+
case "HtmlMorph": {
|
|
855
|
+
const target = this.resolve(m.target);
|
|
856
|
+
if (!target) throw problem("Morph");
|
|
857
|
+
if (m.action === wire.MorphAction.ReplaceChildren && this.deps.morph && d.createRange) {
|
|
858
|
+
const previous = Array.from(target.querySelectorAll("*"));
|
|
859
|
+
this.deps.morph(target, d.createRange().createContextualFragment(m.content), d);
|
|
860
|
+
const removed = new Set(previous.filter(n => !target.contains(n)));
|
|
861
|
+
for (const n of removed) if (!removed.has(n.parentNode)) this.discard(n);
|
|
862
|
+
} else {
|
|
863
|
+
switch (m.action) {
|
|
864
|
+
case wire.MorphAction.ReplaceChildren:
|
|
865
|
+
for (const child of Array.from(target.childNodes ?? [])) this.discard(child);
|
|
866
|
+
target.innerHTML = m.content;
|
|
867
|
+
break;
|
|
868
|
+
case wire.MorphAction.ReplaceElement:
|
|
869
|
+
target.insertAdjacentHTML("afterend", m.content);
|
|
870
|
+
this.discard(target);
|
|
871
|
+
target.remove();
|
|
872
|
+
break;
|
|
873
|
+
case wire.MorphAction.InsertBefore: target.insertAdjacentHTML("beforebegin", m.content); break;
|
|
874
|
+
case wire.MorphAction.InsertAfter: target.insertAdjacentHTML("afterend", m.content); break;
|
|
875
|
+
case wire.MorphAction.AppendSibling:
|
|
876
|
+
(target.parentNode ?? target.parent)?.insertAdjacentHTML("beforeend", m.content);
|
|
877
|
+
break;
|
|
878
|
+
default: throw problem("Morph");
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
break;
|
|
882
|
+
}
|
|
883
|
+
case "ScriptNode": {
|
|
884
|
+
const el = d.createElement("script");
|
|
885
|
+
el.setAttribute("primal:script", ""); el.setAttribute("scoped", "");
|
|
886
|
+
// The hydrator runs the body in the parent scope.
|
|
887
|
+
el.type = "application/primal-script";
|
|
888
|
+
el.textContent = m.body;
|
|
889
|
+
const parent = this.node(m.parentId);
|
|
890
|
+
parent.appendChild(el);
|
|
891
|
+
this.deps.hydrate?.(parent, d); break;
|
|
892
|
+
}
|
|
893
|
+
case "WebBehaviour": {
|
|
894
|
+
this.bindings.push({registry: this.registry, node:this.node(id),id,index,name:m.custom,args:m.args,shared:false});
|
|
895
|
+
break;
|
|
896
|
+
}
|
|
897
|
+
case "WebProperty": {
|
|
898
|
+
let value = m.value;
|
|
899
|
+
try { value = JSON.parse(value); } catch { /* A plain string is a valid property. */ }
|
|
900
|
+
this.node(id)[property()] = value;
|
|
901
|
+
break;
|
|
902
|
+
}
|
|
903
|
+
case "WebStyle": this.node(id).style[property()] = m.value; break;
|
|
904
|
+
case "WebAddClass": this.node(id).classList.add(m.className); break;
|
|
905
|
+
case "WebRemoveClass": this.node(id).classList.remove(m.className); break;
|
|
906
|
+
case "WebAddListener": case "WebRemoveListener": {
|
|
907
|
+
const node = this.node(id), event = property();
|
|
908
|
+
let listeners = this.elementListeners.get(node);
|
|
909
|
+
if (!listeners) this.elementListeners.set(node, listeners = new Map());
|
|
910
|
+
if (name === "WebAddListener" && !listeners.has(event)) {
|
|
911
|
+
const deliver = this.origin?.onEvent ?? this.deps.onEvent;
|
|
912
|
+
const handler = value => deliver?.(event, id, value, node);
|
|
913
|
+
listeners.set(event, handler);
|
|
914
|
+
node.addEventListener(event, handler);
|
|
915
|
+
} else if (name === "WebRemoveListener" && listeners.has(event)) {
|
|
916
|
+
node.removeEventListener(event, listeners.get(event));
|
|
917
|
+
listeners.delete(event);
|
|
918
|
+
}
|
|
919
|
+
break;
|
|
920
|
+
}
|
|
921
|
+
default: throw problem("UnknownOp", {field:"web"});
|
|
922
|
+
}
|
|
923
|
+
}
|
|
924
|
+
applyColumnar(batch, index) {
|
|
925
|
+
const codes = batch.opCodesArray() ?? [];
|
|
926
|
+
const cols = ["nodeIds", "argA", "argB", "blobAOff", "blobBOff"].map((name, i) =>
|
|
927
|
+
vector(batch, name, 6 + 2*i, Uint32Array, this.stats));
|
|
928
|
+
const [nodes, args, values, starts, second] = cols;
|
|
929
|
+
const bytes = batch.blobBytesArray() ?? new Uint8Array();
|
|
930
|
+
if (cols.some((v,i) => v.length !== codes.length + Number(i >= 3)) ||
|
|
931
|
+
starts[0] !== 0 || starts.at(-1) !== bytes.length ||
|
|
932
|
+
(second[0] !== 0 && second[0] !== bytes.length)) throw problem("BadFrame");
|
|
933
|
+
const bits = new DataView(new ArrayBuffer(4));
|
|
934
|
+
for (let i = 0; i < codes.length; i++) {
|
|
935
|
+
try {
|
|
936
|
+
if (starts[i] > starts[i+1] || starts[i+1] > bytes.length || second[i] !== second[i+1]) throw problem("BadFrame");
|
|
937
|
+
const blob = bytes.subarray(starts[i], starts[i+1]);
|
|
938
|
+
const name = wire.UiOperation[codes[i]];
|
|
939
|
+
const nodeId = nodes[i], a = args[i], b = values[i];
|
|
940
|
+
const m = { nodeId };
|
|
941
|
+
switch (name) {
|
|
942
|
+
case "CreateNode": m.kind = a; break;
|
|
943
|
+
case "SetText": m.text = utf8.decode(blob); break;
|
|
944
|
+
case "SetProp": {
|
|
945
|
+
m.prop = a & 0xffff;
|
|
946
|
+
const kind = vocab.PROP_KIND[m.prop];
|
|
947
|
+
m.valueType = wire.PropValue[kind];
|
|
948
|
+
bits.setUint32(0, b, true);
|
|
949
|
+
switch (kind) {
|
|
950
|
+
case "Text": m.value = {v: utf8.decode(blob)}; break;
|
|
951
|
+
case "Length": m.value = {v: {value: bits.getFloat32(0, true), unit: a >>> 16}}; break;
|
|
952
|
+
case "ColorToken": case "FontToken": m.value = {id: b}; break;
|
|
953
|
+
case "Bool": m.value = {v: Boolean(b)}; break;
|
|
954
|
+
case "Axis": case "Alignment": m.value = {v: b}; break;
|
|
955
|
+
default: throw problem("BadFrame");
|
|
956
|
+
}
|
|
957
|
+
break;
|
|
958
|
+
}
|
|
959
|
+
case "InsertBefore": case "AppendChild": Object.assign(m, {parentId: nodeId, childId: a, beforeId: b}); break;
|
|
960
|
+
case "Remove": break;
|
|
961
|
+
case "BindAction": m.action = utf8.decode(blob); m.event = a; break;
|
|
962
|
+
case "UnbindAction": m.event = a; break;
|
|
963
|
+
case "AttachState": m.rootNode = nodeId; m.state = blob; break;
|
|
964
|
+
default: throw problem("UnknownOp", {field: "columnar"});
|
|
965
|
+
}
|
|
966
|
+
this.applyUi(name, m, index); this.stats.rows++;
|
|
967
|
+
} catch (e) { this.report(e.report?.code ?? "BadFrame", {unitIndex: index, ...(e.report ?? {}), row: i}); }
|
|
968
|
+
}
|
|
969
|
+
}
|
|
970
|
+
applyData(data) {
|
|
971
|
+
const table = data.table();
|
|
972
|
+
let detail;
|
|
973
|
+
if (table) {
|
|
974
|
+
const columns = [];
|
|
975
|
+
const types = { I32: [wire.I32s, Int32Array], I64: [wire.I64s, BigInt64Array],
|
|
976
|
+
F64: [wire.F64s, Float64Array], Bool: [wire.Bools, Uint8Array], Utf8: [wire.Strings] };
|
|
977
|
+
for (let i = 0; i < table.columnsLength(); i++) {
|
|
978
|
+
const col = table.columns(i);
|
|
979
|
+
const type = types[wire.ColumnData[col.dataType()]];
|
|
980
|
+
if (!type) throw problem("BadFrame");
|
|
981
|
+
const values = col.data(new type[0]());
|
|
982
|
+
const items = type[1] ? vector(values, "values", 4, type[1]) :
|
|
983
|
+
Array.from({length: values.valuesLength()}, (_, j) => values.values(j));
|
|
984
|
+
columns.push({name: col.name(), data: items, validity: col.validityArray()});
|
|
985
|
+
}
|
|
986
|
+
detail = {kind: "table", table: {rows: table.rows(), columns}};
|
|
987
|
+
} else {
|
|
988
|
+
const blob = data.arrow() ?? data.msgpack();
|
|
989
|
+
if (!blob) throw problem("BadFrame");
|
|
990
|
+
detail = {kind: data.arrow() ? "arrow-ipc" : "messagepack", bytes: blob.bytesArray()};
|
|
991
|
+
}
|
|
992
|
+
const target = data.targetNode() ? this.node(data.targetNode()) : this.receivingView();
|
|
993
|
+
dispatchEvent(target || this.document, "ewe:data", detail);
|
|
994
|
+
}
|
|
995
|
+
applyControl(control) {
|
|
996
|
+
if (control.caps()) this.deps.onCaps?.(control.caps().unpack());
|
|
997
|
+
for (const [field, code] of [["stateExpired", "StateExpired"], ["updateRequired", "UpdateRequired"]]) {
|
|
998
|
+
if (control[field]()) this.deps.onError?.({ ...control[field]().unpack(), code });
|
|
999
|
+
}
|
|
1000
|
+
if (control.error()) {
|
|
1001
|
+
const error = control.error().unpack();
|
|
1002
|
+
const detail = { ...error, code: wire.ErrorCode[error.code] };
|
|
1003
|
+
this.deps.onError?.(detail); dispatchEvent(this.document, "ewe:error", detail);
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
export function installFrameRuntime(wasmUi, options = {}) {
|
|
1009
|
+
const doc = options.document ?? globalThis.document;
|
|
1010
|
+
const runtime = wasmUi.Patcher.runtime;
|
|
1011
|
+
if (runtime.frames?.document === doc) return runtime.frames;
|
|
1012
|
+
if (runtime.document && runtime.document !== doc) runtime.dispatcher = null;
|
|
1013
|
+
runtime.frames = new FrameApplicator({document: doc, registry: wasmUi.Patcher.ensureRegistry(doc),
|
|
1014
|
+
morph: wasmUi.MorphDom.morph, hydrate: wasmUi.Hydrator.hydrate, runtime, onApplied: wasmUi.Patcher.markApplied,
|
|
1015
|
+
...options });
|
|
1016
|
+
bindLiveMounts(runtime, runtime.frames);
|
|
1017
|
+
wasmUi.Hydrator.behaviourMarkers = registryBehaviours.hydrateMarkers;
|
|
1018
|
+
if (doc.body) registryBehaviours.hydrateMarkers(doc.body);
|
|
1019
|
+
wasmUi.ProtocolHandler.frameHook = {isFrame, splitFrames, readFrames, readViewResponse, maxFrameBytes: runtime.frames.maxFrameBytes};
|
|
1020
|
+
return runtime.frames;
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
globalThis.EweFrames = {installFrameRuntime};
|