@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.
@@ -9,6 +9,10 @@
9
9
  *
10
10
  * Output pattern: HTML: pre-rendered with data-bind, :prop="key", @event="key" JS: state (reactive
11
11
  * state + computed signals), bind (DOM getters), on (event handlers), hydrate()
12
+ *
13
+ * A template string written as a text child has no element to carry a `data-bind`, so it is emitted
14
+ * between two comments, `<!--jx-text:_tN-->…<!--/jx-text-->`, and `hydrate()` keeps the text node
15
+ * after the opening comment current (compiler.md §2.2).
12
16
  */
13
17
 
14
18
  import {
@@ -21,6 +25,10 @@ import {
21
25
  ATTR_HELPER,
22
26
  refuseBodyWithSrc,
23
27
  attrHelperSource,
28
+ collectClientClasses,
29
+ emitExternalClassResolution,
30
+ externalClassHelperSource,
31
+ isClientExternalClass,
24
32
  booleanAttrValue,
25
33
  DEFAULT_LIT_HTML_SRC,
26
34
  DEFAULT_REACTIVITY_SRC,
@@ -47,6 +55,9 @@ import {
47
55
  collectFunctionImports,
48
56
  emitSrcImports,
49
57
  templateValueSource,
58
+ authorClassValue,
59
+ styleHandleOf,
60
+ writesMergedClass,
50
61
  } from "../shared.ts";
51
62
  import {
52
63
  hasStructuredBody,
@@ -64,7 +75,7 @@ import {
64
75
  isTagExpression,
65
76
  tagNameCandidates,
66
77
  } from "@jxsuite/schema/guards";
67
- import type { CompileContext, SrcImports } from "../shared.ts";
78
+ import type { ClientClasses, CompileContext, SrcImports } from "../shared.ts";
68
79
  import {
69
80
  escapeToken,
70
81
  objectKey,
@@ -81,6 +92,7 @@ import type {
81
92
  JxExpressionNode,
82
93
  JxMappedArray,
83
94
  JxMutableNode,
95
+ JxPrototypeDef,
84
96
  JxStyle,
85
97
  } from "@jxsuite/schema/types";
86
98
 
@@ -90,6 +102,34 @@ import type {
90
102
  */
91
103
  type RepeaterSlot = Omit<JxMappedArray, "items"> & { items?: JxMappedArray["items"] };
92
104
 
105
+ /**
106
+ * The key counters one compilation shares between the tree walker and the module emitter, and what
107
+ * the walker found that the module has to carry.
108
+ */
109
+ interface ClientCounter {
110
+ /** Inline event handlers (`_hN`). */
111
+ h: number;
112
+ /** Lit-rendered regions (`_listN`, `_childrenN`). */
113
+ l: number;
114
+ m: number;
115
+ /** Whether any region is rendered through lit-html. */
116
+ needsLit: boolean;
117
+ /** Bound style declarations (`_sN`). */
118
+ s: number;
119
+ /** `$switch` regions (`_swN`). */
120
+ sw: number;
121
+ /** Template bindings (`_tN`): `textContent`, attributes, properties and text children. */
122
+ t: number;
123
+ /** Whether any text child is bound between comment markers (compiler.md §2.2). */
124
+ textParts: boolean;
125
+ }
126
+
127
+ /**
128
+ * Elements whose content HTML parses as text, so a comment written there is rendered literally and
129
+ * cannot mark a bound text child.
130
+ */
131
+ const RAW_TEXT_TAGS = new Set(["script", "style", "textarea", "title"]);
132
+
93
133
  /** A compiled event handler entry: parameter names + function body. */
94
134
  interface HandlerDef {
95
135
  /** The parameters the body is built with: `state` first, then the event under some name. */
@@ -127,6 +167,11 @@ export function compileClient(
127
167
  * module, so the base has to be known when it is compiled.
128
168
  */
129
169
  serverBaseUrl?: string;
170
+ /**
171
+ * The URL a `timing: "client"` external class's module is served at (compiler.md §3, §12). Only
172
+ * a site build has one; without it such an entry is a compile error.
173
+ */
174
+ resolveClass?: (def: JxPrototypeDef) => string;
130
175
  },
131
176
  ) {
132
177
  const {
@@ -143,7 +188,16 @@ export function compileClient(
143
188
  const styleBlock = compileStyles(raw, raw.$media ?? {}, opts.projectStyle ?? null);
144
189
 
145
190
  // Collectors for bindings and handlers
146
- const counter = { h: 0, l: 0, m: 0, needsLit: false, s: 0, sw: 0, t: 0 };
191
+ const counter: ClientCounter = {
192
+ h: 0,
193
+ l: 0,
194
+ m: 0,
195
+ needsLit: false,
196
+ s: 0,
197
+ sw: 0,
198
+ t: 0,
199
+ textParts: false,
200
+ };
147
201
  const bindings = new Map<string, string>(); // Key → expression string
148
202
  const handlers = new Map<string, HandlerDef>(); // Key → { body, args }
149
203
 
@@ -156,6 +210,8 @@ export function compileClient(
156
210
  const serverCalls: string[] = []; // One block per `timing: "server"` entry, after the computed block
157
211
 
158
212
  const defs = raw.state ?? {};
213
+ // `timing: "client"` external classes: null until the module below resolves them (compiler.md §3)
214
+ const clientClasses = collectClientClasses(defs, opts.resolveClass);
159
215
  for (const [key, def] of Object.entries(defs)) {
160
216
  if (!isNonNullObject(def) || Array.isArray(def)) {
161
217
  // Naked primitive or array → reactive state
@@ -257,6 +313,11 @@ export function compileClient(
257
313
  initBlocks.push(emitCookieInit(key, def.name ?? key, def.default ?? null));
258
314
  continue;
259
315
  }
316
+
317
+ if (isClientExternalClass(def)) {
318
+ stateEntries.push([key, null]);
319
+ continue;
320
+ }
260
321
  }
261
322
 
262
323
  // `timing: "server"`: null until the site worker's route answers (compiler.md §6.1)
@@ -303,6 +364,7 @@ export function compileClient(
303
364
  counter,
304
365
  reactivitySrc,
305
366
  opts.rewriteSrc,
367
+ clientClasses,
306
368
  );
307
369
 
308
370
  // Build importmap entries — always include lit-html since compiled custom elements need it
@@ -349,15 +411,7 @@ ${importmapEntries.join(",\n")}
349
411
  * @param {CompileContext} context
350
412
  * @param {Map<string, string>} bindings
351
413
  * @param {Map<string, HandlerDef>} handlers
352
- * @param {{
353
- * t: number;
354
- * s: number;
355
- * h: number;
356
- * m: number;
357
- * sw: number;
358
- * l: number;
359
- * needsLit: boolean;
360
- * }} counter
414
+ * @param {ClientCounter} counter
361
415
  * @returns {string}
362
416
  */
363
417
  function buildClientNode(
@@ -365,19 +419,24 @@ function buildClientNode(
365
419
  context: CompileContext,
366
420
  bindings: Map<string, string>,
367
421
  handlers: Map<string, HandlerDef>,
368
- counter: {
369
- t: number;
370
- s: number;
371
- h: number;
372
- m: number;
373
- sw: number;
374
- l: number;
375
- needsLit: boolean;
376
- },
422
+ counter: ClientCounter,
377
423
  ) {
378
424
  // String children are text nodes
379
425
  if (isString(def)) {
380
- return escapeHtml(def);
426
+ if (!isTemplateString(def)) {
427
+ return escapeHtml(def);
428
+ }
429
+ /* A template text child is bound without a wrapper element (spec.md §8.4): the two comments
430
+ delimit the one text node the binding owns, so the separator after it and any text sibling
431
+ the parser would merge with it stay out. It holds whatever prerender can resolve, as a
432
+ bound `textContent` does. */
433
+ const key = `_t${counter.t}`;
434
+ counter.t += 1;
435
+ counter.textParts = true;
436
+ bindings.set(key, `() => \`${def}\``);
437
+ const value = resolveStaticValue(def, context.scope);
438
+ const text = value == null ? "" : escapeHtml(String(value));
439
+ return `<!--jx-text:${key}-->${text}<!--/jx-text-->`;
381
440
  }
382
441
  if (isNumber(def) || isBoolean(def)) {
383
442
  return escapeHtml(String(def));
@@ -500,6 +559,22 @@ function buildClientNode(
500
559
  // Dynamic attributes
501
560
  if (isNonNullObject(def.attributes)) {
502
561
  for (const [attr, val] of Object.entries(def.attributes)) {
562
+ const handle = attr === "class" ? styleHandleOf(def) : undefined;
563
+ if (handle !== undefined && (isRefObject(val) || isTemplateString(val))) {
564
+ /* A bound `class` attribute would replace the whole attribute and take the style handle
565
+ with it, so its binding joins the bound value and the handle. A key of its own: a ref's
566
+ shared key is also read by every other element binding the same ref. */
567
+ const key = `_t${counter.t}`;
568
+ counter.t += 1;
569
+ const source = isRefObject(val) ? stateRead(val.$ref) : `\`${val}\``;
570
+ bindAttrs.push(`:attr.class="${key}"`);
571
+ bindings.set(
572
+ key,
573
+ `() => [${source}, ${JSON.stringify(handle)}].filter((c) => c != null && c !== "").join(" ")`,
574
+ );
575
+ needsBind = true;
576
+ continue;
577
+ }
503
578
  if (isRefObject(val)) {
504
579
  const key = refToBindingKey(val.$ref);
505
580
  bindAttrs.push(`:attr.${attr}="${key}"`);
@@ -644,6 +719,12 @@ function buildClientNode(
644
719
  const bindAttrStr2 = ` ${bindAttrs.join(" ")}`;
645
720
  return `<${tag}${staticAttrs} data-bind${bindAttrStr2}></${tag}>`;
646
721
  } else if (Array.isArray(source.children)) {
722
+ if (RAW_TEXT_TAGS.has(tag) && source.children.some((c) => isTemplateString(c))) {
723
+ throw new Error(
724
+ `A template text child of <${tag}> cannot be bound: HTML reads its content as text. ` +
725
+ "Write it as the element's textContent.",
726
+ );
727
+ }
647
728
  inner = source.children
648
729
  .map((c) => buildClientNode(c, nextContext, bindings, handlers, counter))
649
730
  .join(childSeparator(nextContext.preformatted));
@@ -690,8 +771,21 @@ function emitLitMapTemplate(def: JxMutableNode | null | undefined, preformatted
690
771
  if (def.id) {
691
772
  attrs += ` id="${def.id}"`;
692
773
  }
693
- if (def.className) {
694
- attrs += ` class="${mapRefsToLit(def.className)}"`;
774
+ /* One `class` attribute: the author's classes, then the style handle the page sheet selects
775
+ (spec.md §9.2). The author's are `attributes.class` when the element writes one. */
776
+ const mergesClass = writesMergedClass(def);
777
+ if (mergesClass) {
778
+ const author = authorClassValue(def);
779
+ let authorText = "";
780
+ if (isRefObject(author)) {
781
+ authorText = `\${${mapRefToClientExpr(author.$ref)} ?? ""}`;
782
+ } else if (isString(author)) {
783
+ authorText = mapRefsToLit(author);
784
+ } else if (isNumber(author)) {
785
+ authorText = String(author);
786
+ }
787
+ const classText = [authorText, styleHandleOf(def) ?? ""].filter((t) => t !== "").join(" ");
788
+ attrs += ` class="${classText}"`;
695
789
  }
696
790
 
697
791
  // $props → lit property bindings. The element target emits these; the client target emitted
@@ -711,6 +805,10 @@ function emitLitMapTemplate(def: JxMutableNode | null | undefined, preformatted
711
805
  // Attributes object
712
806
  if (isNonNullObject(def.attributes)) {
713
807
  for (const [k, v] of Object.entries(def.attributes)) {
808
+ // Written once above, merged with the style handle.
809
+ if (mergesClass && k === "class") {
810
+ continue;
811
+ }
714
812
  if (isTemplateString(v)) {
715
813
  attrs += ` ${k}="${mapRefsToLit(v)}"`;
716
814
  continue;
@@ -732,7 +830,10 @@ function emitLitMapTemplate(def: JxMutableNode | null | undefined, preformatted
732
830
  }
733
831
  }
734
832
 
735
- // Style → inline CSS
833
+ /* Style → inline CSS, for templated declarations only. A literal declaration is a rule on the
834
+ element's handle in the page sheet (`collectStyles` walks row templates, `$switch` cases and
835
+ mixed children), and an inline copy would outweigh that rule's own `:hover` and `@media`
836
+ blocks, so none is written. */
736
837
  if (isNonNullObject(def.style)) {
737
838
  const parts: string[] = [];
738
839
  for (const [k, v] of Object.entries(def.style)) {
@@ -748,11 +849,8 @@ function emitLitMapTemplate(def: JxMutableNode | null | undefined, preformatted
748
849
  if (isNonDeclarationValue(v)) {
749
850
  continue;
750
851
  }
751
- const cssProp = camelToKebab(k);
752
852
  if (isTemplateString(String(v))) {
753
- parts.push(`${cssProp}: ${mapRefsToLit(String(v))}`);
754
- } else {
755
- parts.push(`${cssProp}: ${v}`);
853
+ parts.push(`${camelToKebab(k)}: ${mapRefsToLit(String(v))}`);
756
854
  }
757
855
  }
758
856
  if (parts.length > 0) {
@@ -910,15 +1008,7 @@ function bareMapRefsToLit(body: string): string {
910
1008
  * @param {string[]} initBlocks
911
1009
  * @param {string[]} serverCalls
912
1010
  * @param {SrcImports} srcImports
913
- * @param {{
914
- * t: number;
915
- * s: number;
916
- * h: number;
917
- * m: number;
918
- * sw: number;
919
- * l: number;
920
- * needsLit: boolean;
921
- * }} counter
1011
+ * @param {ClientCounter} counter
922
1012
  * @param {string} _reactivitySrc
923
1013
  * @returns {string}
924
1014
  */
@@ -930,20 +1020,13 @@ function emitClientModule(
930
1020
  initBlocks: string[],
931
1021
  serverCalls: string[],
932
1022
  srcImports: SrcImports,
933
- counter: {
934
- t: number;
935
- s: number;
936
- h: number;
937
- m: number;
938
- sw: number;
939
- l: number;
940
- needsLit: boolean;
941
- },
1023
+ counter: ClientCounter,
942
1024
  _reactivitySrc: string,
943
- rewriteSrc?: (specifier: string) => string,
1025
+ rewriteSrc: ((specifier: string) => string) | undefined,
1026
+ clientClasses: ClientClasses,
944
1027
  ) {
945
1028
  const lines: string[] = [];
946
- const { needsLit } = counter;
1029
+ const { needsLit, textParts } = counter;
947
1030
  const needsComputed = computedEntries.length > 0;
948
1031
 
949
1032
  lines.push("// Generated by @jxsuite/compiler — do not edit manually");
@@ -967,10 +1050,14 @@ function emitClientModule(
967
1050
  // State — reactive state
968
1051
  /* The boolean-attribute rule, inlined because this module loads with `@vue/reactivity` and
969
1052
  nothing else — see `attrHelperSource`. The hydration script below is its only caller. */
970
- lines.push(...src.imports, ...src.loaders, "", attrHelperSource());
1053
+ lines.push(...src.imports, ...clientClasses.imports, ...src.loaders, "", attrHelperSource());
971
1054
  if (serverCalls.length > 0) {
972
1055
  lines.push("", serverCallHelperSource());
973
1056
  }
1057
+ const waitsForClasses = clientClasses.entries.length > 0;
1058
+ if (waitsForClasses) {
1059
+ lines.push("", externalClassHelperSource(), "const _jxInstances = new Map();");
1060
+ }
974
1061
  lines.push("", "const state = reactive({");
975
1062
  for (const [key, val] of stateEntries) {
976
1063
  /*
@@ -1032,9 +1119,20 @@ function emitClientModule(
1032
1119
  lines.push("const on = {};");
1033
1120
  }
1034
1121
  // Hydration function
1122
+ lines.push("", "function hydrate(root) {");
1123
+ if (textParts) {
1124
+ /* Collected BEFORE the element pass, so a region lit renders during it is never walked. 128 is
1125
+ `NodeFilter.SHOW_COMMENT`, written as a literal so the module needs no further global. */
1126
+ lines.push(
1127
+ " const texts = [];",
1128
+ " const walker = document.createTreeWalker(root, 128);",
1129
+ " while (walker.nextNode()) {",
1130
+ " const c = walker.currentNode;",
1131
+ " if (c.data.startsWith('jx-text:') && c.data.slice(8) in bind) { texts.push(c); }",
1132
+ " }",
1133
+ );
1134
+ }
1035
1135
  lines.push(
1036
- "",
1037
- "function hydrate(root) {",
1038
1136
  " root.querySelectorAll('[data-bind]').forEach(el => {",
1039
1137
  " [...el.attributes].forEach(a => {",
1040
1138
  " if (a.name.startsWith(':')) {",
@@ -1070,11 +1168,35 @@ function emitClientModule(
1070
1168
  " }",
1071
1169
  " });",
1072
1170
  " });",
1073
- "}",
1074
- "",
1075
- "hydrate(document);",
1076
- "",
1077
1171
  );
1172
+ if (textParts) {
1173
+ // The prerendered text node is reused; an empty prerender has none, so one is put there.
1174
+ lines.push(
1175
+ " texts.forEach(c => {",
1176
+ " const key = c.data.slice(8);",
1177
+ " let text = c.nextSibling;",
1178
+ " if (!text || text.nodeType !== 3) {",
1179
+ " text = document.createTextNode('');",
1180
+ " c.after(text);",
1181
+ " }",
1182
+ " effect(() => { text.data = bind[key](); });",
1183
+ " });",
1184
+ );
1185
+ }
1186
+ lines.push("}", "");
1187
+ if (waitsForClasses) {
1188
+ /* Hydration waits for the classes: a binding that reads a class's value
1189
+ (`${state.forecast.days.length}`) then reads the value, as it does under the interpreter,
1190
+ which awaits every class before it renders. The prerendered page stays on screen meanwhile. */
1191
+ lines.push(
1192
+ `await ${emitExternalClassResolution(clientClasses.entries, {
1193
+ indent: "",
1194
+ instances: "_jxInstances",
1195
+ statePrefix: "state",
1196
+ })};`,
1197
+ );
1198
+ }
1199
+ lines.push("hydrate(document);", "");
1078
1200
 
1079
1201
  return lines.join("\n");
1080
1202
  }