@jxsuite/compiler 8.7.0 → 9.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/shared.ts CHANGED
@@ -21,8 +21,11 @@ import {
21
21
  SLOT_MARK,
22
22
  SLOT_RECORD_KEY,
23
23
  SLOT_WHITESPACE,
24
+ absorbAttribute,
24
25
  booleanAttrValue,
25
26
  buildStyleRules,
27
+ commentedRuleText,
28
+ declaredDefaults,
26
29
  enumeratedAttrNames,
27
30
  isNestedSelectorKey,
28
31
  camelToKebab,
@@ -39,6 +42,7 @@ import {
39
42
  isPureNamedFormula,
40
43
  } from "@jxsuite/runtime/expression";
41
44
  import { runStatements } from "@jxsuite/runtime/statements";
45
+ import { BUILT_IN_PROTOTYPES } from "@jxsuite/schema/defs";
42
46
  import { buildSiteStyleCSS } from "@jxsuite/site/site-style";
43
47
  import {
44
48
  childrenContainArray,
@@ -518,10 +522,18 @@ function withoutPureFormulas(def: JxElement | JxMutableNode): string {
518
522
  /**
519
523
  * Determine whether a node (or any of its descendants) requires client-side JavaScript.
520
524
  *
525
+ * A template string written as a text child counts, at any depth, exactly as a template in a
526
+ * property does (compiler.md §2.1, §2.2): the site build bakes every one it can before routing, so
527
+ * one that reaches here needs the client. A whole-`children` template string is not a text child
528
+ * and is not counted (spec.md §8.4 resolves it at build time only).
529
+ *
521
530
  * @param {JxElement | JxMutableNode | string} def
522
531
  * @returns {boolean}
523
532
  */
524
533
  export function isDynamic(def: JxElement | JxMutableNode | string) {
534
+ if (isString(def)) {
535
+ return isTemplateString(def);
536
+ }
525
537
  if (!isNonNullObject(def)) {
526
538
  return false;
527
539
  }
@@ -606,74 +618,6 @@ export function isDynamic(def: JxElement | JxMutableNode | string) {
606
618
  return false;
607
619
  }
608
620
 
609
- /**
610
- * Shallow variant of isDynamic — checks only this node's own properties, not its children.
611
- *
612
- * @param {JxElement | JxMutableNode | string} def
613
- * @returns {boolean}
614
- */
615
- export function isNodeDynamic(def: JxElement | JxMutableNode | string) {
616
- if (!isNonNullObject(def)) {
617
- return false;
618
- }
619
-
620
- if (def.$switch) {
621
- return true;
622
- }
623
- if (isMappedArray(def) || childrenContainArray(def.children)) {
624
- return true;
625
- }
626
-
627
- for (const [key, val] of Object.entries(def)) {
628
- if (RESERVED_KEYS.has(key)) {
629
- continue;
630
- }
631
- if (isRef(val)) {
632
- return true;
633
- }
634
- if (isTemplateString(val)) {
635
- return true;
636
- }
637
- }
638
-
639
- if (isNonNullObject(def.style)) {
640
- for (const val of Object.values(def.style)) {
641
- if (isTemplateString(val)) {
642
- return true;
643
- }
644
- }
645
- }
646
-
647
- if (isNonNullObject(def.attributes)) {
648
- for (const val of Object.values(def.attributes)) {
649
- if (isTemplateString(val)) {
650
- return true;
651
- }
652
- }
653
- }
654
-
655
- return false;
656
- }
657
-
658
- /**
659
- * Returns true if any node in the tree will need dynamic handling.
660
- *
661
- * @param {JxElement | JxMutableNode | string} def
662
- * @returns {boolean}
663
- */
664
- export function hasAnyIsland(def: JxElement | JxMutableNode | string): boolean {
665
- if (!isNonNullObject(def)) {
666
- return false;
667
- }
668
- if (isDynamic(def)) {
669
- return true;
670
- }
671
- if (Array.isArray(def.children)) {
672
- return def.children.some((c): boolean => hasAnyIsland(c));
673
- }
674
- return false;
675
- }
676
-
677
621
  // ─── Scope / value resolution ─────────────────────────────────────────────────
678
622
 
679
623
  /** What a compile target threads down the tree: the scope in effect, its definitions and `$media`. */
@@ -1137,6 +1081,10 @@ export function buildInitialScope(
1137
1081
  // A client-timing fetch has no build-time value at all — not even a placeholder.
1138
1082
  runtimeOnly.add(key);
1139
1083
  }
1084
+ if (isClientExternalClass(def)) {
1085
+ // Its value is whatever the class resolves to in the browser (compiler.md §3).
1086
+ runtimeOnly.add(key);
1087
+ }
1140
1088
  }
1141
1089
 
1142
1090
  // A state entry that reads a runtime-only key cannot resolve until hydration either, so it is
@@ -1408,7 +1356,17 @@ export function buildAttrs(def: JxElement | JxMutableNode, scope: JxScope | null
1408
1356
  let out = "";
1409
1357
 
1410
1358
  const id = resolveStaticValue(def.id, scope);
1411
- const className = resolveStaticValue(def.className, scope);
1359
+ /* One `class` attribute, at the `className` position: the author's classes, then the style
1360
+ handle (spec.md §9.2). The author's are `attributes.class` when the element writes one, which
1361
+ is what the runtime leaves in effect, since it applies attributes after properties. */
1362
+ const mergesClass = writesMergedClass(def);
1363
+ const authorClass = mergesClass ? resolveStaticValue(authorClassValue(def), scope) : null;
1364
+ const className = [
1365
+ isString(authorClass) || isNumber(authorClass) ? String(authorClass) : "",
1366
+ styleHandleOf(def) ?? "",
1367
+ ]
1368
+ .filter((token) => token !== "")
1369
+ .join(" ");
1412
1370
  const hidden = resolveStaticValue(def.hidden, scope);
1413
1371
  const tabIndex = resolveStaticValue(def.tabIndex, scope);
1414
1372
  const title = resolveStaticValue(def.title, scope);
@@ -1419,7 +1377,7 @@ export function buildAttrs(def: JxElement | JxMutableNode, scope: JxScope | null
1419
1377
  out += ` id="${escapeHtml(String(id))}"`;
1420
1378
  }
1421
1379
  if (className) {
1422
- out += ` class="${escapeHtml(String(className))}"`;
1380
+ out += ` class="${escapeHtml(className)}"`;
1423
1381
  }
1424
1382
  if (hidden) {
1425
1383
  out += " hidden";
@@ -1454,6 +1412,10 @@ export function buildAttrs(def: JxElement | JxMutableNode, scope: JxScope | null
1454
1412
  }
1455
1413
  if (def.attributes) {
1456
1414
  for (const [k, v] of Object.entries(def.attributes)) {
1415
+ // Already written above, merged with the style handle.
1416
+ if (mergesClass && k === "class") {
1417
+ continue;
1418
+ }
1457
1419
  const value = resolveStaticValue(v, scope);
1458
1420
  /*
1459
1421
  * A boolean is the attribute's PRESENCE or its text, depending on which family HTML puts the
@@ -1581,7 +1543,8 @@ export function colorSchemePrePaintScript(): string {
1581
1543
  }
1582
1544
 
1583
1545
  /**
1584
- * Push the rules one style object becomes, scoped to `selector`.
1546
+ * Push the rules one style object becomes, scoped to `selector`: each rule's text, and above it the
1547
+ * comment a static build writes for a block that carries a `$description` (spec.md §9.2).
1585
1548
  *
1586
1549
  * The single door from the compiler to `buildStyleRules`, which is now the ONE definition of what a
1587
1550
  * Jx style object means as CSS — shared with the DOM runtime and the site-style builder. Three
@@ -1613,7 +1576,7 @@ function pushStyleRules(
1613
1576
  resolveValue: (property, value) => recordDroppedReactive(property, value, selector),
1614
1577
  scope: selector,
1615
1578
  })) {
1616
- rules.push(rule.text);
1579
+ rules.push(commentedRuleText(rule));
1617
1580
  }
1618
1581
  }
1619
1582
 
@@ -1698,6 +1661,123 @@ export function attrHelperSource(): string {
1698
1661
  );
1699
1662
  }
1700
1663
 
1664
+ /** The name of the prop-supply helper an element module with a property bridge calls. */
1665
+ export const PROP_SUPPLY_HELPER = "__jxSupplies";
1666
+
1667
+ /** The name of the helper that finds the platform's own setter for a bridged key. */
1668
+ export const NATIVE_SETTER_HELPER = "__jxNativeSetter";
1669
+
1670
+ /**
1671
+ * The property bridge's two rules as source for a generated element module (compiler.md §4.4),
1672
+ * inlined for the reason {@link attrHelperSource} gives.
1673
+ *
1674
+ * `__jxSupplies` restates `instanceSupplies` from `@jxsuite/runtime` line for line, the rule
1675
+ * spec.md §13.2 states: an instance carries a prop when it has an own property of that name, an
1676
+ * attribute of that name, or the kebab attribute a camelCase reflection writes. The rule is logic
1677
+ * rather than data, so its guard is behavioural: `compile-element-render.test.ts` runs this source
1678
+ * and the runtime's export over one input matrix.
1679
+ *
1680
+ * `__jxNativeSetter` is the walk the interpreter's accessor makes for a key the platform already
1681
+ * owns (spec.md §16.2): the first descriptor of that name on the prototype chain, whose setter the
1682
+ * forwarding accessor calls before it writes state, so `title` and `hidden` still reflect.
1683
+ *
1684
+ * @returns {string} Two `function` declarations, ready to push into a module's line list.
1685
+ */
1686
+ export function propSupplyHelperSource(): string {
1687
+ return [
1688
+ `function ${PROP_SUPPLY_HELPER}(el, k) {`,
1689
+ " if (Object.hasOwn(el, k)) return true;",
1690
+ " if (el.hasAttribute(k)) return true;",
1691
+ " const kebab = k.replace(/[A-Z]/g, (c) => '-' + c.toLowerCase());",
1692
+ " return kebab !== k && el.hasAttribute(kebab);",
1693
+ "}",
1694
+ `function ${NATIVE_SETTER_HELPER}(el, k) {`,
1695
+ " for (let p = Object.getPrototypeOf(el); p; p = Object.getPrototypeOf(p)) {",
1696
+ " const d = Object.getOwnPropertyDescriptor(p, k);",
1697
+ " if (d) return d.set;",
1698
+ " }",
1699
+ " return undefined;",
1700
+ "}",
1701
+ ].join("\n");
1702
+ }
1703
+
1704
+ /** The name of the observed-attribute helper an element module that observes any calls. */
1705
+ export const OBSERVED_ATTR_HELPER = "__jxAbsorbAttr";
1706
+
1707
+ /**
1708
+ * The observed-attribute rule (spec.md §16.5) as source for a generated element module:
1709
+ * `absorbAttribute` from `@jxsuite/runtime`, restated line for line and inlined for the reason
1710
+ * {@link attrHelperSource} gives. The key is the attribute's name camel-cased; a computed entry
1711
+ * (present in the defaults with `undefined`) is never written; a boolean is presence, with the text
1712
+ * `false` counting as absent; a removal restores the declared default, or falls back by the type of
1713
+ * the value held; a number parses and anything else is the string.
1714
+ *
1715
+ * The rule is logic, so its guard is behavioural: `observed-attr-agreement.test.ts` runs this
1716
+ * source and the runtime's export over one matrix of held type, attribute value and default. The
1717
+ * defaults a module passes are not re-derived either: they are `declaredDefaults`' output for the
1718
+ * observed keys, serialized ({@link observedDefaultsSource}).
1719
+ *
1720
+ * @returns {string} One `function` declaration, ready to push into a module's line list.
1721
+ */
1722
+ export function observedAttrHelperSource(): string {
1723
+ return [
1724
+ `function ${OBSERVED_ATTR_HELPER}(state, name, value, defaults) {`,
1725
+ " const key = name.replace(/-([a-z])/g, (_, c) => c.toUpperCase());",
1726
+ " if (defaults && defaults.has(key) && defaults.get(key) === undefined) return;",
1727
+ " const current = state[key];",
1728
+ " if (typeof current === 'boolean') {",
1729
+ " state[key] = value !== null && value !== 'false';",
1730
+ " return;",
1731
+ " }",
1732
+ " if (value === null) {",
1733
+ " const declared = defaults ? defaults.get(key) : undefined;",
1734
+ " state[key] = declared === undefined ? (typeof current === 'number' ? 0 : '') : declared;",
1735
+ " return;",
1736
+ " }",
1737
+ " state[key] = typeof current === 'number' ? Number(value) : value;",
1738
+ "}",
1739
+ ].join("\n");
1740
+ }
1741
+
1742
+ /** The state key an observed attribute writes: its name, camel-cased (spec.md §16.5). */
1743
+ function observedStateKey(name: string): string {
1744
+ return name.replaceAll(/-([a-z])/g, (_: string, c: string) => c.toUpperCase());
1745
+ }
1746
+
1747
+ /**
1748
+ * The names a definition observes: its `observedAttributes`, when that is an array, less anything
1749
+ * in it that is not a string.
1750
+ *
1751
+ * @param {JxElement | JxDocument} def
1752
+ * @returns {string[]}
1753
+ */
1754
+ export function observedAttributeNames(def: JxElement | JxDocument): string[] {
1755
+ const { observedAttributes: observed } = def;
1756
+ return Array.isArray(observed) ? observed.filter((name) => isString(name)) : [];
1757
+ }
1758
+
1759
+ /**
1760
+ * The declared defaults of a definition's observed keys as the source of a `new Map([...])`
1761
+ * expression: the runtime's `declaredDefaults(def)`, kept to the observed keys and serialized. A
1762
+ * `Map`, because an object literal would give a `__proto__` key meaning. A computed entry is
1763
+ * written as `undefined`, which JSON cannot spell and which is how the rule knows never to write
1764
+ * it. The module evaluates the expression per use, so an object default is a fresh copy for each
1765
+ * removal rather than one object every instance then mutates.
1766
+ *
1767
+ * @param {JxElement | JxDocument} def
1768
+ * @returns {string}
1769
+ */
1770
+ export function observedDefaultsSource(def: JxElement | JxDocument): string {
1771
+ const defaults = declaredDefaults(def);
1772
+ const keys = new Set(observedAttributeNames(def).map((name) => observedStateKey(name)));
1773
+ const pairs = [...defaults].flatMap(([key, value]) =>
1774
+ keys.has(key)
1775
+ ? [`[${JSON.stringify(key)}, ${value === undefined ? "undefined" : JSON.stringify(value)}]`]
1776
+ : [],
1777
+ );
1778
+ return `new Map([${pairs.join(", ")}])`;
1779
+ }
1780
+
1701
1781
  /** The name of the call helper a module holding a `timing: "server"` entry declares once. */
1702
1782
  export const SERVER_CALL_HELPER = "__jxServerCall";
1703
1783
 
@@ -1731,6 +1811,180 @@ export function serverCallHelperSource(): string {
1731
1811
  ].join("\n");
1732
1812
  }
1733
1813
 
1814
+ // ─── External classes (compiler.md §3) ────────────────────────────────────────
1815
+
1816
+ /**
1817
+ * The keys the prototype system owns on a state entry, stripped before the rest is handed to an
1818
+ * external class as its config (spec.md §12.3). One list for the build-time resolver and both
1819
+ * compile targets, so a class is constructed with the same config at either timing.
1820
+ */
1821
+ export const EXTERNAL_CONFIG_RESERVED: ReadonlySet<string> = new Set([
1822
+ "$prototype",
1823
+ "$src",
1824
+ "$export",
1825
+ "timing",
1826
+ "default",
1827
+ "description",
1828
+ ]);
1829
+
1830
+ /** An external class's config as its state entry wrote it: any keys, document values. */
1831
+ export type ExternalClassEntryConfig = Record<string, JxDocumentValue>;
1832
+
1833
+ /**
1834
+ * The config an external class is constructed with: the entry's own keys minus the reserved ones,
1835
+ * values as written.
1836
+ *
1837
+ * @param {JxPrototypeDef} def
1838
+ * @returns {ExternalClassEntryConfig}
1839
+ */
1840
+ export function externalClassConfig(def: JxPrototypeDef) {
1841
+ const config: ExternalClassEntryConfig = {};
1842
+ for (const [key, value] of Object.entries(def)) {
1843
+ if (!EXTERNAL_CONFIG_RESERVED.has(key) && value !== undefined) {
1844
+ config[key] = value;
1845
+ }
1846
+ }
1847
+ return config;
1848
+ }
1849
+
1850
+ const BUILT_IN_PROTOTYPE_NAMES: ReadonlySet<string> = new Set(BUILT_IN_PROTOTYPES);
1851
+
1852
+ /**
1853
+ * Whether a state entry names an external class: a `$prototype` that is not one of the built-ins
1854
+ * (spec.md §12), which always mean the built-in.
1855
+ */
1856
+ export function isExternalClassDef(def: unknown): def is JxPrototypeDef {
1857
+ return isPrototypeDef(def) && !BUILT_IN_PROTOTYPE_NAMES.has(def.$prototype);
1858
+ }
1859
+
1860
+ /**
1861
+ * Whether a state entry is an external class the compiled page or element constructs in the
1862
+ * browser. Only an explicit `timing: "client"` is: an entry with no `timing` is resolved during the
1863
+ * build. This is the one predicate that decides what hydrates.
1864
+ */
1865
+ export function isClientExternalClass(def: unknown): def is JxPrototypeDef {
1866
+ return isExternalClassDef(def) && def.timing === "client";
1867
+ }
1868
+
1869
+ /** The name of the helper a module holding a `timing: "client"` external class declares once. */
1870
+ export const EXTERNAL_CLASS_HELPER = "__jxInstantiate";
1871
+
1872
+ /**
1873
+ * The external class contract (spec.md §12.3) as source for a generated module's preamble, inlined
1874
+ * for the reason {@link attrHelperSource} gives: construct the class with its config, then take
1875
+ * `resolve()` when the instance has one, else `value` when it has that, else the instance. It
1876
+ * answers with the value and the instance, which the caller keeps for `subscribe`.
1877
+ *
1878
+ * The order is `instantiateAndResolve`'s (`site/external-class.ts`), the build-time half of the
1879
+ * same rule, and `external-class-hydration.test.ts` runs this source and that export over one
1880
+ * matrix of class shapes.
1881
+ *
1882
+ * @returns {string} One `async function` declaration.
1883
+ */
1884
+ export function externalClassHelperSource(): string {
1885
+ return [
1886
+ `async function ${EXTERNAL_CLASS_HELPER}(C, name, config) {`,
1887
+ " if (typeof C !== 'function') throw new TypeError('Jx: \"' + name + '\" is not a class');",
1888
+ " const i = new C(config);",
1889
+ " const v = typeof i.resolve === 'function' ? await i.resolve() : 'value' in i ? i.value : i;",
1890
+ " return [v, i];",
1891
+ "}",
1892
+ ].join("\n");
1893
+ }
1894
+
1895
+ /** One `timing: "client"` external class of a document, as a compile target emits it. */
1896
+ export interface ClientClassEntry {
1897
+ /** The state key the class's value is written to. */
1898
+ key: string;
1899
+ /** The module-level name its class is imported under. */
1900
+ binding: string;
1901
+ /** The class's name as the entry wrote it, for diagnostics. */
1902
+ name: string;
1903
+ /** What the class is constructed with ({@link externalClassConfig}). */
1904
+ config: ExternalClassEntryConfig;
1905
+ }
1906
+
1907
+ /** A document's client classes, and the import each distinct class module needs. */
1908
+ export interface ClientClasses {
1909
+ entries: ClientClassEntry[];
1910
+ imports: string[];
1911
+ }
1912
+
1913
+ /**
1914
+ * Collect a document's `timing: "client"` external classes and the imports their modules need, one
1915
+ * default import per distinct module URL.
1916
+ *
1917
+ * `resolveClass` answers the URL a class's module is served at, and only a site build has one: it
1918
+ * is what bundles the module (compiler.md §12). Without it a client class cannot be delivered, so
1919
+ * the compile fails and names the entry.
1920
+ *
1921
+ * @param {Record<string, JxStateDefinition>} defs
1922
+ * @param {((def: JxPrototypeDef) => string) | undefined} resolveClass
1923
+ * @returns {ClientClasses}
1924
+ */
1925
+ export function collectClientClasses(
1926
+ defs: Record<string, JxStateDefinition>,
1927
+ resolveClass?: (def: JxPrototypeDef) => string,
1928
+ ): ClientClasses {
1929
+ const entries: ClientClassEntry[] = [];
1930
+ const bindings = new Map<string, string>();
1931
+ for (const [key, def] of Object.entries(defs)) {
1932
+ if (!isClientExternalClass(def)) {
1933
+ continue;
1934
+ }
1935
+ if (resolveClass === undefined) {
1936
+ throw new Error(
1937
+ `"${key}": external class "${def.$prototype}" with timing "client" compiles only in a site build`,
1938
+ );
1939
+ }
1940
+ const url = resolveClass(def);
1941
+ let binding = bindings.get(url);
1942
+ if (binding === undefined) {
1943
+ binding = `_JxClass${bindings.size}`;
1944
+ bindings.set(url, binding);
1945
+ }
1946
+ entries.push({ binding, config: externalClassConfig(def), key, name: def.$prototype });
1947
+ }
1948
+ return {
1949
+ entries,
1950
+ imports: [...bindings].map(([url, binding]) => `import ${binding} from '${url}';`),
1951
+ };
1952
+ }
1953
+
1954
+ /**
1955
+ * The expression that constructs and resolves every client class of a document: a `Promise.all`
1956
+ * that settles once each entry has its value in state, or has failed.
1957
+ *
1958
+ * Each entry writes its value to state, records its instance under its state key in `instances` (a
1959
+ * `Map`, where a teardown finds what it subscribed to), and follows `subscribe` when the class
1960
+ * offers one. A class that fails to construct or resolve is logged and its entry stays `null`, so
1961
+ * one failing class does not keep the rest of the page from hydrating.
1962
+ *
1963
+ * @param {ClientClassEntry[]} entries
1964
+ * @param {{ statePrefix: string; instances: string; indent: string }} opts
1965
+ * @returns {string}
1966
+ */
1967
+ export function emitExternalClassResolution(
1968
+ entries: readonly ClientClassEntry[],
1969
+ opts: { statePrefix: string; instances: string; indent: string },
1970
+ ): string {
1971
+ const { indent, instances, statePrefix } = opts;
1972
+ const lines = ["Promise.all(["];
1973
+ for (const { binding, config, key, name } of entries) {
1974
+ const target = refAccessor(statePrefix, escapeToken(key));
1975
+ const label = JSON.stringify(key);
1976
+ lines.push(
1977
+ `${indent} ${EXTERNAL_CLASS_HELPER}(${binding}, ${JSON.stringify(name)}, ${JSON.stringify(config)}).then(([v, i]) => {`,
1978
+ `${indent} ${target} = v;`,
1979
+ `${indent} ${instances}.set(${label}, i);`,
1980
+ `${indent} if (typeof i.subscribe === 'function') i.subscribe((n) => { ${target} = n; });`,
1981
+ `${indent} }).catch((e) => { console.error(${JSON.stringify(`Jx: external class "${key}" failed`)}, e); }),`,
1982
+ );
1983
+ }
1984
+ lines.push(`${indent}])`);
1985
+ return lines.join("\n");
1986
+ }
1987
+
1734
1988
  /** The capture helper a light-DOM component module calls before its first render. */
1735
1989
  export const SLOT_CAPTURE_HELPER = "__jxCaptureSlotted";
1736
1990
 
@@ -1917,6 +2171,8 @@ export function compileStyles(
1917
2171
  mediaQueries,
1918
2172
  (value) => value,
1919
2173
  recordDroppedReactive,
2174
+ undefined,
2175
+ { comments: true },
1920
2176
  );
1921
2177
  if (projectSheet !== "") {
1922
2178
  rules.push(projectSheet);
@@ -1944,14 +2200,165 @@ export function escapeStyleText(css: string): string {
1944
2200
  }
1945
2201
 
1946
2202
  /**
1947
- * @param {JxElement | JxMutableNode | string} def
2203
+ * Where a style pass keeps the handle it gave a node. A symbol, because `className` is author data
2204
+ * that may be a `$ref` or a template and is never written; an assigned symbol-keyed property is
2205
+ * enumerable, so it survives the object spreads the prerender and the element target make, and it
2206
+ * stays out of `JSON.stringify` (`data-jx-props`, emitted documents). `structuredClone` would drop
2207
+ * it: a pass that deep-clones a node between a style pass and an emitter must carry it over.
2208
+ */
2209
+ const STYLE_HANDLE = Symbol("jx.styleHandle");
2210
+
2211
+ /** A node as a style pass leaves it. */
2212
+ interface Handled {
2213
+ [STYLE_HANDLE]?: string;
2214
+ }
2215
+
2216
+ /** A node a style pass walks: an element, or a repeater standing among its children. */
2217
+ type StyleScopeNode = JxElement | JxMutableNode | JxMappedArray;
2218
+
2219
+ /**
2220
+ * The generated class a style pass gave `node`, without its dot, or `undefined` for a node no pass
2221
+ * has handled. The class selects that element and nothing else (for a repeater's item template, the
2222
+ * rows it renders), and its static rules are keyed on it (spec.md §9.2).
2223
+ *
2224
+ * @param {StyleScopeNode} node
2225
+ * @returns {string | undefined}
2226
+ * @docs framework/concepts/styling
2227
+ */
2228
+ export function styleHandleOf(node: StyleScopeNode): string | undefined {
2229
+ /* SAFETY: `STYLE_HANDLE` is module-private and `handleFor` is its only writer, which always
2230
+ stores a string under it; a node no pass has walked answers undefined. */
2231
+ return (node as Handled)[STYLE_HANDLE];
2232
+ }
2233
+
2234
+ /**
2235
+ * The handle of `def`, minted on first use. Idempotent: a node keeps the first handle any pass
2236
+ * gives it, because one object can be walked by two passes that must agree (the element module's
2237
+ * stamping pass and the page sheet, in `compile()`'s custom-element route).
2238
+ */
2239
+ function handleFor(def: JxElement | JxMutableNode, counter: { n: number }, prefix: string): string {
2240
+ const existing = styleHandleOf(def);
2241
+ if (existing !== undefined) {
2242
+ return existing;
2243
+ }
2244
+ const handle = `${prefix}-${counter.n}`;
2245
+ counter.n += 1;
2246
+ /* SAFETY: the same private slot `styleHandleOf` reads; no declared member of a node is touched. */
2247
+ (def as Handled)[STYLE_HANDLE] = handle;
2248
+ return handle;
2249
+ }
2250
+
2251
+ /**
2252
+ * The members a style pass descends into from `def`: an array `children`, or the repeater itself
2253
+ * when `children` is one (the legacy whole-children form).
2254
+ *
2255
+ * @param {JxElement | JxMutableNode} def
2256
+ * @returns {(StyleScopeNode | string)[]}
2257
+ */
2258
+ export function styleChildren(def: JxElement | JxMutableNode): (StyleScopeNode | string)[] {
2259
+ const { children } = def;
2260
+ if (Array.isArray(children)) {
2261
+ return children;
2262
+ }
2263
+ return isMappedArray(children) ? [children] : [];
2264
+ }
2265
+
2266
+ /**
2267
+ * The one traversal every style pass makes, so the sheet and each emitter number the same nodes in
2268
+ * the same order. Pre-order: the node, its children in order with a repeater's `map` template at
2269
+ * the repeater's position, then its `$switch` cases. A repeater is not itself an element, so only
2270
+ * its template is visited, and one with no template is skipped.
2271
+ */
2272
+ function walkStyleScopes(
2273
+ def: StyleScopeNode | string,
2274
+ visit: (node: JxElement | JxMutableNode) => void,
2275
+ ): void {
2276
+ if (!isNonNullObject(def)) {
2277
+ return;
2278
+ }
2279
+ if (isMappedArray(def)) {
2280
+ if (def.map) {
2281
+ walkStyleScopes(def.map, visit);
2282
+ }
2283
+ return;
2284
+ }
2285
+ visit(def);
2286
+ for (const child of styleChildren(def)) {
2287
+ walkStyleScopes(child, visit);
2288
+ }
2289
+ // $switch case nodes render in place of the container's content — walk them too
2290
+ if (isNonNullObject(def.cases)) {
2291
+ for (const c of Object.values<JxElement | JxMutableNode>(def.cases)) {
2292
+ walkStyleScopes(c, visit);
2293
+ }
2294
+ }
2295
+ }
2296
+
2297
+ /**
2298
+ * Give every node under `def` that carries a `style` object its handle, without building a rule.
2299
+ * The element target stamps its template with this: its sheet is `buildComponentCSS`'s, and
2300
+ * building the rules a second time would record each dropped reactive declaration twice.
2301
+ *
2302
+ * @param {StyleScopeNode | string} def
2303
+ * @param {{ n: number }} counter
2304
+ * @param {string} prefix - Names the sheet that holds the rules: `jx`, `jxs`, or a component's tag
2305
+ */
2306
+ export function assignStyleHandles(
2307
+ def: StyleScopeNode | string,
2308
+ counter: { n: number },
2309
+ prefix: string,
2310
+ ): void {
2311
+ walkStyleScopes(def, (node) => {
2312
+ if (node.style) {
2313
+ handleFor(node, counter, prefix);
2314
+ }
2315
+ });
2316
+ }
2317
+
2318
+ /**
2319
+ * Whether an emitter writes this element's `class` attribute once, merged: it has a style handle or
2320
+ * a `className`. An element with neither keeps whatever `attributes.class` it writes, where and how
2321
+ * it always was.
2322
+ *
2323
+ * @param {JxElement | JxMutableNode} def
2324
+ * @returns {boolean}
2325
+ */
2326
+ export function writesMergedClass(def: JxElement | JxMutableNode): boolean {
2327
+ return styleHandleOf(def) !== undefined || Boolean(def.className);
2328
+ }
2329
+
2330
+ /**
2331
+ * The author's own classes for an element: `attributes.class` when the element writes one, else
2332
+ * `className`. The runtime applies attributes after properties, so that is the value it leaves in
2333
+ * effect, and the compiled emitters follow it.
2334
+ *
2335
+ * @param {JxElement | JxMutableNode} def
2336
+ * @returns {JxDocumentValue | undefined} A string, a `$ref`, or whatever the document holds there
2337
+ */
2338
+ export function authorClassValue(def: JxElement | JxMutableNode): JxDocumentValue | undefined {
2339
+ const { attributes } = def;
2340
+ return isNonNullObject(attributes) && Object.hasOwn(attributes, "class")
2341
+ ? attributes.class
2342
+ : def.className;
2343
+ }
2344
+
2345
+ /**
2346
+ * Collect the static rules of every styled node under `def`, each keyed on a generated class of the
2347
+ * node's own (spec.md §9.2): never an author's class, which every other element carrying it would
2348
+ * share, and never an `id`, whose rule would outweigh the runtime's (0,1,0) handle and make a built
2349
+ * page cascade differently from its preview. A repeater's item template gets one handle its rows
2350
+ * share. The class reaches markup through `styleHandleOf`, which every emitter reads.
2351
+ *
2352
+ * @param {StyleScopeNode | string} def
1948
2353
  * @param {string[]} rules
1949
2354
  * @param {Record<string, string>} mediaQueries
1950
2355
  * @param {string} [_parentSel]
1951
- * @param {{ n: number }} [counter]
2356
+ * @param {{ n: number }} [counterArg]
2357
+ * @param {string} [prefix] - Names the sheet that holds the rules: `jx`, `jxs`, or a component's
2358
+ * tag
1952
2359
  */
1953
2360
  export function collectStyles(
1954
- def: JxElement | JxMutableNode | string,
2361
+ def: StyleScopeNode | string,
1955
2362
  rules: string[],
1956
2363
  mediaQueries: Record<string, string>,
1957
2364
  _parentSel = "",
@@ -1959,42 +2366,11 @@ export function collectStyles(
1959
2366
  prefix = "jx",
1960
2367
  ) {
1961
2368
  const counter = counterArg ?? { n: 0 };
1962
- if (!isNonNullObject(def)) {
1963
- return;
1964
- }
1965
-
1966
- if (def.style && !def.id && !def.className) {
1967
- def.className = `${prefix}-${counter.n}`;
1968
- counter.n += 1;
1969
- }
1970
-
1971
- /* A chosen tag needs a selector that matches every candidate, not the first one.
1972
- `#id` and `.class` are unaffected — they identify the element regardless of what it turns out
1973
- to be — but a bare tag selector has to become the union, or styling an `<a>|<div>` wrapper
1974
- would style exactly one of the two branches and silently miss the other. */
1975
- const tagSelector = tagNameCandidates(def.tagName).join(", ") || "*";
1976
- const selector = def.id
1977
- ? `#${def.id}`
1978
- : def.className
1979
- ? `.${def.className.split(" ")[0]}`
1980
- : tagSelector;
1981
-
1982
- if (def.style) {
1983
- pushStyleRules(rules, def.style, selector, mediaQueries);
1984
- }
1985
-
1986
- if (Array.isArray(def.children)) {
1987
- for (const c of def.children) {
1988
- collectStyles(c, rules, mediaQueries, selector, counter, prefix);
1989
- }
1990
- }
1991
-
1992
- // $switch case nodes render in place of the container's content — collect their styles too
1993
- if (isNonNullObject(def.cases)) {
1994
- for (const c of Object.values<JxElement | JxMutableNode>(def.cases)) {
1995
- collectStyles(c, rules, mediaQueries, selector, counter, prefix);
2369
+ walkStyleScopes(def, (node) => {
2370
+ if (node.style) {
2371
+ pushStyleRules(rules, node.style, `.${handleFor(node, counter, prefix)}`, mediaQueries);
1996
2372
  }
1997
- }
2373
+ });
1998
2374
  }
1999
2375
 
2000
2376
  // ─── Utilities ────────────────────────────────────────────────────────────────
@@ -2040,7 +2416,8 @@ export function tagNameToClassName(tagName: string) {
2040
2416
  }
2041
2417
 
2042
2418
  /**
2043
- * Recursively collect unique $src values from $prototype: "Function" entries.
2419
+ * Recursively collect unique $src values from $prototype: "Function" entries. The site build asks
2420
+ * it whether a page still loads a module whose state reads it cannot see.
2044
2421
  *
2045
2422
  * @param {JxElement} doc
2046
2423
  * @returns {string[]}
@@ -2373,6 +2750,57 @@ export function buildInstanceScope(
2373
2750
  return buildInitialScope(stateDefs, null);
2374
2751
  }
2375
2752
 
2753
+ /**
2754
+ * The props an instance's observed attributes amount to at build time (spec.md §16.5), or null when
2755
+ * it writes none: what the element's own first-connection read would put into state, so the
2756
+ * prerender shows it on the first paint.
2757
+ *
2758
+ * Each observed attribute the instance writes with a statically resolvable value is turned into the
2759
+ * attribute text `buildAttrs` would emit for it (a boolean through `booleanAttrValue`, where null
2760
+ * means the attribute is absent), then coerced by the runtime's own `absorbAttribute` against the
2761
+ * definition's build-time scope and its declared defaults, so a computed entry is skipped here as
2762
+ * it is in the browser. The caller lays the result UNDER the instance's `$props`, which is the
2763
+ * order the element applies, and never writes it into `data-jx-props`: the module reads the
2764
+ * attribute itself, and a prop there would outrank a later attribute change on the first
2765
+ * connection.
2766
+ *
2767
+ * @param {JxElement} def - The component definition
2768
+ * @param {JxElement["attributes"]} attributes - The instance's attributes, `props.*` already lifted
2769
+ * @param {JxScope | null} scope - The scope the instance's attribute values resolve against
2770
+ * @returns {Record<string, JsonValue> | null}
2771
+ */
2772
+ export function observedAttributeProps(
2773
+ def: JxElement,
2774
+ attributes: JxElement["attributes"],
2775
+ scope: JxScope | null,
2776
+ ): Record<string, JsonValue> | null {
2777
+ const names = observedAttributeNames(def).filter((name) => Object.hasOwn(attributes ?? {}, name));
2778
+ if (!attributes || names.length === 0) {
2779
+ return null;
2780
+ }
2781
+ const defaults = declaredDefaults(def);
2782
+ const scratch = buildInstanceScope(def, null);
2783
+ let out: Record<string, JsonValue> | null = null;
2784
+ for (const name of names) {
2785
+ const value = resolveStaticValue(attributes[name], scope);
2786
+ let text: string | null = null;
2787
+ if (isBoolean(value)) {
2788
+ text = booleanAttrValue(name, value);
2789
+ } else if (isString(value) || isNumber(value)) {
2790
+ text = String(value);
2791
+ }
2792
+ const key = observedStateKey(name);
2793
+ if (text === null || (defaults.has(key) && defaults.get(key) === undefined)) {
2794
+ continue;
2795
+ }
2796
+ absorbAttribute(scratch, name, text, defaults);
2797
+ out ??= {};
2798
+ /* SAFETY: `absorbAttribute` has just written this key with a boolean, a number or the string. */
2799
+ out[key] = scratch[key] as JsonValue;
2800
+ }
2801
+ return out;
2802
+ }
2803
+
2376
2804
  /**
2377
2805
  * Resolved host declarations by (camelCase) property: each is what its template read from the
2378
2806
  * instance's scope.
@@ -2560,7 +2988,8 @@ export function renderStaticNode(
2560
2988
  *
2561
2989
  * - Props: `props.*` attributes lifted, then `$props`; a template value resolves against the PARENT's
2562
2990
  * scope, which is what `resolveDocTemplates` does for a page-level instance before the page walk
2563
- * reaches it.
2991
+ * reaches it. Beneath them, the instance's observed attributes, coerced (spec.md §16.5), which
2992
+ * feed the scope and the path but never `data-jx-props`.
2564
2993
  * - Slot content: the instance's own children, rendered in the parent's scope and with the parent's
2565
2994
  * fill, so a `<slot>` written among them passes the grandparent's group of that name through, and
2566
2995
  * placed in the definition's slots by name (`createSlotFill`, spec.md §8.5). A live instance
@@ -2605,9 +3034,14 @@ function renderComponentInstance(
2605
3034
  props[key] = (resolveStaticValue(value, scope) as JsonValue | null) ?? value;
2606
3035
  }
2607
3036
  const hasProps = Object.keys(props).length > 0;
3037
+ /* What the instance's scope is built from: its observed attributes, coerced, with its props over
3038
+ them (spec.md §16.5). It is the instance's identity on the path too (spec.md §16.9), so two
3039
+ nested instances of one tag told apart only by an observed attribute are two instances. */
3040
+ const scopeProps = { ...observedAttributeProps(def, attributes, scope), ...props };
3041
+ const hasScopeProps = Object.keys(scopeProps).length > 0;
2608
3042
 
2609
3043
  const path = context.path ?? [];
2610
- const frame: PrerenderFrame = { key: JSON.stringify(props), tag };
3044
+ const frame: PrerenderFrame = { key: JSON.stringify(scopeProps), tag };
2611
3045
  const chain = [...path.map((f) => f.tag), tag].join(" → ");
2612
3046
  if (path.some((f) => f.tag === frame.tag && f.key === frame.key)) {
2613
3047
  throw new Error(
@@ -2629,7 +3063,7 @@ function renderComponentInstance(
2629
3063
 
2630
3064
  const shadow = resolveShadowMode(def, context.defaults);
2631
3065
  const isStatic = isComponentFullyStatic(def);
2632
- const instanceScope = buildInstanceScope(def, hasProps ? props : null);
3066
+ const instanceScope = buildInstanceScope(def, hasScopeProps ? scopeProps : null);
2633
3067
  let innerHTML: string;
2634
3068
  let slotId: number | null = null;
2635
3069
  if (shadow) {
@@ -2694,12 +3128,20 @@ export function preRenderComponentHtml(
2694
3128
  * Check if a component definition is fully static (no runtime behavior needed).
2695
3129
  *
2696
3130
  * Returns true when: no event handlers, no $prototype entries (Functions, Request, Storage), no
2697
- * $ref values. Conservative — returns false when uncertain.
3131
+ * $ref values, and no observed attributes. Conservative — returns false when uncertain.
3132
+ *
3133
+ * A definition that declares `observedAttributes` is never static (spec.md §16.5): declaring the
3134
+ * list is declaring a runtime interface, since every later change and removal of one must apply and
3135
+ * only the element's module can hear it. Asked of the root alone, the only place the list is
3136
+ * declared.
2698
3137
  *
2699
3138
  * @param {JxElement} doc - Component JSON definition
2700
3139
  * @returns {boolean}
2701
3140
  */
2702
3141
  export function isComponentFullyStatic(doc: JxElement) {
3142
+ if (observedAttributeNames(doc).length > 0) {
3143
+ return false;
3144
+ }
2703
3145
  return _isStaticNode(doc);
2704
3146
  }
2705
3147
 
@@ -2760,7 +3202,7 @@ function _isStaticNode(node: JxElement | string | (JxElement | string)[]): boole
2760
3202
 
2761
3203
  /**
2762
3204
  * Generate CSS rules for a component: host-level styles using tag selector, plus inner element
2763
- * styles using .jx-N selectors via collectStyles.
3205
+ * styles keyed on each element's generated `.<tagName>-<n>` class via collectStyles.
2764
3206
  *
2765
3207
  * @param {string} tagName - The custom element tag name (used as CSS selector)
2766
3208
  * @param {JxStyle | null} styleDef - The component's style object
@@ -2864,9 +3306,9 @@ export function buildComponentCSS(
2864
3306
  }
2865
3307
  }
2866
3308
 
2867
- if (doc && Array.isArray(doc.children)) {
3309
+ if (doc) {
2868
3310
  const counter = { n: 0 };
2869
- for (const child of doc.children) {
3311
+ for (const child of styleChildren(doc)) {
2870
3312
  collectStyles(child, rules, mediaQueries, "", counter, tagName);
2871
3313
  }
2872
3314
  }