@jxsuite/compiler 9.1.0 → 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
@@ -27,12 +27,13 @@ import {
27
27
  commentedRuleText,
28
28
  declaredDefaults,
29
29
  enumeratedAttrNames,
30
- isNestedSelectorKey,
31
30
  camelToKebab,
32
31
  isSingleExpression,
33
- splitSelectorList,
32
+ mappedListItems,
34
33
  } from "@jxsuite/runtime";
35
- 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";
36
37
  import {
37
38
  compileOperandSource,
38
39
  evaluateExpression,
@@ -45,6 +46,7 @@ import { runStatements } from "@jxsuite/runtime/statements";
45
46
  import { BUILT_IN_PROTOTYPES } from "@jxsuite/schema/defs";
46
47
  import { buildSiteStyleCSS } from "@jxsuite/site/site-style";
47
48
  import {
49
+ attributeStateKey,
48
50
  childrenContainArray,
49
51
  hasStructuredBody,
50
52
  isExpressionDef,
@@ -69,11 +71,19 @@ import {
69
71
  import type { TagNameSlot } from "@jxsuite/schema/guards";
70
72
  import { resolveShadowMode, styleScopePrefix } from "./shadow.ts";
71
73
  import type { ShadowMode } from "./shadow.ts";
72
- 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";
73
82
  import type { JxScope } from "@jxsuite/runtime/types";
74
83
  import type {
75
84
  CemParameter,
76
85
  JsonValue,
86
+ JxAttributeValue,
77
87
  JxDocument,
78
88
  JxDocumentValue,
79
89
  JxElement,
@@ -389,6 +399,50 @@ const RUNTIME_ONLY_KEYS = Symbol("jx.runtimeOnlyStateKeys");
389
399
  export const DEFAULT_REACTIVITY_SRC = "https://esm.sh/@vue/reactivity@3.5.40";
390
400
  export const DEFAULT_LIT_HTML_SRC = "https://esm.sh/lit-html@3.3.0";
391
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
+
392
446
  // ─── Schema keywords & detection ─────────────────────────────────────────────
393
447
  // Centralized in @jxsuite/schema/guards; re-exported here for existing callers.
394
448
 
@@ -587,8 +641,10 @@ export function isDynamic(def: JxElement | JxMutableNode | string) {
587
641
  return true;
588
642
  }
589
643
 
644
+ const finished = isExpandedInstance(def);
590
645
  for (const [key, val] of Object.entries(def)) {
591
- 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")) {
592
648
  continue;
593
649
  }
594
650
  if (isRef(val)) {
@@ -618,6 +674,20 @@ export function isDynamic(def: JxElement | JxMutableNode | string) {
618
674
  return false;
619
675
  }
620
676
 
677
+ /**
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).
683
+ *
684
+ * @param {JxElement | JxMutableNode} def
685
+ * @returns {boolean}
686
+ */
687
+ export function isExpandedInstance(def: JxElement | JxMutableNode): boolean {
688
+ return def.$static === true || def.$prerendered === true;
689
+ }
690
+
621
691
  // ─── Scope / value resolution ─────────────────────────────────────────────────
622
692
 
623
693
  /** What a compile target threads down the tree: the scope in effect, its definitions and `$media`. */
@@ -687,6 +757,25 @@ export function isRuntimeOnlyStateKey(scope: JxScope, key: string): boolean {
687
757
  return runtimeOnlyKeysOf(scope)?.has(key) ?? false;
688
758
  }
689
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
+
690
779
  /**
691
780
  * `state.x = …`, `state.x += …`, `state.x++` — every form a string handler body can use to write a
692
781
  * state entry. `===`/`!==`/`<=`/`>=` are excluded by the `(?!=)` guard and by the operator set.
@@ -730,6 +819,25 @@ function movesState(read: string, at: number, bare: boolean): boolean {
730
819
  * @param options `bare` moves `state` alone too, not only `state.member`; `code: false` reads text
731
820
  * that is not a body (an attribute's template), where nothing is a string or a comment.
732
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
+
733
841
  export function rewriteState(
734
842
  text: string,
735
843
  to: string,
@@ -811,6 +919,36 @@ function collectAssignedStateKeys(node: JxDocumentValue | undefined, into: Set<s
811
919
  }
812
920
  }
813
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
+
814
952
  /**
815
953
  * Refuse a Function declaration that names both a `body` and a `$src` (spec.md §5.3 4d). The pair
816
954
  * has no meaning: each tier used to keep a different half, so a document that built in one target
@@ -934,14 +1072,37 @@ export function emitSrcImports(
934
1072
  return { imports: importLines, loaders };
935
1073
  }
936
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
+
937
1093
  /**
1094
+ * The build-time scope of a `state` block: what each entry holds before any handler has run.
1095
+ *
938
1096
  * @param {Record<string, JxStateDefinition>} [defs]
939
1097
  * @param {JxScope | null} [parentScope]
1098
+ * @param {BuildScopeOptions} [options]
940
1099
  * @returns {JxScope}
1100
+ * @docs framework/build
941
1101
  */
942
1102
  export function buildInitialScope(
943
1103
  defs: Record<string, JxStateDefinition> = {},
944
1104
  parentScope: JxScope | null = null,
1105
+ options: BuildScopeOptions = {},
945
1106
  ) {
946
1107
  const scope = emptyScope(parentScope);
947
1108
  // Keys whose real value only exists after hydration, so prerender must not interpolate them —
@@ -957,19 +1118,26 @@ export function buildInitialScope(
957
1118
  writable: true,
958
1119
  });
959
1120
 
960
- // Pass 0: every entry some handler in this document writes to is mutable, so prerender must not
961
- // Bake a binding over it. Narrow on purpose — an entry nothing ever writes stays bakeable, so
962
- // Prerendered content is preserved for SEO. A `$src` handler's assignments live in a JS file this
963
- // Builder cannot open, so a write that only happens there is still missed (issue #125).
964
- const assigned = new Set<string>();
965
- for (const def of Object.values(defs)) {
966
- if (isFunctionDef(def) || isExpressionDef(def)) {
967
- 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
+ }
968
1133
  }
969
- }
970
- for (const key of assigned) {
971
- if (key in defs) {
972
- 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
+ }
973
1141
  }
974
1142
  }
975
1143
 
@@ -1003,6 +1171,12 @@ export function buildInitialScope(
1003
1171
  // The scope as its already-evaluated *result*, so a template reading it sees an ordinary string
1004
1172
  // And prerender bakes it — destroying the binding rather than merely staling it (issue #124).
1005
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][] = [];
1006
1180
 
1007
1181
  for (const [key, def] of Object.entries(defs)) {
1008
1182
  if (isTemplateString(def)) {
@@ -1014,6 +1188,7 @@ export function buildInitialScope(
1014
1188
  }
1015
1189
  if (isExpressionDef(def)) {
1016
1190
  const node = def.$expression;
1191
+ entrySources.push([key, JSON.stringify(node)]);
1017
1192
  if (isNamedFormulaDef(def)) {
1018
1193
  // Named formula: callable, positional args mapped onto its declared parameters.
1019
1194
  const params: readonly FormulaParameter[] = def.parameters;
@@ -1044,6 +1219,7 @@ export function buildInitialScope(
1044
1219
  // Structured body (spec §20): a side-effecting handler in the build-time scope. Build-time
1045
1220
  // Code may call it bare, so the scope it runs against falls back to this one.
1046
1221
  const { body } = def;
1222
+ entrySources.push([key, JSON.stringify(body)]);
1047
1223
  setOwnScopeValue(scope, key, (s?: JxScope, event?: Event) => {
1048
1224
  void runStatements(body, s ?? scope, event ?? null);
1049
1225
  });
@@ -1061,6 +1237,7 @@ export function buildInitialScope(
1061
1237
  computedBodies.push([key, body]);
1062
1238
  } else {
1063
1239
  setOwnScopeValue(scope, key, fn);
1240
+ entrySources.push([key, body]);
1064
1241
  }
1065
1242
  } else {
1066
1243
  // Bodyless `$src` Function — the real implementation is only loaded in the browser, so this
@@ -1101,6 +1278,12 @@ export function buildInitialScope(
1101
1278
  marked = true;
1102
1279
  }
1103
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
+ }
1104
1287
  }
1105
1288
 
1106
1289
  for (const [key, template] of templateDefs) {
@@ -1171,8 +1354,9 @@ export function resolveRefValue(refValue: JsonValue | undefined, scope: JxScope)
1171
1354
  if (!isString(refValue)) {
1172
1355
  return refValue;
1173
1356
  }
1174
- if (refValue.startsWith("$map/")) {
1175
- const parts = refValue.split("/");
1357
+ const mapRef = canonicalMapRef(refValue);
1358
+ if (mapRef.startsWith("$map/")) {
1359
+ const parts = mapRef.split("/");
1176
1360
  const key = parts[1]!;
1177
1361
  /* SAFETY: `?.` stops at null and undefined, and every other value answers a member read by
1178
1362
  name; the member comes back as a scope member, so the view claims nothing about its type. */
@@ -1237,6 +1421,27 @@ function readsRuntimeOnlyState(str: string, scope: JxScope | null) {
1237
1421
  return false;
1238
1422
  }
1239
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
+
1240
1445
  /**
1241
1446
  * The JavaScript expression a Shape 3 template string compiles to (spec.md §5.3): the expression
1242
1447
  * itself, parenthesized, when the template is ONE expression, so it keeps its own type, and a
@@ -1268,11 +1473,22 @@ export function evaluateStaticTemplate(str: string, scope: JxScope | null) {
1268
1473
  * ReferenceError the catch below turned into a silent null. A `$head` title referencing the site
1269
1474
  * name reached the page as the literal template text.
1270
1475
  */
1271
- const args = ["state", "$map", "$site", "$page"] as const;
1476
+ const args = ["state", "$map", "$site", "$page"];
1272
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
+ }
1273
1489
  try {
1274
1490
  const body = isSingleExpression(str) ? `return (${str.slice(2, -1)})` : `return \`${str}\``;
1275
- /* 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
1276
1492
  template's value, which is whatever the scope it reads holds: one more scope member. */
1277
1493
  const fn = new Function(...args, body) as (...a: JxScope[string][]) => JxScope[string];
1278
1494
  return fn(...values);
@@ -1341,9 +1557,112 @@ export function inlineStyleDeclarations(
1341
1557
  .join("; ");
1342
1558
  }
1343
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
+
1344
1650
  /**
1345
1651
  * Build an HTML attribute string from a static element definition.
1346
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
+ *
1347
1666
  * @param {JxElement | JxMutableNode} def
1348
1667
  * @param {JxScope | null} scope
1349
1668
  * @param {string} [hostStyle] - Declarations resolved by the caller against ANOTHER scope, folded
@@ -1351,11 +1670,19 @@ export function inlineStyleDeclarations(
1351
1670
  * caller: its own `style` resolves against the parent's scope, while the definition's host style
1352
1671
  * resolves against the instance's, and an element cannot carry two `style` attributes.
1353
1672
  * @returns {string}
1673
+ * @docs framework/concepts/elements
1354
1674
  */
1355
1675
  export function buildAttrs(def: JxElement | JxMutableNode, scope: JxScope | null, hostStyle = "") {
1356
- 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;
1357
1681
 
1358
1682
  const id = resolveStaticValue(def.id, scope);
1683
+ if (id) {
1684
+ written.set("id", serializeAttr("id", String(id), false));
1685
+ }
1359
1686
  /* One `class` attribute, at the `className` position: the author's classes, then the style
1360
1687
  handle (spec.md §9.2). The author's are `attributes.class` when the element writes one, which
1361
1688
  is what the runtime leaves in effect, since it applies attributes after properties. */
@@ -1367,49 +1694,56 @@ export function buildAttrs(def: JxElement | JxMutableNode, scope: JxScope | null
1367
1694
  ]
1368
1695
  .filter((token) => token !== "")
1369
1696
  .join(" ");
1370
- const hidden = resolveStaticValue(def.hidden, scope);
1371
- const tabIndex = resolveStaticValue(def.tabIndex, scope);
1372
- const title = resolveStaticValue(def.title, scope);
1373
- const lang = resolveStaticValue(def.lang, scope);
1374
- const dir = resolveStaticValue(def.dir, scope);
1375
-
1376
- if (id) {
1377
- out += ` id="${escapeHtml(String(id))}"`;
1378
- }
1379
1697
  if (className) {
1380
- out += ` class="${escapeHtml(className)}"`;
1698
+ written.set("class", serializeAttr("class", className, false));
1381
1699
  }
1382
- if (hidden) {
1383
- out += " hidden";
1384
- }
1385
- if (tabIndex !== undefined && tabIndex !== null) {
1386
- out += ` tabindex="${escapeHtml(String(tabIndex))}"`;
1387
- }
1388
- if (title) {
1389
- out += ` title="${escapeHtml(String(title))}"`;
1390
- }
1391
- if (lang) {
1392
- out += ` lang="${escapeHtml(String(lang))}"`;
1700
+
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]);
1393
1728
  }
1394
- if (dir) {
1395
- out += ` dir="${escapeHtml(String(dir))}"`;
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]);
1396
1744
  }
1397
1745
 
1398
- // The host declarations go last: in one `style` attribute the later declaration of a property
1399
- // Wins, and the page walk gives the definition's resolved host style the same precedence over an
1400
- // Instance's own (`{ ...node.style, ...resolvedStyle }`), so the two paths agree.
1401
- const inline = [inlineStyleDeclarations(def.style, scope), hostStyle].filter(Boolean).join("; ");
1402
- if (inline) {
1403
- /*
1404
- * Escaped like every other attribute. Both halves carry values a template string resolved
1405
- * from data — a `background-image: url("…")` host style reads its target from a prop — and a
1406
- * `"` in that data would otherwise end the attribute and hand the rest of the value to the
1407
- * parser as attributes. The HTML parser decodes `&quot;` before the CSS parser sees the
1408
- * declaration, so `url(&quot;…&quot;)` renders exactly as `url("…")`, and `rewriteHtmlBase`
1409
- * already reads the entity-wrapped form back when it re-roots a `url()`.
1410
- */
1411
- out += ` style="${escapeHtml(inline)}"`;
1412
- }
1746
+ let rest = "";
1413
1747
  if (def.attributes) {
1414
1748
  for (const [k, v] of Object.entries(def.attributes)) {
1415
1749
  // Already written above, merged with the style handle.
@@ -1434,19 +1768,53 @@ export function buildAttrs(def: JxElement | JxMutableNode, scope: JxScope | null
1434
1768
  * Sidebar's own not-the-current-page marker, and second-guessing it would be this same defect
1435
1769
  * Pointed the other way.
1436
1770
  */
1771
+ let serialized: string | null = null;
1437
1772
  if (isBoolean(value)) {
1438
1773
  const text = booleanAttrValue(k, value);
1439
- if (text !== null) {
1440
- out += text === "" ? ` ${k}` : ` ${k}="${escapeHtml(text)}"`;
1441
- }
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)) {
1442
1782
  continue;
1443
1783
  }
1444
- if (isString(value) || isNumber(value)) {
1445
- 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;
1446
1791
  }
1792
+ rest += serialized ?? "";
1447
1793
  }
1448
1794
  }
1449
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
+
1450
1818
  if (def.$static) {
1451
1819
  out += ` data-jx-static`;
1452
1820
  } else if (def.$prerendered) {
@@ -1456,6 +1824,47 @@ export function buildAttrs(def: JxElement | JxMutableNode, scope: JxScope | null
1456
1824
  return out;
1457
1825
  }
1458
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
+
1459
1868
  /**
1460
1869
  * Tags rendered with `white-space: pre` by every UA, where inter-element whitespace is content
1461
1870
  * rather than formatting. Emitters indent nested children for readability; inside these tags — and
@@ -1483,7 +1892,7 @@ export function childSeparator(preformatted: boolean | undefined, indent = " ")
1483
1892
  export type InnerCompileContext = Omit<CompileContext, "scope"> & { scope: JxScope | null };
1484
1893
 
1485
1894
  /**
1486
- * 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.
1487
1896
  *
1488
1897
  * @param {JxElement} def
1489
1898
  * @param {JxElement | null} raw
@@ -1515,6 +1924,14 @@ export function buildInner(
1515
1924
  const value = resolveStaticValue(source.innerHTML, context.scope);
1516
1925
  return value == null ? "" : String(value);
1517
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
+ }
1518
1935
  if (Array.isArray(source.children)) {
1519
1936
  const rawChildren = raw?.children;
1520
1937
  return source.children
@@ -1542,6 +1959,12 @@ export function colorSchemePrePaintScript(): string {
1542
1959
  return `(function(){try{var s=localStorage.getItem(${key});if(s==="light"||s==="dark"){document.documentElement.setAttribute(${attr},s)}}catch(e){}})()`;
1543
1960
  }
1544
1961
 
1962
+ /**
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
+
1545
1968
  /**
1546
1969
  * Push the rules one style object becomes, scoped to `selector`: each rule's text, and above it the
1547
1970
  * comment a static build writes for a block that carries a `$description` (spec.md §9.2).
@@ -1559,14 +1982,17 @@ export function colorSchemePrePaintScript(): string {
1559
1982
  * @param {JxStyle} style
1560
1983
  * @param {string | null} selector - The scope, or null for a bare declaration-body at-rule
1561
1984
  * @param {Record<string, string>} mediaQueries
1985
+ * @param {StyleTreeOptions} [options] - Which tree the rules are written into
1562
1986
  */
1563
1987
  function pushStyleRules(
1564
1988
  rules: string[],
1565
1989
  style: JxStyle,
1566
1990
  selector: string | null,
1567
1991
  mediaQueries: Record<string, string>,
1992
+ options: StyleTreeOptions = {},
1568
1993
  ) {
1569
1994
  for (const rule of buildStyleRules(style, {
1995
+ ...options,
1570
1996
  mediaQueries,
1571
1997
  /* Records what a STATIC build drops, and returns `null` so it drops exactly as before — the
1572
1998
  emitted bytes are unchanged. A reactive declaration is a runtime declaration: it resolves
@@ -1661,6 +2087,275 @@ export function attrHelperSource(): string {
1661
2087
  );
1662
2088
  }
1663
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
+
1664
2359
  /** The name of the prop-supply helper an element module with a property bridge calls. */
1665
2360
  export const PROP_SUPPLY_HELPER = "__jxSupplies";
1666
2361
 
@@ -1741,7 +2436,7 @@ export function observedAttrHelperSource(): string {
1741
2436
 
1742
2437
  /** The state key an observed attribute writes: its name, camel-cased (spec.md §16.5). */
1743
2438
  function observedStateKey(name: string): string {
1744
- return name.replaceAll(/-([a-z])/g, (_: string, c: string) => c.toUpperCase());
2439
+ return attributeStateKey(name);
1745
2440
  }
1746
2441
 
1747
2442
  /**
@@ -1985,6 +2680,101 @@ export function emitExternalClassResolution(
1985
2680
  return lines.join("\n");
1986
2681
  }
1987
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
+
1988
2778
  /** The capture helper a light-DOM component module calls before its first render. */
1989
2779
  export const SLOT_CAPTURE_HELPER = "__jxCaptureSlotted";
1990
2780
 
@@ -2356,6 +3146,7 @@ export function authorClassValue(def: JxElement | JxMutableNode): JxDocumentValu
2356
3146
  * @param {{ n: number }} [counterArg]
2357
3147
  * @param {string} [prefix] - Names the sheet that holds the rules: `jx`, `jxs`, or a component's
2358
3148
  * tag
3149
+ * @param {{ shadowTree?: boolean }} [options] - Set `shadowTree` for nodes inside a shadow root
2359
3150
  */
2360
3151
  export function collectStyles(
2361
3152
  def: StyleScopeNode | string,
@@ -2364,11 +3155,18 @@ export function collectStyles(
2364
3155
  _parentSel = "",
2365
3156
  counterArg?: { n: number },
2366
3157
  prefix = "jx",
3158
+ options: Pick<StyleTreeOptions, "shadowTree"> = {},
2367
3159
  ) {
2368
3160
  const counter = counterArg ?? { n: 0 };
2369
3161
  walkStyleScopes(def, (node) => {
2370
3162
  if (node.style) {
2371
- pushStyleRules(rules, node.style, `.${handleFor(node, counter, prefix)}`, mediaQueries);
3163
+ pushStyleRules(
3164
+ rules,
3165
+ node.style,
3166
+ `.${handleFor(node, counter, prefix)}`,
3167
+ mediaQueries,
3168
+ options,
3169
+ );
2372
3170
  }
2373
3171
  });
2374
3172
  }
@@ -2563,6 +3361,13 @@ export interface ComponentPrerenderContext {
2563
3361
  * it; without one (a unit test, a definition preview) no instance is stamped or bracketed.
2564
3362
  */
2565
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;
2566
3371
  }
2567
3372
 
2568
3373
  /**
@@ -2608,7 +3413,7 @@ export function nextSlotId(context: ComponentPrerenderContext | null): number |
2608
3413
  export function createSlotFill(
2609
3414
  children: SlotChildren,
2610
3415
  scope: JxScope | null,
2611
- render: (child: StaticChild) => string,
3416
+ render: (child: StaticChild | JxMappedArray) => string,
2612
3417
  id: number | null = null,
2613
3418
  ): SlotFill {
2614
3419
  const groups: SlotFill["groups"] = new Map();
@@ -2623,8 +3428,8 @@ export function createSlotFill(
2623
3428
  }
2624
3429
  content = html !== "";
2625
3430
  } else if (isMappedArray(child)) {
2626
- // A repeater renders nothing statically; it is content all the same, as its rows will be.
2627
- html = "";
3431
+ // A repeater is content whether or not the build can render its rows, as its rows will be.
3432
+ html = render(child);
2628
3433
  } else if (!isNodeObject(child)) {
2629
3434
  html = render(child);
2630
3435
  content = html !== "";
@@ -2807,6 +3612,9 @@ export function observedAttributeProps(
2807
3612
  */
2808
3613
  export type ResolvedHostStyle = Record<string, JxScope[string]>;
2809
3614
 
3615
+ /** A definition's root attributes, resolved against one instance. */
3616
+ export type ResolvedHostAttributes = Record<string, JxAttributeValue>;
3617
+
2810
3618
  /**
2811
3619
  * The definition's host `style` entries that depend on the instance, resolved against it.
2812
3620
  *
@@ -2819,6 +3627,36 @@ export type ResolvedHostStyle = Record<string, JxScope[string]>;
2819
3627
  * @param {JxScope} scope - The instance's scope (`buildInstanceScope`)
2820
3628
  * @returns {ResolvedHostStyle}
2821
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
+
2822
3660
  export function resolveHostStyle(
2823
3661
  style: JxStyle | null | undefined,
2824
3662
  scope: JxScope,
@@ -2846,6 +3684,8 @@ export function resolveHostStyle(
2846
3684
  * @param {JxScope | null} scope
2847
3685
  * @param {SlotFill | null} slots
2848
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
2849
3689
  * @returns {string}
2850
3690
  */
2851
3691
  function renderInner(
@@ -2853,6 +3693,7 @@ function renderInner(
2853
3693
  scope: JxScope | null,
2854
3694
  slots: SlotFill | null,
2855
3695
  context: ComponentPrerenderContext | null,
3696
+ preformatted = false,
2856
3697
  ): string {
2857
3698
  if (node.textContent !== undefined) {
2858
3699
  const val = resolveStaticValue(node.textContent, scope);
@@ -2862,14 +3703,112 @@ function renderInner(
2862
3703
  const val = resolveStaticValue(node.innerHTML, scope);
2863
3704
  return val != null ? String(val) : node.innerHTML;
2864
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
+ }
2865
3715
  if (Array.isArray(node.children)) {
2866
3716
  return node.children
2867
- .map((c: JxElement | JxMutableNode | string) => renderStaticNode(c, scope, slots, context))
2868
- .join("\n");
3717
+ .map((c: JxElement | JxMutableNode | string) =>
3718
+ renderStaticNode(c, scope, slots, context, preformatted),
3719
+ )
3720
+ .join(preformatted ? "" : "\n");
2869
3721
  }
2870
3722
  return "";
2871
3723
  }
2872
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
+
2873
3812
  /**
2874
3813
  * A child slot as the static renderer meets it: a node or a text string, plus the JSON scalars,
2875
3814
  * holes and nested lists a hand-written `children` array may also carry.
@@ -2893,18 +3832,28 @@ export type StaticChild =
2893
3832
  * literal (a shadow root, or a definition rendered with no instance)
2894
3833
  * @param {ComponentPrerenderContext | null} [context] - The component registry, when a custom
2895
3834
  * element tag met here should be expanded rather than emitted bare
3835
+ * @param {boolean} [preformatted] - Inside a `<pre>`-like subtree (see `renderInner`)
2896
3836
  * @returns {string}
2897
3837
  */
2898
3838
  export function renderStaticNode(
2899
- node: StaticChild,
3839
+ node: StaticChild | JxMappedArray,
2900
3840
  scope: JxScope | null,
2901
3841
  slots: SlotFill | null = null,
2902
3842
  context: ComponentPrerenderContext | null = null,
3843
+ preformatted = false,
2903
3844
  ): string {
2904
3845
  if (isString(node)) {
2905
3846
  if (isTemplateString(node) && scope) {
2906
3847
  const val = evaluateStaticTemplate(node, scope);
2907
- 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);
2908
3857
  }
2909
3858
  return escapeHtml(node);
2910
3859
  }
@@ -2912,15 +3861,17 @@ export function renderStaticNode(
2912
3861
  return escapeHtml(String(node));
2913
3862
  }
2914
3863
  if (Array.isArray(node)) {
2915
- 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");
2916
3867
  }
2917
3868
  if (!isNonNullObject(node)) {
2918
3869
  return "";
2919
3870
  }
2920
3871
 
2921
- // Skip mapped arrays — can't pre-render dynamic lists
2922
- if (node.$prototype === "Array") {
2923
- 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);
2924
3875
  }
2925
3876
 
2926
3877
  // $switch/cases — resolve the key statically and render the matched case inside a container
@@ -2929,11 +3880,14 @@ export function renderStaticNode(
2929
3880
  if (node.$switch) {
2930
3881
  const switchTag = node.tagName ?? "div";
2931
3882
  const attrs = buildAttrs(node, scope);
2932
- 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);
2933
3887
  const caseDef = key == null ? undefined : node.cases?.[String(key)];
2934
3888
  const inner =
2935
3889
  caseDef !== undefined && !isRefObject(caseDef)
2936
- ? renderStaticNode(caseDef, scope, slots, context)
3890
+ ? renderStaticNode(caseDef, scope, slots, context, preformatted)
2937
3891
  : "";
2938
3892
  return `<${switchTag}${attrs}>${inner}</${switchTag}>`;
2939
3893
  }
@@ -2963,7 +3917,7 @@ export function renderStaticNode(
2963
3917
  takeSlotNames(node.children, scope, slots);
2964
3918
  return out;
2965
3919
  }
2966
- const fallback = renderInner(node, scope, slots, context);
3920
+ const fallback = renderInner(node, scope, slots, context, preformatted);
2967
3921
  return out === "" ? fallback : fallback === "" ? out : `${out}\n${fallback}`;
2968
3922
  }
2969
3923
 
@@ -2979,7 +3933,14 @@ export function renderStaticNode(
2979
3933
  return `<${tag}${attrs}>`;
2980
3934
  }
2981
3935
 
2982
- 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}>`;
2983
3944
  }
2984
3945
 
2985
3946
  /**
@@ -3059,10 +4020,11 @@ function renderComponentInstance(
3059
4020
 
3060
4021
  // The instance's children are the parent's nodes: parent scope, parent fill, parent path.
3061
4022
  const { children } = node;
3062
- const renderChild = (c: StaticChild) => renderStaticNode(c, scope, parentSlots, context);
4023
+ const renderChild = (c: StaticChild | JxMappedArray) =>
4024
+ renderStaticNode(c, scope, parentSlots, context);
3063
4025
 
3064
4026
  const shadow = resolveShadowMode(def, context.defaults);
3065
- const isStatic = isComponentFullyStatic(def);
4027
+ const isStatic = !isLiveComponent(tag, def, context.liveTags);
3066
4028
  const instanceScope = buildInstanceScope(def, hasScopeProps ? scopeProps : null);
3067
4029
  let innerHTML: string;
3068
4030
  let slotId: number | null = null;
@@ -3073,7 +4035,7 @@ function renderComponentInstance(
3073
4035
  : "";
3074
4036
  innerHTML =
3075
4037
  `<template shadowrootmode="${shadow}">` +
3076
- `<link rel="stylesheet" href="/components/${tag}.css">` +
4038
+ `<link rel="stylesheet" href="${componentStylesheetHref(tag)}">` +
3077
4039
  `${renderInner(def, instanceScope, null, nested)}</template>${light}`;
3078
4040
  } else {
3079
4041
  slotId = !isStatic && definitionHasSlot(def.children) ? nextSlotId(context) : null;
@@ -3090,8 +4052,12 @@ function renderComponentInstance(
3090
4052
  const instance = { ...node };
3091
4053
  delete instance.$props;
3092
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) };
3093
4057
  instance.attributes =
3094
- !isStatic && hasProps ? { ...attributes, "data-jx-props": JSON.stringify(props) } : attributes;
4058
+ !isStatic && hasProps
4059
+ ? { ...hostAttributes, "data-jx-props": JSON.stringify(props) }
4060
+ : hostAttributes;
3095
4061
  if (slotId !== null) {
3096
4062
  instance.attributes = { ...instance.attributes, [SLOT_ATTR]: String(slotId) };
3097
4063
  }
@@ -3124,11 +4090,163 @@ export function preRenderComponentHtml(
3124
4090
  return renderInner(doc, buildInstanceScope(doc, propsOverride), slots, context);
3125
4091
  }
3126
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
+
3127
4243
  /**
3128
4244
  * Check if a component definition is fully static (no runtime behavior needed).
3129
4245
  *
3130
4246
  * Returns true when: no event handlers, no $prototype entries (Functions, Request, Storage), no
3131
- * $ref values, and no observed attributes. 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.
3132
4250
  *
3133
4251
  * A definition that declares `observedAttributes` is never static (spec.md §16.5): declaring the
3134
4252
  * list is declaring a runtime interface, since every later change and removal of one must apply and
@@ -3149,7 +4267,7 @@ export function isComponentFullyStatic(doc: JxElement) {
3149
4267
  * @param {JxElement | string | (JxElement | string)[]} node
3150
4268
  * @returns {boolean}
3151
4269
  */
3152
- function _isStaticNode(node: JxElement | string | (JxElement | string)[]): boolean {
4270
+ function _isStaticNode(node: JxElement | JxMappedArray | string | (JxElement | string)[]): boolean {
3153
4271
  if (!isNonNullObject(node)) {
3154
4272
  return true;
3155
4273
  }
@@ -3157,10 +4275,26 @@ function _isStaticNode(node: JxElement | string | (JxElement | string)[]): boole
3157
4275
  return node.every((n) => _isStaticNode(n));
3158
4276
  }
3159
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
+ }
3160
4289
  // Check for $prototype (Functions, Request, Storage, etc.)
3161
4290
  if (node.$prototype) {
3162
4291
  return false;
3163
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
+ }
3164
4298
  // Check for $ref
3165
4299
  if (node.$ref) {
3166
4300
  return false;
@@ -3192,72 +4326,82 @@ function _isStaticNode(node: JxElement | string | (JxElement | string)[]): boole
3192
4326
  if (Array.isArray(node.children)) {
3193
4327
  return node.children.every((c) => _isStaticNode(c));
3194
4328
  }
3195
- // 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.
3196
4330
  if (isMappedArray(node.children)) {
3197
- return false;
4331
+ return _isStaticNode(node.children);
3198
4332
  }
3199
4333
 
3200
4334
  return true;
3201
4335
  }
3202
4336
 
3203
4337
  /**
3204
- * Generate CSS rules for a component: host-level styles using tag selector, plus inner element
3205
- * styles keyed on each element's generated `.<tagName>-<n>` class 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.
3206
4340
  *
3207
- * @param {string} tagName - The custom element tag name (used as CSS selector)
3208
- * @param {JxStyle | null} styleDef - The component's style object
3209
- * @param {JxElement | null} [doc] - The full component document (for walking children)
3210
- * @param {Record<string, string>} [mediaQueries] - Project media query definitions
3211
- * @returns {string} CSS text, or empty string if no styles
4341
+ * @param {string} tagName
4342
+ * @returns {string}
3212
4343
  */
3213
- /** `::slotted()` and `::part()` select through a shadow boundary, not the host that owns it. */
3214
- const SHADOW_STANDALONE = /^(?:::slotted\(|::part\()/;
4344
+ export function componentStylesheetHref(tagName: string): string {
4345
+ return `/components/${tagName}.css`;
4346
+ }
3215
4347
 
3216
4348
  /**
3217
- * 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.
3218
4351
  *
3219
- * Three shapes, and the interesting one is `:host`. A style object should mean the same thing in
3220
- * both modes, so `:host` and `:host(.foo)` are **translated** rather than passed through: inside a
3221
- * shadow root they stand alone, and in the light DOM they become the tag name and `<tag>.foo` —
3222
- * which is what "the host, matching this" means when there is no shadow root. Moving a component
3223
- * 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.
3224
4357
  *
3225
- * @param {string} prop - The style-object key, e.g. `":hover"`, `"& .inner"`, `":host(.wide)"`
3226
- * @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
3227
4362
  * @returns {string}
3228
4363
  */
3229
- function resolveSelector(prop: string, scope: string): string {
3230
- /* Member by member, for the reason css.ts's `resolveNestedSelector` does it: a key may be a
3231
- SELECTOR LIST, and splicing one as a single string spliced only its first `&`. `"& .a, & .b"`
3232
- came out as `sty-card .a, & .b`, and a raw `&` in a built stylesheet is not a nesting selector
3233
- at all — the browser discards the list and the component silently loses those rules. This is
3234
- the one selector path that does not go through the shared builder, because `:host` has to be
3235
- translated before the scope is applied, so it needed the same fix separately. */
3236
- return splitSelectorList(prop)
3237
- .map((member) => resolveSelectorMember(member, scope))
3238
- .join(", ");
3239
- }
3240
-
3241
- /** One member of {@link resolveSelector}'s list against the scope. */
3242
- function resolveSelectorMember(prop: string, scope: string): string {
3243
- const spliced = spliceNestingSelector(prop, scope);
3244
- if (spliced !== null) {
3245
- return spliced;
3246
- }
3247
- if (prop.startsWith(":host")) {
3248
- const inner = /^:host\((.*)\)$/.exec(prop)?.[1];
3249
- if (scope === ":host") {
3250
- 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);
3251
4381
  }
3252
- return inner === undefined ? scope : `${scope}${inner}`;
3253
- }
3254
- // `:host::slotted(x)` matches nothing — the pseudo-element attaches to a slot, not the host.
3255
- if (scope === ":host" && SHADOW_STANDALONE.test(prop)) {
3256
- return prop;
3257
- }
3258
- return `${scope}${prop}`;
4382
+ };
4383
+ visit(tag);
4384
+ return sheets.join("");
3259
4385
  }
3260
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
+ */
3261
4405
  export function buildComponentCSS(
3262
4406
  tagName: string,
3263
4407
  styleDef?: JxStyle | null | undefined,
@@ -3266,50 +4410,31 @@ export function buildComponentCSS(
3266
4410
  shadow: ShadowMode | null = null,
3267
4411
  ) {
3268
4412
  const rules: string[] = [];
3269
- /*
3270
- * The scope prefix. In light DOM it is the tag name, which is what keeps `sty-card .inner` from
3271
- * reaching another component's `.inner`. Inside a shadow root the selector cannot see the host's
3272
- * tag name at all, and `:host` is the standard's way to address it — so the same style object
3273
- * produces different, correct CSS in each mode without the author restating it.
3274
- */
3275
4413
  const scope = styleScopePrefix(tagName, shadow);
3276
-
3277
- if (isNonNullObject(styleDef)) {
3278
- /* The top level is walked here rather than handed straight to the builder, because ONE of its
3279
- keys does not mean what `resolveNestedSelector` would make of it: `:host` and `:host(.foo)`
3280
- are TRANSLATED per {@link resolveSelector} so a style object means the same thing in both
3281
- modes. Everything below the top level is ordinary nesting, so each block goes to the builder
3282
- whole — which is also what gives a component's nested selectors the recursion they never had
3283
- (this used to emit exactly one level and drop anything under it). */
3284
- const own: JxStyle = {};
3285
- const blocks: [string, JxStyle][] = [];
3286
- for (const [prop, value] of Object.entries(styleDef)) {
3287
- /* `isRef` first, and it is the whole point: an object carrying `$ref` is a reactive VALUE,
3288
- not a nested block (spec.md §9.1). Sorted into `blocks` it matched neither branch below —
3289
- not an at-rule, not a nested selector — and was dropped without reaching the builder at
3290
- all, so the one emitter that could have reported it never saw it. */
3291
- if (isRef(value)) {
3292
- own[prop] = value;
3293
- } else if (isNonNullObject(value) && !Array.isArray(value)) {
3294
- blocks.push([prop, value]);
3295
- } else if (!prop.startsWith("@") && !isNestedSelectorKey(prop)) {
3296
- own[prop] = value;
3297
- }
3298
- }
3299
- pushStyleRules(rules, own, scope, mediaQueries);
3300
- for (const [prop, val] of blocks) {
3301
- if (prop.startsWith("@")) {
3302
- pushStyleRules(rules, { [prop]: val }, scope, mediaQueries);
3303
- } else if (isNestedSelectorKey(prop)) {
3304
- pushStyleRules(rules, val, resolveSelector(prop, scope), mediaQueries);
3305
- }
3306
- }
3307
- }
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
+ );
3308
4431
 
3309
4432
  if (doc) {
3310
4433
  const counter = { n: 0 };
3311
4434
  for (const child of styleChildren(doc)) {
3312
- collectStyles(child, rules, mediaQueries, "", counter, tagName);
4435
+ collectStyles(child, rules, mediaQueries, "", counter, tagName, {
4436
+ shadowTree: shadow !== null,
4437
+ });
3313
4438
  }
3314
4439
  }
3315
4440