@jxsuite/compiler 9.0.1 → 9.1.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.
@@ -21,11 +21,26 @@ import {
21
21
  booleanAttrValue,
22
22
  definitionHasSlot,
23
23
  LIT_PART_GUARD,
24
+ NATIVE_SETTER_HELPER,
25
+ OBSERVED_ATTR_HELPER,
24
26
  PREFORMATTED_TAGS,
27
+ PROP_SUPPLY_HELPER,
28
+ propSupplyHelperSource,
29
+ observedAttrHelperSource,
30
+ collectClientClasses,
31
+ emitExternalClassResolution,
32
+ externalClassHelperSource,
33
+ isClientExternalClass,
34
+ observedAttributeNames,
35
+ observedDefaultsSource,
25
36
  SLOT_CAPTURE_HELPER,
26
37
  SLOT_DISTRIBUTE_HELPER,
27
38
  slotHelperSource,
28
- collectStyles,
39
+ assignStyleHandles,
40
+ authorClassValue,
41
+ styleChildren,
42
+ styleHandleOf,
43
+ writesMergedClass,
29
44
  compileExpression,
30
45
  compileOperandSource,
31
46
  compileStatements,
@@ -53,6 +68,7 @@ import {
53
68
  isNamedFormulaDef,
54
69
  isNonNullObject,
55
70
  isNumber,
71
+ isPrivateStateKey,
56
72
  isPrototypeDef,
57
73
  isRef,
58
74
  isServerFnDef,
@@ -68,6 +84,7 @@ import type {
68
84
  JsonPrimitive,
69
85
  JxDocument,
70
86
  JxDocumentValue,
87
+ JxElement,
71
88
  JxExpressionDef,
72
89
  JxExpressionNode,
73
90
  JxFunctionDef,
@@ -88,6 +105,25 @@ import type {
88
105
  */
89
106
  type LitChild = JxMutableNode | JsonPrimitive;
90
107
 
108
+ /**
109
+ * The names the emitted class defines itself. A state key with one of these names still arrives
110
+ * through `data-jx-props` and `props.*`, which write `this.state[key]`, but is neither merged from
111
+ * a property nor given a forwarding accessor (compiler.md §4.4): reading `this.state` as a prop
112
+ * would merge state into itself, and an accessor named `template` or `connectedCallback` would
113
+ * replace the member the element runs on. The interpreter's element class has no such members, so
114
+ * this is the compiled tier's one exception. A change that adds a public member to the emitted
115
+ * class adds its name here.
116
+ */
117
+ const ELEMENT_MEMBERS: ReadonlySet<string> = new Set([
118
+ "state",
119
+ "template",
120
+ "constructor",
121
+ "connectedCallback",
122
+ "disconnectedCallback",
123
+ "adoptedCallback",
124
+ "attributeChangedCallback",
125
+ ]);
126
+
91
127
  /** Options accepted by compileElement. */
92
128
  export interface CompileElementOptions {
93
129
  /** Resolve an `$elements` ref path to its emitted JS module path. */
@@ -123,6 +159,23 @@ export interface CompileElementOptions {
123
159
  * document.
124
160
  */
125
161
  projectState?: Record<string, JxStateDefinition> | undefined;
162
+ /**
163
+ * Called with each document as it is read, the component's own and every `$elements`
164
+ * dependency's, before anything is compiled from it. A site build resolves the document's
165
+ * build-time external classes here (compiler.md §3), so the module is compiled from state that
166
+ * already holds their values. `filePath` is `null` for a document passed as an object.
167
+ */
168
+ prepareDocument?: (doc: JxDocument, filePath: string | null) => Promise<void>;
169
+ /**
170
+ * The URL a `timing: "client"` external class's module is served at (compiler.md §3, §12), given
171
+ * the entry, the directory of the document that declares it and that document's `imports`. Only a
172
+ * site build has one; without it such an entry is a compile error.
173
+ */
174
+ resolveClass?: (
175
+ def: JxPrototypeDef,
176
+ docDir: string | null,
177
+ imports: Record<string, string>,
178
+ ) => string;
126
179
  }
127
180
 
128
181
  /**
@@ -185,6 +238,9 @@ export async function compileElement(
185
238
  }
186
239
  }
187
240
 
241
+ await opts.prepareDocument?.(doc, filePath);
242
+
243
+ const declaredState = doc.state ?? {};
188
244
  doc = inheritProjectFormulas(doc, opts.projectState);
189
245
 
190
246
  const { tagName } = doc;
@@ -220,7 +276,8 @@ export async function compileElement(
220
276
  if (optsMedia) {
221
277
  doc.$media = { ...optsMedia, ...doc.$media };
222
278
  }
223
- const { rewriteSrc } = opts;
279
+ const { resolveClass, rewriteSrc } = opts;
280
+ const classImports = doc.imports ?? {};
224
281
  const jsContent = emitElementModule(
225
282
  doc,
226
283
  className,
@@ -228,6 +285,10 @@ export async function compileElement(
228
285
  rewriteSrc ? (spec: string) => rewriteSrc(spec, currentDir) : undefined,
229
286
  resolveShadowMode(doc, opts.defaults),
230
287
  opts.serverBaseUrl,
288
+ Object.keys(doc.state ?? {}).filter((key) => !(key in declaredState)),
289
+ resolveClass
290
+ ? (def: JxPrototypeDef) => resolveClass(def, currentDir, classImports)
291
+ : undefined,
231
292
  );
232
293
  const outputPath = filePath ? filePath.replace(/\.(?:json|jxn)$/i, ".js") : `${tagName}.js`;
233
294
  files.push({ content: jsContent, path: outputPath, tagName });
@@ -327,6 +388,10 @@ function extractInitialValue(def: JxStateDefinition) {
327
388
  if (def.$prototype === "Request") {
328
389
  return "null";
329
390
  }
391
+ // A `timing: "client"` external class holds nothing until its class resolves (compiler.md §3)
392
+ if (isClientExternalClass(def)) {
393
+ return "null";
394
+ }
330
395
  // A `timing: "server"` entry holds nothing until the site worker's route answers (§6.1)
331
396
  if (isServerFnDef(def)) {
332
397
  return "null";
@@ -350,6 +415,8 @@ export function emitElementModule(
350
415
  rewriteSrc?: (specifier: string) => string,
351
416
  shadow: ShadowMode | null = null,
352
417
  serverBaseUrl = "/_jx/server",
418
+ inherited: readonly string[] = [],
419
+ resolveClass?: (def: JxPrototypeDef) => string,
353
420
  ) {
354
421
  const lines: string[] = ["// Generated by @jxsuite/compiler — do not edit manually"];
355
422
 
@@ -369,6 +436,14 @@ export function emitElementModule(
369
436
  // The site build bundles them after all documents compile (spec.md §12).
370
437
  lines.push(...srcImports.imports);
371
438
 
439
+ /* `timing: "client"` external classes (compiler.md §3): each class module is imported here, and
440
+ the instance constructs and resolves them before it first renders. Everything below that
441
+ exists for them is emitted only when the document has one, so a document without a client
442
+ class compiles to exactly the module it did before. */
443
+ const clientClasses = collectClientClasses(defs, resolveClass);
444
+ const waitsForClasses = clientClasses.entries.length > 0;
445
+ lines.push(...clientClasses.imports);
446
+
372
447
  // `$prototype: "Request"` entries each get an auto-fetch effect in connectedCallback, plus the
373
448
  // Machinery to stop those effects again on disconnect. Both are emitted only when one exists, so
374
449
  // Documents without a Request produce exactly the same module as before.
@@ -390,9 +465,41 @@ export function emitElementModule(
390
465
  `import { render, html, nothing } from 'lit-html';`,
391
466
  attrHelperSource(),
392
467
  );
468
+
469
+ /* The property bridge's key sets, taken from the DEFINITION (spec.md §13.2, §16.2). Not from
470
+ `this.state`: a pure type definition (`{ "type": "string" }`) holds no value, so it is not in
471
+ the reactive object until a prop sets it, and a membership test against state refused the most
472
+ common way to declare a prop. `__jxProps` is what the two attribute sources accept; the
473
+ bridged keys are those that can also be a property of the element. */
474
+ const propKeys = Object.keys(defs).filter((key) => !isPrivateStateKey(key));
475
+ const bridgedKeys = propKeys.filter((key) => !ELEMENT_MEMBERS.has(key));
476
+ /* An inherited project formula is in the scope and not in the element's interface (spec.md
477
+ §13.4): it is bridged only on an instance that was given a prop of that name. */
478
+ const inheritedKeys = bridgedKeys.filter((key) => inherited.includes(key));
479
+ const tracksGiven = inheritedKeys.length > 0;
480
+ lines.push(`const __jxProps = ${JSON.stringify(propKeys)};`);
481
+ if (bridgedKeys.length > 0) {
482
+ lines.push(`const __jxBridged = ${JSON.stringify(bridgedKeys)};`, propSupplyHelperSource());
483
+ }
484
+ if (tracksGiven) {
485
+ lines.push(`const __jxInherited = new Set(${JSON.stringify(inheritedKeys)});`);
486
+ }
487
+ /* Observed attributes (spec.md §16.5), emitted only when the definition declares any: the rule,
488
+ the list the platform reads, and the observed keys' declared defaults. */
489
+ const observed = observedAttributeNames(doc);
490
+ if (observed.length > 0) {
491
+ lines.push(
492
+ observedAttrHelperSource(),
493
+ `const __jxObserved = ${JSON.stringify(observed)};`,
494
+ `const __jxObservedDefaults = () => ${observedDefaultsSource(doc)};`,
495
+ );
496
+ }
393
497
  if (serverEntries.length > 0) {
394
498
  lines.push(serverCallHelperSource());
395
499
  }
500
+ if (waitsForClasses) {
501
+ lines.push(externalClassHelperSource());
502
+ }
396
503
  /* Light-DOM slot distribution, by the rule the interpreter applies (spec.md §8.5): only a module
397
504
  whose template draws a slot carries it, and a shadow component never does — its light children
398
505
  ARE the slotted content, and a real `<slot>` distributes them. */
@@ -413,7 +520,21 @@ export function emitElementModule(
413
520
  " #effects = [];",
414
521
  " #rendered = false;",
415
522
  ...(shadow === null ? [] : [" #root = null;"]),
523
+ /* A component with client classes draws in `#jxRender()`, once they have resolved: the
524
+ instances by state key, the one resolution an instance ever starts, the connection a pending
525
+ draw belongs to, and whether a draw has happened yet. */
526
+ ...(waitsForClasses
527
+ ? [
528
+ " #jxInstances = new Map();",
529
+ " #jxReady = null;",
530
+ " #jxConnection = 0;",
531
+ " #jxDrawn = false;",
532
+ ]
533
+ : []),
416
534
  "",
535
+ ...(observed.length > 0
536
+ ? [" static get observedAttributes() { return __jxObserved; }", ""]
537
+ : []),
417
538
  // Constructor: build reactive state
418
539
  " constructor() {",
419
540
  " super();",
@@ -562,13 +683,12 @@ export function emitElementModule(
562
683
 
563
684
  lines.push(" }", ""); // End constructor
564
685
 
565
- // Collect CSS rules from children tree (assigns .jx-N classes to defs)
566
- const cssRules: string[] = [];
567
- if (Array.isArray(doc.children)) {
568
- const counter = { n: 0 };
569
- for (const child of doc.children) {
570
- collectStyles(child, cssRules, doc.$media ?? {}, "", counter, doc.tagName);
571
- }
686
+ /* Give the template's styled nodes the handles the component's sheet selects (spec.md §9.2).
687
+ The sheet itself is `buildComponentCSS`'s; this walk makes the same traversal over this parse,
688
+ so the two number the same nodes alike, and it builds no rule. */
689
+ const handleCounter = { n: 0 };
690
+ for (const child of styleChildren(doc)) {
691
+ assignStyleHandles(child, handleCounter, doc.tagName ?? "jx");
572
692
  }
573
693
 
574
694
  // Subtrees a branching construct would otherwise repeat are lifted into `const _cN = html`…``
@@ -619,13 +739,45 @@ export function emitElementModule(
619
739
  ]),
620
740
  // ConnectedCallback
621
741
  " connectedCallback() {",
742
+ /*
743
+ * What happens to an instance ONCE is decided by this flag, read before anything else.
744
+ * `connectedCallback` runs again each time the element is put back in a document (a list
745
+ * reordered with `append`, a panel moved between containers), and `disconnectedCallback` only
746
+ * stopped the effects: the tree lit drew is still there, and so is the part lit cached on the
747
+ * container for it. Clearing the container a second time removed the nodes that part still
748
+ * points at, so the render that followed updated a detached tree and the element stayed empty
749
+ * for good. A second slot capture is wrong for its own reason: by then the host's children are
750
+ * the component's own render, not what the author slotted. And a second property merge would
751
+ * read the element's own accessors back into the state they forward to.
752
+ */
753
+ " const _first = !this.#rendered;",
754
+ " this.#rendered = true;",
755
+ ...(tracksGiven ? [" const _given = new Set();"] : []),
756
+ /*
757
+ * Observed attributes already on the element, read first so that `$props` and a property a
758
+ * parent set still win (spec.md §16.5), and on the first connection only: a re-insertion must
759
+ * not put an attribute's value back over state a handler has changed since. A browser has
760
+ * already delivered these through `attributeChangedCallback` when the element was created or
761
+ * upgraded, so the read repeats it there; it is kept because it is the interpreter's shape,
762
+ * and because it does not depend on that delivery.
763
+ */
764
+ ...(observed.length > 0
765
+ ? [
766
+ " if (_first) {",
767
+ " const _d = __jxObservedDefaults();",
768
+ " for (const _a of __jxObserved) {",
769
+ ` if (this.hasAttribute(_a)) ${OBSERVED_ATTR_HELPER}(this.state, _a, this.getAttribute(_a), _d);`,
770
+ " }",
771
+ " }",
772
+ ]
773
+ : []),
622
774
  /*
623
775
  * Each of the three absorption paths below skips a `#`-prefixed key: private state is not part
624
- * of the component's interface and is never settable through $props (spec.md §5.6). Emitted as
625
- * a runtime check rather than resolved at build time because all three read keys that arrive
626
- * with the instance — an attribute payload, an attribute name, a property a parent set — none
627
- * of which the compiler can see. The interpreter enforces the same rule in `runtime.ts`; the
628
- * two tiers agreeing is the point, since a document is authored against whichever runs.
776
+ * of the component's interface and is never settable through $props (spec.md §5.6). The two
777
+ * attribute paths check at run time because they read keys that arrive with the instance — an
778
+ * attribute payload, an attribute name — which the compiler cannot see; the property path reads
779
+ * a list that never held one. The interpreter enforces the same rule in `runtime.ts`; the two
780
+ * tiers agreeing is the point, since a document is authored against whichever runs.
629
781
  */
630
782
  // Read $props from data-jx-props attribute (set by compiler for pre-rendered instances)
631
783
  " const _pa = this.getAttribute('data-jx-props');",
@@ -634,7 +786,9 @@ export function emitElementModule(
634
786
  " const _p = JSON.parse(_pa);",
635
787
  " for (const [k, v] of Object.entries(_p)) {",
636
788
  " if (k.startsWith('#')) continue;",
637
- " if (k in this.state) this.state[k] = v;",
789
+ tracksGiven
790
+ ? " if (__jxProps.includes(k)) { this.state[k] = v; _given.add(k); }"
791
+ : " if (__jxProps.includes(k)) this.state[k] = v;",
638
792
  " }",
639
793
  " } catch {}",
640
794
  " this.removeAttribute('data-jx-props');",
@@ -646,21 +800,78 @@ export function emitElementModule(
646
800
  " for (const _n of _pn) {",
647
801
  " const _k = _n.slice(6);",
648
802
  " if (_k.startsWith('#')) { this.removeAttribute(_n); continue; }",
649
- " if (_k in this.state) {",
803
+ " if (__jxProps.includes(_k)) {",
650
804
  " this.state[_k] = this.getAttribute(_n);",
805
+ ...(tracksGiven ? [" _given.add(_k);"] : []),
651
806
  " this.removeAttribute(_n);",
652
807
  " }",
653
808
  " }",
654
- // Merge JS properties set before connection (by parent runtime).
655
- // Only check own properties to avoid inherited DOM properties like `title`.
656
- " for (const key of Object.keys(this.state)) {",
657
- " if (key.startsWith('#')) continue;",
658
- " if (this.hasOwnProperty(key) && this[key] !== undefined) {",
659
- " this.state[key] = this[key];",
660
- " }",
661
- " }",
662
809
  );
663
810
 
811
+ if (bridgedKeys.length > 0) {
812
+ lines.push(
813
+ /*
814
+ * The property bridge (spec.md §13.2, §16.2), on the first connection only, as the
815
+ * interpreter does it. First the merge: a property the instance genuinely carries, by the
816
+ * supply rule, so a reflected name nobody set (`title` answering "") does not beat the
817
+ * declared default, and a parent's `.title=`, which creates no own property, is not dropped.
818
+ * Then the accessors, on the INSTANCE and after the merge: a write before connection made an
819
+ * own property the merge has just read, and the accessor now replaces it. On the prototype it
820
+ * would have put that early write straight into state, where the two attribute reads above
821
+ * would then overwrite it, and a property is the source that wins.
822
+ */
823
+ " if (_first) {",
824
+ " for (const _k of __jxBridged) {",
825
+ ` if (_k in this && this[_k] !== undefined && ${PROP_SUPPLY_HELPER}(this, _k)) {`,
826
+ " this.state[_k] = this[_k];",
827
+ ...(tracksGiven ? [" _given.add(_k);"] : []),
828
+ " }",
829
+ " }",
830
+ " for (const _k of __jxBridged) {",
831
+ ...(tracksGiven ? [" if (__jxInherited.has(_k) && !_given.has(_k)) continue;"] : []),
832
+ // A name the platform owns keeps reflecting: its own setter runs first, then state.
833
+ ` const _set = ${NATIVE_SETTER_HELPER}(this, _k);`,
834
+ " Object.defineProperty(this, _k, {",
835
+ " configurable: true,",
836
+ " get: () => this.state[_k],",
837
+ " set: (v) => { if (_set) _set.call(this, v); this.state[_k] = v; },",
838
+ " });",
839
+ " }",
840
+ " }",
841
+ );
842
+ }
843
+
844
+ if (waitsForClasses) {
845
+ lines.push(
846
+ /*
847
+ * The classes are constructed once per instance, after the merge above so a class reads the
848
+ * props the instance arrived with, and the first draw waits for them: a template that reads
849
+ * a class's value (`${state.forecast.days.length}`) sees the value, as it does under the
850
+ * interpreter, which awaits every class before it renders. The prerendered markup stays in
851
+ * place meanwhile. A draw belongs to the connection that asked for it: an instance removed
852
+ * before its classes settle does not draw, and one put back draws once, for the connection
853
+ * it now has.
854
+ */
855
+ ` this.#jxReady ??= ${emitExternalClassResolution(clientClasses.entries, {
856
+ indent: " ",
857
+ instances: "this.#jxInstances",
858
+ statePrefix: "this.state",
859
+ })};`,
860
+ " const _c = ++this.#jxConnection;",
861
+ " this.#jxReady.then(() => {",
862
+ " if (_c === this.#jxConnection && this.isConnected) this.#jxRender();",
863
+ " });",
864
+ " }",
865
+ "",
866
+ /* Everything a connection does once its classes have resolved. `_first` is the first DRAW
867
+ here, not the first connection: an instance removed and put back before its classes
868
+ settled has connected twice and drawn nothing. */
869
+ " #jxRender() {",
870
+ " const _first = !this.#jxDrawn;",
871
+ " this.#jxDrawn = true;",
872
+ );
873
+ }
874
+
664
875
  // `$prototype: "Request"` entries fetch on connect — after the `$props`/property merge above, so
665
876
  // A template `url` interpolates the values the parent passed in rather than the initial ones.
666
877
  // Runners are collected so disconnectedCallback can stop them: a reactive URL would otherwise
@@ -724,17 +935,6 @@ export function emitElementModule(
724
935
  * `data-jx-prerendered` goes and before the clear: a prerendered instance's children are its
725
936
  * markup, and capture recovers what the prerender placed from its brackets instead.
726
937
  */
727
- /*
728
- * Everything from here to the render effect happens to an instance ONCE. `connectedCallback` runs
729
- * again each time the element is put back in a document (a list reordered with `append`, a panel
730
- * moved between containers), and `disconnectedCallback` only stopped the effects: the tree lit
731
- * drew is still there, and so is the part lit cached on the container for it. Clearing the
732
- * container a second time removed the nodes that part still points at, so the render that
733
- * followed updated a detached tree and the element stayed empty for good. A second capture is
734
- * wrong for its own reason: by then the host's children are the component's own render, not
735
- * what the author slotted.
736
- */
737
- lines.push(" const _first = !this.#rendered;", " this.#rendered = true;");
738
938
  if (hasSlot) {
739
939
  lines.push(` const _slotted = _first ? ${SLOT_CAPTURE_HELPER}(this) : null;`);
740
940
  }
@@ -784,9 +984,13 @@ export function emitElementModule(
784
984
  lines.push(` if (_first) ${SLOT_DISTRIBUTE_HELPER}(this, _slotted);`);
785
985
  }
786
986
  lines.push(
787
- // Lifecycle: onMount (spec §16.4) — same microtask contract as the runtime
788
- " if (typeof this.state.onMount === 'function') {",
789
- " queueMicrotask(() => this.state.onMount(this.state));",
987
+ /* Lifecycle: onMount (spec.md §16.4), by the interpreter's contract. On a microtask after the
988
+ render; with the scope and the HOST, and the host as its receiver, so a sidecar reaches the
989
+ element it belongs to; and on the first connection only, like everything else that happens
990
+ to an instance once. A parent's slot distribution moves a slotted element straight after it
991
+ rendered, and a hook that ran per connection handed every slotted component its host twice. */
992
+ " if (_first && typeof this.state.onMount === 'function') {",
993
+ " queueMicrotask(() => this.state.onMount.call(this, this.state, this));",
790
994
  " }",
791
995
  " }",
792
996
  "",
@@ -796,11 +1000,27 @@ export function emitElementModule(
796
1000
  " this.#effects.length = 0;",
797
1001
  " if (typeof this.state.onUnmount === 'function') { this.state.onUnmount(this.state); }",
798
1002
  " }",
799
- "}",
800
- "",
801
- `customElements.define('${doc.tagName}', ${className});`,
802
- "",
803
1003
  );
1004
+ if ("onAdopted" in defs) {
1005
+ lines.push(
1006
+ "",
1007
+ " adoptedCallback() {",
1008
+ " if (typeof this.state.onAdopted === 'function') { this.state.onAdopted(this.state); }",
1009
+ " }",
1010
+ );
1011
+ }
1012
+ if (observed.length > 0) {
1013
+ lines.push(
1014
+ "",
1015
+ /* The constructor built the state, so unlike the interpreter this needs no state guard and
1016
+ hears a change made before connection too. */
1017
+ " attributeChangedCallback(name, oldVal, newVal) {",
1018
+ " if (oldVal === newVal) return;",
1019
+ ` ${OBSERVED_ATTR_HELPER}(this.state, name, newVal, __jxObservedDefaults());`,
1020
+ " }",
1021
+ );
1022
+ }
1023
+ lines.push("}", "", `customElements.define('${doc.tagName}', ${className});`, "");
804
1024
 
805
1025
  return lines.join("\n");
806
1026
  }
@@ -1000,8 +1220,14 @@ ${no}
1000
1220
 
1001
1221
  const parts: string[] = [];
1002
1222
 
1223
+ const classAttr = litClassAttr(def, toLitExpr, refToExpr);
1224
+
1003
1225
  if (def.attributes) {
1004
1226
  for (const [key, val] of Object.entries(def.attributes)) {
1227
+ // Written once below, merged with the style handle.
1228
+ if (key === "class" && classAttr !== null) {
1229
+ continue;
1230
+ }
1005
1231
  /* Every branch here answers the same question the runtime's `applyAttributes` answers, and
1006
1232
  must answer it the same way or a prerendered page changes meaning as it hydrates (spec.md
1007
1233
  §8.3). A LITERAL boolean is decided now; a BOUND one cannot be, because its resolved type
@@ -1034,8 +1260,8 @@ ${no}
1034
1260
  if (def.id) {
1035
1261
  parts.push(`id="${toLitExpr(String(def.id))}"`);
1036
1262
  }
1037
- if (def.className) {
1038
- parts.push(`class="${toLitExpr(String(def.className))}"`);
1263
+ if (classAttr !== null) {
1264
+ parts.push(classAttr);
1039
1265
  }
1040
1266
 
1041
1267
  for (const [key, val] of Object.entries(def)) {
@@ -1219,8 +1445,13 @@ function emitMappedArray(arrayDef: JxMappedArray, indent: string) {
1219
1445
 
1220
1446
  // The map root gets the same attribute treatment as any other element (emitLitNode above);
1221
1447
  // `${item…}`/`${index…}` templates resolve against the map callback's own parameters.
1448
+ const classAttr = litClassAttr(mapDef, toLitExpr, mapRefToExpr);
1222
1449
  if (mapDef.attributes) {
1223
1450
  for (const [key, val] of Object.entries(mapDef.attributes)) {
1451
+ // Written once below, merged with the style handle.
1452
+ if (key === "class" && classAttr !== null) {
1453
+ continue;
1454
+ }
1224
1455
  if (isRef(val)) {
1225
1456
  parts.push(`${key}="\${${mapRefToExpr(val.$ref)}}"`);
1226
1457
  } else if (isString(val) && val.includes("${")) {
@@ -1234,8 +1465,8 @@ function emitMappedArray(arrayDef: JxMappedArray, indent: string) {
1234
1465
  if (mapDef.id) {
1235
1466
  parts.push(`id="${toLitExpr(String(mapDef.id))}"`);
1236
1467
  }
1237
- if (mapDef.className) {
1238
- parts.push(`class="${toLitExpr(String(mapDef.className))}"`);
1468
+ if (classAttr !== null) {
1469
+ parts.push(classAttr);
1239
1470
  }
1240
1471
 
1241
1472
  // IDL properties (`value`, `checked`, `selected`, …) go straight on the element, exactly as they
@@ -1339,6 +1570,37 @@ function emitMappedArray(arrayDef: JxMappedArray, indent: string) {
1339
1570
  return `${indent}\${${itemsExpr}.map(${callback})}`;
1340
1571
  }
1341
1572
 
1573
+ /**
1574
+ * An element's one `class` attribute for a lit template: the author's classes, then the style
1575
+ * handle (spec.md §9.2). `null` for an element with neither a handle nor a `className`, whose
1576
+ * `attributes.class` is then emitted by the attributes loop as it always was.
1577
+ *
1578
+ * @param {JxMutableNode | JxElement} def
1579
+ * @param {(template: string) => string} templ - Rewrites a string's `${…}` for the template
1580
+ * @param {(ref: string) => string} ref - Lowers a `$ref` to the expression that reads it
1581
+ * @returns {string | null}
1582
+ */
1583
+ function litClassAttr(
1584
+ def: JxMutableNode | JxElement,
1585
+ templ: (template: string) => string,
1586
+ ref: (pointer: string) => string,
1587
+ ): string | null {
1588
+ if (!writesMergedClass(def)) {
1589
+ return null;
1590
+ }
1591
+ const author = authorClassValue(def);
1592
+ let authorText = "";
1593
+ if (isRef(author)) {
1594
+ authorText = `\${${ref(author.$ref)} ?? ""}`;
1595
+ } else if (isString(author)) {
1596
+ authorText = templ(author);
1597
+ } else if (isNumber(author)) {
1598
+ authorText = String(author);
1599
+ }
1600
+ const handle = styleHandleOf(def) ?? "";
1601
+ return `class="${[authorText, handle].filter((token) => token !== "").join(" ")}"`;
1602
+ }
1603
+
1342
1604
  /**
1343
1605
  * Whether a document value binds through a non-empty `$ref` pointer. An empty pointer names no
1344
1606
  * state, so the emitters treat that object as a literal value rather than a binding.