@jxsuite/compiler 9.1.0 → 11.0.0

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.
@@ -12,7 +12,7 @@ import {
12
12
  declaresParameters,
13
13
  handlerParamNames,
14
14
  } from "@jxsuite/schema/function-role";
15
- import { RESERVED_KEYS, camelToKebab } from "@jxsuite/runtime";
15
+ import { RESERVED_KEYS, camelToKebab, derivedStateKeys, formStateKeys } from "@jxsuite/runtime";
16
16
  import {
17
17
  ATTR_HELPER,
18
18
  DEFAULT_LIT_HTML_SRC,
@@ -20,6 +20,17 @@ import {
20
20
  attrHelperSource,
21
21
  booleanAttrValue,
22
22
  definitionHasSlot,
23
+ KEYED_LIST_HELPER,
24
+ KEYED_LIST_IMPORTS,
25
+ keyedListDirectiveSource,
26
+ keyPath,
27
+ LIST_LITERAL_HELPER,
28
+ LIST_ITEMS_HELPER,
29
+ listHelperSource,
30
+ mappedArrayFeatures,
31
+ pageImportMap,
32
+ readsBareState,
33
+ refuseTemplateItems,
23
34
  LIT_PART_GUARD,
24
35
  NATIVE_SETTER_HELPER,
25
36
  OBSERVED_ATTR_HELPER,
@@ -35,6 +46,8 @@ import {
35
46
  observedDefaultsSource,
36
47
  SLOT_CAPTURE_HELPER,
37
48
  SLOT_DISTRIBUTE_HELPER,
49
+ FORM_ASSOCIATION_HELPER,
50
+ formAssociationHelperSource,
38
51
  slotHelperSource,
39
52
  assignStyleHandles,
40
53
  authorClassValue,
@@ -79,7 +92,13 @@ import { isNativeDocumentPath, parseNativeDocument } from "@jxsuite/schema/jxn";
79
92
  import { resolveShadowMode } from "../shadow.ts";
80
93
  import type { ShadowMode } from "../shadow.ts";
81
94
  import type { FormatRegistry } from "@jxsuite/schema/format-registry";
82
- import { escapeToken, objectKey, refAccessor, refSegments } from "@jxsuite/runtime/pointer";
95
+ import {
96
+ canonicalMapRef,
97
+ escapeToken,
98
+ objectKey,
99
+ refAccessor,
100
+ refSegments,
101
+ } from "@jxsuite/runtime/pointer";
83
102
  import type {
84
103
  JsonPrimitive,
85
104
  JxDocument,
@@ -122,6 +141,8 @@ const ELEMENT_MEMBERS: ReadonlySet<string> = new Set([
122
141
  "disconnectedCallback",
123
142
  "adoptedCallback",
124
143
  "attributeChangedCallback",
144
+ "formResetCallback",
145
+ "formDisabledCallback",
125
146
  ]);
126
147
 
127
148
  /** Options accepted by compileElement. */
@@ -176,6 +197,24 @@ export interface CompileElementOptions {
176
197
  docDir: string | null,
177
198
  imports: Record<string, string>,
178
199
  ) => string;
200
+ /**
201
+ * The URL of a shadow component's stylesheet, by tag, or `null` for a component whose sheet the
202
+ * caller does not write (spec.md §16.6). A root the module attaches itself, for an instance no
203
+ * prerender drew, links it, because the document's sheets cannot reach into the root. A result
204
+ * opening with `./` or `../` is resolved against the module's own URL, which is how a pack names
205
+ * the sibling it ships; anything else is linked as written. Without the option nothing is linked.
206
+ * Read for every `$elements` dependency too, and never for a light-DOM component.
207
+ */
208
+ stylesheetHref?: (tagName: string) => string | null;
209
+ }
210
+
211
+ /**
212
+ * The source of a stylesheet link's `href`: a module-relative reference resolved against the
213
+ * module's own URL when it runs, anything else as a literal.
214
+ */
215
+ function stylesheetHrefSource(href: string): string {
216
+ const literal = JSON.stringify(href);
217
+ return /^\.{1,2}\//u.test(href) ? `new URL(${literal}, import.meta.url).href` : literal;
179
218
  }
180
219
 
181
220
  /**
@@ -289,6 +328,7 @@ export async function compileElement(
289
328
  resolveClass
290
329
  ? (def: JxPrototypeDef) => resolveClass(def, currentDir, classImports)
291
330
  : undefined,
331
+ opts.stylesheetHref?.(tagName) ?? null,
292
332
  );
293
333
  const outputPath = filePath ? filePath.replace(/\.(?:json|jxn)$/i, ".js") : `${tagName}.js`;
294
334
  files.push({ content: jsContent, path: outputPath, tagName });
@@ -303,6 +343,8 @@ export interface CompileElementPageOptions extends CompileElementOptions {
303
343
  title?: string;
304
344
  reactivitySrc?: string;
305
345
  litHtmlSrc?: string;
346
+ /** The build's whole import map, written in place of the two sources above (compiler.md §12). */
347
+ runtimeImports?: Record<string, string>;
306
348
  }
307
349
 
308
350
  /**
@@ -341,14 +383,7 @@ export async function compileElementPage(
341
383
  <meta charset="utf-8">
342
384
  <meta name="viewport" content="width=device-width, initial-scale=1">
343
385
  <title>${escapeHtml(title)}</title>
344
- <script type="importmap">
345
- {
346
- "imports": {
347
- "@vue/reactivity": "${reactivitySrc}",
348
- "lit-html": "${litHtmlSrc}"
349
- }
350
- }
351
- </script>
386
+ ${pageImportMap({ litHtmlSrc, reactivitySrc, runtimeImports: opts.runtimeImports })}
352
387
  </head>
353
388
  <body>
354
389
  <${root.tagName}></${root.tagName}>
@@ -417,6 +452,7 @@ export function emitElementModule(
417
452
  serverBaseUrl = "/_jx/server",
418
453
  inherited: readonly string[] = [],
419
454
  resolveClass?: (def: JxPrototypeDef) => string,
455
+ stylesheetHref: string | null = null,
420
456
  ) {
421
457
  const lines: string[] = ["// Generated by @jxsuite/compiler — do not edit manually"];
422
458
 
@@ -457,14 +493,26 @@ export function emitElementModule(
457
493
  isServerFnDef(def) ? [[key, def]] : [],
458
494
  );
459
495
 
496
+ /* What the document's lists need (compiler.md §4.7), decided before anything is emitted. A
497
+ module with no filtered, sorted or keyed list carries none of it. */
498
+ const lists = mappedArrayFeatures(doc);
460
499
  lines.push(
461
- `import { reactive, computed, effect, stop } from '@vue/reactivity';`,
500
+ lists.keyed
501
+ ? `import { reactive, computed, effect, stop, shallowRef } from '@vue/reactivity';`
502
+ : `import { reactive, computed, effect, stop } from '@vue/reactivity';`,
462
503
  /* `nothing` is what REMOVES an attribute in a lit template, and it is the only way to express a
463
504
  false presence attribute: writing `open="false"` produces an OPEN <details>. See
464
505
  `attrHelperSource`. */
465
506
  `import { render, html, nothing } from 'lit-html';`,
507
+ ...(lists.keyed ? KEYED_LIST_IMPORTS : []),
466
508
  attrHelperSource(),
467
509
  );
510
+ if (lists.arranged || lists.keyed) {
511
+ lines.push(listHelperSource());
512
+ }
513
+ if (lists.keyed) {
514
+ lines.push(keyedListDirectiveSource());
515
+ }
468
516
 
469
517
  /* The property bridge's key sets, taken from the DEFINITION (spec.md §13.2, §16.2). Not from
470
518
  `this.state`: a pure type definition (`{ "type": "string" }`) holds no value, so it is not in
@@ -478,9 +526,16 @@ export function emitElementModule(
478
526
  const inheritedKeys = bridgedKeys.filter((key) => inherited.includes(key));
479
527
  const tracksGiven = inheritedKeys.length > 0;
480
528
  lines.push(`const __jxProps = ${JSON.stringify(propKeys)};`);
529
+ /* The bridged keys the scope DERIVES (spec.md §16.2): each gets a getter and no setter, from
530
+ the verdict the interpreter reads, and is never merged from a property. */
531
+ const derived = derivedStateKeys(doc);
532
+ const derivedKeys = bridgedKeys.filter((key) => derived.has(key));
481
533
  if (bridgedKeys.length > 0) {
482
534
  lines.push(`const __jxBridged = ${JSON.stringify(bridgedKeys)};`, propSupplyHelperSource());
483
535
  }
536
+ if (derivedKeys.length > 0) {
537
+ lines.push(`const __jxDerived = new Set(${JSON.stringify(derivedKeys)});`);
538
+ }
484
539
  if (tracksGiven) {
485
540
  lines.push(`const __jxInherited = new Set(${JSON.stringify(inheritedKeys)});`);
486
541
  }
@@ -508,6 +563,13 @@ export function emitElementModule(
508
563
  lines.push(slotHelperSource());
509
564
  }
510
565
 
566
+ /* Form association (spec.md §16.11). Everything it adds is emitted only for a definition that
567
+ declares `formAssociated: true`, so every other module is the one it was. */
568
+ const formAssociated = doc.formAssociated === true;
569
+ if (formAssociated) {
570
+ lines.push(formAssociationHelperSource());
571
+ }
572
+
511
573
  // `$lazy` entries load on their first call instead of with the page (spec.md §5.3 4d).
512
574
  lines.push(
513
575
  ...srcImports.loaders,
@@ -519,7 +581,16 @@ export function emitElementModule(
519
581
  // Held a handle to.
520
582
  " #effects = [];",
521
583
  " #rendered = false;",
584
+ /* The part lit's `render()` returns, kept by a module with a keyed list so the element can
585
+ tell lit when its host leaves and returns: standalone `render()` never disconnects an
586
+ `AsyncDirective` on its own, and the list's effect would keep a removed element subscribed
587
+ to an array its parent owns. */
588
+ ...(lists.keyed ? [" #part = null;"] : []),
522
589
  ...(shadow === null ? [] : [" #root = null;"]),
590
+ /* The one `attachInternals()` an element may make, shared by a closed root's adoption and the
591
+ form binding, and the binding itself. `undefined` is "not asked yet"; `null`, a platform
592
+ with no `ElementInternals`, where the element is simply not associated. */
593
+ ...(formAssociated ? [" #internals;", " #form = null;"] : []),
523
594
  /* A component with client classes draws in `#jxRender()`, once they have resolved: the
524
595
  instances by state key, the one resolution an instance ever starts, the connection a pending
525
596
  draw belongs to, and whether a draw has happened yet. */
@@ -535,6 +606,19 @@ export function emitElementModule(
535
606
  ...(observed.length > 0
536
607
  ? [" static get observedAttributes() { return __jxObserved; }", ""]
537
608
  : []),
609
+ ...(formAssociated
610
+ ? [
611
+ " static formAssociated = true;",
612
+ "",
613
+ " #attach() {",
614
+ " if (this.#internals === undefined) {",
615
+ " this.#internals = typeof this.attachInternals === 'function' ? this.attachInternals() : null;",
616
+ " }",
617
+ " return this.#internals;",
618
+ " }",
619
+ "",
620
+ ]
621
+ : []),
538
622
  // Constructor: build reactive state
539
623
  " constructor() {",
540
624
  " super();",
@@ -653,9 +737,15 @@ export function emitElementModule(
653
737
  runtime and the build-time scope evaluate it (spec.md §5.3), so a component reads the same
654
738
  value hydrated as it did prerendered. */
655
739
  for (const [key, template] of templateEntries) {
740
+ const rewritten = rewriteState(template, "this.state", { code: false });
741
+ const value = templateValueSource(rewritten);
742
+ /* A template may hand the scope itself to a helper (`${state.applySelection(state)}`), which
743
+ the interpreter binds as a parameter. Here it is declared for the computed that reads it. */
656
744
  lines.push(
657
745
  "",
658
- ` ${refAccessor("this.state", escapeToken(key))} = computed(() => ${templateValueSource(rewriteState(template, "this.state", { code: false }))});`,
746
+ holesReadBareState(rewritten)
747
+ ? ` ${refAccessor("this.state", escapeToken(key))} = computed(() => { const state = this.state; return ${value}; });`
748
+ : ` ${refAccessor("this.state", escapeToken(key))} = computed(() => ${value});`,
659
749
  );
660
750
  }
661
751
 
@@ -681,6 +771,20 @@ export function emitElementModule(
681
771
  }
682
772
  }
683
773
 
774
+ /* Root-level handlers listen on the host (spec.md §16.1, §4.3). They have no node in the
775
+ template, so the constructor attaches each to the element, lowered as a child's binding is. It
776
+ runs once per instance, which is the once-only the interpreter gets from its initialized flag:
777
+ no options, the element's own lifetime, never removed. The block keeps `s` out of the
778
+ constructor's scope, where a `$src` import could share the name. */
779
+ const listeners = hostHandlers(doc);
780
+ if (listeners.length > 0) {
781
+ lines.push("", " {", " const s = this.state;");
782
+ for (const { type, source } of listeners) {
783
+ lines.push(` this.addEventListener(${JSON.stringify(type)}, ${source});`);
784
+ }
785
+ lines.push(" }");
786
+ }
787
+
684
788
  lines.push(" }", ""); // End constructor
685
789
 
686
790
  /* Give the template's styled nodes the handles the component's sheet selects (spec.md §9.2).
@@ -705,10 +809,16 @@ export function emitElementModule(
705
809
  ? ` ${toLitTextContent(doc.textContent)}`
706
810
  : emitLitChildren(doc.children, doc.style, " ", false, false, hoistScope);
707
811
 
812
+ /* `state` on its own inside a template hole (a helper handed the scope) reads the same object
813
+ `s` does; declared only for a template that names it. */
814
+ const templateNamesState = [templateBody, ...hoistScope.decls].some((text) =>
815
+ holesReadBareState(text),
816
+ );
708
817
  lines.push(
709
818
  // Template method
710
819
  " template() {",
711
820
  " const s = this.state;",
821
+ ...(templateNamesState ? [" const state = s;"] : []),
712
822
  ...hoistScope.decls,
713
823
  " return html`",
714
824
  templateBody,
@@ -731,8 +841,20 @@ export function emitElementModule(
731
841
  " #renderRoot() {",
732
842
  " if (this.#root) return this.#root;",
733
843
  shadow === "closed"
734
- ? " this.#root = this.attachInternals().shadowRoot ?? this.attachShadow({ mode: 'closed' });"
735
- : " this.#root = this.shadowRoot ?? this.attachShadow({ mode: 'open' });",
844
+ ? formAssociated
845
+ ? " const _a = this.#attach()?.shadowRoot ?? null;"
846
+ : " const _a = this.attachInternals().shadowRoot;"
847
+ : " const _a = this.shadowRoot;",
848
+ ` this.#root = _a ?? this.attachShadow({ mode: '${shadow}' });`,
849
+ /* A root the parser made carries the link its prerender wrote. One attached here, for
850
+ an instance a list, a `$switch` case or a script created, has none, and the
851
+ document's sheets cannot reach in, so the module links the same sheet itself. */
852
+ ...(stylesheetHref === null
853
+ ? []
854
+ : [
855
+ " if (!_a) this.#root.append(Object.assign(document.createElement('link'), " +
856
+ `{ rel: 'stylesheet', href: ${stylesheetHrefSource(stylesheetHref)} }));`,
857
+ ]),
736
858
  " return this.#root;",
737
859
  " }",
738
860
  "",
@@ -752,6 +874,7 @@ export function emitElementModule(
752
874
  */
753
875
  " const _first = !this.#rendered;",
754
876
  " this.#rendered = true;",
877
+ ...(lists.keyed ? [" this.#part?.setConnected(true);"] : []),
755
878
  ...(tracksGiven ? [" const _given = new Set();"] : []),
756
879
  /*
757
880
  * Observed attributes already on the element, read first so that `$props` and a property a
@@ -822,6 +945,8 @@ export function emitElementModule(
822
945
  */
823
946
  " if (_first) {",
824
947
  " for (const _k of __jxBridged) {",
948
+ // A derived key has no cell to merge into; the property a parent wrote is discarded below.
949
+ ...(derivedKeys.length > 0 ? [" if (__jxDerived.has(_k)) continue;"] : []),
825
950
  ` if (_k in this && this[_k] !== undefined && ${PROP_SUPPLY_HELPER}(this, _k)) {`,
826
951
  " this.state[_k] = this[_k];",
827
952
  ...(tracksGiven ? [" _given.add(_k);"] : []),
@@ -829,6 +954,15 @@ export function emitElementModule(
829
954
  " }",
830
955
  " for (const _k of __jxBridged) {",
831
956
  ...(tracksGiven ? [" if (__jxInherited.has(_k) && !_given.has(_k)) continue;"] : []),
957
+ // A derived key is read-only: a getter and no setter, as a read-only IDL attribute has.
958
+ ...(derivedKeys.length > 0
959
+ ? [
960
+ " if (__jxDerived.has(_k)) {",
961
+ " Object.defineProperty(this, _k, { configurable: true, get: () => this.state[_k] });",
962
+ " continue;",
963
+ " }",
964
+ ]
965
+ : []),
832
966
  // A name the platform owns keeps reflecting: its own setter runs first, then state.
833
967
  ` const _set = ${NATIVE_SETTER_HELPER}(this, _k);`,
834
968
  " Object.defineProperty(this, _k, {",
@@ -897,6 +1031,9 @@ export function emitElementModule(
897
1031
  }),
898
1032
  );
899
1033
  }
1034
+ /* The definition's root `attributes`, written on the host (spec.md §16.1) after the props merge
1035
+ and before the render, as the interpreter's `applyAttributes(this, def.attributes)` is. */
1036
+ lines.push(...hostAttributeLines(doc));
900
1037
  if (isNonNullObject(doc.style)) {
901
1038
  const dynamicStyles: [string, string][] = [];
902
1039
  for (const [prop, value] of Object.entries(doc.style)) {
@@ -953,7 +1090,9 @@ export function emitElementModule(
953
1090
  * module a site ships.
954
1091
  */
955
1092
  " if (_first) this.replaceChildren();",
956
- " this.#effects.push(effect(() => render(this.template(), this)));",
1093
+ lists.keyed
1094
+ ? " this.#effects.push(effect(() => { this.#part = render(this.template(), this); }));"
1095
+ : " this.#effects.push(effect(() => render(this.template(), this)));",
957
1096
  );
958
1097
  } else {
959
1098
  /*
@@ -976,13 +1115,30 @@ export function emitElementModule(
976
1115
  " if (!(_n.nodeType === 1 && _n.tagName === 'LINK')) _n.remove();",
977
1116
  " }",
978
1117
  " }",
979
- " this.#effects.push(effect(() => render(this.template(), _root)));",
1118
+ lists.keyed
1119
+ ? " this.#effects.push(effect(() => { this.#part = render(this.template(), _root); }));"
1120
+ : " this.#effects.push(effect(() => render(this.template(), _root)));",
980
1121
  );
981
1122
  }
982
1123
  if (hasSlot) {
983
1124
  // Once, after the first render: a slot a later render draws stays literal (spec.md §8.5).
984
1125
  lines.push(` if (_first) ${SLOT_DISTRIBUTE_HELPER}(this, _slotted);`);
985
1126
  }
1127
+ if (formAssociated) {
1128
+ /* Bound once, after the first render, so the element's control is in its tree; the reactive
1129
+ half starts again on every connection, with effects `disconnectedCallback` stops. */
1130
+ lines.push(
1131
+ " if (_first) {",
1132
+ " const _i = this.#attach();",
1133
+ " if (_i) {",
1134
+ ` this.#form = ${FORM_ASSOCIATION_HELPER}(this, _i, this.state, ${JSON.stringify(formStateKeys(doc))}, ` +
1135
+ `() => ${shadow === null ? "this" : "this.#renderRoot()"}, ${formValueSource(doc.formValue)}, ` +
1136
+ "(fn) => { this.#effects.push(effect(fn)); });",
1137
+ " }",
1138
+ " }",
1139
+ " if (this.#form) this.#form.start();",
1140
+ );
1141
+ }
986
1142
  lines.push(
987
1143
  /* Lifecycle: onMount (spec.md §16.4), by the interpreter's contract. On a microtask after the
988
1144
  render; with the scope and the HOST, and the host as its receiver, so a sidecar reaches the
@@ -996,6 +1152,7 @@ export function emitElementModule(
996
1152
  "",
997
1153
  // DisconnectedCallback
998
1154
  " disconnectedCallback() {",
1155
+ ...(lists.keyed ? [" this.#part?.setConnected(false);"] : []),
999
1156
  " for (const _e of this.#effects) { stop(_e); }",
1000
1157
  " this.#effects.length = 0;",
1001
1158
  " if (typeof this.state.onUnmount === 'function') { this.state.onUnmount(this.state); }",
@@ -1009,6 +1166,14 @@ export function emitElementModule(
1009
1166
  " }",
1010
1167
  );
1011
1168
  }
1169
+ if (formAssociated) {
1170
+ lines.push(
1171
+ "",
1172
+ " formResetCallback() { if (this.#form) this.#form.reset(); }",
1173
+ "",
1174
+ " formDisabledCallback(disabled) { if (this.#form) this.#form.disabled(disabled); }",
1175
+ );
1176
+ }
1012
1177
  if (observed.length > 0) {
1013
1178
  lines.push(
1014
1179
  "",
@@ -1319,23 +1484,9 @@ ${no}
1319
1484
  }
1320
1485
  refuseBodyWithSrc(`inline "${key}" handler`, val);
1321
1486
  const eventName = key.slice(2).toLowerCase();
1322
- if (isBoundRef(val)) {
1323
- parts.push(
1324
- mapCtx
1325
- ? `@${eventName}="\${(e) => { ${mapCtx}${refToExpr(val.$ref)}(s, e); }}"`
1326
- : `@${eventName}="\${(e) => ${refToExpr(val.$ref)}(s, e)}"`,
1327
- );
1328
- } else if (isNonNullObject(val) && "$expression" in val) {
1329
- /* SAFETY: an `on*` binding object carrying `$expression` is a declarative handler, and the
1330
- document schema types that member as an expression node (spec.md §19). It is passed on
1331
- unvalidated, exactly as authored, so a malformed node fails inside compileExpression. */
1332
- const compiled = compileExpression(val.$expression as JxExpressionNode, {
1333
- eventParam: "e",
1334
- statePrefix: "s",
1335
- });
1336
- parts.push(`@${eventName}="\${(e) => { ${mapCtx}${compiled}; }}"`);
1337
- } else if (isFunctionDef(val)) {
1338
- parts.push(`@${eventName}="\${(e) => { ${mapCtx}${inlineHandlerBody(val)} }}"`);
1487
+ const handler = handlerSource(val, mapCtx);
1488
+ if (handler !== null) {
1489
+ parts.push(`@${eventName}="\${${handler}}"`);
1339
1490
  }
1340
1491
  }
1341
1492
 
@@ -1433,7 +1584,21 @@ function emitNodeInner(
1433
1584
  * @returns {string}
1434
1585
  */
1435
1586
  function emitMappedArray(arrayDef: JxMappedArray, indent: string) {
1436
- const itemsExpr = isRef(arrayDef.items) ? refToExpr(arrayDef.items.$ref) : "ITEMS";
1587
+ /* A literal `items` is written into the module as JSON, as the client target writes it. A
1588
+ pointer that reads nothing is an empty list, as in the interpreter, not a `TypeError` thrown
1589
+ inside the render effect after the prerender has been cleared. */
1590
+ refuseTemplateItems(arrayDef);
1591
+ const keyed = isRef(arrayDef.key);
1592
+ const literal = JSON.stringify(Array.isArray(arrayDef.items) ? arrayDef.items : []);
1593
+ let itemsExpr = keyed ? `${LIST_LITERAL_HELPER}(${JSON.stringify(literal)})` : literal;
1594
+ if (isRef(arrayDef.items)) {
1595
+ itemsExpr = `(${refToExpr(arrayDef.items.$ref)} ?? [])`;
1596
+ }
1597
+ /* `filter` and `sort` are each a `$ref` to a callable (spec.md §10.3); anything else is ignored,
1598
+ as the interpreter ignores it. */
1599
+ const filterExpr = isRef(arrayDef.filter) ? refToExpr(arrayDef.filter.$ref) : "undefined";
1600
+ const sortExpr = isRef(arrayDef.sort) ? refToExpr(arrayDef.sort.$ref) : "undefined";
1601
+ const arranged = isRef(arrayDef.filter) || isRef(arrayDef.sort);
1437
1602
  const mapDef = arrayDef.map;
1438
1603
 
1439
1604
  if (!mapDef) {
@@ -1524,17 +1689,10 @@ function emitMappedArray(arrayDef: JxMappedArray, indent: string) {
1524
1689
  }
1525
1690
  refuseBodyWithSrc(`inline "${key}" handler`, val);
1526
1691
  const eventName = key.slice(2).toLowerCase();
1527
- if (isRef(val)) {
1528
- parts.push(`@${eventName}="\${(e) => { s.$map = $map; ${refToExpr(val.$ref)}(s, e); }}"`);
1529
- } else if (isExpressionDef(val)) {
1530
- const compiled = compileExpression(val.$expression, {
1531
- eventParam: "e",
1532
- statePrefix: "s",
1533
- });
1534
- parts.push(`@${eventName}="\${(e) => { s.$map = $map; ${compiled}; }}"`);
1535
- } else if (isFunctionDef(val)) {
1536
- // A map root binds an inline handler as any other element does, with the iteration published.
1537
- parts.push(`@${eventName}="\${(e) => { s.$map = $map; ${inlineHandlerBody(val)} }}"`);
1692
+ // A map root binds a handler as any other element does, with the iteration published.
1693
+ const handler = handlerSource(val, "s.$map = $map; ");
1694
+ if (handler !== null) {
1695
+ parts.push(`@${eventName}="\${${handler}}"`);
1538
1696
  }
1539
1697
  }
1540
1698
 
@@ -1567,7 +1725,27 @@ function emitMappedArray(arrayDef: JxMappedArray, indent: string) {
1567
1725
  ? `(item, index) => { ${prelude}return ${body}; }`
1568
1726
  : `(item, index) => ${body}`;
1569
1727
 
1570
- return `${indent}\${${itemsExpr}.map(${callback})}`;
1728
+ /* Three lowerings (spec.md §10.3, §10.4, compiler.md §4.7). A keyed list goes through the
1729
+ directive, which shapes it, keys it and hands lit's `repeat()` a snapshot. An unkeyed list has
1730
+ no identity but its position, which is what lit's own array rendering reconciles by, so it is a
1731
+ plain `.map()`, over `__jxListItems(…)` when it filters or sorts and over `items` as written when
1732
+ it declares neither, which is every list compiled before either existed. */
1733
+ if (isRef(arrayDef.key)) {
1734
+ const pointer = arrayDef.key.$ref;
1735
+ const args = [
1736
+ itemsExpr,
1737
+ filterExpr,
1738
+ sortExpr,
1739
+ JSON.stringify(keyPath(pointer)),
1740
+ JSON.stringify(pointer),
1741
+ callback,
1742
+ ];
1743
+ return `${indent}\${${KEYED_LIST_HELPER}(${args.join(", ")})}`;
1744
+ }
1745
+ const listExpr = arranged
1746
+ ? `${LIST_ITEMS_HELPER}(${itemsExpr}, ${filterExpr}, ${sortExpr})`
1747
+ : itemsExpr;
1748
+ return `${indent}\${${listExpr}.map(${callback})}`;
1571
1749
  }
1572
1750
 
1573
1751
  /**
@@ -1618,7 +1796,8 @@ function isBoundRef(value: JxDocumentValue | undefined): value is JxRef {
1618
1796
  * @param {string} ref
1619
1797
  * @returns {string}
1620
1798
  */
1621
- function refToExpr(ref: string) {
1799
+ function refToExpr(written: string) {
1800
+ const ref = canonicalMapRef(written);
1622
1801
  if (ref.startsWith("#/state/")) {
1623
1802
  return refAccessor("s", ref.slice("#/state/".length));
1624
1803
  }
@@ -1658,7 +1837,8 @@ function mapVarAccessor(path: string) {
1658
1837
  * @param {string} ref
1659
1838
  * @returns {string}
1660
1839
  */
1661
- function mapRefToExpr(ref: string) {
1840
+ function mapRefToExpr(written: string) {
1841
+ const ref = canonicalMapRef(written);
1662
1842
  if (ref.startsWith("$map/")) {
1663
1843
  return mapVarAccessor(ref.slice("$map/".length));
1664
1844
  }
@@ -1705,6 +1885,166 @@ function toLitTextContent(value: string | null | JxRef) {
1705
1885
  return String(value);
1706
1886
  }
1707
1887
 
1888
+ /**
1889
+ * Whether any `${…}` hole of emitted lit template text names `state` on its own ({@link
1890
+ * readsBareState}). Only the holes are read: the word in a template's literal text is text.
1891
+ *
1892
+ * @param {string} text - Emitted template source
1893
+ * @returns {boolean}
1894
+ */
1895
+ function holesReadBareState(text: string): boolean {
1896
+ let depth = 0;
1897
+ let hole = "";
1898
+ for (let at = 0; at < text.length; at++) {
1899
+ const char = text.charAt(at);
1900
+ if (depth === 0) {
1901
+ if (char === "$" && text.charAt(at + 1) === "{") {
1902
+ depth = 1;
1903
+ hole = "";
1904
+ at += 1;
1905
+ }
1906
+ continue;
1907
+ }
1908
+ if (char === "{") {
1909
+ depth += 1;
1910
+ } else if (char === "}") {
1911
+ depth -= 1;
1912
+ if (depth === 0) {
1913
+ if (readsBareState(hole)) {
1914
+ return true;
1915
+ }
1916
+ continue;
1917
+ }
1918
+ }
1919
+ hole += char;
1920
+ }
1921
+ return false;
1922
+ }
1923
+
1924
+ /**
1925
+ * The arrow an `on*` value lowers to, in each of the spellings a handler has (spec.md §4.3), or
1926
+ * `null` for a value that is none of them. One lowering for every place a handler binds: a child's
1927
+ * `@event` binding, a map root's, and a listener on the host (spec.md §16.1), which says a root
1928
+ * handler attaches "exactly as they would to an element inside a document".
1929
+ *
1930
+ * @param {JxDocumentValue | undefined} val - The `on*` value as the document holds it
1931
+ * @param {string} mapCtx - The statement that publishes the iteration inside a map, or `""`
1932
+ * @returns {string | null}
1933
+ */
1934
+ function handlerSource(val: JxDocumentValue | undefined, mapCtx: string): string | null {
1935
+ if (isBoundRef(val)) {
1936
+ return mapCtx
1937
+ ? `(e) => { ${mapCtx}${refToExpr(val.$ref)}(s, e); }`
1938
+ : `(e) => ${refToExpr(val.$ref)}(s, e)`;
1939
+ }
1940
+ if (isNonNullObject(val) && "$expression" in val) {
1941
+ /* SAFETY: an `on*` binding object carrying `$expression` is a declarative handler, and the
1942
+ document schema types that member as an expression node (spec.md §19). It is passed on
1943
+ unvalidated, exactly as authored, so a malformed node fails inside compileExpression. */
1944
+ const compiled = compileExpression(val.$expression as JxExpressionNode, {
1945
+ eventParam: "e",
1946
+ statePrefix: "s",
1947
+ });
1948
+ return `(e) => { ${mapCtx}${compiled}; }`;
1949
+ }
1950
+ if (isFunctionDef(val)) {
1951
+ return `(e) => { ${mapCtx}${inlineHandlerBody(val)} }`;
1952
+ }
1953
+ return null;
1954
+ }
1955
+
1956
+ /**
1957
+ * A definition's root-level event handlers (spec.md §16.1), as the listeners the constructor
1958
+ * attaches to the host: every root key that passes the interpreter's test (`bindDefinitionHandlers`
1959
+ * in `@jxsuite/runtime`: it starts with `on` and is not reserved) and holds a handler.
1960
+ *
1961
+ * @param {JxDocument} doc
1962
+ * @returns {{ type: string; source: string }[]}
1963
+ */
1964
+ function hostHandlers(doc: JxDocument): { type: string; source: string }[] {
1965
+ const listeners: { type: string; source: string }[] = [];
1966
+ for (const [key, val] of Object.entries(doc)) {
1967
+ if (!key.startsWith("on") || RESERVED_KEYS.has(key)) {
1968
+ continue;
1969
+ }
1970
+ refuseBodyWithSrc(`root "${key}" handler`, val);
1971
+ const source = handlerSource(val, "");
1972
+ if (source !== null) {
1973
+ listeners.push({ source, type: key.slice(2).toLowerCase() });
1974
+ }
1975
+ }
1976
+ return listeners;
1977
+ }
1978
+
1979
+ /**
1980
+ * The statements that write a definition's root `attributes` on the host (spec.md §16.1), by the
1981
+ * rule the interpreter's `applyAttributes` applies to them: a value that resolves to nothing takes
1982
+ * the attribute off, a boolean is presence or text by its attribute's family (spec.md §8.3), and
1983
+ * anything else is its string form. A literal is written once, on the first connection; a `$ref` or
1984
+ * a template is an effect, registered with the element's others so it stops when the host leaves.
1985
+ *
1986
+ * In `connectedCallback` and never the constructor: a custom element constructor must not add
1987
+ * attributes, and the values read state the props merge has just filled.
1988
+ *
1989
+ * @param {JxDocument} doc
1990
+ * @returns {string[]} Lines for `connectedCallback`, at its indentation
1991
+ */
1992
+ function hostAttributeLines(doc: JxDocument): string[] {
1993
+ const lines: string[] = [];
1994
+ const write = (name: string, expr: string, namesState: boolean): string[] => [
1995
+ " this.#effects.push(effect(() => {",
1996
+ namesState ? " const s = this.state, state = s;" : " const s = this.state;",
1997
+ ` const _v = ${ATTR_HELPER}(${name}, ${expr});`,
1998
+ ` if (_v === null || _v === undefined) this.removeAttribute(${name});`,
1999
+ ` else this.setAttribute(${name}, String(_v));`,
2000
+ " }));",
2001
+ ];
2002
+ for (const [key, val] of Object.entries(doc.attributes ?? {})) {
2003
+ const name = JSON.stringify(key);
2004
+ if (isRef(val)) {
2005
+ lines.push(...write(name, refToExpr(val.$ref), false));
2006
+ } else if (isString(val) && isWholeTemplate(val)) {
2007
+ const template = toLitExpr(val);
2008
+ lines.push(...write(name, template.slice(2, -1), holesReadBareState(template)));
2009
+ } else if (isString(val) && val.includes("${")) {
2010
+ const template = toLitExpr(val);
2011
+ lines.push(...write(name, `\`${template}\``, holesReadBareState(template)));
2012
+ } else if (isBoolean(val)) {
2013
+ const text = booleanAttrValue(key, val);
2014
+ if (text !== null) {
2015
+ lines.push(` if (_first) this.setAttribute(${name}, ${JSON.stringify(text)});`);
2016
+ }
2017
+ } else if (isString(val) || isNumber(val)) {
2018
+ // A document is JSON, so anything else here (a `null`) names no attribute.
2019
+ lines.push(` if (_first) this.setAttribute(${name}, ${JSON.stringify(String(val))});`);
2020
+ }
2021
+ }
2022
+ return lines;
2023
+ }
2024
+
2025
+ /**
2026
+ * A definition's declared `formValue` (spec.md §16.11) as the source of the function the form
2027
+ * binding reads it through, or `null` when it declares none: a `$ref`, a `${…}` template, which
2028
+ * submits nothing while its expression throws, or a literal.
2029
+ *
2030
+ * @param {JxDocument["formValue"]} value
2031
+ * @returns {string}
2032
+ */
2033
+ function formValueSource(value: JxDocument["formValue"]): string {
2034
+ if (value === undefined) {
2035
+ return "null";
2036
+ }
2037
+ if (isRef(value)) {
2038
+ return `() => { const s = this.state; return ${refToExpr(value.$ref)}; }`;
2039
+ }
2040
+ if (isString(value) && value.includes("${")) {
2041
+ const template = toLitExpr(value);
2042
+ const expr = isWholeTemplate(value) ? template.slice(2, -1) : `\`${template}\``;
2043
+ return `() => { const s = this.state, state = s; try { return ${expr}; } catch { return null; } }`;
2044
+ }
2045
+ return `() => ${JSON.stringify(value)}`;
2046
+ }
2047
+
1708
2048
  /**
1709
2049
  * @param {import("@jxsuite/schema/types").JxFunctionDef} def
1710
2050
  * @returns {string}