@gramlot/gramlot 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,618 @@
1
+ import {BuilderBase, SourceBag, sourceTarget} from '@genrojs/builders';
2
+ import {HtmlElement} from '../view/html.js';
3
+ import {ControlAdapter, RadioGroups, SelectControl} from '../view/controls.js';
4
+ import {ButtonBinding} from '../view/button.js';
5
+ import {NativeEventBinding} from '../view/events.js';
6
+ import {References} from '../references.js';
7
+ import {GramlotBuilderBag, GramlotBuilderBagNode} from '../builder/source.js';
8
+ import {BindingRuntime} from '../binding/runtime.js';
9
+ import {requireInstallable} from '../binding/installation.js';
10
+ import {GramlotHtmlRenderer} from './gramlot-html-renderer.js';
11
+ import {displayItem} from './attributes.js';
12
+
13
+ /**
14
+ * Own the live DOM lifecycle driven by typed Source insert/update/delete events.
15
+ * The attribute rules are GramlotHtmlRenderer's; this class replaces its output with DOM elements.
16
+ */
17
+ export class GramlotRenderer extends GramlotHtmlRenderer {
18
+ static renderType = 'object';
19
+ // Nodes inside buildNode: events on them are ignored on arrival (P4, R04).
20
+ #constructing = new Set();
21
+ // The attributes of each node after runtimeValues and the `==` evaluation, binding attributes included.
22
+ #resolvedAttributes = new WeakMap();
23
+ // The resolved projection that `project` hands to the rebuild of a control whose shape changed.
24
+ #rebuildAttributes = new WeakMap();
25
+
26
+ /** The live renderer of one Gramlot page: `binding` is the page's BindingRuntime (§4.3). */
27
+ constructor(builder, source, destination, {binding} = {}) {
28
+ super(builder);
29
+ if (!(builder instanceof BuilderBase) || !(source instanceof GramlotBuilderBag) || destination?.nodeType !== 1) {
30
+ throw new TypeError('GramlotRenderer requires a BuilderBase, GramlotBuilderBag and HTML destination');
31
+ }
32
+ if (!(binding instanceof BindingRuntime)) throw new TypeError('GramlotRenderer requires a BindingRuntime');
33
+ if (!(source._builder instanceof BuilderBase)) throw new TypeError('SourceBag requires builder ownership');
34
+ this._binding = binding;
35
+ this.source = source;
36
+ this.destination = destination;
37
+ this.html = new HtmlElement({metadataAttributes: ['__ref']});
38
+ this.records = new Map();
39
+ this.references = new References(source);
40
+ this.pending = [];
41
+ this.building = false;
42
+ this.disposed = false;
43
+ this.elements = new WeakMap();
44
+ // The instance id scopes the generated radio names to this page (P11, S11).
45
+ this.instanceId = crypto.randomUUID();
46
+ this.radioGroups = new RadioGroups(this);
47
+ this.subscription = `html-source-renderer-${this.instanceId}`;
48
+ source.subscribe(this.subscription, {any: event => this.receive(event)});
49
+ }
50
+
51
+ get binding() { return this._binding; }
52
+ /** The page's InlineCompiler: the live renderer evaluates the `==` expressions (S09). */
53
+ get inlineCompiler() { return this.binding.inlineCompiler; }
54
+
55
+ /**
56
+ * The resolved projection of `node` (runtimeValues, then `==`, GC-210 C04.1), kept for the consumers
57
+ * of binding attributes that never reach the element: `type`, `multiple`, `group`, `live`, `visible`.
58
+ * The rebuild of a control whose shape changed receives the projection `project` just computed, so
59
+ * its `==` are evaluated once.
60
+ */
61
+ evaluateExpressions(node, runtimeAttrs) {
62
+ const attrs = this.#rebuildAttributes.get(node) ?? super.evaluateExpressions(node, runtimeAttrs);
63
+ this.#rebuildAttributes.delete(node);
64
+ this.#resolvedAttributes.set(node, attrs);
65
+ return attrs;
66
+ }
67
+
68
+ /**
69
+ * Structural Source fragments are owned by the live renderer.
70
+ * A data-element has no DOM: it is recognized before validation and runtimeValues (R08).
71
+ * A node brought into the Source during the current construction, by a Source event still in
72
+ * the queue (an `_init`, an observer), is built when that event is processed (P4).
73
+ */
74
+ render(node, opts = {}) {
75
+ if (!(node instanceof GramlotBuilderBagNode)) throw new TypeError('Source children must be GramlotBuilderBagNodes');
76
+ if (node._getMeta('data_element')) return null;
77
+ if (!this.binding.bindingFor(node) && this.#queued(node)) return null;
78
+ if (node.nodeTag) this.html.validate(node, node._getMeta('subbuilder') ? node.parentBag._builder : node.builder);
79
+ else if (!(node.value instanceof SourceBag)) throw new TypeError('Source fragments must contain child SourceBags');
80
+ return node.nodeTag ? super.render(node, opts) : this.renderFragment(node, opts);
81
+ }
82
+
83
+ renderFragment(node, {document = this.destination.ownerDocument, ...opts} = {}) {
84
+ const fragment = document.createDocumentFragment();
85
+ const record = {
86
+ node, binding: this.#nodeBinding(node), container: null, parent: null, children: new Set(), cleanup: [],
87
+ start: document.createComment('source-fragment'),
88
+ end: document.createComment('/source-fragment'),
89
+ };
90
+ this.records.set(node, record);
91
+ this.elements.set(fragment, record);
92
+ fragment.append(record.start);
93
+ for (const child of node.value.getNodes()) {
94
+ const rendered = this.render(child, {document, ...opts});
95
+ if (rendered === null) continue;
96
+ fragment.append(rendered);
97
+ const childRecord = this.elements.get(rendered);
98
+ if (childRecord) {
99
+ childRecord.parent = record;
100
+ record.children.add(child);
101
+ }
102
+ }
103
+ fragment.append(record.end);
104
+ return fragment;
105
+ }
106
+
107
+ /**
108
+ * RendererBase's dialect hook: create one detached element. The attributes arrive adapted by the
109
+ * node's renderer (this one for HTML, GramlotSvgRenderer for SVG); an HTML node also gets its
110
+ * noConvertStyle attributes back and its display directives consumed, as in the string output.
111
+ * A form control gets its ControlAdapter after `compose`, so the first projection of a `select`
112
+ * finds its options (S10); the adapter is detached through `record.cleanup`, which also takes a
113
+ * radio out of its RadioGroups group (S11). A `<button>` gets its ButtonBinding, then each
114
+ * `connect_on<event>` its NativeEventBinding, so the button mechanism runs first (S12); both are
115
+ * detached through `record.cleanup`.
116
+ */
117
+ renderedItem(node, item, runtimeAttrs, {tag, document = this.destination.ownerDocument} = {}) {
118
+ let attrs = runtimeAttrs;
119
+ item = this.expressionValue(node, item);
120
+ if (this.getRender(node.builder) === this) {
121
+ [item, attrs] = displayItem(item, this.restoreNativeAttributes(node, runtimeAttrs));
122
+ }
123
+ const children = Array.isArray(item) ? item : [];
124
+ const text = Array.isArray(item) ? attrs._text : item;
125
+ const resolved = this.#resolvedAttributes.get(node);
126
+ const record = {
127
+ node,
128
+ binding: this.#nodeBinding(node),
129
+ container: null,
130
+ parent: null,
131
+ children: new Set(),
132
+ cleanup: [],
133
+ resolved,
134
+ ...this.html.create(node, document, tag, attrs, resolved.visible ?? null),
135
+ };
136
+ this.html.compose(record, text, children);
137
+ record.shape = ControlAdapter.shape(record.element, resolved);
138
+ // Registered before any listener: a failed first projection leaves a record the failed-build
139
+ // cleanup removes, listeners included (ASTRA-06).
140
+ this.records.set(node, record);
141
+ this.elements.set(record.element, record);
142
+ const control = ControlAdapter.for(record.binding, record);
143
+ if (control) {
144
+ record.control = control;
145
+ control.attach();
146
+ record.cleanup.push(() => control.detach());
147
+ this.#projectControl(record, node, attrs, null);
148
+ }
149
+ const button = ButtonBinding.for(record.binding, record);
150
+ if (button) {
151
+ record.button = button;
152
+ button.attach();
153
+ record.cleanup.push(() => button.detach());
154
+ }
155
+ this.#connectEvents(record);
156
+ this.references?.register(node, record.element);
157
+ for (const element of children) {
158
+ const child = this.elements.get(element);
159
+ if (!child) continue;
160
+ child.parent = record;
161
+ child.container = record.element;
162
+ record.children.add(child.node);
163
+ }
164
+ return record.element;
165
+ }
166
+
167
+ /**
168
+ * Validate a detached candidate without changing the observed Source (§5.1 step 1): grammar,
169
+ * installation rules (`requireInstallable`) and references. Mounted references below
170
+ * replacingNode are excluded when checking a replacement.
171
+ */
172
+ validateCandidate(block, {replacingNode = null} = {}) {
173
+ if (!(block instanceof GramlotBuilderBag)) throw new TypeError('Source values must be GramlotBuilderBags');
174
+ const excluded = new Set();
175
+ const exclude = node => {
176
+ excluded.add(node);
177
+ for (const child of this.records.get(node)?.children ?? []) exclude(child);
178
+ };
179
+ // Replacing a node's VALUE retains that node and its reference. Only
180
+ // the rendered descendants which the replacement removes leave the ref set.
181
+ // During freeze these can differ from the current Source descendants.
182
+ for (const child of this.records.get(replacingNode)?.children ?? []) exclude(child);
183
+ this.#validateBlock(block, replacingNode ? replacingNode.nodeTag : null);
184
+ requireInstallable(block);
185
+ this.references?.validate(block, excluded);
186
+ return block;
187
+ }
188
+
189
+ #validateBlock(block, parentTag = null) {
190
+ const bags = new Set();
191
+ const walk = (bag, parentTag = null) => {
192
+ if (!(bag instanceof GramlotBuilderBag) || bags.has(bag)) {
193
+ throw new TypeError('Source values must be unshared, acyclic GramlotBuilderBags');
194
+ }
195
+ if (!(bag._builder instanceof BuilderBase)) throw new TypeError('SourceBag requires builder ownership');
196
+ bags.add(bag);
197
+ for (const node of bag.getNodes()) {
198
+ if (!(node instanceof GramlotBuilderBagNode)) throw new TypeError('Source children must be GramlotBuilderBagNodes');
199
+ if (!(node.builder instanceof BuilderBase)) throw new TypeError('SourceBagNode requires builder ownership');
200
+ if (node.resolver) throw new TypeError('Source resolvers are outside this port');
201
+ if (node._getMeta('data_element')) {
202
+ // A data-element is not a visual child: its own declaration only.
203
+ node.builder.validateNode(node);
204
+ } else if (node.nodeTag) {
205
+ // The enclosing Bag owns the boundary declaration; the node
206
+ // and its contents already belong to the entered dialect.
207
+ const owner = node._getMeta('subbuilder') ? bag._builder : node.builder;
208
+ this.html.validate(node, owner);
209
+ if (!node._getMeta('subbuilder')) {
210
+ node.builder.validateParent(node.nodeTag, parentTag);
211
+ }
212
+ } else {
213
+ if (!(node.value instanceof SourceBag)) {
214
+ throw new TypeError('Source fragments must contain child SourceBags');
215
+ }
216
+ if (Object.keys(node.attr).some(key => key !== '_meta')) {
217
+ throw new TypeError('Fragment attributes are unsupported');
218
+ }
219
+ }
220
+ if (node.value instanceof SourceBag) {
221
+ walk(node.value, node._getMeta('subbuilder') ? null : (node.nodeTag ?? parentTag));
222
+ }
223
+ }
224
+ };
225
+ walk(block, parentTag);
226
+ }
227
+
228
+ /** Suspend rendering for a mounted branch; Source keeps changing normally. */
229
+ freeze(node) {
230
+ node = sourceTarget(node);
231
+ const record = this.records.get(node);
232
+ if (!record || this.disposed) throw new Error('Freeze requires a mounted Source node');
233
+ record.frozen = true;
234
+ }
235
+
236
+ /** Resume the whole branch and build its current Source once. */
237
+ unfreeze(node) {
238
+ node = sourceTarget(node);
239
+ const record = this.records.get(node);
240
+ if (!record || this.disposed) throw new Error('Unfreeze requires a mounted Source node');
241
+ const thaw = record => {
242
+ delete record.frozen;
243
+ for (const child of record.children) thaw(this.records.get(child));
244
+ };
245
+ thaw(record);
246
+ if (this.#isFrozen(node)) return;
247
+ if (this.attached(node)) this.#rebuild(node);
248
+ else this.remove(node);
249
+ }
250
+
251
+ #isFrozen(node) {
252
+ while (node) {
253
+ const record = this.records.get(node);
254
+ if (record?.frozen) return true;
255
+ // Deleted nodes may have lost their Source parent. Their existing
256
+ // mount record still belongs to the frozen, previously rendered branch.
257
+ node = node.parentBag?.parentNode ?? record?.parent?.node;
258
+ }
259
+ return false;
260
+ }
261
+
262
+ /**
263
+ * Source event intake (§5.2): an event on a node under construction is ignored
264
+ * on arrival; every other event is queued and processed in arrival order.
265
+ * Semantic work runs for every event, also under freeze; structural work only
266
+ * outside frozen branches. A failing disposer does not block the rest: the
267
+ * closing errors of the semantic work and the cleanup errors of the removals
268
+ * are thrown after the structural work of the event.
269
+ */
270
+ receive(event) {
271
+ if (this.disposed) return;
272
+ if (Array.isArray(event.node)) {
273
+ const nodes = event.node.filter(node => !this.#constructing.has(node));
274
+ if (!nodes.length) return;
275
+ event = {...event, node: nodes};
276
+ } else if (this.#constructing.has(event.node)) return;
277
+ this.pending.push(event);
278
+ if (this.building) return;
279
+ this.building = true;
280
+ try {
281
+ while (this.pending.length) {
282
+ const next = this.pending.shift();
283
+ if (next.evt !== 'del' && !this.attached(next.node)) continue;
284
+ if (next.evt !== 'del' && next.evt !== 'upd_attrs') this.#requireGramlotClasses(next);
285
+ const errors = this.binding.handleSourceEvent(next);
286
+ try { this.#applyStructure(next, errors); }
287
+ catch (error) {
288
+ if (!errors.length) throw error;
289
+ errors.push(error);
290
+ }
291
+ if (errors.length) throw errors.length === 1 ? errors[0] : new AggregateError(errors, 'Source cleanup failed');
292
+ }
293
+ } catch (error) {
294
+ this.pending.length = 0;
295
+ throw error;
296
+ } finally {
297
+ this.building = false;
298
+ }
299
+ }
300
+
301
+ /**
302
+ * The structural work of one Source event outside frozen branches: `insert`, `remove`, `update`.
303
+ * The cleanup errors of the removals of a `del` go to `errors`, so every removed node leaves.
304
+ */
305
+ #applyStructure(event, errors) {
306
+ if (event.evt === 'del') {
307
+ for (const node of Array.isArray(event.node) ? event.node : [event.node]) {
308
+ if (this.#isFrozen(node)) continue;
309
+ const parent = this.records.get(node)?.parent ?? null;
310
+ try { this.remove(node); } catch (error) { errors.push(error); }
311
+ this.#optionsChanged(parent);
312
+ }
313
+ return;
314
+ }
315
+ if (this.#isFrozen(event.node)) return;
316
+ if (event.evt === 'ins') this.insert(event.node);
317
+ else if (event.evt.startsWith('upd_')) this.update(event.node, event.evt);
318
+ else throw new Error(`Unsupported Source event: ${event.evt}`);
319
+ }
320
+
321
+ /** Whether `node` still belongs to the observed Source. */
322
+ attached(node) {
323
+ let bag = node.parentBag;
324
+ while (bag && bag !== this.source) bag = bag.parentNode?.parentBag;
325
+ return bag === this.source;
326
+ }
327
+
328
+ /** Whether `node` or one of its ancestors is the node of a Source event still in the queue. */
329
+ #queued(node) {
330
+ const pending = new Set(this.pending.flatMap(event => Array.isArray(event.node) ? event.node : [event.node]));
331
+ for (let current = node; current; current = current.parentBag?.parentNode) {
332
+ if (pending.has(current)) return true;
333
+ }
334
+ return false;
335
+ }
336
+
337
+ /** R07: an inserted node or a new value is made of Gramlot Source classes, checked before any effect. */
338
+ #requireGramlotClasses(event) {
339
+ const walk = node => {
340
+ if (!(node instanceof GramlotBuilderBagNode)) throw new TypeError('Source children must be GramlotBuilderBagNodes');
341
+ if (node.value instanceof SourceBag) {
342
+ if (!(node.value instanceof GramlotBuilderBag)) throw new TypeError('Source values must be GramlotBuilderBags');
343
+ for (const child of node.value.getNodes()) walk(child);
344
+ }
345
+ };
346
+ walk(event.node);
347
+ }
348
+
349
+ /**
350
+ * Build an inserted node, then report the build to the BindingRuntime (§5.1 step 7). A node that
351
+ * left the Source meanwhile (an `_init` that removed its own branch, P4) is not built, nor a node
352
+ * already built with its ancestor while its own event waited in the queue. A data-element has no
353
+ * DOM: its build is the report alone.
354
+ */
355
+ insert(node) {
356
+ if (!this.attached(node) || this.records.has(node)) return;
357
+ if (node._getMeta('data_element')) {
358
+ // A `dataController` inserted in a button may give it a mechanism, or an ambiguous one (S12).
359
+ this.records.get(node.parentBag?.parentNode)?.button?.refresh();
360
+ this.binding.branchBuilt(node);
361
+ return;
362
+ }
363
+ const parent = this.records.get(node.parentBag?.parentNode);
364
+ const container = parent?.element ?? parent?.container ?? this.destination;
365
+ const siblings = node.parentBag.getNodes();
366
+ let before = parent?.end ?? null;
367
+ for (let i = siblings.indexOf(node) + 1; i < siblings.length; i++) {
368
+ const record = this.records.get(siblings[i]);
369
+ if (record) { before = record.element ?? record.start; break; }
370
+ }
371
+ this.buildNode(node, container, before, parent);
372
+ }
373
+
374
+ buildNode(node, container, before = null, parent = null) {
375
+ this.#constructing.add(node);
376
+ let output;
377
+ try { output = this.render(node, {document: container.ownerDocument}); }
378
+ catch (error) { this.#discardBuild(node, error); }
379
+ finally { this.#constructing.delete(node); }
380
+ const record = this.records.get(node);
381
+ container.insertBefore(output, before);
382
+ record.parent = parent;
383
+ this.assignContainer(record, container);
384
+ parent?.children.add(node);
385
+ this.#optionsChanged(parent);
386
+ this.binding.branchBuilt(node);
387
+ return record;
388
+ }
389
+
390
+ /**
391
+ * A failed build leaves no record: the children render before their parent, so the records made
392
+ * for the branch before the error are removed with their cleanups (listeners, controls, radio
393
+ * groups, references); then the error propagates. A node not built yet has no built descendant.
394
+ */
395
+ #discardBuild(node, error) {
396
+ const errors = [error];
397
+ const nodes = [];
398
+ const walk = current => {
399
+ nodes.push(current);
400
+ if (current.value instanceof SourceBag) for (const child of current.value.getNodes()) walk(child);
401
+ };
402
+ walk(node);
403
+ for (const each of nodes.reverse()) {
404
+ try { this.remove(each); } catch (cleanupError) { errors.push(cleanupError); }
405
+ }
406
+ throw errors.length === 1 ? error : new AggregateError(errors, 'Source build and cleanup failed');
407
+ }
408
+
409
+ assignContainer(record, container) {
410
+ record.container = container;
411
+ const childContainer = record.element ?? container;
412
+ for (const childNode of record.children) {
413
+ const child = this.records.get(childNode);
414
+ if (child) this.assignContainer(child, childContainer);
415
+ }
416
+ }
417
+
418
+ update(node, event) {
419
+ const record = this.records.get(node);
420
+ if (!record) { this.insert(node); return; }
421
+ const scalarValue = node.value == null || ['string', 'number', 'boolean'].includes(typeof node.value);
422
+ const scalarValueUpdate = event === 'upd_value' && scalarValue
423
+ && record.element && record.children.size === 0 && this.html.matches(record, node);
424
+ if ((event === 'upd_attrs' || scalarValueUpdate) && record.element && this.html.matches(record, node)) {
425
+ if (node.nodeTag) this.html.validate(node, node._getMeta('subbuilder') ? node.parentBag._builder : node.builder);
426
+ this.project(node);
427
+ // A change of `type`, `multiple` or `group` rebuilt the element inside project (C04.1).
428
+ if (event === 'upd_attrs' && this.records.get(node) === record) {
429
+ this.references?.remove(node);
430
+ this.references?.register(node, record.element);
431
+ }
432
+ } else {
433
+ this.#rebuild(node);
434
+ }
435
+ }
436
+
437
+ /**
438
+ * Project the current Source and Data of `node` on its element, keeping the element: the same
439
+ * adaptation as the first render, by the node's own renderer (R16). A node without an element
440
+ * (not built yet, frozen before its first build, a fragment) is left alone; under freeze the
441
+ * elements already built are projected. `change` is the DataChange that asked for it, or null.
442
+ * A form control whose resolved `type`, `multiple` or `group` changed is rebuilt instead, keeping
443
+ * its NodeBinding; under freeze the rebuild waits for the thaw (C04.1, D7). The resolved projection
444
+ * (runtimeValues, then `==`) is computed once and is what every consumer reads, the rebuild included.
445
+ */
446
+ project(node, change = null) {
447
+ const record = this.records.get(node);
448
+ if (!record?.element) return;
449
+ const renderer = this.getRender(node.builder);
450
+ const [value, runtimeAttrs] = node.builder.runtimeValues(node);
451
+ const [, resolvedAttrs] = renderer._handleMeta(node, runtimeAttrs);
452
+ const resolved = this.#resolvedAttributes.get(node);
453
+ if (record.shape !== ControlAdapter.shape(record.element, resolved)) {
454
+ if (this.#isFrozen(node)) return;
455
+ this.#rebuildAttributes.set(node, resolved);
456
+ try { this.#rebuild(node); }
457
+ finally { this.#rebuildAttributes.delete(node); }
458
+ return;
459
+ }
460
+ record.resolved = resolved;
461
+ let attrs = node._getMeta('subbuilder') ? resolvedAttrs : renderer.adaptAttrs(resolvedAttrs);
462
+ const branch = node.value instanceof SourceBag;
463
+ let text = branch ? [] : this.expressionValue(node, value);
464
+ if (renderer === this) [text, attrs] = displayItem(text, this.restoreNativeAttributes(node, attrs));
465
+ this.html.update(record, node, attrs, branch ? attrs._text : text, resolved.visible ?? null);
466
+ this.#projectControl(record, node, attrs, change);
467
+ record.control?.refresh();
468
+ record.button?.refresh();
469
+ this.#connectEvents(record);
470
+ if (record.element.localName === 'option' || record.element.localName === 'optgroup') {
471
+ this.#optionsChanged(record.parent);
472
+ }
473
+ }
474
+
475
+ /**
476
+ * The resolved `value` to the ControlAdapter of `record` when the node declares a `value`, or declared
477
+ * one at the previous projection: its removal shows the control empty once, as html.js did (S10).
478
+ */
479
+ #projectControl(record, node, attrs, change) {
480
+ if (!record.control) return;
481
+ const declared = node.getAttr('value') != null;
482
+ if (declared || record.valueDeclared) record.control.project(attrs.value ?? null, change);
483
+ record.valueDeclared = declared;
484
+ }
485
+
486
+ /**
487
+ * Make the NativeEventBindings of `record` follow the `connect_on<event>` attributes of its node:
488
+ * a removed or changed attribute loses its listener, a new or changed one gets a new listener,
489
+ * an unchanged one keeps its own (S12). The first listener of the record brings one cleanup that
490
+ * detaches them all.
491
+ */
492
+ #connectEvents(record) {
493
+ const declared = new Map(NativeEventBinding.declared(record.node).map(item => [item[0], item]));
494
+ if (!record.events) {
495
+ if (!declared.size) return;
496
+ record.events = new Map();
497
+ record.cleanup.push(() => {
498
+ for (const binding of record.events.values()) binding.detach();
499
+ record.events.clear();
500
+ });
501
+ }
502
+ for (const [attribute, binding] of [...record.events]) {
503
+ if (declared.get(attribute)?.[2] === binding.handler) continue;
504
+ binding.detach();
505
+ record.events.delete(attribute);
506
+ }
507
+ for (const [attribute, [, eventName, handler]] of declared) {
508
+ if (record.events.has(attribute)) continue;
509
+ const binding = new NativeEventBinding(record.binding, record, eventName, handler, attribute);
510
+ binding.attach();
511
+ record.events.set(attribute, binding);
512
+ }
513
+ }
514
+
515
+ /**
516
+ * The children of `record` changed: the nearest `select` above it, through option groups and
517
+ * fragments, is projected again, so its Data value meets the current options (gate decision 8).
518
+ */
519
+ #optionsChanged(record) {
520
+ for (let current = record; current; current = current.parent) {
521
+ if (current.control instanceof SelectControl) {
522
+ this.project(current.node);
523
+ return;
524
+ }
525
+ if (current.element && current.element.localName !== 'optgroup') return;
526
+ }
527
+ }
528
+
529
+ /** The element built from `node`, or null (fragment, data-element, node not built or no longer in the Source). */
530
+ getDomNode(sourceNode) {
531
+ const node = sourceTarget(sourceNode);
532
+ const record = this.records.get(node);
533
+ return record && this.attached(node) ? record.element ?? null : null;
534
+ }
535
+
536
+ /** The Source node of the nearest element generated by this renderer, climbing from `domNode`, or null. */
537
+ getBaseSourceNode(domNode) {
538
+ for (let current = domNode; current; current = current.parentNode) {
539
+ const record = current.nodeType === 1 ? this.elements.get(current) : null;
540
+ if (record) return this.attached(record.node) ? record.node : null;
541
+ }
542
+ return null;
543
+ }
544
+
545
+ /** The NodeBinding of a node being rendered: it is opened before rendering (§5.1 step 4). */
546
+ #nodeBinding(node) {
547
+ const binding = this.binding.bindingFor(node);
548
+ if (!binding) throw new Error(`${node.nodeTag ?? 'fragment'} '${node.label}': rendered without an open NodeBinding`);
549
+ return binding;
550
+ }
551
+
552
+ #rebuild(node) {
553
+ const record = this.records.get(node);
554
+ const before = record.element?.nextSibling ?? record.end?.nextSibling ?? null;
555
+ const container = record.container;
556
+ const parent = record.parent;
557
+ let removeError = null;
558
+ try { this.remove(node); }
559
+ catch (error) { removeError = error; }
560
+ try {
561
+ this.buildNode(node, container, before, parent);
562
+ } catch (commitError) {
563
+ if (removeError) {
564
+ throw new AggregateError(
565
+ [removeError, commitError],
566
+ 'Source replacement cleanup and commit failed',
567
+ );
568
+ }
569
+ throw commitError;
570
+ }
571
+ if (removeError) throw removeError;
572
+ }
573
+
574
+ onDispose(node, callback) {
575
+ const record = this.records.get(node);
576
+ if (!record) throw new Error('Source node is not mounted');
577
+ record.cleanup.push(callback);
578
+ return () => {
579
+ const index = record.cleanup.indexOf(callback);
580
+ if (index !== -1) record.cleanup.splice(index, 1);
581
+ };
582
+ }
583
+
584
+ remove(node) {
585
+ const record = this.records.get(node);
586
+ if (!record) return;
587
+ const errors = [];
588
+ for (const child of [...record.children]) {
589
+ try { this.remove(child); } catch (error) { errors.push(error); }
590
+ }
591
+ for (const cleanup of record.cleanup.splice(0).reverse()) {
592
+ try { cleanup(); } catch (error) { errors.push(error); }
593
+ }
594
+ this.references?.remove(node);
595
+ if (record.element) this.elements.delete(record.element);
596
+ record.element?.remove();
597
+ record.start?.remove();
598
+ record.end?.remove();
599
+ record.parent?.children.delete(node);
600
+ this.records.delete(node);
601
+ if (errors.length) throw new AggregateError(errors, 'Source cleanup failed');
602
+ }
603
+
604
+ dispose() {
605
+ if (this.disposed) return;
606
+ this.disposed = true;
607
+ this.source.unsubscribe(this.subscription, {any: true});
608
+ this.pending.length = 0;
609
+ const errors = [];
610
+ const roots = [...this.records.entries()]
611
+ .filter(([, record]) => !record.parent)
612
+ .map(([node]) => node);
613
+ for (const node of roots) {
614
+ try { this.remove(node); } catch (error) { errors.push(error); }
615
+ }
616
+ if (errors.length) throw new AggregateError(errors, 'Renderer cleanup failed');
617
+ }
618
+ }
@@ -0,0 +1,53 @@
1
+ import {SvgRenderer, svgAttributes} from '@genrojs/builders';
2
+ import {boundaryAttributes, domNames, textValue, withoutBindingAttributes, withoutNullValues} from './attributes.js';
3
+
4
+ // SVG elements written `<tag … />`, as the Python SvgRenderer of Builder (the grammar gives them no children).
5
+ const SVG_VOID_TAGS = new Set([
6
+ 'animate', 'animateMotion', 'animateTransform', 'circle',
7
+ 'ellipse', 'feBlend', 'feColorMatrix', 'feComposite',
8
+ 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap',
9
+ 'feDistantLight', 'feDropShadow', 'feFlood', 'feGaussianBlur',
10
+ 'feImage', 'feMergeNode', 'feMorphology', 'feOffset',
11
+ 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile',
12
+ 'feTurbulence', 'image', 'line', 'metadata', 'path', 'polygon',
13
+ 'polyline', 'rect', 'set', 'stop', 'use',
14
+ ]);
15
+
16
+ /**
17
+ * The renderer of the SVG nodes of a Gramlot Source, owned by a GramlotHtmlRenderer.
18
+ * Attributes: Builder's `svgAttributes`, no style shortcuts, Gramlot names. Output: a string
19
+ * under a string owner, the owner's DOM under the live GramlotRenderer.
20
+ */
21
+ export class GramlotSvgRenderer extends SvgRenderer {
22
+ constructor(builder, owner) {
23
+ super(builder);
24
+ this._owner = owner;
25
+ }
26
+
27
+ get owner() { return this._owner; }
28
+
29
+ /** Builder's meta on the attributes with the `==` evaluated by the owner; a sub-builder boundary node keeps its attributes literal, with the Gramlot filters and names. */
30
+ _handleMeta(node, runtimeAttrs) {
31
+ const [tag, attrs] = super._handleMeta(node, this.owner.evaluateExpressions(node, runtimeAttrs));
32
+ return node._getMeta('subbuilder') ? [tag, svgAttributes(boundaryAttributes(attrs))] : [tag, attrs];
33
+ }
34
+
35
+ /** `_meta`, binding attributes and null values out; Builder's `svgAttributes`; Gramlot names. */
36
+ adaptAttrs(attrs) {
37
+ const {_meta, ...rest} = attrs;
38
+ return domNames(super.adaptAttrs(withoutNullValues(withoutBindingAttributes(rest))));
39
+ }
40
+
41
+ /** The owner's DOM element under the live renderer; otherwise the SVG string, `_text` as node text. */
42
+ renderedItem(node, item, runtimeAttrs, opts = {}) {
43
+ if (this.owner.renderType === 'object') return this.owner.renderedItem(node, item, runtimeAttrs, opts);
44
+ const {_text, ...attrs} = runtimeAttrs;
45
+ item = this.owner.expressionValue(node, item);
46
+ if (Array.isArray(item) && _text != null) item = [this._escapeText(textValue(_text)), ...item];
47
+ if (SVG_VOID_TAGS.has(opts.tag)) {
48
+ const indent = opts.pretty ? ' '.repeat(this._nodeDepth(node, opts.depthOffset ?? 0)) : '';
49
+ return `${indent}<${opts.tag}${this._formatAttrs(attrs)} />${opts.pretty ? '\n' : ''}`;
50
+ }
51
+ return super.renderedItem(node, item, attrs, opts);
52
+ }
53
+ }