@jxsuite/compiler 9.0.1 → 10.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.
package/src/shared.ts CHANGED
@@ -21,15 +21,19 @@ import {
21
21
  SLOT_MARK,
22
22
  SLOT_RECORD_KEY,
23
23
  SLOT_WHITESPACE,
24
+ absorbAttribute,
24
25
  booleanAttrValue,
25
26
  buildStyleRules,
27
+ commentedRuleText,
28
+ declaredDefaults,
26
29
  enumeratedAttrNames,
27
- isNestedSelectorKey,
28
30
  camelToKebab,
29
31
  isSingleExpression,
30
- splitSelectorList,
32
+ mappedListItems,
31
33
  } from "@jxsuite/runtime";
32
- import { spliceNestingSelector } from "@jxsuite/runtime/css";
34
+ import type { CssBuildOptions } from "@jxsuite/runtime/css";
35
+ import { isContentProperty, reflectedAttribute } from "@jxsuite/runtime/dom-properties";
36
+ import type { Reflection } from "@jxsuite/runtime/dom-properties";
33
37
  import {
34
38
  compileOperandSource,
35
39
  evaluateExpression,
@@ -39,8 +43,10 @@ import {
39
43
  isPureNamedFormula,
40
44
  } from "@jxsuite/runtime/expression";
41
45
  import { runStatements } from "@jxsuite/runtime/statements";
46
+ import { BUILT_IN_PROTOTYPES } from "@jxsuite/schema/defs";
42
47
  import { buildSiteStyleCSS } from "@jxsuite/site/site-style";
43
48
  import {
49
+ attributeStateKey,
44
50
  childrenContainArray,
45
51
  hasStructuredBody,
46
52
  isExpressionDef,
@@ -65,11 +71,19 @@ import {
65
71
  import type { TagNameSlot } from "@jxsuite/schema/guards";
66
72
  import { resolveShadowMode, styleScopePrefix } from "./shadow.ts";
67
73
  import type { ShadowMode } from "./shadow.ts";
68
- import { escapeToken, objectKey, readPath, refAccessor } from "@jxsuite/runtime/pointer";
74
+ import {
75
+ canonicalMapRef,
76
+ escapeToken,
77
+ objectKey,
78
+ readPath,
79
+ refAccessor,
80
+ refSegments,
81
+ } from "@jxsuite/runtime/pointer";
69
82
  import type { JxScope } from "@jxsuite/runtime/types";
70
83
  import type {
71
84
  CemParameter,
72
85
  JsonValue,
86
+ JxAttributeValue,
73
87
  JxDocument,
74
88
  JxDocumentValue,
75
89
  JxElement,
@@ -385,6 +399,50 @@ const RUNTIME_ONLY_KEYS = Symbol("jx.runtimeOnlyStateKeys");
385
399
  export const DEFAULT_REACTIVITY_SRC = "https://esm.sh/@vue/reactivity@3.5.40";
386
400
  export const DEFAULT_LIT_HTML_SRC = "https://esm.sh/lit-html@3.3.0";
387
401
 
402
+ /**
403
+ * Render the `<script type="importmap">` block for an `imports` object.
404
+ *
405
+ * @param {Record<string, string>} imports
406
+ * @returns {string}
407
+ */
408
+ export function renderImportMap(imports: Record<string, string>): string {
409
+ const entries = Object.entries(imports)
410
+ .map(([name, url]) => ` ${JSON.stringify(name)}: ${JSON.stringify(url)}`)
411
+ .join(",\n");
412
+ return `<script type="importmap">\n {\n "imports": {\n${entries}\n }\n }\n </script>`;
413
+ }
414
+
415
+ /** What a page-template tier is told about where its runtime modules are served. */
416
+ export interface PageImportSources {
417
+ /** The build's whole import map, prefix keys included. Wins over the two sources below. */
418
+ runtimeImports?: Record<string, string> | undefined;
419
+ reactivitySrc: string;
420
+ litHtmlSrc: string;
421
+ }
422
+
423
+ /**
424
+ * The import map a page-template tier writes (compiler.md §12). A site build hands over its whole
425
+ * map, so a page's own map carries the prefix keys a compiled module's package subpath resolves
426
+ * through (`lit-html/directives/repeat.js`, which a keyed list imports). A document compiled on its
427
+ * own gets the two exact keys, plus the `lit-html/` prefix when lit is served from the default CDN,
428
+ * whose URL space has the subpaths under it. A caller's own `litHtmlSrc` names one file and says
429
+ * nothing about where its siblings are, so no prefix is invented for it.
430
+ *
431
+ * @param {PageImportSources} sources
432
+ * @returns {string} The `<script type="importmap">` block
433
+ */
434
+ export function pageImportMap(sources: PageImportSources): string {
435
+ if (sources.runtimeImports !== undefined) {
436
+ return renderImportMap(sources.runtimeImports);
437
+ }
438
+ const exact = { "@vue/reactivity": sources.reactivitySrc, "lit-html": sources.litHtmlSrc };
439
+ return renderImportMap(
440
+ sources.litHtmlSrc === DEFAULT_LIT_HTML_SRC
441
+ ? { ...exact, "lit-html/": `${DEFAULT_LIT_HTML_SRC}/` }
442
+ : exact,
443
+ );
444
+ }
445
+
388
446
  // ─── Schema keywords & detection ─────────────────────────────────────────────
389
447
  // Centralized in @jxsuite/schema/guards; re-exported here for existing callers.
390
448
 
@@ -518,10 +576,18 @@ function withoutPureFormulas(def: JxElement | JxMutableNode): string {
518
576
  /**
519
577
  * Determine whether a node (or any of its descendants) requires client-side JavaScript.
520
578
  *
579
+ * A template string written as a text child counts, at any depth, exactly as a template in a
580
+ * property does (compiler.md §2.1, §2.2): the site build bakes every one it can before routing, so
581
+ * one that reaches here needs the client. A whole-`children` template string is not a text child
582
+ * and is not counted (spec.md §8.4 resolves it at build time only).
583
+ *
521
584
  * @param {JxElement | JxMutableNode | string} def
522
585
  * @returns {boolean}
523
586
  */
524
587
  export function isDynamic(def: JxElement | JxMutableNode | string) {
588
+ if (isString(def)) {
589
+ return isTemplateString(def);
590
+ }
525
591
  if (!isNonNullObject(def)) {
526
592
  return false;
527
593
  }
@@ -575,57 +641,10 @@ export function isDynamic(def: JxElement | JxMutableNode | string) {
575
641
  return true;
576
642
  }
577
643
 
644
+ const finished = isExpandedInstance(def);
578
645
  for (const [key, val] of Object.entries(def)) {
579
- if (RESERVED_KEYS.has(key)) {
580
- continue;
581
- }
582
- if (isRef(val)) {
583
- return true;
584
- }
585
- if (isTemplateString(val)) {
586
- return true;
587
- }
588
- }
589
-
590
- if (isNonNullObject(def.style)) {
591
- for (const val of Object.values(def.style)) {
592
- if (isTemplateString(val)) {
593
- return true;
594
- }
595
- }
596
- }
597
-
598
- if (isNonNullObject(def.attributes)) {
599
- for (const val of Object.values(def.attributes)) {
600
- if (isTemplateString(val)) {
601
- return true;
602
- }
603
- }
604
- }
605
-
606
- return false;
607
- }
608
-
609
- /**
610
- * Shallow variant of isDynamic — checks only this node's own properties, not its children.
611
- *
612
- * @param {JxElement | JxMutableNode | string} def
613
- * @returns {boolean}
614
- */
615
- export function isNodeDynamic(def: JxElement | JxMutableNode | string) {
616
- if (!isNonNullObject(def)) {
617
- return false;
618
- }
619
-
620
- if (def.$switch) {
621
- return true;
622
- }
623
- if (isMappedArray(def) || childrenContainArray(def.children)) {
624
- return true;
625
- }
626
-
627
- for (const [key, val] of Object.entries(def)) {
628
- if (RESERVED_KEYS.has(key)) {
646
+ // An expanded instance's `innerHTML` is its prerender: a `${` in it is text, not a template.
647
+ if (RESERVED_KEYS.has(key) || (finished && key === "innerHTML")) {
629
648
  continue;
630
649
  }
631
650
  if (isRef(val)) {
@@ -656,22 +675,17 @@ export function isNodeDynamic(def: JxElement | JxMutableNode | string) {
656
675
  }
657
676
 
658
677
  /**
659
- * Returns true if any node in the tree will need dynamic handling.
678
+ * Whether a node is a component instance the site build already expanded: it carries the stamp, and
679
+ * its `innerHTML` is the definition's prerender. That markup is finished HTML, resolved against the
680
+ * instance's own scope, so no later pass reads a `${` in it as a template: resolved against the
681
+ * page's scope a code sample would render `undefined`, and the template alone would route a static
682
+ * page to the client target (compiler.md §8.1).
660
683
  *
661
- * @param {JxElement | JxMutableNode | string} def
684
+ * @param {JxElement | JxMutableNode} def
662
685
  * @returns {boolean}
663
686
  */
664
- export function hasAnyIsland(def: JxElement | JxMutableNode | string): boolean {
665
- if (!isNonNullObject(def)) {
666
- return false;
667
- }
668
- if (isDynamic(def)) {
669
- return true;
670
- }
671
- if (Array.isArray(def.children)) {
672
- return def.children.some((c): boolean => hasAnyIsland(c));
673
- }
674
- return false;
687
+ export function isExpandedInstance(def: JxElement | JxMutableNode): boolean {
688
+ return def.$static === true || def.$prerendered === true;
675
689
  }
676
690
 
677
691
  // ─── Scope / value resolution ─────────────────────────────────────────────────
@@ -743,6 +757,25 @@ export function isRuntimeOnlyStateKey(scope: JxScope, key: string): boolean {
743
757
  return runtimeOnlyKeysOf(scope)?.has(key) ?? false;
744
758
  }
745
759
 
760
+ /**
761
+ * Whether a `$ref` names state the build holds as runtime-only: a `#/state/<key>` pointer whose
762
+ * first reference token is marked. A `$map/` pointer never is. Asked BEFORE the pointer is read,
763
+ * because reading a marked computed runs a getter that is free to throw on partial build-time data,
764
+ * and a bodyless `$src` Function reads as a placeholder callable, never as its value.
765
+ *
766
+ * @param {string} ref - The `$ref` as written
767
+ * @param {JxScope} scope - The build-time scope, or a row scope whose prototype chain reaches it
768
+ * @returns {boolean}
769
+ */
770
+ export function isRuntimeOnlyRef(ref: string, scope: JxScope): boolean {
771
+ if (!ref.startsWith("#/state/")) {
772
+ return false;
773
+ }
774
+ // The first reference token, unescaped as RFC 6901 §4 orders it (`~1` before `~0`).
775
+ const [token = ""] = ref.slice("#/state/".length).split("/");
776
+ return isRuntimeOnlyStateKey(scope, token.replaceAll("~1", "/").replaceAll("~0", "~"));
777
+ }
778
+
746
779
  /**
747
780
  * `state.x = …`, `state.x += …`, `state.x++` — every form a string handler body can use to write a
748
781
  * state entry. `===`/`!==`/`<=`/`>=` are excluded by the `(?!=)` guard and by the operator set.
@@ -786,6 +819,25 @@ function movesState(read: string, at: number, bare: boolean): boolean {
786
819
  * @param options `bare` moves `state` alone too, not only `state.member`; `code: false` reads text
787
820
  * that is not a body (an attribute's template), where nothing is a string or a comment.
788
821
  */
822
+ /**
823
+ * Whether emitted source still names `state` on its own, after {@link rewriteState} moved every
824
+ * `state.member` read: `${state.applySelection(state)}` hands the scope itself to a helper, as a
825
+ * template may (the interpreter binds `state` as a parameter of every template). The element target
826
+ * has no variable of that name, so a module whose templates do this declares one beside the alias
827
+ * it reads through. A false positive (the word in literal text) costs one unused `const`.
828
+ *
829
+ * @param {string} source - Emitted template or expression source
830
+ * @returns {boolean}
831
+ */
832
+ export function readsBareState(source: string): boolean {
833
+ for (let at = source.indexOf("state"); at !== -1; at = source.indexOf("state", at + 1)) {
834
+ if (movesState(source, at, true) && !movesState(source, at, false)) {
835
+ return true;
836
+ }
837
+ }
838
+ return false;
839
+ }
840
+
789
841
  export function rewriteState(
790
842
  text: string,
791
843
  to: string,
@@ -867,6 +919,36 @@ function collectAssignedStateKeys(node: JxDocumentValue | undefined, into: Set<s
867
919
  }
868
920
  }
869
921
 
922
+ /**
923
+ * The state keys written by handlers declared inline on an element (`onclick: { "$prototype":
924
+ * "Function", … }` or an `$expression`), anywhere a render can reach: `children` in either shape, a
925
+ * repeater's `map`, and a `$switch`'s `cases`.
926
+ *
927
+ * @param {SlotChildren} children
928
+ * @param {Set<string>} into
929
+ */
930
+ function collectInlineHandlerWrites(children: SlotChildren, into: Set<string>): void {
931
+ for (const child of slotChildList(children)) {
932
+ if (isMappedArray(child)) {
933
+ collectInlineHandlerWrites(child.map ? [child.map] : [], into);
934
+ continue;
935
+ }
936
+ if (!isNodeObject(child)) {
937
+ continue;
938
+ }
939
+ for (const [key, value] of Object.entries(child)) {
940
+ if (key.startsWith("on") && (isFunctionDef(value) || isExpressionDef(value))) {
941
+ collectAssignedStateKeys(value.body ?? value.$expression, into);
942
+ }
943
+ }
944
+ collectInlineHandlerWrites(
945
+ Object.values(child.cases ?? {}).filter((c) => isNodeObject(c) && !isRefObject(c)),
946
+ into,
947
+ );
948
+ collectInlineHandlerWrites(child.children, into);
949
+ }
950
+ }
951
+
870
952
  /**
871
953
  * Refuse a Function declaration that names both a `body` and a `$src` (spec.md §5.3 4d). The pair
872
954
  * has no meaning: each tier used to keep a different half, so a document that built in one target
@@ -990,14 +1072,37 @@ export function emitSrcImports(
990
1072
  return { imports: importLines, loaders };
991
1073
  }
992
1074
 
1075
+ /** How {@link buildInitialScope} treats an entry a handler writes. */
1076
+ export interface BuildScopeOptions {
1077
+ /**
1078
+ * Hold every entry a handler in the document writes as runtime-only, so no template reading it
1079
+ * resolves. Only the pass that REPLACES a template with its value asks for this (the site build's
1080
+ * page-document scope, compiler.md §8.1): a baked value there is a dead binding. Everywhere a
1081
+ * binding survives the prerender (a component's module re-renders its template, a dynamic page's
1082
+ * module binds what it prerenders) the entry bakes its initial value, which is the first paint.
1083
+ */
1084
+ holdMutable?: boolean;
1085
+ /**
1086
+ * The document the `state` block belongs to, for a holding scope: a handler written inline on an
1087
+ * element's `on*` key writes state exactly as one declared in `state` does, and its writes are
1088
+ * held too (compiler.md §8.1 scans "every handler body in the document").
1089
+ */
1090
+ document?: JxElement | JxMutableNode | undefined;
1091
+ }
1092
+
993
1093
  /**
1094
+ * The build-time scope of a `state` block: what each entry holds before any handler has run.
1095
+ *
994
1096
  * @param {Record<string, JxStateDefinition>} [defs]
995
1097
  * @param {JxScope | null} [parentScope]
1098
+ * @param {BuildScopeOptions} [options]
996
1099
  * @returns {JxScope}
1100
+ * @docs framework/build
997
1101
  */
998
1102
  export function buildInitialScope(
999
1103
  defs: Record<string, JxStateDefinition> = {},
1000
1104
  parentScope: JxScope | null = null,
1105
+ options: BuildScopeOptions = {},
1001
1106
  ) {
1002
1107
  const scope = emptyScope(parentScope);
1003
1108
  // Keys whose real value only exists after hydration, so prerender must not interpolate them —
@@ -1013,19 +1118,26 @@ export function buildInitialScope(
1013
1118
  writable: true,
1014
1119
  });
1015
1120
 
1016
- // Pass 0: every entry some handler in this document writes to is mutable, so prerender must not
1017
- // Bake a binding over it. Narrow on purpose — an entry nothing ever writes stays bakeable, so
1018
- // Prerendered content is preserved for SEO. A `$src` handler's assignments live in a JS file this
1019
- // Builder cannot open, so a write that only happens there is still missed (issue #125).
1020
- const assigned = new Set<string>();
1021
- for (const def of Object.values(defs)) {
1022
- if (isFunctionDef(def) || isExpressionDef(def)) {
1023
- collectAssignedStateKeys(def.body ?? def.$expression, assigned);
1121
+ // Pass 0, for a holding scope only: every entry some handler in this document writes to is
1122
+ // Mutable, so a pass that replaces a template with its value must not bake over it. Narrow on
1123
+ // Purpose: an entry nothing ever writes stays bakeable, so prerendered content is preserved for
1124
+ // SEO. A `$src` handler's assignments live in a JS file this builder cannot open, so a write that
1125
+ // Only happens there is still missed. A scope that does not hold bakes the entry's initial value,
1126
+ // Because the binding that reads it outlives the prerender (compiler.md §8.1).
1127
+ if (options.holdMutable === true) {
1128
+ const assigned = new Set<string>();
1129
+ for (const def of Object.values(defs)) {
1130
+ if (isFunctionDef(def) || isExpressionDef(def)) {
1131
+ collectAssignedStateKeys(def.body ?? def.$expression, assigned);
1132
+ }
1024
1133
  }
1025
- }
1026
- for (const key of assigned) {
1027
- if (key in defs) {
1028
- runtimeOnly.add(key);
1134
+ if (options.document) {
1135
+ collectInlineHandlerWrites([options.document], assigned);
1136
+ }
1137
+ for (const key of assigned) {
1138
+ if (key in defs) {
1139
+ runtimeOnly.add(key);
1140
+ }
1029
1141
  }
1030
1142
  }
1031
1143
 
@@ -1059,6 +1171,12 @@ export function buildInitialScope(
1059
1171
  // The scope as its already-evaluated *result*, so a template reading it sees an ordinary string
1060
1172
  // And prerender bakes it — destroying the binding rather than merely staling it (issue #124).
1061
1173
  const computedBodies: [string, string][] = [];
1174
+ /* Every other entry the scope holds a value or a callable for, by its source: an `$expression`
1175
+ (a computed, a handler or a named formula) and a Function body, string or structured. Each
1176
+ joins the fixpoint below, so what compiler.md §8.1 says of a computed holds of them all: one
1177
+ that reads a runtime-only entry is runtime-only in turn. A repeater asks this of its `items`,
1178
+ `filter` and `sort` before the build expands it (`isRuntimeOnlyRef`). */
1179
+ const entrySources: [string, string][] = [];
1062
1180
 
1063
1181
  for (const [key, def] of Object.entries(defs)) {
1064
1182
  if (isTemplateString(def)) {
@@ -1070,6 +1188,7 @@ export function buildInitialScope(
1070
1188
  }
1071
1189
  if (isExpressionDef(def)) {
1072
1190
  const node = def.$expression;
1191
+ entrySources.push([key, JSON.stringify(node)]);
1073
1192
  if (isNamedFormulaDef(def)) {
1074
1193
  // Named formula: callable, positional args mapped onto its declared parameters.
1075
1194
  const params: readonly FormulaParameter[] = def.parameters;
@@ -1100,6 +1219,7 @@ export function buildInitialScope(
1100
1219
  // Structured body (spec §20): a side-effecting handler in the build-time scope. Build-time
1101
1220
  // Code may call it bare, so the scope it runs against falls back to this one.
1102
1221
  const { body } = def;
1222
+ entrySources.push([key, JSON.stringify(body)]);
1103
1223
  setOwnScopeValue(scope, key, (s?: JxScope, event?: Event) => {
1104
1224
  void runStatements(body, s ?? scope, event ?? null);
1105
1225
  });
@@ -1117,6 +1237,7 @@ export function buildInitialScope(
1117
1237
  computedBodies.push([key, body]);
1118
1238
  } else {
1119
1239
  setOwnScopeValue(scope, key, fn);
1240
+ entrySources.push([key, body]);
1120
1241
  }
1121
1242
  } else {
1122
1243
  // Bodyless `$src` Function — the real implementation is only loaded in the browser, so this
@@ -1137,6 +1258,10 @@ export function buildInitialScope(
1137
1258
  // A client-timing fetch has no build-time value at all — not even a placeholder.
1138
1259
  runtimeOnly.add(key);
1139
1260
  }
1261
+ if (isClientExternalClass(def)) {
1262
+ // Its value is whatever the class resolves to in the browser (compiler.md §3).
1263
+ runtimeOnly.add(key);
1264
+ }
1140
1265
  }
1141
1266
 
1142
1267
  // A state entry that reads a runtime-only key cannot resolve until hydration either, so it is
@@ -1153,6 +1278,12 @@ export function buildInitialScope(
1153
1278
  marked = true;
1154
1279
  }
1155
1280
  }
1281
+ for (const [key, source] of entrySources) {
1282
+ if (!runtimeOnly.has(key) && readsMarkedState(source, runtimeOnly)) {
1283
+ runtimeOnly.add(key);
1284
+ marked = true;
1285
+ }
1286
+ }
1156
1287
  }
1157
1288
 
1158
1289
  for (const [key, template] of templateDefs) {
@@ -1223,8 +1354,9 @@ export function resolveRefValue(refValue: JsonValue | undefined, scope: JxScope)
1223
1354
  if (!isString(refValue)) {
1224
1355
  return refValue;
1225
1356
  }
1226
- if (refValue.startsWith("$map/")) {
1227
- const parts = refValue.split("/");
1357
+ const mapRef = canonicalMapRef(refValue);
1358
+ if (mapRef.startsWith("$map/")) {
1359
+ const parts = mapRef.split("/");
1228
1360
  const key = parts[1]!;
1229
1361
  /* SAFETY: `?.` stops at null and undefined, and every other value answers a member read by
1230
1362
  name; the member comes back as a scope member, so the view claims nothing about its type. */
@@ -1289,6 +1421,27 @@ function readsRuntimeOnlyState(str: string, scope: JxScope | null) {
1289
1421
  return false;
1290
1422
  }
1291
1423
 
1424
+ /**
1425
+ * Whether an entry's source reads a state key already marked runtime-only: a `#/state/<key>`
1426
+ * pointer in a structured body or an `$expression`, or a `state.<key>` member in a string body.
1427
+ * Narrower than {@link readsRuntimeOnlyState} on purpose: it consults the marks alone and never
1428
+ * reads the scope, so a callable that names another callable is not marked for that.
1429
+ *
1430
+ * @param {string} source - A string body, or the JSON text of a structured body or expression
1431
+ * @param {ReadonlySet<string>} runtimeOnly
1432
+ * @returns {boolean}
1433
+ */
1434
+ function readsMarkedState(source: string, runtimeOnly: ReadonlySet<string>): boolean {
1435
+ for (const match of source.matchAll(/#\/state\/([^"/\\]+)|\bstate\.([A-Za-z_$][\w$]*)/g)) {
1436
+ const [, token, member] = match;
1437
+ const key = token === undefined ? member : token.replaceAll("~1", "/").replaceAll("~0", "~");
1438
+ if (key !== undefined && runtimeOnly.has(key)) {
1439
+ return true;
1440
+ }
1441
+ }
1442
+ return false;
1443
+ }
1444
+
1292
1445
  /**
1293
1446
  * The JavaScript expression a Shape 3 template string compiles to (spec.md §5.3): the expression
1294
1447
  * itself, parenthesized, when the template is ONE expression, so it keeps its own type, and a
@@ -1320,11 +1473,22 @@ export function evaluateStaticTemplate(str: string, scope: JxScope | null) {
1320
1473
  * ReferenceError the catch below turned into a silent null. A `$head` title referencing the site
1321
1474
  * name reached the page as the literal template text.
1322
1475
  */
1323
- const args = ["state", "$map", "$site", "$page"] as const;
1476
+ const args = ["state", "$map", "$site", "$page"];
1324
1477
  const values = [scope, scope?.$map, scope?.$site, scope?.$page];
1478
+ /* Inside a repeater row the bare `item` and `index` are bound too, as the compiled map callback
1479
+ and the interpreter bind them (spec.md §10.2). Only there: outside a row the names stay
1480
+ unbound, so a template that reads one fails to resolve as it always did. */
1481
+ const row = scope?.$map;
1482
+ if (isNonNullObject(row) && !Array.isArray(row)) {
1483
+ args.push("item", "index");
1484
+ /* SAFETY: a non-array object answers a member read by name, and a row frame's members are scope
1485
+ values; the view claims nothing about their types. */
1486
+ const frame = row as JxScope;
1487
+ values.push(frame.item, frame.index);
1488
+ }
1325
1489
  try {
1326
1490
  const body = isSingleExpression(str) ? `return (${str.slice(2, -1)})` : `return \`${str}\``;
1327
- /* SAFETY: `new Function` compiles exactly the four parameters in `args`, and its body returns a
1491
+ /* SAFETY: `new Function` compiles exactly the parameters in `args`, and its body returns a
1328
1492
  template's value, which is whatever the scope it reads holds: one more scope member. */
1329
1493
  const fn = new Function(...args, body) as (...a: JxScope[string][]) => JxScope[string];
1330
1494
  return fn(...values);
@@ -1393,9 +1557,112 @@ export function inlineStyleDeclarations(
1393
1557
  .join("; ");
1394
1558
  }
1395
1559
 
1560
+ /**
1561
+ * The text a DOM property writes into its content attribute, converted as the property's setter
1562
+ * converts it (spec.md §8.1), or `null` when it writes no attribute.
1563
+ *
1564
+ * - `null`, `undefined` and anything that is not a string, number or boolean write nothing.
1565
+ * - A `text` row writes the value's string form, the empty string included (`alt=""` and `value=""`
1566
+ * mean something).
1567
+ * - A `boolean` row applies ToBoolean, then writes its keyword (`translate` is `yes` or `no`) or what
1568
+ * `booleanAttrValue` gives the attribute: `""` for presence, a word for an enumerated one.
1569
+ * - `hidden` keeps the `until-found` keyword and otherwise follows truthiness.
1570
+ *
1571
+ * @param {Reflection} reflection - The row `reflectedAttribute` returned for the property
1572
+ * @param {JxScope[string]} value - The property's value, already resolved
1573
+ * @returns {string | null} The attribute's text (`""` is the bare form for a `boolean` or `hidden`
1574
+ * row), or null to write nothing
1575
+ * @docs framework/concepts/elements
1576
+ */
1577
+ export function propertyAttrText(reflection: Reflection, value: JxScope[string]): string | null {
1578
+ if (!isString(value) && !isNumber(value) && !isBoolean(value)) {
1579
+ return null;
1580
+ }
1581
+ if (reflection.kind === "text") {
1582
+ return String(value);
1583
+ }
1584
+ if (reflection.kind === "hidden") {
1585
+ if (isString(value) && value.toLowerCase() === "until-found") {
1586
+ return "until-found";
1587
+ }
1588
+ return value ? "" : null;
1589
+ }
1590
+ const on = Boolean(value);
1591
+ if (reflection.keywords) {
1592
+ return reflection.keywords[on ? 0 : 1];
1593
+ }
1594
+ return booleanAttrValue(reflection.attribute, on);
1595
+ }
1596
+
1597
+ /** The properties `buildAttrs` has always written, in the order it writes them. */
1598
+ const LEADING_PROPERTIES = ["hidden", "tabIndex", "title", "lang", "dir"] as const;
1599
+
1600
+ /** Keys `buildAttrs` writes at a fixed position, ahead of the definition's other properties. */
1601
+ const NON_PROPERTY_KEYS: ReadonlySet<string> = new Set([...LEADING_PROPERTIES, "id", "className"]);
1602
+
1603
+ /**
1604
+ * Every key `buildAttrs` does not read as a property in key order, so a member costs one lookup:
1605
+ * the reserved keys, the positioned ones, and the two content members nearly every element sets,
1606
+ * which HTML reflects to no attribute.
1607
+ */
1608
+ const POSITIONED_OR_RESERVED_KEYS: ReadonlySet<string> = new Set([
1609
+ ...RESERVED_KEYS,
1610
+ ...NON_PROPERTY_KEYS,
1611
+ "textContent",
1612
+ "innerHTML",
1613
+ ]);
1614
+
1615
+ /**
1616
+ * A property's value at build time, or `undefined` when the build has none: the pointer names
1617
+ * runtime-only state (asked before the read, as `renderMappedRows` does), or reading it threw,
1618
+ * which a computed's getter is free to do on build-time data.
1619
+ *
1620
+ * @param {JxDocumentValue | undefined} value
1621
+ * @param {JxScope | null} scope
1622
+ * @returns {JxScope[string]}
1623
+ */
1624
+ function resolvePropertyValue(
1625
+ value: JxDocumentValue | undefined,
1626
+ scope: JxScope | null,
1627
+ ): JxScope[string] {
1628
+ if (isRef(value) && (scope === null || isRuntimeOnlyRef(value.$ref, scope))) {
1629
+ return undefined;
1630
+ }
1631
+ try {
1632
+ return resolveStaticValue(value, scope);
1633
+ } catch {
1634
+ return undefined;
1635
+ }
1636
+ }
1637
+
1638
+ /**
1639
+ * One attribute as it is written into a start tag: bare when a boolean wrote the empty string.
1640
+ *
1641
+ * @param {string} name
1642
+ * @param {string} text
1643
+ * @param {boolean} bare - Whether an empty text is presence (`open`) and not a value (`alt=""`)
1644
+ * @returns {string}
1645
+ */
1646
+ function serializeAttr(name: string, text: string, bare: boolean): string {
1647
+ return bare && text === "" ? ` ${name}` : ` ${name}="${escapeHtml(text)}"`;
1648
+ }
1649
+
1396
1650
  /**
1397
1651
  * Build an HTML attribute string from a static element definition.
1398
1652
  *
1653
+ * Every DOM property the definition sets is written as the content attribute HTML reflects it to
1654
+ * (spec.md §8.1), from the one table in `@jxsuite/runtime/dom-properties`: the runtime assigns the
1655
+ * property and the platform reflects it, and built HTML has to say the same thing in attributes.
1656
+ * Order: `id`, `class`, then `hidden`, `tabindex`, `title`, `lang` and `dir`, then the other
1657
+ * properties in the definition's key order, then `style`, then `attributes`, then the markers.
1658
+ *
1659
+ * Each attribute name is written once. Where a property and an `attributes` entry name the same
1660
+ * attribute, the entry is written in the property's place, because the runtime applies attributes
1661
+ * after properties; an entry that resolves to nothing removes it. A live row (`value` on an
1662
+ * `<input>`, `checked`, `selected`, `muted`) is the exception: the property set a state a later
1663
+ * attribute write does not move, so the property's attribute stays. `class` is one attribute by its
1664
+ * own rule (spec.md §9.2).
1665
+ *
1399
1666
  * @param {JxElement | JxMutableNode} def
1400
1667
  * @param {JxScope | null} scope
1401
1668
  * @param {string} [hostStyle] - Declarations resolved by the caller against ANOTHER scope, folded
@@ -1403,57 +1670,86 @@ export function inlineStyleDeclarations(
1403
1670
  * caller: its own `style` resolves against the parent's scope, while the definition's host style
1404
1671
  * resolves against the instance's, and an element cannot carry two `style` attributes.
1405
1672
  * @returns {string}
1673
+ * @docs framework/concepts/elements
1406
1674
  */
1407
1675
  export function buildAttrs(def: JxElement | JxMutableNode, scope: JxScope | null, hostStyle = "") {
1408
- let out = "";
1676
+ const tag = resolveStaticTagName(def.tagName, scope);
1677
+ // Attribute name to its serialized form, in the order written. Names are lowercase.
1678
+ const written = new Map<string, string>();
1679
+ // Allocated by the first live row: most elements have none.
1680
+ let live: Set<string> | undefined;
1409
1681
 
1410
1682
  const id = resolveStaticValue(def.id, scope);
1411
- const className = resolveStaticValue(def.className, scope);
1412
- const hidden = resolveStaticValue(def.hidden, scope);
1413
- const tabIndex = resolveStaticValue(def.tabIndex, scope);
1414
- const title = resolveStaticValue(def.title, scope);
1415
- const lang = resolveStaticValue(def.lang, scope);
1416
- const dir = resolveStaticValue(def.dir, scope);
1417
-
1418
1683
  if (id) {
1419
- out += ` id="${escapeHtml(String(id))}"`;
1420
- }
1684
+ written.set("id", serializeAttr("id", String(id), false));
1685
+ }
1686
+ /* One `class` attribute, at the `className` position: the author's classes, then the style
1687
+ handle (spec.md §9.2). The author's are `attributes.class` when the element writes one, which
1688
+ is what the runtime leaves in effect, since it applies attributes after properties. */
1689
+ const mergesClass = writesMergedClass(def);
1690
+ const authorClass = mergesClass ? resolveStaticValue(authorClassValue(def), scope) : null;
1691
+ const className = [
1692
+ isString(authorClass) || isNumber(authorClass) ? String(authorClass) : "",
1693
+ styleHandleOf(def) ?? "",
1694
+ ]
1695
+ .filter((token) => token !== "")
1696
+ .join(" ");
1421
1697
  if (className) {
1422
- out += ` class="${escapeHtml(String(className))}"`;
1423
- }
1424
- if (hidden) {
1425
- out += " hidden";
1426
- }
1427
- if (tabIndex !== undefined && tabIndex !== null) {
1428
- out += ` tabindex="${escapeHtml(String(tabIndex))}"`;
1429
- }
1430
- if (title) {
1431
- out += ` title="${escapeHtml(String(title))}"`;
1432
- }
1433
- if (lang) {
1434
- out += ` lang="${escapeHtml(String(lang))}"`;
1435
- }
1436
- if (dir) {
1437
- out += ` dir="${escapeHtml(String(dir))}"`;
1698
+ written.set("class", serializeAttr("class", className, false));
1438
1699
  }
1439
1700
 
1440
- // The host declarations go last: in one `style` attribute the later declaration of a property
1441
- // Wins, and the page walk gives the definition's resolved host style the same precedence over an
1442
- // Instance's own (`{ ...node.style, ...resolvedStyle }`), so the two paths agree.
1443
- const inline = [inlineStyleDeclarations(def.style, scope), hostStyle].filter(Boolean).join("; ");
1444
- if (inline) {
1445
- /*
1446
- * Escaped like every other attribute. Both halves carry values a template string resolved
1447
- * from data — a `background-image: url("…")` host style reads its target from a prop — and a
1448
- * `"` in that data would otherwise end the attribute and hand the rest of the value to the
1449
- * parser as attributes. The HTML parser decodes `&quot;` before the CSS parser sees the
1450
- * declaration, so `url(&quot;…&quot;)` renders exactly as `url("…")`, and `rewriteHtmlBase`
1451
- * already reads the entity-wrapped form back when it re-roots a `url()`.
1452
- */
1453
- out += ` style="${escapeHtml(inline)}"`;
1701
+ const writeProperty = (key: string, value: JxDocumentValue | undefined) => {
1702
+ // An absent member writes nothing and decides nothing, so it is not worth a table lookup.
1703
+ if (value === undefined) {
1704
+ return;
1705
+ }
1706
+ const reflection = reflectedAttribute(tag, key);
1707
+ if (!reflection) {
1708
+ return;
1709
+ }
1710
+ const resolved = resolvePropertyValue(value, scope);
1711
+ /* A live row decides its attribute even when it writes none: `checked: false` leaves the box
1712
+ unchecked whatever `attributes.checked` says afterwards. A value the build cannot read
1713
+ decides nothing. */
1714
+ if (reflection.live && resolved !== undefined) {
1715
+ live ??= new Set();
1716
+ live.add(reflection.attribute);
1717
+ }
1718
+ const text = propertyAttrText(reflection, resolved);
1719
+ if (text !== null) {
1720
+ written.set(
1721
+ reflection.attribute,
1722
+ serializeAttr(reflection.attribute, text, reflection.kind !== "text"),
1723
+ );
1724
+ }
1725
+ };
1726
+ for (const key of LEADING_PROPERTIES) {
1727
+ writeProperty(key, def[key]);
1728
+ }
1729
+ /* Read by key, not as entries: this runs for every element a build writes, and an entry array per
1730
+ member was a measurable share of a static page's compile. */
1731
+ const members: Readonly<Record<string, JxDocumentValue | undefined>> = def;
1732
+ for (const key of Object.keys(members)) {
1733
+ if (
1734
+ POSITIONED_OR_RESERVED_KEYS.has(key) ||
1735
+ key.startsWith("$") ||
1736
+ key.startsWith("on") ||
1737
+ isContentProperty(tag, key)
1738
+ ) {
1739
+ continue;
1740
+ }
1741
+ /* A definition's own member outside the reserved, `$` and `on` keys is a DOM property's value,
1742
+ which a document writes as a literal, a `$ref` or a template (spec.md §8.1). */
1743
+ writeProperty(key, members[key]);
1454
1744
  }
1745
+
1746
+ let rest = "";
1455
1747
  if (def.attributes) {
1456
1748
  for (const [k, v] of Object.entries(def.attributes)) {
1749
+ // Already written above, merged with the style handle.
1750
+ if (mergesClass && k === "class") {
1751
+ continue;
1752
+ }
1457
1753
  const value = resolveStaticValue(v, scope);
1458
1754
  /*
1459
1755
  * A boolean is the attribute's PRESENCE or its text, depending on which family HTML puts the
@@ -1472,19 +1768,53 @@ export function buildAttrs(def: JxElement | JxMutableNode, scope: JxScope | null
1472
1768
  * Sidebar's own not-the-current-page marker, and second-guessing it would be this same defect
1473
1769
  * Pointed the other way.
1474
1770
  */
1771
+ let serialized: string | null = null;
1475
1772
  if (isBoolean(value)) {
1476
1773
  const text = booleanAttrValue(k, value);
1477
- if (text !== null) {
1478
- out += text === "" ? ` ${k}` : ` ${k}="${escapeHtml(text)}"`;
1479
- }
1774
+ serialized = text === null ? null : serializeAttr(k, text, true);
1775
+ } else if (isString(value) || isNumber(value)) {
1776
+ serialized = serializeAttr(k, String(value), false);
1777
+ }
1778
+ /* A name a property already wrote (`setAttribute` lowercases the name on an HTML element, so
1779
+ the match ignores ASCII case) is written once, as the runtime leaves it. */
1780
+ const name = k.toLowerCase();
1781
+ if (live?.has(name)) {
1480
1782
  continue;
1481
1783
  }
1482
- if (isString(value) || isNumber(value)) {
1483
- out += ` ${k}="${escapeHtml(String(value))}"`;
1784
+ if (written.has(name)) {
1785
+ if (serialized === null && (value === null || value === undefined || isBoolean(value))) {
1786
+ written.delete(name);
1787
+ } else if (serialized !== null) {
1788
+ written.set(name, serialized);
1789
+ }
1790
+ continue;
1484
1791
  }
1792
+ rest += serialized ?? "";
1485
1793
  }
1486
1794
  }
1487
1795
 
1796
+ let out = "";
1797
+ for (const serialized of written.values()) {
1798
+ out += serialized;
1799
+ }
1800
+
1801
+ // The host declarations go last: in one `style` attribute the later declaration of a property
1802
+ // Wins, and the page walk gives the definition's resolved host style the same precedence over an
1803
+ // Instance's own (`{ ...node.style, ...resolvedStyle }`), so the two paths agree.
1804
+ const inline = [inlineStyleDeclarations(def.style, scope), hostStyle].filter(Boolean).join("; ");
1805
+ if (inline) {
1806
+ /*
1807
+ * Escaped like every other attribute. Both halves carry values a template string resolved
1808
+ * from data — a `background-image: url("…")` host style reads its target from a prop — and a
1809
+ * `"` in that data would otherwise end the attribute and hand the rest of the value to the
1810
+ * parser as attributes. The HTML parser decodes `&quot;` before the CSS parser sees the
1811
+ * declaration, so `url(&quot;…&quot;)` renders exactly as `url("…")`, and `rewriteHtmlBase`
1812
+ * already reads the entity-wrapped form back when it re-roots a `url()`.
1813
+ */
1814
+ out += ` style="${escapeHtml(inline)}"`;
1815
+ }
1816
+ out += rest;
1817
+
1488
1818
  if (def.$static) {
1489
1819
  out += ` data-jx-static`;
1490
1820
  } else if (def.$prerendered) {
@@ -1494,6 +1824,47 @@ export function buildAttrs(def: JxElement | JxMutableNode, scope: JxScope | null
1494
1824
  return out;
1495
1825
  }
1496
1826
 
1827
+ /**
1828
+ * The element's text when one of its content properties sets it (spec.md §8.1): `innerText`
1829
+ * anywhere, `value` on a `<textarea>` or `<output>`, `text` on an `<option>`. Each of those setters
1830
+ * replaces the element's children with text, so built HTML writes it as escaped text; `innerText`
1831
+ * also turns each line break into a `<br>`, as its setter does. The first one in the definition's
1832
+ * key order wins: a definition with two has contradicted itself. An expanded component instance has
1833
+ * none, because its `innerHTML` is its finished content (`isExpandedInstance`).
1834
+ *
1835
+ * @param {JxElement | JxMutableNode} source
1836
+ * @param {string} tag - The element's resolved tag
1837
+ * @param {JxScope | null} scope
1838
+ * @returns {string | undefined} Escaped HTML, or undefined when the definition sets none
1839
+ * @docs framework/concepts/elements
1840
+ */
1841
+ export function contentPropertyText(
1842
+ source: JxElement | JxMutableNode,
1843
+ tag: string,
1844
+ scope: JxScope | null,
1845
+ ): string | undefined {
1846
+ if (isExpandedInstance(source)) {
1847
+ return undefined;
1848
+ }
1849
+ // The four keys `isContentProperty` can say yes to: most elements name none of them.
1850
+ if (
1851
+ !("innerText" in source || "value" in source || "defaultValue" in source || "text" in source)
1852
+ ) {
1853
+ return undefined;
1854
+ }
1855
+ for (const [key, raw] of Object.entries(source)) {
1856
+ if (raw === undefined || !isContentProperty(tag, key)) {
1857
+ continue;
1858
+ }
1859
+ /* SAFETY: a content property is a DOM property like any other, written as a literal, a `$ref`
1860
+ or a template (spec.md §8.1). */
1861
+ const value = resolvePropertyValue(raw as JxDocumentValue, scope);
1862
+ const text = value === null || value === undefined ? "" : escapeHtml(String(value));
1863
+ return key === "innerText" ? text.replaceAll(/\r\n|\r|\n/gu, "<br>") : text;
1864
+ }
1865
+ return undefined;
1866
+ }
1867
+
1497
1868
  /**
1498
1869
  * Tags rendered with `white-space: pre` by every UA, where inter-element whitespace is content
1499
1870
  * rather than formatting. Emitters indent nested children for readability; inside these tags — and
@@ -1521,7 +1892,7 @@ export function childSeparator(preformatted: boolean | undefined, indent = " ")
1521
1892
  export type InnerCompileContext = Omit<CompileContext, "scope"> & { scope: JxScope | null };
1522
1893
 
1523
1894
  /**
1524
- * Build the inner HTML (textContent or children) for a node.
1895
+ * Build the inner HTML (textContent, innerHTML, a content property or children) for a node.
1525
1896
  *
1526
1897
  * @param {JxElement} def
1527
1898
  * @param {JxElement | null} raw
@@ -1553,6 +1924,14 @@ export function buildInner(
1553
1924
  const value = resolveStaticValue(source.innerHTML, context.scope);
1554
1925
  return value == null ? "" : String(value);
1555
1926
  }
1927
+ const content = contentPropertyText(
1928
+ source,
1929
+ resolveStaticTagName(source.tagName, context.scope),
1930
+ context.scope,
1931
+ );
1932
+ if (content !== undefined) {
1933
+ return content;
1934
+ }
1556
1935
  if (Array.isArray(source.children)) {
1557
1936
  const rawChildren = raw?.children;
1558
1937
  return source.children
@@ -1581,7 +1960,14 @@ export function colorSchemePrePaintScript(): string {
1581
1960
  }
1582
1961
 
1583
1962
  /**
1584
- * Push the rules one style object becomes, scoped to `selector`.
1963
+ * Which tree a style object's rules are written into: the builder's `host` and `shadowTree`
1964
+ * (spec.md §16.6), passed through by every emitter that writes a component's sheet.
1965
+ */
1966
+ export type StyleTreeOptions = Pick<CssBuildOptions, "host" | "shadowTree">;
1967
+
1968
+ /**
1969
+ * Push the rules one style object becomes, scoped to `selector`: each rule's text, and above it the
1970
+ * comment a static build writes for a block that carries a `$description` (spec.md §9.2).
1585
1971
  *
1586
1972
  * The single door from the compiler to `buildStyleRules`, which is now the ONE definition of what a
1587
1973
  * Jx style object means as CSS — shared with the DOM runtime and the site-style builder. Three
@@ -1596,14 +1982,17 @@ export function colorSchemePrePaintScript(): string {
1596
1982
  * @param {JxStyle} style
1597
1983
  * @param {string | null} selector - The scope, or null for a bare declaration-body at-rule
1598
1984
  * @param {Record<string, string>} mediaQueries
1985
+ * @param {StyleTreeOptions} [options] - Which tree the rules are written into
1599
1986
  */
1600
1987
  function pushStyleRules(
1601
1988
  rules: string[],
1602
1989
  style: JxStyle,
1603
1990
  selector: string | null,
1604
1991
  mediaQueries: Record<string, string>,
1992
+ options: StyleTreeOptions = {},
1605
1993
  ) {
1606
1994
  for (const rule of buildStyleRules(style, {
1995
+ ...options,
1607
1996
  mediaQueries,
1608
1997
  /* Records what a STATIC build drops, and returns `null` so it drops exactly as before — the
1609
1998
  emitted bytes are unchanged. A reactive declaration is a runtime declaration: it resolves
@@ -1613,7 +2002,7 @@ function pushStyleRules(
1613
2002
  resolveValue: (property, value) => recordDroppedReactive(property, value, selector),
1614
2003
  scope: selector,
1615
2004
  })) {
1616
- rules.push(rule.text);
2005
+ rules.push(commentedRuleText(rule));
1617
2006
  }
1618
2007
  }
1619
2008
 
@@ -1698,6 +2087,392 @@ export function attrHelperSource(): string {
1698
2087
  );
1699
2088
  }
1700
2089
 
2090
+ /** What the mapped arrays of a document need from the module compiled for it. */
2091
+ export interface MappedArrayFeatures {
2092
+ /** Some list declares a `$ref` `filter` or `sort`, so the module carries `__jxListItems`. */
2093
+ arranged: boolean;
2094
+ /** Some list declares a `key`, so the module carries the keyed-list directive. */
2095
+ keyed: boolean;
2096
+ }
2097
+
2098
+ /**
2099
+ * Which list helpers a document's module needs, from one walk made before anything is emitted: its
2100
+ * `children` in either shape, every repeater's `map`, and every `$switch` case. Decided here and
2101
+ * not while emitting, because a list is reached through emitters that carry no module-level state.
2102
+ *
2103
+ * @param {JxElement | JxMutableNode} doc
2104
+ * @returns {MappedArrayFeatures}
2105
+ */
2106
+ export function mappedArrayFeatures(doc: JxElement | JxMutableNode): MappedArrayFeatures {
2107
+ const features: MappedArrayFeatures = { keyed: false, arranged: false };
2108
+ const visit = (children: SlotChildren): void => {
2109
+ for (const child of slotChildList(children)) {
2110
+ if (isMappedArray(child)) {
2111
+ features.arranged ||= isRef(child.filter) || isRef(child.sort);
2112
+ features.keyed ||= isRef(child.key);
2113
+ visit(child.map ? [child.map] : []);
2114
+ continue;
2115
+ }
2116
+ if (!isNodeObject(child)) {
2117
+ continue;
2118
+ }
2119
+ visit(Object.values(child.cases ?? {}).filter((c) => isNodeObject(c) && !isRefObject(c)));
2120
+ visit(child.children);
2121
+ }
2122
+ };
2123
+ visit([doc]);
2124
+ return features;
2125
+ }
2126
+
2127
+ /**
2128
+ * Whether everything a mapped array reads is settled at build time: none of `items`, `filter` and
2129
+ * `sort` names runtime-only state ({@link isRuntimeOnlyRef}), and the same holds of every mapped
2130
+ * array in its `map` template, through `children` and `$switch` cases. A list nested in the
2131
+ * template is asked too, because a row left unexpanded inside an expanded one would lose the `$map`
2132
+ * it reads.
2133
+ *
2134
+ * @param {JxMappedArray} arrayDef
2135
+ * @param {JxScope} scope - The build-time scope the repeater sits in
2136
+ * @returns {boolean}
2137
+ */
2138
+ export function listSettled(arrayDef: JxMappedArray, scope: JxScope): boolean {
2139
+ for (const source of [arrayDef.items, arrayDef.filter, arrayDef.sort]) {
2140
+ if (isRef(source) && isRuntimeOnlyRef(source.$ref, scope)) {
2141
+ return false;
2142
+ }
2143
+ }
2144
+ const settled = (children: SlotChildren): boolean => {
2145
+ for (const child of slotChildList(children)) {
2146
+ if (isMappedArray(child)) {
2147
+ if (!listSettled(child, scope)) {
2148
+ return false;
2149
+ }
2150
+ continue;
2151
+ }
2152
+ if (!isNodeObject(child)) {
2153
+ continue;
2154
+ }
2155
+ const cases = Object.values(child.cases ?? {}).filter(
2156
+ (c) => isNodeObject(c) && !isRefObject(c),
2157
+ );
2158
+ if (!settled(cases) || !settled(child.children)) {
2159
+ return false;
2160
+ }
2161
+ }
2162
+ return true;
2163
+ };
2164
+ return settled(arrayDef.map ? [arrayDef.map] : []);
2165
+ }
2166
+
2167
+ /**
2168
+ * Refuse a repeater whose `items` is a template string. `items` is a `$ref` or a literal array
2169
+ * (spec.md §10.1); a `${…}` template there is a string in every tier, which is no rows and no
2170
+ * diagnostic, so the build says so instead of shipping an empty list.
2171
+ *
2172
+ * @param {{ items?: JxDocumentValue }} arrayDef - A repeater as the document holds it
2173
+ */
2174
+ export function refuseTemplateItems(arrayDef: { items?: JxDocumentValue | undefined }): void {
2175
+ const { items } = arrayDef;
2176
+ if (isTemplateString(items)) {
2177
+ throw new Error(
2178
+ `A repeater's items must be a $ref or a literal array, not the template string ` +
2179
+ `${JSON.stringify(items)}. A template is not read as a list: bind items to a state entry ` +
2180
+ "by $ref, and compute the list in that entry.",
2181
+ );
2182
+ }
2183
+ }
2184
+
2185
+ /**
2186
+ * The member names a `key` pointer walks from each item (spec.md §10.4): none for `$map/item`, the
2187
+ * unescaped reference tokens for `$map/item/<path>`, in either spelling, and `null` for a pointer
2188
+ * that names no item, which the emitted key rule reports and answers with the index. Split here so
2189
+ * the emitted helper walks plain names and carries no pointer grammar.
2190
+ *
2191
+ * @param {string} pointer - The `key` pointer as written
2192
+ * @returns {string[] | null}
2193
+ */
2194
+ export function keyPath(pointer: string): string[] | null {
2195
+ const ref = canonicalMapRef(pointer);
2196
+ if (ref === "$map/item") {
2197
+ return [];
2198
+ }
2199
+ return ref.startsWith("$map/item/") ? refSegments(ref.slice("$map/item/".length)) : null;
2200
+ }
2201
+
2202
+ /** The name of the list-shaping helper a module with a filtered or sorted list calls. */
2203
+ export const LIST_ITEMS_HELPER = "__jxListItems";
2204
+
2205
+ /** The name of the row-key helper the keyed-list directive calls. */
2206
+ export const LIST_KEYS_HELPER = "__jxRowKeys";
2207
+
2208
+ /** The name of the helper that holds a keyed list's literal `items` array across renders. */
2209
+ export const LIST_LITERAL_HELPER = "__jxLiteral";
2210
+
2211
+ /** The name of the keyed-list directive a module with a keyed list calls in its template. */
2212
+ export const KEYED_LIST_HELPER = "__jxKeyed";
2213
+
2214
+ /**
2215
+ * The source of the two list rules, to be emitted into a generated module's preamble:
2216
+ * `__jxListItems`, the port of `mappedListItems` (spec.md §10.3), and `__jxRowKeys`, the port of
2217
+ * `mappedRowKeys` over a key path split at compile time (spec.md §10.4, {@link keyPath}).
2218
+ *
2219
+ * Inlined copies for the reason `attrHelperSource` gives: a compiled module loads `lit-html` and
2220
+ * `@vue/reactivity` and nothing else. `list-helpers.test.ts` evaluates this text and holds each
2221
+ * function to the runtime export it ports, messages included.
2222
+ *
2223
+ * @returns {string} Two `function` declarations
2224
+ * @docs framework/concepts/lists
2225
+ */
2226
+ export function listHelperSource(): string {
2227
+ return (
2228
+ `function ${LIST_ITEMS_HELPER}(items, filter, sort) {\n` +
2229
+ ` if (!Array.isArray(items)) return [];\n` +
2230
+ ` let list = items;\n` +
2231
+ ` if (typeof filter === 'function') list = list.filter(filter);\n` +
2232
+ ` if (typeof sort === 'function') list = [...list].sort(sort);\n` +
2233
+ ` return list;\n` +
2234
+ `}\n` +
2235
+ `function ${LIST_KEYS_HELPER}(list, path, pointer, warn) {\n` +
2236
+ ` const keys = list.map((item, index) => {\n` +
2237
+ ` if (pointer === null) return index;\n` +
2238
+ ` if (path === null) {\n` +
2239
+ ' warn(`key "${pointer}" is not a $map/item pointer — rows fall back to their index`);\n' +
2240
+ ` return index;\n` +
2241
+ ` }\n` +
2242
+ ` if (path.length === 0) return item;\n` +
2243
+ ` let key = item;\n` +
2244
+ ` for (const name of path) key = key?.[name];\n` +
2245
+ ` if (key === undefined || key === null) {\n` +
2246
+ ' warn(`key "${pointer}" is empty for some items — those rows fall back to their index`);\n' +
2247
+ ` return index;\n` +
2248
+ ` }\n` +
2249
+ ` return key;\n` +
2250
+ ` });\n` +
2251
+ ` const seen = new Set();\n` +
2252
+ ` for (let i = 0; i < keys.length; i++) {\n` +
2253
+ ` if (seen.has(keys[i])) {\n` +
2254
+ " warn(`duplicate key ${String(keys[i])} — every occurrence after the first is rebuilt on each change`);\n" +
2255
+ ` keys[i] = { duplicate: i };\n` +
2256
+ ` } else {\n` +
2257
+ ` seen.add(keys[i]);\n` +
2258
+ ` }\n` +
2259
+ ` }\n` +
2260
+ ` return keys;\n` +
2261
+ `}`
2262
+ );
2263
+ }
2264
+
2265
+ /** The lit imports a module with a keyed list adds: the directive base class, and `repeat`. */
2266
+ export const KEYED_LIST_IMPORTS: readonly string[] = [
2267
+ `import { AsyncDirective, directive } from 'lit-html/async-directive.js';`,
2268
+ `import { repeat } from 'lit-html/directives/repeat.js';`,
2269
+ ];
2270
+
2271
+ /**
2272
+ * The source of the keyed-list directive (spec.md §10.4), to be emitted after `listHelperSource()`
2273
+ * in a module that imports {@link KEYED_LIST_IMPORTS} and `effect`, `stop` and `shallowRef`.
2274
+ *
2275
+ * `__jxKeyed(items, filter, sort, path, pointer, row)` sits in a lit template where a list goes and
2276
+ * renders lit's `repeat()` over a snapshot it owns. The snapshot is computed in an effect of the
2277
+ * directive's own, which is what gives a compiled keyed list the interpreter's two properties:
2278
+ *
2279
+ * - **Coalescing.** A reactive array mutated in place (`reverse()`, `sort()`, an index write)
2280
+ * triggers once per element it touches. The host's render is synchronous, so a `repeat()` fed the
2281
+ * live array would reconcile against an array that is half of each state and tear down the row
2282
+ * whose key exists to keep it. The directive's effect runs on one microtask per burst, as
2283
+ * `renderMappedArrayInto`'s does, and only then hands the host a new snapshot.
2284
+ * - **A plain copy.** The snapshot is `Array.from` of the arranged list, taken inside that effect, so
2285
+ * the host render never iterates the reactive source and is not re-run per index.
2286
+ *
2287
+ * Row templates stay in the host's render: `row(item, index)` is called by `repeat()` there, so a
2288
+ * row's own bindings update synchronously with the rest of the template.
2289
+ *
2290
+ * The first run is synchronous, inside the host's first render. A reconnected directive's first run
2291
+ * is queued, because lit reconnects inside a commit, where a write to the snapshot could not
2292
+ * re-trigger the host effect that is running it.
2293
+ *
2294
+ * @returns {string} One class declaration and the directive made from it
2295
+ * @docs framework/concepts/lists
2296
+ */
2297
+ export function keyedListDirectiveSource(): string {
2298
+ return [
2299
+ "class __JxKeyedList extends AsyncDirective {",
2300
+ " #args = null;",
2301
+ " #runner = null;",
2302
+ " #queued = false;",
2303
+ " #warned = false;",
2304
+ " #snap = shallowRef({ list: [], keys: [] });",
2305
+ " #warn = (message) => {",
2306
+ " if (this.#warned) return;",
2307
+ " this.#warned = true;",
2308
+ " console.warn(`Jx $map: ${message}`);",
2309
+ " };",
2310
+ " #compute = () => {",
2311
+ " const [items, filter, sort, path, pointer] = this.#args;",
2312
+ ` const list = Array.from(${LIST_ITEMS_HELPER}(items, filter, sort));`,
2313
+ ` this.#snap.value = { list, keys: ${LIST_KEYS_HELPER}(list, path, pointer, this.#warn) };`,
2314
+ " };",
2315
+ " #schedule = () => {",
2316
+ " if (this.#queued) return;",
2317
+ " this.#queued = true;",
2318
+ " queueMicrotask(() => {",
2319
+ " this.#queued = false;",
2320
+ " if (this.#runner) this.#runner();",
2321
+ " });",
2322
+ " };",
2323
+ " #start(lazy) {",
2324
+ " this.#runner = effect(this.#compute, { lazy, scheduler: this.#schedule });",
2325
+ " if (lazy) this.#schedule();",
2326
+ " }",
2327
+ " render() {}",
2328
+ " update(_part, args) {",
2329
+ " const previous = this.#args;",
2330
+ " this.#args = args;",
2331
+ " if (!this.#runner) {",
2332
+ " if (this.isConnected) this.#start(false);",
2333
+ " } else if (previous[0] !== args[0] || previous[1] !== args[1] || previous[2] !== args[2]) {",
2334
+ " this.#schedule();",
2335
+ " }",
2336
+ " const snap = this.#snap.value;",
2337
+ " return repeat(snap.list, (_item, index) => snap.keys[index], args[5]);",
2338
+ " }",
2339
+ " disconnected() {",
2340
+ " if (this.#runner) stop(this.#runner);",
2341
+ " this.#runner = null;",
2342
+ " }",
2343
+ " reconnected() {",
2344
+ " if (!this.#runner && this.#args) this.#start(true);",
2345
+ " }",
2346
+ "}",
2347
+ `const ${KEYED_LIST_HELPER} = directive(__JxKeyedList);`,
2348
+ /* A literal `items` array, by its JSON text, parsed once. Written inline it would be a new
2349
+ array on every render, which the directive reads as a new list: it would reshape, hand the
2350
+ host a new snapshot, and the host's re-render would hand it another new array, forever. */
2351
+ "const __jxLiterals = new Map();",
2352
+ `function ${LIST_LITERAL_HELPER}(text) {`,
2353
+ " if (!__jxLiterals.has(text)) __jxLiterals.set(text, JSON.parse(text));",
2354
+ " return __jxLiterals.get(text);",
2355
+ "}",
2356
+ ].join("\n");
2357
+ }
2358
+
2359
+ /** The name of the prop-supply helper an element module with a property bridge calls. */
2360
+ export const PROP_SUPPLY_HELPER = "__jxSupplies";
2361
+
2362
+ /** The name of the helper that finds the platform's own setter for a bridged key. */
2363
+ export const NATIVE_SETTER_HELPER = "__jxNativeSetter";
2364
+
2365
+ /**
2366
+ * The property bridge's two rules as source for a generated element module (compiler.md §4.4),
2367
+ * inlined for the reason {@link attrHelperSource} gives.
2368
+ *
2369
+ * `__jxSupplies` restates `instanceSupplies` from `@jxsuite/runtime` line for line, the rule
2370
+ * spec.md §13.2 states: an instance carries a prop when it has an own property of that name, an
2371
+ * attribute of that name, or the kebab attribute a camelCase reflection writes. The rule is logic
2372
+ * rather than data, so its guard is behavioural: `compile-element-render.test.ts` runs this source
2373
+ * and the runtime's export over one input matrix.
2374
+ *
2375
+ * `__jxNativeSetter` is the walk the interpreter's accessor makes for a key the platform already
2376
+ * owns (spec.md §16.2): the first descriptor of that name on the prototype chain, whose setter the
2377
+ * forwarding accessor calls before it writes state, so `title` and `hidden` still reflect.
2378
+ *
2379
+ * @returns {string} Two `function` declarations, ready to push into a module's line list.
2380
+ */
2381
+ export function propSupplyHelperSource(): string {
2382
+ return [
2383
+ `function ${PROP_SUPPLY_HELPER}(el, k) {`,
2384
+ " if (Object.hasOwn(el, k)) return true;",
2385
+ " if (el.hasAttribute(k)) return true;",
2386
+ " const kebab = k.replace(/[A-Z]/g, (c) => '-' + c.toLowerCase());",
2387
+ " return kebab !== k && el.hasAttribute(kebab);",
2388
+ "}",
2389
+ `function ${NATIVE_SETTER_HELPER}(el, k) {`,
2390
+ " for (let p = Object.getPrototypeOf(el); p; p = Object.getPrototypeOf(p)) {",
2391
+ " const d = Object.getOwnPropertyDescriptor(p, k);",
2392
+ " if (d) return d.set;",
2393
+ " }",
2394
+ " return undefined;",
2395
+ "}",
2396
+ ].join("\n");
2397
+ }
2398
+
2399
+ /** The name of the observed-attribute helper an element module that observes any calls. */
2400
+ export const OBSERVED_ATTR_HELPER = "__jxAbsorbAttr";
2401
+
2402
+ /**
2403
+ * The observed-attribute rule (spec.md §16.5) as source for a generated element module:
2404
+ * `absorbAttribute` from `@jxsuite/runtime`, restated line for line and inlined for the reason
2405
+ * {@link attrHelperSource} gives. The key is the attribute's name camel-cased; a computed entry
2406
+ * (present in the defaults with `undefined`) is never written; a boolean is presence, with the text
2407
+ * `false` counting as absent; a removal restores the declared default, or falls back by the type of
2408
+ * the value held; a number parses and anything else is the string.
2409
+ *
2410
+ * The rule is logic, so its guard is behavioural: `observed-attr-agreement.test.ts` runs this
2411
+ * source and the runtime's export over one matrix of held type, attribute value and default. The
2412
+ * defaults a module passes are not re-derived either: they are `declaredDefaults`' output for the
2413
+ * observed keys, serialized ({@link observedDefaultsSource}).
2414
+ *
2415
+ * @returns {string} One `function` declaration, ready to push into a module's line list.
2416
+ */
2417
+ export function observedAttrHelperSource(): string {
2418
+ return [
2419
+ `function ${OBSERVED_ATTR_HELPER}(state, name, value, defaults) {`,
2420
+ " const key = name.replace(/-([a-z])/g, (_, c) => c.toUpperCase());",
2421
+ " if (defaults && defaults.has(key) && defaults.get(key) === undefined) return;",
2422
+ " const current = state[key];",
2423
+ " if (typeof current === 'boolean') {",
2424
+ " state[key] = value !== null && value !== 'false';",
2425
+ " return;",
2426
+ " }",
2427
+ " if (value === null) {",
2428
+ " const declared = defaults ? defaults.get(key) : undefined;",
2429
+ " state[key] = declared === undefined ? (typeof current === 'number' ? 0 : '') : declared;",
2430
+ " return;",
2431
+ " }",
2432
+ " state[key] = typeof current === 'number' ? Number(value) : value;",
2433
+ "}",
2434
+ ].join("\n");
2435
+ }
2436
+
2437
+ /** The state key an observed attribute writes: its name, camel-cased (spec.md §16.5). */
2438
+ function observedStateKey(name: string): string {
2439
+ return attributeStateKey(name);
2440
+ }
2441
+
2442
+ /**
2443
+ * The names a definition observes: its `observedAttributes`, when that is an array, less anything
2444
+ * in it that is not a string.
2445
+ *
2446
+ * @param {JxElement | JxDocument} def
2447
+ * @returns {string[]}
2448
+ */
2449
+ export function observedAttributeNames(def: JxElement | JxDocument): string[] {
2450
+ const { observedAttributes: observed } = def;
2451
+ return Array.isArray(observed) ? observed.filter((name) => isString(name)) : [];
2452
+ }
2453
+
2454
+ /**
2455
+ * The declared defaults of a definition's observed keys as the source of a `new Map([...])`
2456
+ * expression: the runtime's `declaredDefaults(def)`, kept to the observed keys and serialized. A
2457
+ * `Map`, because an object literal would give a `__proto__` key meaning. A computed entry is
2458
+ * written as `undefined`, which JSON cannot spell and which is how the rule knows never to write
2459
+ * it. The module evaluates the expression per use, so an object default is a fresh copy for each
2460
+ * removal rather than one object every instance then mutates.
2461
+ *
2462
+ * @param {JxElement | JxDocument} def
2463
+ * @returns {string}
2464
+ */
2465
+ export function observedDefaultsSource(def: JxElement | JxDocument): string {
2466
+ const defaults = declaredDefaults(def);
2467
+ const keys = new Set(observedAttributeNames(def).map((name) => observedStateKey(name)));
2468
+ const pairs = [...defaults].flatMap(([key, value]) =>
2469
+ keys.has(key)
2470
+ ? [`[${JSON.stringify(key)}, ${value === undefined ? "undefined" : JSON.stringify(value)}]`]
2471
+ : [],
2472
+ );
2473
+ return `new Map([${pairs.join(", ")}])`;
2474
+ }
2475
+
1701
2476
  /** The name of the call helper a module holding a `timing: "server"` entry declares once. */
1702
2477
  export const SERVER_CALL_HELPER = "__jxServerCall";
1703
2478
 
@@ -1731,6 +2506,275 @@ export function serverCallHelperSource(): string {
1731
2506
  ].join("\n");
1732
2507
  }
1733
2508
 
2509
+ // ─── External classes (compiler.md §3) ────────────────────────────────────────
2510
+
2511
+ /**
2512
+ * The keys the prototype system owns on a state entry, stripped before the rest is handed to an
2513
+ * external class as its config (spec.md §12.3). One list for the build-time resolver and both
2514
+ * compile targets, so a class is constructed with the same config at either timing.
2515
+ */
2516
+ export const EXTERNAL_CONFIG_RESERVED: ReadonlySet<string> = new Set([
2517
+ "$prototype",
2518
+ "$src",
2519
+ "$export",
2520
+ "timing",
2521
+ "default",
2522
+ "description",
2523
+ ]);
2524
+
2525
+ /** An external class's config as its state entry wrote it: any keys, document values. */
2526
+ export type ExternalClassEntryConfig = Record<string, JxDocumentValue>;
2527
+
2528
+ /**
2529
+ * The config an external class is constructed with: the entry's own keys minus the reserved ones,
2530
+ * values as written.
2531
+ *
2532
+ * @param {JxPrototypeDef} def
2533
+ * @returns {ExternalClassEntryConfig}
2534
+ */
2535
+ export function externalClassConfig(def: JxPrototypeDef) {
2536
+ const config: ExternalClassEntryConfig = {};
2537
+ for (const [key, value] of Object.entries(def)) {
2538
+ if (!EXTERNAL_CONFIG_RESERVED.has(key) && value !== undefined) {
2539
+ config[key] = value;
2540
+ }
2541
+ }
2542
+ return config;
2543
+ }
2544
+
2545
+ const BUILT_IN_PROTOTYPE_NAMES: ReadonlySet<string> = new Set(BUILT_IN_PROTOTYPES);
2546
+
2547
+ /**
2548
+ * Whether a state entry names an external class: a `$prototype` that is not one of the built-ins
2549
+ * (spec.md §12), which always mean the built-in.
2550
+ */
2551
+ export function isExternalClassDef(def: unknown): def is JxPrototypeDef {
2552
+ return isPrototypeDef(def) && !BUILT_IN_PROTOTYPE_NAMES.has(def.$prototype);
2553
+ }
2554
+
2555
+ /**
2556
+ * Whether a state entry is an external class the compiled page or element constructs in the
2557
+ * browser. Only an explicit `timing: "client"` is: an entry with no `timing` is resolved during the
2558
+ * build. This is the one predicate that decides what hydrates.
2559
+ */
2560
+ export function isClientExternalClass(def: unknown): def is JxPrototypeDef {
2561
+ return isExternalClassDef(def) && def.timing === "client";
2562
+ }
2563
+
2564
+ /** The name of the helper a module holding a `timing: "client"` external class declares once. */
2565
+ export const EXTERNAL_CLASS_HELPER = "__jxInstantiate";
2566
+
2567
+ /**
2568
+ * The external class contract (spec.md §12.3) as source for a generated module's preamble, inlined
2569
+ * for the reason {@link attrHelperSource} gives: construct the class with its config, then take
2570
+ * `resolve()` when the instance has one, else `value` when it has that, else the instance. It
2571
+ * answers with the value and the instance, which the caller keeps for `subscribe`.
2572
+ *
2573
+ * The order is `instantiateAndResolve`'s (`site/external-class.ts`), the build-time half of the
2574
+ * same rule, and `external-class-hydration.test.ts` runs this source and that export over one
2575
+ * matrix of class shapes.
2576
+ *
2577
+ * @returns {string} One `async function` declaration.
2578
+ */
2579
+ export function externalClassHelperSource(): string {
2580
+ return [
2581
+ `async function ${EXTERNAL_CLASS_HELPER}(C, name, config) {`,
2582
+ " if (typeof C !== 'function') throw new TypeError('Jx: \"' + name + '\" is not a class');",
2583
+ " const i = new C(config);",
2584
+ " const v = typeof i.resolve === 'function' ? await i.resolve() : 'value' in i ? i.value : i;",
2585
+ " return [v, i];",
2586
+ "}",
2587
+ ].join("\n");
2588
+ }
2589
+
2590
+ /** One `timing: "client"` external class of a document, as a compile target emits it. */
2591
+ export interface ClientClassEntry {
2592
+ /** The state key the class's value is written to. */
2593
+ key: string;
2594
+ /** The module-level name its class is imported under. */
2595
+ binding: string;
2596
+ /** The class's name as the entry wrote it, for diagnostics. */
2597
+ name: string;
2598
+ /** What the class is constructed with ({@link externalClassConfig}). */
2599
+ config: ExternalClassEntryConfig;
2600
+ }
2601
+
2602
+ /** A document's client classes, and the import each distinct class module needs. */
2603
+ export interface ClientClasses {
2604
+ entries: ClientClassEntry[];
2605
+ imports: string[];
2606
+ }
2607
+
2608
+ /**
2609
+ * Collect a document's `timing: "client"` external classes and the imports their modules need, one
2610
+ * default import per distinct module URL.
2611
+ *
2612
+ * `resolveClass` answers the URL a class's module is served at, and only a site build has one: it
2613
+ * is what bundles the module (compiler.md §12). Without it a client class cannot be delivered, so
2614
+ * the compile fails and names the entry.
2615
+ *
2616
+ * @param {Record<string, JxStateDefinition>} defs
2617
+ * @param {((def: JxPrototypeDef) => string) | undefined} resolveClass
2618
+ * @returns {ClientClasses}
2619
+ */
2620
+ export function collectClientClasses(
2621
+ defs: Record<string, JxStateDefinition>,
2622
+ resolveClass?: (def: JxPrototypeDef) => string,
2623
+ ): ClientClasses {
2624
+ const entries: ClientClassEntry[] = [];
2625
+ const bindings = new Map<string, string>();
2626
+ for (const [key, def] of Object.entries(defs)) {
2627
+ if (!isClientExternalClass(def)) {
2628
+ continue;
2629
+ }
2630
+ if (resolveClass === undefined) {
2631
+ throw new Error(
2632
+ `"${key}": external class "${def.$prototype}" with timing "client" compiles only in a site build`,
2633
+ );
2634
+ }
2635
+ const url = resolveClass(def);
2636
+ let binding = bindings.get(url);
2637
+ if (binding === undefined) {
2638
+ binding = `_JxClass${bindings.size}`;
2639
+ bindings.set(url, binding);
2640
+ }
2641
+ entries.push({ binding, config: externalClassConfig(def), key, name: def.$prototype });
2642
+ }
2643
+ return {
2644
+ entries,
2645
+ imports: [...bindings].map(([url, binding]) => `import ${binding} from '${url}';`),
2646
+ };
2647
+ }
2648
+
2649
+ /**
2650
+ * The expression that constructs and resolves every client class of a document: a `Promise.all`
2651
+ * that settles once each entry has its value in state, or has failed.
2652
+ *
2653
+ * Each entry writes its value to state, records its instance under its state key in `instances` (a
2654
+ * `Map`, where a teardown finds what it subscribed to), and follows `subscribe` when the class
2655
+ * offers one. A class that fails to construct or resolve is logged and its entry stays `null`, so
2656
+ * one failing class does not keep the rest of the page from hydrating.
2657
+ *
2658
+ * @param {ClientClassEntry[]} entries
2659
+ * @param {{ statePrefix: string; instances: string; indent: string }} opts
2660
+ * @returns {string}
2661
+ */
2662
+ export function emitExternalClassResolution(
2663
+ entries: readonly ClientClassEntry[],
2664
+ opts: { statePrefix: string; instances: string; indent: string },
2665
+ ): string {
2666
+ const { indent, instances, statePrefix } = opts;
2667
+ const lines = ["Promise.all(["];
2668
+ for (const { binding, config, key, name } of entries) {
2669
+ const target = refAccessor(statePrefix, escapeToken(key));
2670
+ const label = JSON.stringify(key);
2671
+ lines.push(
2672
+ `${indent} ${EXTERNAL_CLASS_HELPER}(${binding}, ${JSON.stringify(name)}, ${JSON.stringify(config)}).then(([v, i]) => {`,
2673
+ `${indent} ${target} = v;`,
2674
+ `${indent} ${instances}.set(${label}, i);`,
2675
+ `${indent} if (typeof i.subscribe === 'function') i.subscribe((n) => { ${target} = n; });`,
2676
+ `${indent} }).catch((e) => { console.error(${JSON.stringify(`Jx: external class "${key}" failed`)}, e); }),`,
2677
+ );
2678
+ }
2679
+ lines.push(`${indent}])`);
2680
+ return lines.join("\n");
2681
+ }
2682
+
2683
+ /** The helper a form-associated component module binds its `ElementInternals` with. */
2684
+ export const FORM_ASSOCIATION_HELPER = "__jxAssociateForm";
2685
+
2686
+ /**
2687
+ * The form-association rule (spec.md §16.11) as source for a generated module: `associateForm` from
2688
+ * `@jxsuite/runtime`, inlined for the reason `attrHelperSource` gives. The module calls it once per
2689
+ * instance and `start()` on each connection, with an `effect` that stops when the element is
2690
+ * removed. `form-association-agreement.test.ts` runs this source and the runtime's function over
2691
+ * one scenario table, which is what keeps the two from drifting.
2692
+ *
2693
+ * @returns {string} One `function` declaration, for a module's preamble.
2694
+ */
2695
+ export function formAssociationHelperSource(): string {
2696
+ return [
2697
+ `function ${FORM_ASSOCIATION_HELPER}(host, internals, state, keys, root, formValue, watch) {`,
2698
+ ` const initial = { checked: state.checked, value: state.value };`,
2699
+ ` let ownDisabled = state.disabled;`,
2700
+ ` let forced = false;`,
2701
+ ` const control = () => root().querySelector('input, textarea, select');`,
2702
+ // `internals.labels` is a live list the document then keeps current on every mutation, so it
2703
+ // Is read only for a host a label can be naming, as the runtime's binding does.
2704
+ ` const mayBeLabelled = () => {`,
2705
+ ` if (host.closest('label')) return true;`,
2706
+ ` const id = host.id;`,
2707
+ ` if (id === '') return false;`,
2708
+ ` const tree = host.getRootNode();`,
2709
+ ` const scope = tree instanceof DocumentFragment ? tree : host.ownerDocument;`,
2710
+ ` return Array.from(scope.querySelectorAll('label[for]'))`,
2711
+ ` .some((label) => label.getAttribute('for') === id);`,
2712
+ ` };`,
2713
+ ` const nameControl = () => {`,
2714
+ ` if (!mayBeLabelled()) return;`,
2715
+ ` const target = control();`,
2716
+ ` const labels = internals.labels;`,
2717
+ ` if (target && labels.length > 0 && 'ariaLabelledByElements' in target &&`,
2718
+ ` !target.hasAttribute('aria-label') && !target.getAttribute('aria-labelledby')) {`,
2719
+ ` target.ariaLabelledByElements = Array.from(labels).filter((l) => l instanceof Element);`,
2720
+ ` }`,
2721
+ ` };`,
2722
+ ` host.addEventListener('click', (event) => {`,
2723
+ ` const target = control();`,
2724
+ ` if (event.target !== host || !target || target.disabled) return;`,
2725
+ ` target.focus();`,
2726
+ ` if (target.type === 'checkbox' || target.type === 'radio') target.click();`,
2727
+ ` });`,
2728
+ ` host.addEventListener('focusin', nameControl);`,
2729
+ ` const valueMissingMessage = () => {`,
2730
+ ` const probe = host.ownerDocument.createElement('input');`,
2731
+ ` probe.required = true;`,
2732
+ ` if (keys.checked) probe.type = 'checkbox';`,
2733
+ ` return probe.validationMessage || 'Please fill out this field.';`,
2734
+ ` };`,
2735
+ ` return {`,
2736
+ ` disabled(flag) {`,
2737
+ ` if (!keys.disabled) return;`,
2738
+ ` if (flag) {`,
2739
+ ` if (!forced) { ownDisabled = host.hasAttribute('disabled') ? false : state.disabled; forced = true; }`,
2740
+ ` state.disabled = true;`,
2741
+ ` } else if (forced) {`,
2742
+ ` forced = false;`,
2743
+ ` state.disabled = ownDisabled;`,
2744
+ ` }`,
2745
+ ` },`,
2746
+ ` reset() {`,
2747
+ ` if (keys.value) state.value = initial.value;`,
2748
+ ` if (keys.checked) state.checked = initial.checked;`,
2749
+ ` },`,
2750
+ ` start() {`,
2751
+ ` if (formValue) {`,
2752
+ ` watch(() => {`,
2753
+ ` const value = formValue();`,
2754
+ ` if (value === null || value === undefined) internals.setFormValue(null);`,
2755
+ ` else if (value instanceof File || value instanceof FormData) internals.setFormValue(value);`,
2756
+ ` else internals.setFormValue(String(value));`,
2757
+ ` });`,
2758
+ ` }`,
2759
+ ` if (keys.required) {`,
2760
+ ` watch(() => {`,
2761
+ ` const empty = keys.checked`,
2762
+ ` ? !state.checked`,
2763
+ ` : state.value === null || state.value === undefined || state.value === '';`,
2764
+ ` if (state.required && empty) {`,
2765
+ ` internals.setValidity({ valueMissing: true }, valueMissingMessage(), control() ?? undefined);`,
2766
+ ` } else {`,
2767
+ ` internals.setValidity({});`,
2768
+ ` }`,
2769
+ ` });`,
2770
+ ` }`,
2771
+ ` nameControl();`,
2772
+ ` },`,
2773
+ ` };`,
2774
+ `}`,
2775
+ ].join("\n");
2776
+ }
2777
+
1734
2778
  /** The capture helper a light-DOM component module calls before its first render. */
1735
2779
  export const SLOT_CAPTURE_HELPER = "__jxCaptureSlotted";
1736
2780
 
@@ -1917,6 +2961,8 @@ export function compileStyles(
1917
2961
  mediaQueries,
1918
2962
  (value) => value,
1919
2963
  recordDroppedReactive,
2964
+ undefined,
2965
+ { comments: true },
1920
2966
  );
1921
2967
  if (projectSheet !== "") {
1922
2968
  rules.push(projectSheet);
@@ -1944,57 +2990,185 @@ export function escapeStyleText(css: string): string {
1944
2990
  }
1945
2991
 
1946
2992
  /**
1947
- * @param {JxElement | JxMutableNode | string} def
2993
+ * Where a style pass keeps the handle it gave a node. A symbol, because `className` is author data
2994
+ * that may be a `$ref` or a template and is never written; an assigned symbol-keyed property is
2995
+ * enumerable, so it survives the object spreads the prerender and the element target make, and it
2996
+ * stays out of `JSON.stringify` (`data-jx-props`, emitted documents). `structuredClone` would drop
2997
+ * it: a pass that deep-clones a node between a style pass and an emitter must carry it over.
2998
+ */
2999
+ const STYLE_HANDLE = Symbol("jx.styleHandle");
3000
+
3001
+ /** A node as a style pass leaves it. */
3002
+ interface Handled {
3003
+ [STYLE_HANDLE]?: string;
3004
+ }
3005
+
3006
+ /** A node a style pass walks: an element, or a repeater standing among its children. */
3007
+ type StyleScopeNode = JxElement | JxMutableNode | JxMappedArray;
3008
+
3009
+ /**
3010
+ * The generated class a style pass gave `node`, without its dot, or `undefined` for a node no pass
3011
+ * has handled. The class selects that element and nothing else (for a repeater's item template, the
3012
+ * rows it renders), and its static rules are keyed on it (spec.md §9.2).
3013
+ *
3014
+ * @param {StyleScopeNode} node
3015
+ * @returns {string | undefined}
3016
+ * @docs framework/concepts/styling
3017
+ */
3018
+ export function styleHandleOf(node: StyleScopeNode): string | undefined {
3019
+ /* SAFETY: `STYLE_HANDLE` is module-private and `handleFor` is its only writer, which always
3020
+ stores a string under it; a node no pass has walked answers undefined. */
3021
+ return (node as Handled)[STYLE_HANDLE];
3022
+ }
3023
+
3024
+ /**
3025
+ * The handle of `def`, minted on first use. Idempotent: a node keeps the first handle any pass
3026
+ * gives it, because one object can be walked by two passes that must agree (the element module's
3027
+ * stamping pass and the page sheet, in `compile()`'s custom-element route).
3028
+ */
3029
+ function handleFor(def: JxElement | JxMutableNode, counter: { n: number }, prefix: string): string {
3030
+ const existing = styleHandleOf(def);
3031
+ if (existing !== undefined) {
3032
+ return existing;
3033
+ }
3034
+ const handle = `${prefix}-${counter.n}`;
3035
+ counter.n += 1;
3036
+ /* SAFETY: the same private slot `styleHandleOf` reads; no declared member of a node is touched. */
3037
+ (def as Handled)[STYLE_HANDLE] = handle;
3038
+ return handle;
3039
+ }
3040
+
3041
+ /**
3042
+ * The members a style pass descends into from `def`: an array `children`, or the repeater itself
3043
+ * when `children` is one (the legacy whole-children form).
3044
+ *
3045
+ * @param {JxElement | JxMutableNode} def
3046
+ * @returns {(StyleScopeNode | string)[]}
3047
+ */
3048
+ export function styleChildren(def: JxElement | JxMutableNode): (StyleScopeNode | string)[] {
3049
+ const { children } = def;
3050
+ if (Array.isArray(children)) {
3051
+ return children;
3052
+ }
3053
+ return isMappedArray(children) ? [children] : [];
3054
+ }
3055
+
3056
+ /**
3057
+ * The one traversal every style pass makes, so the sheet and each emitter number the same nodes in
3058
+ * the same order. Pre-order: the node, its children in order with a repeater's `map` template at
3059
+ * the repeater's position, then its `$switch` cases. A repeater is not itself an element, so only
3060
+ * its template is visited, and one with no template is skipped.
3061
+ */
3062
+ function walkStyleScopes(
3063
+ def: StyleScopeNode | string,
3064
+ visit: (node: JxElement | JxMutableNode) => void,
3065
+ ): void {
3066
+ if (!isNonNullObject(def)) {
3067
+ return;
3068
+ }
3069
+ if (isMappedArray(def)) {
3070
+ if (def.map) {
3071
+ walkStyleScopes(def.map, visit);
3072
+ }
3073
+ return;
3074
+ }
3075
+ visit(def);
3076
+ for (const child of styleChildren(def)) {
3077
+ walkStyleScopes(child, visit);
3078
+ }
3079
+ // $switch case nodes render in place of the container's content — walk them too
3080
+ if (isNonNullObject(def.cases)) {
3081
+ for (const c of Object.values<JxElement | JxMutableNode>(def.cases)) {
3082
+ walkStyleScopes(c, visit);
3083
+ }
3084
+ }
3085
+ }
3086
+
3087
+ /**
3088
+ * Give every node under `def` that carries a `style` object its handle, without building a rule.
3089
+ * The element target stamps its template with this: its sheet is `buildComponentCSS`'s, and
3090
+ * building the rules a second time would record each dropped reactive declaration twice.
3091
+ *
3092
+ * @param {StyleScopeNode | string} def
3093
+ * @param {{ n: number }} counter
3094
+ * @param {string} prefix - Names the sheet that holds the rules: `jx`, `jxs`, or a component's tag
3095
+ */
3096
+ export function assignStyleHandles(
3097
+ def: StyleScopeNode | string,
3098
+ counter: { n: number },
3099
+ prefix: string,
3100
+ ): void {
3101
+ walkStyleScopes(def, (node) => {
3102
+ if (node.style) {
3103
+ handleFor(node, counter, prefix);
3104
+ }
3105
+ });
3106
+ }
3107
+
3108
+ /**
3109
+ * Whether an emitter writes this element's `class` attribute once, merged: it has a style handle or
3110
+ * a `className`. An element with neither keeps whatever `attributes.class` it writes, where and how
3111
+ * it always was.
3112
+ *
3113
+ * @param {JxElement | JxMutableNode} def
3114
+ * @returns {boolean}
3115
+ */
3116
+ export function writesMergedClass(def: JxElement | JxMutableNode): boolean {
3117
+ return styleHandleOf(def) !== undefined || Boolean(def.className);
3118
+ }
3119
+
3120
+ /**
3121
+ * The author's own classes for an element: `attributes.class` when the element writes one, else
3122
+ * `className`. The runtime applies attributes after properties, so that is the value it leaves in
3123
+ * effect, and the compiled emitters follow it.
3124
+ *
3125
+ * @param {JxElement | JxMutableNode} def
3126
+ * @returns {JxDocumentValue | undefined} A string, a `$ref`, or whatever the document holds there
3127
+ */
3128
+ export function authorClassValue(def: JxElement | JxMutableNode): JxDocumentValue | undefined {
3129
+ const { attributes } = def;
3130
+ return isNonNullObject(attributes) && Object.hasOwn(attributes, "class")
3131
+ ? attributes.class
3132
+ : def.className;
3133
+ }
3134
+
3135
+ /**
3136
+ * Collect the static rules of every styled node under `def`, each keyed on a generated class of the
3137
+ * node's own (spec.md §9.2): never an author's class, which every other element carrying it would
3138
+ * share, and never an `id`, whose rule would outweigh the runtime's (0,1,0) handle and make a built
3139
+ * page cascade differently from its preview. A repeater's item template gets one handle its rows
3140
+ * share. The class reaches markup through `styleHandleOf`, which every emitter reads.
3141
+ *
3142
+ * @param {StyleScopeNode | string} def
1948
3143
  * @param {string[]} rules
1949
3144
  * @param {Record<string, string>} mediaQueries
1950
3145
  * @param {string} [_parentSel]
1951
- * @param {{ n: number }} [counter]
3146
+ * @param {{ n: number }} [counterArg]
3147
+ * @param {string} [prefix] - Names the sheet that holds the rules: `jx`, `jxs`, or a component's
3148
+ * tag
3149
+ * @param {{ shadowTree?: boolean }} [options] - Set `shadowTree` for nodes inside a shadow root
1952
3150
  */
1953
3151
  export function collectStyles(
1954
- def: JxElement | JxMutableNode | string,
3152
+ def: StyleScopeNode | string,
1955
3153
  rules: string[],
1956
3154
  mediaQueries: Record<string, string>,
1957
3155
  _parentSel = "",
1958
3156
  counterArg?: { n: number },
1959
3157
  prefix = "jx",
3158
+ options: Pick<StyleTreeOptions, "shadowTree"> = {},
1960
3159
  ) {
1961
3160
  const counter = counterArg ?? { n: 0 };
1962
- if (!isNonNullObject(def)) {
1963
- return;
1964
- }
1965
-
1966
- if (def.style && !def.id && !def.className) {
1967
- def.className = `${prefix}-${counter.n}`;
1968
- counter.n += 1;
1969
- }
1970
-
1971
- /* A chosen tag needs a selector that matches every candidate, not the first one.
1972
- `#id` and `.class` are unaffected — they identify the element regardless of what it turns out
1973
- to be — but a bare tag selector has to become the union, or styling an `<a>|<div>` wrapper
1974
- would style exactly one of the two branches and silently miss the other. */
1975
- const tagSelector = tagNameCandidates(def.tagName).join(", ") || "*";
1976
- const selector = def.id
1977
- ? `#${def.id}`
1978
- : def.className
1979
- ? `.${def.className.split(" ")[0]}`
1980
- : tagSelector;
1981
-
1982
- if (def.style) {
1983
- pushStyleRules(rules, def.style, selector, mediaQueries);
1984
- }
1985
-
1986
- if (Array.isArray(def.children)) {
1987
- for (const c of def.children) {
1988
- collectStyles(c, rules, mediaQueries, selector, counter, prefix);
1989
- }
1990
- }
1991
-
1992
- // $switch case nodes render in place of the container's content — collect their styles too
1993
- if (isNonNullObject(def.cases)) {
1994
- for (const c of Object.values<JxElement | JxMutableNode>(def.cases)) {
1995
- collectStyles(c, rules, mediaQueries, selector, counter, prefix);
3161
+ walkStyleScopes(def, (node) => {
3162
+ if (node.style) {
3163
+ pushStyleRules(
3164
+ rules,
3165
+ node.style,
3166
+ `.${handleFor(node, counter, prefix)}`,
3167
+ mediaQueries,
3168
+ options,
3169
+ );
1996
3170
  }
1997
- }
3171
+ });
1998
3172
  }
1999
3173
 
2000
3174
  // ─── Utilities ────────────────────────────────────────────────────────────────
@@ -2040,7 +3214,8 @@ export function tagNameToClassName(tagName: string) {
2040
3214
  }
2041
3215
 
2042
3216
  /**
2043
- * Recursively collect unique $src values from $prototype: "Function" entries.
3217
+ * Recursively collect unique $src values from $prototype: "Function" entries. The site build asks
3218
+ * it whether a page still loads a module whose state reads it cannot see.
2044
3219
  *
2045
3220
  * @param {JxElement} doc
2046
3221
  * @returns {string[]}
@@ -2186,6 +3361,13 @@ export interface ComponentPrerenderContext {
2186
3361
  * it; without one (a unit test, a definition preview) no instance is stamped or bracketed.
2187
3362
  */
2188
3363
  slotIds?: { n: number } | undefined;
3364
+ /**
3365
+ * The tags whose instances ship their module (`computeLiveTags`): every definition that is not
3366
+ * fully static, and every registered tag such a definition renders. An instance of one is stamped
3367
+ * `data-jx-prerendered` and keeps its props as data. Without the set (a unit test, a definition
3368
+ * preview) each definition answers for itself through `isComponentFullyStatic`.
3369
+ */
3370
+ liveTags?: ReadonlySet<string> | undefined;
2189
3371
  }
2190
3372
 
2191
3373
  /**
@@ -2231,7 +3413,7 @@ export function nextSlotId(context: ComponentPrerenderContext | null): number |
2231
3413
  export function createSlotFill(
2232
3414
  children: SlotChildren,
2233
3415
  scope: JxScope | null,
2234
- render: (child: StaticChild) => string,
3416
+ render: (child: StaticChild | JxMappedArray) => string,
2235
3417
  id: number | null = null,
2236
3418
  ): SlotFill {
2237
3419
  const groups: SlotFill["groups"] = new Map();
@@ -2246,8 +3428,8 @@ export function createSlotFill(
2246
3428
  }
2247
3429
  content = html !== "";
2248
3430
  } else if (isMappedArray(child)) {
2249
- // A repeater renders nothing statically; it is content all the same, as its rows will be.
2250
- html = "";
3431
+ // A repeater is content whether or not the build can render its rows, as its rows will be.
3432
+ html = render(child);
2251
3433
  } else if (!isNodeObject(child)) {
2252
3434
  html = render(child);
2253
3435
  content = html !== "";
@@ -2373,12 +3555,66 @@ export function buildInstanceScope(
2373
3555
  return buildInitialScope(stateDefs, null);
2374
3556
  }
2375
3557
 
3558
+ /**
3559
+ * The props an instance's observed attributes amount to at build time (spec.md §16.5), or null when
3560
+ * it writes none: what the element's own first-connection read would put into state, so the
3561
+ * prerender shows it on the first paint.
3562
+ *
3563
+ * Each observed attribute the instance writes with a statically resolvable value is turned into the
3564
+ * attribute text `buildAttrs` would emit for it (a boolean through `booleanAttrValue`, where null
3565
+ * means the attribute is absent), then coerced by the runtime's own `absorbAttribute` against the
3566
+ * definition's build-time scope and its declared defaults, so a computed entry is skipped here as
3567
+ * it is in the browser. The caller lays the result UNDER the instance's `$props`, which is the
3568
+ * order the element applies, and never writes it into `data-jx-props`: the module reads the
3569
+ * attribute itself, and a prop there would outrank a later attribute change on the first
3570
+ * connection.
3571
+ *
3572
+ * @param {JxElement} def - The component definition
3573
+ * @param {JxElement["attributes"]} attributes - The instance's attributes, `props.*` already lifted
3574
+ * @param {JxScope | null} scope - The scope the instance's attribute values resolve against
3575
+ * @returns {Record<string, JsonValue> | null}
3576
+ */
3577
+ export function observedAttributeProps(
3578
+ def: JxElement,
3579
+ attributes: JxElement["attributes"],
3580
+ scope: JxScope | null,
3581
+ ): Record<string, JsonValue> | null {
3582
+ const names = observedAttributeNames(def).filter((name) => Object.hasOwn(attributes ?? {}, name));
3583
+ if (!attributes || names.length === 0) {
3584
+ return null;
3585
+ }
3586
+ const defaults = declaredDefaults(def);
3587
+ const scratch = buildInstanceScope(def, null);
3588
+ let out: Record<string, JsonValue> | null = null;
3589
+ for (const name of names) {
3590
+ const value = resolveStaticValue(attributes[name], scope);
3591
+ let text: string | null = null;
3592
+ if (isBoolean(value)) {
3593
+ text = booleanAttrValue(name, value);
3594
+ } else if (isString(value) || isNumber(value)) {
3595
+ text = String(value);
3596
+ }
3597
+ const key = observedStateKey(name);
3598
+ if (text === null || (defaults.has(key) && defaults.get(key) === undefined)) {
3599
+ continue;
3600
+ }
3601
+ absorbAttribute(scratch, name, text, defaults);
3602
+ out ??= {};
3603
+ /* SAFETY: `absorbAttribute` has just written this key with a boolean, a number or the string. */
3604
+ out[key] = scratch[key] as JsonValue;
3605
+ }
3606
+ return out;
3607
+ }
3608
+
2376
3609
  /**
2377
3610
  * Resolved host declarations by (camelCase) property: each is what its template read from the
2378
3611
  * instance's scope.
2379
3612
  */
2380
3613
  export type ResolvedHostStyle = Record<string, JxScope[string]>;
2381
3614
 
3615
+ /** A definition's root attributes, resolved against one instance. */
3616
+ export type ResolvedHostAttributes = Record<string, JxAttributeValue>;
3617
+
2382
3618
  /**
2383
3619
  * The definition's host `style` entries that depend on the instance, resolved against it.
2384
3620
  *
@@ -2391,6 +3627,36 @@ export type ResolvedHostStyle = Record<string, JxScope[string]>;
2391
3627
  * @param {JxScope} scope - The instance's scope (`buildInstanceScope`)
2392
3628
  * @returns {ResolvedHostStyle}
2393
3629
  */
3630
+ /**
3631
+ * A definition's root `attributes` as an instance's host carries them at build time (spec.md
3632
+ * §16.1): each value resolved against the instance's scope, so the prerendered host already holds
3633
+ * what the element writes on itself when it connects, and a static instance, which never runs a
3634
+ * module, holds them at all. A value the build cannot resolve, or one that resolves to nothing, is
3635
+ * left out: the module decides it.
3636
+ *
3637
+ * @param {JxElement["attributes"]} attributes - The definition's root `attributes`
3638
+ * @param {JxScope} scope - The instance's scope
3639
+ * @returns {ResolvedHostAttributes}
3640
+ */
3641
+ export function resolveHostAttributes(attributes: JxElement["attributes"], scope: JxScope) {
3642
+ const resolved: ResolvedHostAttributes = {};
3643
+ for (const [name, value] of Object.entries(attributes ?? {})) {
3644
+ if (isRef(value) && isRuntimeOnlyRef(value.$ref, scope)) {
3645
+ continue;
3646
+ }
3647
+ let result: JxScope[string];
3648
+ try {
3649
+ result = resolveStaticValue(value, scope);
3650
+ } catch {
3651
+ continue;
3652
+ }
3653
+ if (isString(result) || isNumber(result) || isBoolean(result)) {
3654
+ resolved[name] = result;
3655
+ }
3656
+ }
3657
+ return resolved;
3658
+ }
3659
+
2394
3660
  export function resolveHostStyle(
2395
3661
  style: JxStyle | null | undefined,
2396
3662
  scope: JxScope,
@@ -2418,6 +3684,8 @@ export function resolveHostStyle(
2418
3684
  * @param {JxScope | null} scope
2419
3685
  * @param {SlotFill | null} slots
2420
3686
  * @param {ComponentPrerenderContext | null} context
3687
+ * @param {boolean} [preformatted] - Inside a `<pre>`-like subtree, where children are joined with
3688
+ * nothing: a separator there is text the page shows
2421
3689
  * @returns {string}
2422
3690
  */
2423
3691
  function renderInner(
@@ -2425,6 +3693,7 @@ function renderInner(
2425
3693
  scope: JxScope | null,
2426
3694
  slots: SlotFill | null,
2427
3695
  context: ComponentPrerenderContext | null,
3696
+ preformatted = false,
2428
3697
  ): string {
2429
3698
  if (node.textContent !== undefined) {
2430
3699
  const val = resolveStaticValue(node.textContent, scope);
@@ -2434,14 +3703,112 @@ function renderInner(
2434
3703
  const val = resolveStaticValue(node.innerHTML, scope);
2435
3704
  return val != null ? String(val) : node.innerHTML;
2436
3705
  }
3706
+ // A content property is the element's text (spec.md §8.1).
3707
+ const content = contentPropertyText(node, resolveStaticTagName(node.tagName, scope), scope);
3708
+ if (content !== undefined) {
3709
+ return content;
3710
+ }
3711
+ // The legacy whole-`children` repeater: the array IS the children slot.
3712
+ if (isMappedArray(node.children)) {
3713
+ return renderMappedRows(node.children, scope, slots, context, preformatted);
3714
+ }
2437
3715
  if (Array.isArray(node.children)) {
2438
3716
  return node.children
2439
- .map((c: JxElement | JxMutableNode | string) => renderStaticNode(c, scope, slots, context))
2440
- .join("\n");
3717
+ .map((c: JxElement | JxMutableNode | string) =>
3718
+ renderStaticNode(c, scope, slots, context, preformatted),
3719
+ )
3720
+ .join(preformatted ? "" : "\n");
2441
3721
  }
2442
3722
  return "";
2443
3723
  }
2444
3724
 
3725
+ /**
3726
+ * The rows of a repeater as the element's first render draws them (compiler.md §8.1), so a
3727
+ * component's list is in the HTML it ships and not only in the DOM its module builds.
3728
+ *
3729
+ * `items` is a literal array, or a `$ref` read from the scope the repeater sits in, and `filter`
3730
+ * and `sort` are applied to it by the rule the element applies (`mappedListItems`, spec.md §10.3),
3731
+ * so the rows here are the rows of its first render, in its order. No row is rendered when any of
3732
+ * the three pointers names runtime-only state (`isRuntimeOnlyRef`, asked before the read: a
3733
+ * placeholder callable must never filter a list to nothing), or when a read or a predicate throws
3734
+ * on build-time data, or when `items` does not yield an array. `key` is not consulted, because
3735
+ * nothing adopts a row (spec.md §16.10).
3736
+ *
3737
+ * Each row renders the `map` template in a scope of its own that inherits the repeater's and
3738
+ * carries the iteration frame the way `resolveRefValue` and `evaluateStaticTemplate` read it, so a
3739
+ * per-row `$switch`, a nested repeater and a per-row component instance need nothing further.
3740
+ *
3741
+ * @param {JxMappedArray} arrayDef
3742
+ * @param {JxScope | null} scope - The scope the repeater sits in
3743
+ * @param {SlotFill | null} slots
3744
+ * @param {ComponentPrerenderContext | null} context
3745
+ * @param {boolean} [preformatted]
3746
+ * @returns {string}
3747
+ * @docs framework/concepts/lists
3748
+ */
3749
+ export function renderMappedRows(
3750
+ arrayDef: JxMappedArray,
3751
+ scope: JxScope | null,
3752
+ slots: SlotFill | null = null,
3753
+ context: ComponentPrerenderContext | null = null,
3754
+ preformatted = false,
3755
+ ): string {
3756
+ const template = arrayDef.map;
3757
+ if (!template) {
3758
+ return "";
3759
+ }
3760
+ refuseTemplateItems(arrayDef);
3761
+ const parent = scope ?? emptyScope();
3762
+ const rows = buildListRows(arrayDef, parent);
3763
+ if (rows === null) {
3764
+ return "";
3765
+ }
3766
+ return rows
3767
+ .map((item, index) => {
3768
+ const rowScope = emptyScope(parent);
3769
+ rowScope.$map = { index, item };
3770
+ rowScope["$map/item"] = item;
3771
+ rowScope["$map/index"] = index;
3772
+ return renderStaticNode(template, rowScope, slots, context, preformatted);
3773
+ })
3774
+ .join(preformatted ? "" : "\n");
3775
+ }
3776
+
3777
+ /**
3778
+ * A repeater's rows at build time: `items` filtered, then sorted, by the interpreter's own rule
3779
+ * (`mappedListItems`), or `null` when the build cannot know them. That is when `items`, `filter` or
3780
+ * `sort` names runtime-only state, when reading one throws (a computed's getter is free to on
3781
+ * build-time data), when a predicate or comparator throws, or when `items` is not an array.
3782
+ *
3783
+ * The component prerender and the site build's page expansion both ask here, so a list is arranged
3784
+ * by one rule wherever the build draws it.
3785
+ *
3786
+ * @param {JxMappedArray} arrayDef
3787
+ * @param {JxScope} scope - The scope the repeater sits in
3788
+ * @returns {readonly JxScope[string][] | null}
3789
+ */
3790
+ export function buildListRows(
3791
+ arrayDef: JxMappedArray,
3792
+ scope: JxScope,
3793
+ ): readonly JxScope[string][] | null {
3794
+ const read = (source: JxDocumentValue | undefined): JxScope[string] =>
3795
+ isRef(source) ? resolveRefValue(source.$ref, scope) : undefined;
3796
+ for (const source of [arrayDef.items, arrayDef.filter, arrayDef.sort]) {
3797
+ if (isRef(source) && isRuntimeOnlyRef(source.$ref, scope)) {
3798
+ return null;
3799
+ }
3800
+ }
3801
+ try {
3802
+ const items = isRef(arrayDef.items) ? read(arrayDef.items) : arrayDef.items;
3803
+ if (!Array.isArray(items)) {
3804
+ return null;
3805
+ }
3806
+ return mappedListItems(items, read(arrayDef.filter), read(arrayDef.sort));
3807
+ } catch {
3808
+ return null;
3809
+ }
3810
+ }
3811
+
2445
3812
  /**
2446
3813
  * A child slot as the static renderer meets it: a node or a text string, plus the JSON scalars,
2447
3814
  * holes and nested lists a hand-written `children` array may also carry.
@@ -2465,18 +3832,28 @@ export type StaticChild =
2465
3832
  * literal (a shadow root, or a definition rendered with no instance)
2466
3833
  * @param {ComponentPrerenderContext | null} [context] - The component registry, when a custom
2467
3834
  * element tag met here should be expanded rather than emitted bare
3835
+ * @param {boolean} [preformatted] - Inside a `<pre>`-like subtree (see `renderInner`)
2468
3836
  * @returns {string}
2469
3837
  */
2470
3838
  export function renderStaticNode(
2471
- node: StaticChild,
3839
+ node: StaticChild | JxMappedArray,
2472
3840
  scope: JxScope | null,
2473
3841
  slots: SlotFill | null = null,
2474
3842
  context: ComponentPrerenderContext | null = null,
3843
+ preformatted = false,
2475
3844
  ): string {
2476
3845
  if (isString(node)) {
2477
3846
  if (isTemplateString(node) && scope) {
2478
3847
  const val = evaluateStaticTemplate(node, scope);
2479
- return val != null ? escapeHtml(String(val)) : escapeHtml(node);
3848
+ if (val != null) {
3849
+ return escapeHtml(String(val));
3850
+ }
3851
+ /* Inside a component a text child that resolves to nothing renders nothing, as the module's
3852
+ first render does and as `textContent` does: the module owns the binding, and its source
3853
+ left in the markup would be read as a template a second time by the page that holds the
3854
+ instance. A page's own text keeps its source, which is what keeps an unresolvable binding
3855
+ alive for the client (compiler.md §8.1). */
3856
+ return context ? "" : escapeHtml(node);
2480
3857
  }
2481
3858
  return escapeHtml(node);
2482
3859
  }
@@ -2484,15 +3861,17 @@ export function renderStaticNode(
2484
3861
  return escapeHtml(String(node));
2485
3862
  }
2486
3863
  if (Array.isArray(node)) {
2487
- return node.map((c): string => renderStaticNode(c, scope, slots, context)).join("\n");
3864
+ return node
3865
+ .map((c): string => renderStaticNode(c, scope, slots, context, preformatted))
3866
+ .join(preformatted ? "" : "\n");
2488
3867
  }
2489
3868
  if (!isNonNullObject(node)) {
2490
3869
  return "";
2491
3870
  }
2492
3871
 
2493
- // Skip mapped arrays — can't pre-render dynamic lists
2494
- if (node.$prototype === "Array") {
2495
- return "";
3872
+ // A repeater among siblings renders its rows in place (the whole-`children` form is `renderInner`'s).
3873
+ if (isMappedArray(node)) {
3874
+ return renderMappedRows(node, scope, slots, context, preformatted);
2496
3875
  }
2497
3876
 
2498
3877
  // $switch/cases — resolve the key statically and render the matched case inside a container
@@ -2501,11 +3880,14 @@ export function renderStaticNode(
2501
3880
  if (node.$switch) {
2502
3881
  const switchTag = node.tagName ?? "div";
2503
3882
  const attrs = buildAttrs(node, scope);
2504
- const key = resolveStaticValue(node.$switch, scope);
3883
+ // A discriminant with no build-time value is not read: the container renders empty.
3884
+ const held =
3885
+ isRef(node.$switch) && scope !== null && isRuntimeOnlyRef(node.$switch.$ref, scope);
3886
+ const key = held ? null : resolveStaticValue(node.$switch, scope);
2505
3887
  const caseDef = key == null ? undefined : node.cases?.[String(key)];
2506
3888
  const inner =
2507
3889
  caseDef !== undefined && !isRefObject(caseDef)
2508
- ? renderStaticNode(caseDef, scope, slots, context)
3890
+ ? renderStaticNode(caseDef, scope, slots, context, preformatted)
2509
3891
  : "";
2510
3892
  return `<${switchTag}${attrs}>${inner}</${switchTag}>`;
2511
3893
  }
@@ -2535,7 +3917,7 @@ export function renderStaticNode(
2535
3917
  takeSlotNames(node.children, scope, slots);
2536
3918
  return out;
2537
3919
  }
2538
- const fallback = renderInner(node, scope, slots, context);
3920
+ const fallback = renderInner(node, scope, slots, context, preformatted);
2539
3921
  return out === "" ? fallback : fallback === "" ? out : `${out}\n${fallback}`;
2540
3922
  }
2541
3923
 
@@ -2551,7 +3933,14 @@ export function renderStaticNode(
2551
3933
  return `<${tag}${attrs}>`;
2552
3934
  }
2553
3935
 
2554
- return `<${tag}${attrs}>${renderInner(node, scope, slots, context)}</${tag}>`;
3936
+ const inner = renderInner(
3937
+ node,
3938
+ scope,
3939
+ slots,
3940
+ context,
3941
+ preformatted || PREFORMATTED_TAGS.has(tag),
3942
+ );
3943
+ return `<${tag}${attrs}>${inner}</${tag}>`;
2555
3944
  }
2556
3945
 
2557
3946
  /**
@@ -2560,7 +3949,8 @@ export function renderStaticNode(
2560
3949
  *
2561
3950
  * - Props: `props.*` attributes lifted, then `$props`; a template value resolves against the PARENT's
2562
3951
  * scope, which is what `resolveDocTemplates` does for a page-level instance before the page walk
2563
- * reaches it.
3952
+ * reaches it. Beneath them, the instance's observed attributes, coerced (spec.md §16.5), which
3953
+ * feed the scope and the path but never `data-jx-props`.
2564
3954
  * - Slot content: the instance's own children, rendered in the parent's scope and with the parent's
2565
3955
  * fill, so a `<slot>` written among them passes the grandparent's group of that name through, and
2566
3956
  * placed in the definition's slots by name (`createSlotFill`, spec.md §8.5). A live instance
@@ -2605,9 +3995,14 @@ function renderComponentInstance(
2605
3995
  props[key] = (resolveStaticValue(value, scope) as JsonValue | null) ?? value;
2606
3996
  }
2607
3997
  const hasProps = Object.keys(props).length > 0;
3998
+ /* What the instance's scope is built from: its observed attributes, coerced, with its props over
3999
+ them (spec.md §16.5). It is the instance's identity on the path too (spec.md §16.9), so two
4000
+ nested instances of one tag told apart only by an observed attribute are two instances. */
4001
+ const scopeProps = { ...observedAttributeProps(def, attributes, scope), ...props };
4002
+ const hasScopeProps = Object.keys(scopeProps).length > 0;
2608
4003
 
2609
4004
  const path = context.path ?? [];
2610
- const frame: PrerenderFrame = { key: JSON.stringify(props), tag };
4005
+ const frame: PrerenderFrame = { key: JSON.stringify(scopeProps), tag };
2611
4006
  const chain = [...path.map((f) => f.tag), tag].join(" → ");
2612
4007
  if (path.some((f) => f.tag === frame.tag && f.key === frame.key)) {
2613
4008
  throw new Error(
@@ -2625,11 +4020,12 @@ function renderComponentInstance(
2625
4020
 
2626
4021
  // The instance's children are the parent's nodes: parent scope, parent fill, parent path.
2627
4022
  const { children } = node;
2628
- const renderChild = (c: StaticChild) => renderStaticNode(c, scope, parentSlots, context);
4023
+ const renderChild = (c: StaticChild | JxMappedArray) =>
4024
+ renderStaticNode(c, scope, parentSlots, context);
2629
4025
 
2630
4026
  const shadow = resolveShadowMode(def, context.defaults);
2631
- const isStatic = isComponentFullyStatic(def);
2632
- const instanceScope = buildInstanceScope(def, hasProps ? props : null);
4027
+ const isStatic = !isLiveComponent(tag, def, context.liveTags);
4028
+ const instanceScope = buildInstanceScope(def, hasScopeProps ? scopeProps : null);
2633
4029
  let innerHTML: string;
2634
4030
  let slotId: number | null = null;
2635
4031
  if (shadow) {
@@ -2639,7 +4035,7 @@ function renderComponentInstance(
2639
4035
  : "";
2640
4036
  innerHTML =
2641
4037
  `<template shadowrootmode="${shadow}">` +
2642
- `<link rel="stylesheet" href="/components/${tag}.css">` +
4038
+ `<link rel="stylesheet" href="${componentStylesheetHref(tag)}">` +
2643
4039
  `${renderInner(def, instanceScope, null, nested)}</template>${light}`;
2644
4040
  } else {
2645
4041
  slotId = !isStatic && definitionHasSlot(def.children) ? nextSlotId(context) : null;
@@ -2656,8 +4052,12 @@ function renderComponentInstance(
2656
4052
  const instance = { ...node };
2657
4053
  delete instance.$props;
2658
4054
  delete instance.children;
4055
+ // The definition's own root attributes over the instance's, as the element writes them (§16.1).
4056
+ const hostAttributes = { ...attributes, ...resolveHostAttributes(def.attributes, instanceScope) };
2659
4057
  instance.attributes =
2660
- !isStatic && hasProps ? { ...attributes, "data-jx-props": JSON.stringify(props) } : attributes;
4058
+ !isStatic && hasProps
4059
+ ? { ...hostAttributes, "data-jx-props": JSON.stringify(props) }
4060
+ : hostAttributes;
2661
4061
  if (slotId !== null) {
2662
4062
  instance.attributes = { ...instance.attributes, [SLOT_ATTR]: String(slotId) };
2663
4063
  }
@@ -2690,16 +4090,176 @@ export function preRenderComponentHtml(
2690
4090
  return renderInner(doc, buildInstanceScope(doc, propsOverride), slots, context);
2691
4091
  }
2692
4092
 
4093
+ /**
4094
+ * Whether an instance of `tag` ships its module: its tag is in the site's live set when there is
4095
+ * one, and otherwise its own definition is not fully static.
4096
+ *
4097
+ * @param {string} tag
4098
+ * @param {JxElement} def
4099
+ * @param {ReadonlySet<string>} [liveTags] - See {@link computeLiveTags}
4100
+ * @returns {boolean}
4101
+ */
4102
+ export function isLiveComponent(
4103
+ tag: string,
4104
+ def: JxElement,
4105
+ liveTags?: ReadonlySet<string>,
4106
+ ): boolean {
4107
+ return liveTags ? liveTags.has(tag) : !isComponentFullyStatic(def);
4108
+ }
4109
+
4110
+ /**
4111
+ * The registered component tags a definition's template can create: every literal `tagName` and
4112
+ * every candidate of a tag expression, walked through `children` (arrays and both repeater forms'
4113
+ * `map`) and `$switch` `cases`. What a live definition renders, it renders from its module, which
4114
+ * creates each element bare, so each of these needs its own module wherever the definition loads.
4115
+ *
4116
+ * @param {JxElement} def - A component definition
4117
+ * @param {ReadonlyMap<string, JxElement>} registry - Tag name → definition
4118
+ * @returns {Set<string>}
4119
+ */
4120
+ export function renderedComponentTags(
4121
+ def: JxElement,
4122
+ registry: ReadonlyMap<string, JxElement>,
4123
+ ): Set<string> {
4124
+ const out = new Set<string>();
4125
+ const visit = (node: StaticChild | JxMappedArray | undefined, root: boolean): void => {
4126
+ if (Array.isArray(node)) {
4127
+ for (const child of node) {
4128
+ visit(child, false);
4129
+ }
4130
+ return;
4131
+ }
4132
+ if (!isNonNullObject(node)) {
4133
+ return;
4134
+ }
4135
+ if (isMappedArray(node)) {
4136
+ visit(node.map, false);
4137
+ return;
4138
+ }
4139
+ // The root is the definition itself, not an instance it renders.
4140
+ if (!root) {
4141
+ for (const tag of tagNameCandidates(node.tagName)) {
4142
+ if (registry.has(tag)) {
4143
+ out.add(tag);
4144
+ }
4145
+ }
4146
+ }
4147
+ visit(node.children, false);
4148
+ for (const caseDef of Object.values<StaticChild>(node.cases ?? {})) {
4149
+ if (!isRefObject(caseDef)) {
4150
+ visit(caseDef, false);
4151
+ }
4152
+ }
4153
+ };
4154
+ visit(def, true);
4155
+ return out;
4156
+ }
4157
+
4158
+ /**
4159
+ * The tags whose module a page loads (compiler.md §8.1): every definition that is not fully static,
4160
+ * and, to a fixpoint, every registered tag that such a definition renders when the page can draw
4161
+ * that definition. The answer is the page's: a static component used on its own on one page and
4162
+ * inside a live one on another is static on the first and live on the second. Without `page` every
4163
+ * live definition counts as drawn, which is the answer for a site as a whole.
4164
+ *
4165
+ * @param {ReadonlyMap<string, JxElement>} registry - Tag name → definition
4166
+ * @param {JxElement} [page] - The composed page document, before its instances are expanded
4167
+ * @returns {Set<string>}
4168
+ * @docs framework/build
4169
+ */
4170
+ export function computeLiveTags(
4171
+ registry: ReadonlyMap<string, JxElement>,
4172
+ page?: JxElement,
4173
+ ): Set<string> {
4174
+ const closure = (seeds: Iterable<string>): Set<string> => {
4175
+ const reached = new Set(seeds);
4176
+ const queue = [...reached];
4177
+ for (let tag = queue.pop(); tag !== undefined; tag = queue.pop()) {
4178
+ /* SAFETY: every tag on the queue was read from `registry` or passed `registry.has`. */
4179
+ for (const rendered of renderedComponentTags(registry.get(tag) as JxElement, registry)) {
4180
+ if (!reached.has(rendered)) {
4181
+ reached.add(rendered);
4182
+ queue.push(rendered);
4183
+ }
4184
+ }
4185
+ }
4186
+ return reached;
4187
+ };
4188
+ const drawn = page ? closure(renderedComponentTags(page, registry)) : undefined;
4189
+ const live = new Set<string>();
4190
+ const seeds: string[] = [];
4191
+ for (const [tag, def] of registry) {
4192
+ if (!isComponentFullyStatic(def)) {
4193
+ live.add(tag);
4194
+ if (!drawn || drawn.has(tag)) {
4195
+ seeds.push(tag);
4196
+ }
4197
+ }
4198
+ }
4199
+ for (const tag of closure(seeds)) {
4200
+ live.add(tag);
4201
+ }
4202
+ return live;
4203
+ }
4204
+
4205
+ /**
4206
+ * Component tags ordered so each comes after every registered tag its definition renders, ties by
4207
+ * name: the order a page's module scripts are written in. Module scripts run in document order, and
4208
+ * an outer element defined before its inner one renders that inner element un-upgraded until the
4209
+ * next script runs. A cycle is broken where it is met.
4210
+ *
4211
+ * @param {readonly string[]} tags
4212
+ * @param {ReadonlyMap<string, JxElement>} registry - Tag name → definition
4213
+ * @returns {string[]}
4214
+ */
4215
+ export function orderComponentTags(
4216
+ tags: readonly string[],
4217
+ registry: ReadonlyMap<string, JxElement>,
4218
+ ): string[] {
4219
+ const wanted = new Set(tags);
4220
+ const seen = new Set<string>();
4221
+ const out: string[] = [];
4222
+ const visit = (tag: string): void => {
4223
+ if (seen.has(tag)) {
4224
+ return;
4225
+ }
4226
+ seen.add(tag);
4227
+ const def = registry.get(tag);
4228
+ if (def) {
4229
+ for (const rendered of [...renderedComponentTags(def, registry)].toSorted()) {
4230
+ visit(rendered);
4231
+ }
4232
+ }
4233
+ if (wanted.has(tag)) {
4234
+ out.push(tag);
4235
+ }
4236
+ };
4237
+ for (const tag of [...tags].toSorted()) {
4238
+ visit(tag);
4239
+ }
4240
+ return out;
4241
+ }
4242
+
2693
4243
  /**
2694
4244
  * Check if a component definition is fully static (no runtime behavior needed).
2695
4245
  *
2696
4246
  * Returns true when: no event handlers, no $prototype entries (Functions, Request, Storage), no
2697
- * $ref values. Conservative — returns false when uncertain.
4247
+ * $ref values, no `$switch`, no tag chosen at creation, and no observed attributes. A repeater is
4248
+ * static only when its `items` is a literal array, it declares no `filter`, `sort` or `key`, and
4249
+ * its `map` is static. Conservative — returns false when uncertain.
4250
+ *
4251
+ * A definition that declares `observedAttributes` is never static (spec.md §16.5): declaring the
4252
+ * list is declaring a runtime interface, since every later change and removal of one must apply and
4253
+ * only the element's module can hear it. Asked of the root alone, the only place the list is
4254
+ * declared.
2698
4255
  *
2699
4256
  * @param {JxElement} doc - Component JSON definition
2700
4257
  * @returns {boolean}
2701
4258
  */
2702
4259
  export function isComponentFullyStatic(doc: JxElement) {
4260
+ if (observedAttributeNames(doc).length > 0) {
4261
+ return false;
4262
+ }
2703
4263
  return _isStaticNode(doc);
2704
4264
  }
2705
4265
 
@@ -2707,7 +4267,7 @@ export function isComponentFullyStatic(doc: JxElement) {
2707
4267
  * @param {JxElement | string | (JxElement | string)[]} node
2708
4268
  * @returns {boolean}
2709
4269
  */
2710
- function _isStaticNode(node: JxElement | string | (JxElement | string)[]): boolean {
4270
+ function _isStaticNode(node: JxElement | JxMappedArray | string | (JxElement | string)[]): boolean {
2711
4271
  if (!isNonNullObject(node)) {
2712
4272
  return true;
2713
4273
  }
@@ -2715,10 +4275,26 @@ function _isStaticNode(node: JxElement | string | (JxElement | string)[]): boole
2715
4275
  return node.every((n) => _isStaticNode(n));
2716
4276
  }
2717
4277
 
4278
+ /* A repeater over a literal array, with nothing to filter, sort or key by, is its rows: the
4279
+ build renders them and nothing changes them. Any other repeater is built at run time. */
4280
+ if (isMappedArray(node)) {
4281
+ return (
4282
+ Array.isArray(node.items) &&
4283
+ node.filter === undefined &&
4284
+ node.sort === undefined &&
4285
+ node.key === undefined &&
4286
+ (node.map === undefined || _isStaticNode(node.map))
4287
+ );
4288
+ }
2718
4289
  // Check for $prototype (Functions, Request, Storage, etc.)
2719
4290
  if (node.$prototype) {
2720
4291
  return false;
2721
4292
  }
4293
+ /* A `$switch` re-chooses its case and a tag expression its element from state, which only the
4294
+ module can do: the discriminant is a `$ref` the checks below never reach. */
4295
+ if (node.$switch !== undefined || isTagExpression(node.tagName)) {
4296
+ return false;
4297
+ }
2722
4298
  // Check for $ref
2723
4299
  if (node.$ref) {
2724
4300
  return false;
@@ -2750,72 +4326,82 @@ function _isStaticNode(node: JxElement | string | (JxElement | string)[]): boole
2750
4326
  if (Array.isArray(node.children)) {
2751
4327
  return node.children.every((c) => _isStaticNode(c));
2752
4328
  }
2753
- // The legacy bare children slot: a mapped array builds its children at runtime.
4329
+ // The legacy bare children slot: the repeater answers for itself, as one among siblings does.
2754
4330
  if (isMappedArray(node.children)) {
2755
- return false;
4331
+ return _isStaticNode(node.children);
2756
4332
  }
2757
4333
 
2758
4334
  return true;
2759
4335
  }
2760
4336
 
2761
4337
  /**
2762
- * Generate CSS rules for a component: host-level styles using tag selector, plus inner element
2763
- * styles using .jx-N selectors via collectStyles.
4338
+ * The URL a site build serves a component's stylesheet at: the one spelling the prerender's
4339
+ * declarative shadow root, the element module and the file written to `dist/` all share.
2764
4340
  *
2765
- * @param {string} tagName - The custom element tag name (used as CSS selector)
2766
- * @param {JxStyle | null} styleDef - The component's style object
2767
- * @param {JxElement | null} [doc] - The full component document (for walking children)
2768
- * @param {Record<string, string>} [mediaQueries] - Project media query definitions
2769
- * @returns {string} CSS text, or empty string if no styles
4341
+ * @param {string} tagName
4342
+ * @returns {string}
2770
4343
  */
2771
- /** `::slotted()` and `::part()` select through a shadow boundary, not the host that owns it. */
2772
- const SHADOW_STANDALONE = /^(?:::slotted\(|::part\()/;
4344
+ export function componentStylesheetHref(tagName: string): string {
4345
+ return `/components/${tagName}.css`;
4346
+ }
2773
4347
 
2774
4348
  /**
2775
- * Turn one nested style key into a selector, given the component's scope prefix.
4349
+ * The text of a shadow component's stylesheet file: its own rules, then the rules of every
4350
+ * light-DOM component its definition can render.
2776
4351
  *
2777
- * Three shapes, and the interesting one is `:host`. A style object should mean the same thing in
2778
- * both modes, so `:host` and `:host(.foo)` are **translated** rather than passed through: inside a
2779
- * shadow root they stand alone, and in the light DOM they become the tag name and `<tag>.foo` —
2780
- * which is what "the host, matching this" means when there is no shadow root. Moving a component
2781
- * between modes therefore does not silently break its styles.
4352
+ * The page inlines a light component's sheet into its `<head>`, which cannot reach into a shadow
4353
+ * root, so a light component rendered inside one was unstyled. Its sheet rides in the root's own
4354
+ * instead, which keeps it one request per root. The walk follows light definitions transitively and
4355
+ * stops at a shadow one, which brings its own root and its own sheet; each sheet is written once,
4356
+ * in first-seen order.
2782
4357
  *
2783
- * @param {string} prop - The style-object key, e.g. `":hover"`, `"& .inner"`, `":host(.wide)"`
2784
- * @param {string} scope - `":host"` in shadow mode, the tag name otherwise
4358
+ * @param {string} tag - A shadow component
4359
+ * @param {ReadonlyMap<string, JxElement>} registry - Tag name → definition
4360
+ * @param {ReadonlyMap<string, string>} ownSheets - Tag name → that component's own rules
4361
+ * @param {ReadonlySet<string>} shadowTags - The components that render into a shadow root
2785
4362
  * @returns {string}
2786
4363
  */
2787
- function resolveSelector(prop: string, scope: string): string {
2788
- /* Member by member, for the reason css.ts's `resolveNestedSelector` does it: a key may be a
2789
- SELECTOR LIST, and splicing one as a single string spliced only its first `&`. `"& .a, & .b"`
2790
- came out as `sty-card .a, & .b`, and a raw `&` in a built stylesheet is not a nesting selector
2791
- at all — the browser discards the list and the component silently loses those rules. This is
2792
- the one selector path that does not go through the shared builder, because `:host` has to be
2793
- translated before the scope is applied, so it needed the same fix separately. */
2794
- return splitSelectorList(prop)
2795
- .map((member) => resolveSelectorMember(member, scope))
2796
- .join(", ");
2797
- }
2798
-
2799
- /** One member of {@link resolveSelector}'s list against the scope. */
2800
- function resolveSelectorMember(prop: string, scope: string): string {
2801
- const spliced = spliceNestingSelector(prop, scope);
2802
- if (spliced !== null) {
2803
- return spliced;
2804
- }
2805
- if (prop.startsWith(":host")) {
2806
- const inner = /^:host\((.*)\)$/.exec(prop)?.[1];
2807
- if (scope === ":host") {
2808
- return prop;
4364
+ export function shadowSheetText(
4365
+ tag: string,
4366
+ registry: ReadonlyMap<string, JxElement>,
4367
+ ownSheets: ReadonlyMap<string, string>,
4368
+ shadowTags: ReadonlySet<string>,
4369
+ ): string {
4370
+ const seen = new Set<string>([tag]);
4371
+ const sheets = [ownSheets.get(tag) ?? ""];
4372
+ const visit = (from: string): void => {
4373
+ // `from` is a registered tag: the walk only ever follows tags the registry answered for.
4374
+ for (const rendered of renderedComponentTags(registry.get(from) ?? {}, registry)) {
4375
+ if (seen.has(rendered) || shadowTags.has(rendered)) {
4376
+ continue;
4377
+ }
4378
+ seen.add(rendered);
4379
+ sheets.push(ownSheets.get(rendered) ?? "");
4380
+ visit(rendered);
2809
4381
  }
2810
- return inner === undefined ? scope : `${scope}${inner}`;
2811
- }
2812
- // `:host::slotted(x)` matches nothing — the pseudo-element attaches to a slot, not the host.
2813
- if (scope === ":host" && SHADOW_STANDALONE.test(prop)) {
2814
- return prop;
2815
- }
2816
- return `${scope}${prop}`;
4382
+ };
4383
+ visit(tag);
4384
+ return sheets.join("");
2817
4385
  }
2818
4386
 
4387
+ /**
4388
+ * The stylesheet of one component: its definition's own style under the host's selector, then the
4389
+ * rules of every styled node the definition renders.
4390
+ *
4391
+ * The scope is the tag name in light DOM, which is what keeps `sty-card .inner` from reaching
4392
+ * another component's `.inner`, and `:host` inside a shadow root, where a selector cannot see the
4393
+ * host's tag name at all. The same style object produces different, correct CSS in each mode
4394
+ * without the author restating it: `:host` keys are translated and a key compounding onto a shadow
4395
+ * host is folded into `:host()` by the one function the interpreter also calls (`resolveHostKey` in
4396
+ * `@jxsuite/runtime/css`, spec.md §16.6).
4397
+ *
4398
+ * @param {string} tagName
4399
+ * @param {JxStyle | null} [styleDef] - The definition's own `style`
4400
+ * @param {JxElement | null} [doc] - The definition, for its children's styles
4401
+ * @param {Record<string, string>} [mediaQueries]
4402
+ * @param {ShadowMode | null} [shadow]
4403
+ * @returns {string} The sheet's text, one rule per line
4404
+ */
2819
4405
  export function buildComponentCSS(
2820
4406
  tagName: string,
2821
4407
  styleDef?: JxStyle | null | undefined,
@@ -2824,50 +4410,31 @@ export function buildComponentCSS(
2824
4410
  shadow: ShadowMode | null = null,
2825
4411
  ) {
2826
4412
  const rules: string[] = [];
2827
- /*
2828
- * The scope prefix. In light DOM it is the tag name, which is what keeps `sty-card .inner` from
2829
- * reaching another component's `.inner`. Inside a shadow root the selector cannot see the host's
2830
- * tag name at all, and `:host` is the standard's way to address it — so the same style object
2831
- * produces different, correct CSS in each mode without the author restating it.
2832
- */
2833
4413
  const scope = styleScopePrefix(tagName, shadow);
4414
+ const tree: StyleTreeOptions = { host: shadow === null ? "light" : "shadow" };
4415
+ if (shadow !== null) {
4416
+ tree.shadowTree = true;
4417
+ }
4418
+ /* A custom element is `inline` by default and a Jx container behaves like a `<div>`, so a
4419
+ definition whose BASE block declares no `display` is given `display: block` in its own rule,
4420
+ ahead of its own declarations (spec.md §9.6). The interpreter writes the same default, so a
4421
+ component lays out alike in Studio and in a built page. Only the base block is read: a
4422
+ `display` inside `:hover` or a breakpoint is not the author supplying one. */
4423
+ const own: JxStyle = isNonNullObject(styleDef) ? styleDef : {};
4424
+ pushStyleRules(
4425
+ rules,
4426
+ "display" in own ? own : { display: "block", ...own },
4427
+ scope,
4428
+ mediaQueries,
4429
+ tree,
4430
+ );
2834
4431
 
2835
- if (isNonNullObject(styleDef)) {
2836
- /* The top level is walked here rather than handed straight to the builder, because ONE of its
2837
- keys does not mean what `resolveNestedSelector` would make of it: `:host` and `:host(.foo)`
2838
- are TRANSLATED per {@link resolveSelector} so a style object means the same thing in both
2839
- modes. Everything below the top level is ordinary nesting, so each block goes to the builder
2840
- whole — which is also what gives a component's nested selectors the recursion they never had
2841
- (this used to emit exactly one level and drop anything under it). */
2842
- const own: JxStyle = {};
2843
- const blocks: [string, JxStyle][] = [];
2844
- for (const [prop, value] of Object.entries(styleDef)) {
2845
- /* `isRef` first, and it is the whole point: an object carrying `$ref` is a reactive VALUE,
2846
- not a nested block (spec.md §9.1). Sorted into `blocks` it matched neither branch below —
2847
- not an at-rule, not a nested selector — and was dropped without reaching the builder at
2848
- all, so the one emitter that could have reported it never saw it. */
2849
- if (isRef(value)) {
2850
- own[prop] = value;
2851
- } else if (isNonNullObject(value) && !Array.isArray(value)) {
2852
- blocks.push([prop, value]);
2853
- } else if (!prop.startsWith("@") && !isNestedSelectorKey(prop)) {
2854
- own[prop] = value;
2855
- }
2856
- }
2857
- pushStyleRules(rules, own, scope, mediaQueries);
2858
- for (const [prop, val] of blocks) {
2859
- if (prop.startsWith("@")) {
2860
- pushStyleRules(rules, { [prop]: val }, scope, mediaQueries);
2861
- } else if (isNestedSelectorKey(prop)) {
2862
- pushStyleRules(rules, val, resolveSelector(prop, scope), mediaQueries);
2863
- }
2864
- }
2865
- }
2866
-
2867
- if (doc && Array.isArray(doc.children)) {
4432
+ if (doc) {
2868
4433
  const counter = { n: 0 };
2869
- for (const child of doc.children) {
2870
- collectStyles(child, rules, mediaQueries, "", counter, tagName);
4434
+ for (const child of styleChildren(doc)) {
4435
+ collectStyles(child, rules, mediaQueries, "", counter, tagName, {
4436
+ shadowTree: shadow !== null,
4437
+ });
2871
4438
  }
2872
4439
  }
2873
4440