@yannosay/sinth 0.13.0 → 0.13.2

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.
@@ -2,440 +2,23 @@ import * as path from "path";
2
2
  import * as fs from "fs";
3
3
  import { Loc, Literal, Expression, Child, Attr, CompUse, IfBlock, ForLoop, RemoveStmt, ReturnStmt, StyleBlock, CompDef, ParamDecl, VarDeclaration, SinthFile, CompileCtx, MixedBlockEntry, SinthError, SinthWarning, TT, AssignStmt, MetaEntry } from "./types.ts";
4
4
  import { Parser } from "./parser.ts";
5
- import { fnv1a, camelToKebab, esc, escAttr, litToString, tagNameToPascal } from "../utils.ts";
5
+ import { fnv1a, camelToKebab, esc, escAttr, litToString, tagNameToPascal, interpolateAttr, renderText } from "../utils.ts";
6
6
  import { compileExprToJS, compileIfToJS, bodyToJS } from "./expr.ts";
7
7
  import { FunctionDef } from "./types.ts";
8
8
  import { parseFile, resolveImports, ResolverConfig, ResolvedImports } from "../resolver.ts";
9
+ import { compileFunctionDef } from "./runtime/functions.ts";
10
+ import { generateHelpers } from "./runtime/helpers.ts";
11
+ import { buildRenderBody } from "./runtime/render.ts";
12
+ import { BUILTIN_MAP, VOID_TAGS, BuiltinInfo } from "./builtins.ts";
13
+ import { processStyleBlock } from "./style-processor.ts";
14
+ import { buildHeadData, renderHead, HeadData } from "./head-builder.ts";
9
15
 
10
16
 
11
-
12
-
13
- export interface BuiltinInfo { tag: string; defaultClass?: string; voidEl?: boolean }
14
-
15
- export const BUILTIN_MAP: Record<string, BuiltinInfo> = {
16
- // structural
17
- Main: { tag: "main" },
18
- Header: { tag: "header" },
19
- Footer: { tag: "footer" },
20
- Nav: { tag: "nav" },
21
- Section: { tag: "section" },
22
- Article: { tag: "article" },
23
- Aside: { tag: "aside" },
24
- Div: { tag: "div" },
25
- Span: { tag: "span" },
26
- Hero: { tag: "section", defaultClass: "hero" },
27
- Container: { tag: "div", defaultClass: "container" },
28
- Grid: { tag: "div", defaultClass: "grid" },
29
- Flex: { tag: "div", defaultClass: "flex" },
30
- Stack: { tag: "div", defaultClass: "stack" },
31
- Row: { tag: "div", defaultClass: "row" },
32
- Column: { tag: "div", defaultClass: "col" },
33
- CardGrid: { tag: "div", defaultClass: "card-grid" },
34
- // typography
35
- Heading: { tag: "h1" },
36
- SubHeading: { tag: "p", defaultClass: "subheading" },
37
- Paragraph: { tag: "p" },
38
- Lead: { tag: "p", defaultClass: "lead" },
39
- Small: { tag: "small" },
40
- Strong: { tag: "strong" },
41
- Em: { tag: "em" },
42
- Code: { tag: "code" },
43
- Pre: { tag: "pre" },
44
- Blockquote: { tag: "blockquote" },
45
- Mark: { tag: "mark" },
46
- Label: { tag: "label" },
47
- Abbr: { tag: "abbr" },
48
- Del: { tag: "del" },
49
- Ins: { tag: "ins" },
50
- Sub: { tag: "sub" },
51
- Sup: { tag: "sup" },
52
- Data: { tag: "data" },
53
- Time: { tag: "time" },
54
- Bdi: { tag: "bdi" },
55
- Bdo: { tag: "bdo" },
56
- Cite: { tag: "cite" },
57
- Dfn: { tag: "dfn" },
58
- Kbd: { tag: "kbd" },
59
- Samp: { tag: "samp" },
60
- Var: { tag: "var" },
61
- Address: { tag: "address" },
62
- Ruby: { tag: "ruby" },
63
- Rt: { tag: "rt" },
64
- Rp: { tag: "rp" },
65
- // interactive
66
- Button: { tag: "button" },
67
- Link: { tag: "a" },
68
- NavLink: { tag: "a" },
69
- Select: { tag: "select" },
70
- Form: { tag: "form" },
71
- Fieldset: { tag: "fieldset" },
72
- Legend: { tag: "legend" },
73
- Details: { tag: "details" },
74
- Summary: { tag: "summary" },
75
- Dialog: { tag: "dialog" },
76
- Textarea: { tag: "textarea" },
77
- Datalist: { tag: "datalist" },
78
- Optgroup: { tag: "optgroup" },
79
- Option: { tag: "option" },
80
- Progress: { tag: "progress" },
81
- Meter: { tag: "meter" },
82
- Output: { tag: "output" },
83
- Map: { tag: "map" },
84
- // media
85
- Picture: { tag: "picture" },
86
- Video: { tag: "video" },
87
- Audio: { tag: "audio" },
88
- Figure: { tag: "figure" },
89
- Figcaption: { tag: "figcaption" },
90
- Canvas: { tag: "canvas" },
91
- Svg: { tag: "svg" },
92
- IFrame: { tag: "iframe" },
93
- Object: { tag: "object" },
94
- // void elements
95
- Img: { tag: "img", voidEl: true },
96
- Logo: { tag: "img", voidEl: true },
97
- Input: { tag: "input", voidEl: true },
98
- Checkbox: { tag: "input", voidEl: true },
99
- Hr: { tag: "hr", voidEl: true },
100
- Br: { tag: "br", voidEl: true },
101
- Wbr: { tag: "wbr", voidEl: true },
102
- Source: { tag: "source", voidEl: true },
103
- Embed: { tag: "embed", voidEl: true },
104
- Col: { tag: "col", voidEl: true },
105
- Area: { tag: "area", voidEl: true },
106
- // lists
107
- Ul: { tag: "ul" }, Ol: { tag: "ol" }, Li: { tag: "li" },
108
- Dl: { tag: "dl" }, Dt: { tag: "dt" }, Dd: { tag: "dd" },
109
- // tables
110
- Table: { tag: "table" },
111
- Caption: { tag: "caption" },
112
- Thead: { tag: "thead" },
113
- Tbody: { tag: "tbody" },
114
- Tfoot: { tag: "tfoot" },
115
- Tr: { tag: "tr" },
116
- Th: { tag: "th" },
117
- Td: { tag: "td" },
118
- Colgroup: { tag: "colgroup" },
119
- // utility
120
- Template: { tag: "template" },
121
- Slot: { tag: "slot" },
122
- NoScript: { tag: "noscript" },
123
- RawHTML: { tag: "__RAW__" },
124
- };
125
-
126
- export const VOID_TAGS = new Set([
127
- "area","base","br","col","embed","hr","img","input",
128
- "link","meta","param","source","track","wbr",
129
- ]);
130
-
131
17
  const EVENT_RE = /^on[A-Z]/;
132
18
  function eventAttrName(name: string): string | null {
133
19
  return EVENT_RE.test(name) ? name.toLowerCase() : null;
134
20
  }
135
21
 
136
- // preprocessor
137
-
138
- /**
139
- * for who's reading this: This maps Sinth Style pseudo-class shorthand keywords to real CSS pseudo-classes.
140
- * these are used inside component style blocks, for example: onHover { color: "blue" }
141
- */
142
- export const SINTH_PSEUDO_CLASS: Record<string, string> = {
143
- onHover: ":hover",
144
- onFocus: ":focus",
145
- onActive: ":active",
146
- onVisited: ":visited",
147
- onChecked: ":checked",
148
- onDisabled: ":disabled",
149
- onEnabled: ":enabled",
150
- onRequired: ":required",
151
- onOptional: ":optional",
152
- onValid: ":valid",
153
- onInvalid: ":invalid",
154
- onPlaceholderShown:":placeholder-shown",
155
- onFocusWithin: ":focus-within",
156
- onFocusVisible: ":focus-visible",
157
- onFirst: ":first-child",
158
- onLast: ":last-child",
159
- onFirstOfType: ":first-of-type",
160
- onLastOfType: ":last-of-type",
161
- onEmpty: ":empty",
162
- onTarget: ":target",
163
- onLink: ":link",
164
- };
165
-
166
- export const SINTH_PSEUDO_ELEMENT: Record<string, string> = {
167
- before: "::before",
168
- after: "::after",
169
- placeholder: "::placeholder",
170
- selection: "::selection",
171
- firstLine: "::first-line",
172
- firstLetter: "::first-letter",
173
- marker: "::marker",
174
- backdrop: "::backdrop",
175
- };
176
-
177
- export function sinthCompToSelector(name: string): string {
178
- const info = BUILTIN_MAP[name];
179
- if (!info) return name.toLowerCase();
180
- if (info.defaultClass) {
181
- const classes = info.defaultClass.split(" ").map(c => `.${c}`).join("");
182
- return `${info.tag}${classes}`;
183
- }
184
- return info.tag;
185
- }
186
-
187
- /**
188
- * supported conversions:
189
- * - component names as selectors: `Paragraph { ... }` → `p { ... }`
190
- * - pseudo-class shorthands: `onHover { ... }` → `&:hover { ... }`
191
- * - pseudo-element shorthands: `before { ... }` → `&::before { ... }`
192
- * - media queries: `media(maxWidth: "600px") { ... }` → `@media (max-width: 600px) { ... }`
193
- * - CSS custom properties: `var --primary: "#3b82f6"` → `--primary: #3b82f6;`
194
- */
195
- export function preprocessSinthStyle(raw: string): string {
196
- const lines = raw.split("\n");
197
- const result: string[] = [];
198
-
199
- for (const line of lines) {
200
- const trimmed = line.trim();
201
- const indent = line.match(/^(\s*)/)?.[1] ?? "";
202
-
203
- if (!trimmed) { result.push(line); continue; }
204
-
205
- if (trimmed.startsWith("--") && !trimmed.startsWith("--[")) { continue; }
206
- // Standard comments pass through
207
- if (trimmed.startsWith("//") || trimmed.startsWith("/*") || trimmed.startsWith("*")) {
208
- result.push(line); continue;
209
- }
210
-
211
- const mediaMatch = trimmed.match(/^media\s*\(([^)]+)\)\s*(\{?\s*)$/);
212
- if (mediaMatch) {
213
- const params = parseSinthMediaParams(mediaMatch[1]);
214
- result.push(`${indent}@media (${params}) {`);
215
- continue;
216
- }
217
-
218
- const blockMatch = trimmed.match(/^([a-zA-Z][a-zA-Z0-9]*)(\s*\{\s*)$/);
219
- if (blockMatch) {
220
- const keyword = blockMatch[1];
221
-
222
- const pseudoCls = SINTH_PSEUDO_CLASS[keyword];
223
- if (pseudoCls) {
224
- result.push(`${indent}&${pseudoCls} {`);
225
- continue;
226
- }
227
-
228
- const pseudoEl = SINTH_PSEUDO_ELEMENT[keyword];
229
- if (pseudoEl) {
230
- result.push(`${indent}&${pseudoEl} {`);
231
- continue;
232
- }
233
-
234
- if (/^[A-Z]/.test(keyword) && BUILTIN_MAP[keyword]) {
235
- result.push(`${indent}${sinthCompToSelector(keyword)} {`);
236
- continue;
237
- }
238
- }
239
-
240
- const varPropMatch = trimmed.match(/^var\s+(--[a-zA-Z][a-zA-Z0-9-]*)\s*:\s*["']?([^"';]+)["']?\s*;?\s*$/);
241
- if (varPropMatch) {
242
- result.push(`${indent}${varPropMatch[1]}: ${varPropMatch[2].trim()};`);
243
- continue;
244
- }
245
-
246
- result.push(line);
247
- }
248
-
249
- return result.join("\n");
250
- }
251
-
252
- export function parseSinthMediaParams(params: string): string {
253
- const parts = params.split(",").map(p => {
254
- const m = p.trim().match(/^([a-zA-Z]+)\s*:\s*["']?([^"',]+)["']?\s*$/);
255
- if (!m) return p.trim();
256
- return `${camelToKebab(m[1])}: ${m[2].trim()}`;
257
- });
258
- return parts.join(") and (");
259
- }
260
-
261
- // style processor
262
-
263
-
264
- export function convertCSSProps(css: string): string {
265
- return css.split("\n").map(line => {
266
- const trimmed = line.trim();
267
- if (!trimmed) return line;
268
- if (trimmed === "}" || trimmed.startsWith("}")) return line;
269
- if (trimmed.startsWith("//") || trimmed.startsWith("/*") || trimmed.startsWith("*")) return line;
270
- if (trimmed.startsWith("@")) return line;
271
- if (trimmed.includes("{")) return line;
272
-
273
- const m = line.match(/^(\s*)([a-zA-Z][a-zA-Z0-9-]*)(\s*:\s*)(.+?)(\s*;?\s*)$/);
274
- if (!m) return line;
275
-
276
- const [, indent, rawProp, , rawVal] = m;
277
-
278
- const hasCamelCase = /[a-z][A-Z]/.test(rawProp) || /^[A-Z]/.test(rawProp);
279
- const hasQuotedVal = /^["']/.test(rawVal.trim());
280
- if (!hasCamelCase && !hasQuotedVal) return line;
281
-
282
- let val = rawVal.trim();
283
- if (val.endsWith(";")) val = val.slice(0, -1).trimEnd();
284
- if ((val.startsWith('"') && val.endsWith('"')) ||
285
- (val.startsWith("'") && val.endsWith("'"))) {
286
- val = val.slice(1, -1);
287
- }
288
-
289
- return `${indent}${camelToKebab(rawProp)}: ${val};`;
290
- }).join("\n");
291
- }
292
-
293
- export function processStyleBlock(
294
- block: StyleBlock,
295
- hash: string,
296
- params: Map<string, string> = new Map(),
297
- ): string {
298
- let raw = block.raw;
299
-
300
- // 1. interpolate {param} placeholders
301
- if (params.size > 0) raw = interpolateAttr(raw, params);
302
-
303
- // 2. sinth style preprocessing
304
- raw = preprocessSinthStyle(raw);
305
-
306
- // 3. warn if & in plain CSS
307
- if (block.lang === "css" && raw.includes("&")) {
308
- SinthWarning.emit(
309
- `'&' (CSS nesting) found in style block. Nested selectors require a modern browser or lang="scss".`,
310
- block.loc,
311
- );
312
- }
313
-
314
- // 4. camelCase → kebab-case
315
- let css = convertCSSProps(raw);
316
-
317
- // 5. SCSS compilation
318
- if (block.lang === "scss") {
319
- try {
320
- // eslint-disable-next-line @typescript-eslint/no-require-imports
321
- const sass: { compileString: (src: string) => { css: string } } = require("sass");
322
- css = sass.compileString(css).css;
323
- } catch (e: unknown) {
324
- const err = e as { code?: string; message?: string };
325
- if (err.code === "MODULE_NOT_FOUND" || err.message?.includes("Cannot find module")) {
326
- throw new SinthError("SCSS requires the 'sass' package. Install with: npm install sass");
327
- }
328
- throw new SinthError(`SCSS compilation failed: ${err.message ?? String(e)}`);
329
- }
330
- }
331
-
332
- // 6. if target component given, wrap content in its CSS selector
333
- if (block.target) {
334
- const selector = sinthCompToSelector(block.target);
335
- css = `${selector} {\n${css}\n}`;
336
- }
337
-
338
- // 7. scope (except it's global)
339
- if (!block.global) css = scopeCSS(css, hash);
340
-
341
- return css;
342
- }
343
-
344
- export function scopeCSS(css: string, hash: string): string {
345
- return processRules(css, `[data-s="${hash}"]`);
346
- }
347
-
348
- export function processRules(css: string, attr: string): string {
349
- let out = "", i = 0;
350
-
351
- while (i < css.length) {
352
- if (/\s/.test(css[i])) { out += css[i++]; continue; }
353
-
354
- if (css[i] === "/" && css[i + 1] === "*") {
355
- const end = css.indexOf("*/", i + 2);
356
- if (end === -1) { out += css.substring(i); break; }
357
- out += css.substring(i, end + 2);
358
- i = end + 2;
359
- continue;
360
- }
361
-
362
- const braceIdx = findCSSBrace(css, i);
363
- if (braceIdx === -1) { out += css.substring(i); break; }
364
-
365
- const selector = css.substring(i, braceIdx).trim();
366
- const { content, end } = extractCSSBlock(css, braceIdx);
367
-
368
- if (/^@(-webkit-|-moz-)?keyframes/.test(selector)) {
369
- out += `${selector} {${content}}\n`;
370
- } else if (/^@(media|supports|layer|container)/.test(selector)) {
371
- out += `${selector} {\n${processRules(content, attr)}\n}\n`;
372
- } else if (selector.startsWith("@")) {
373
- out += `${selector} {${content}}\n`;
374
- } else if (selector.length > 0) {
375
- out += `${scopeSelectors(selector, attr)} {${content}}\n`;
376
- }
377
-
378
- i = end;
379
- }
380
- return out;
381
- }
382
-
383
- export function scopeSelectors(selList: string, attr: string): string {
384
- return selList
385
- .split(",")
386
- .map(s => {
387
- s = s.trim();
388
- if (!s) return "";
389
- if (/^(html|body|:root)(\s|$|{|,)/.test(s)) return s;
390
- const m = s.match(/^(.*?)((?::{1,2}[a-zA-Z-]+(?:\([^)]*\))?)+)$/);
391
- if (m && m[1].trim()) {
392
- return `${attr} ${m[1].trimEnd()}${m[2]}, ${m[1].trimEnd()}${attr}${m[2]}`;
393
- }
394
- return `${attr} ${s}, ${s}${attr}`;
395
- })
396
- .filter(Boolean)
397
- .join(",\n");
398
- }
399
-
400
- export function findCSSBrace(css: string, from: number): number {
401
- let i = from;
402
- while (i < css.length) {
403
- if (css[i] === '"' || css[i] === "'") {
404
- const q = css[i++];
405
- while (i < css.length && css[i] !== q) { if (css[i] === "\\") i++; i++; }
406
- i++;
407
- } else if (css[i] === "{") {
408
- return i;
409
- } else { i++; }
410
- }
411
- return -1;
412
- }
413
-
414
- export function extractCSSBlock(css: string, openBrace: number): { content: string; end: number } {
415
- let i = openBrace + 1, depth = 1;
416
- while (i < css.length && depth > 0) {
417
- if (css[i] === '"' || css[i] === "'") {
418
- const q = css[i++];
419
- while (i < css.length && css[i] !== q) { if (css[i] === "\\") i++; i++; }
420
- i++;
421
- } else if (css[i] === "/" && css[i + 1] === "*") {
422
- i += 2;
423
- while (i < css.length - 1 && !(css[i] === "*" && css[i + 1] === "/")) i++;
424
- i += 2;
425
- } else if (css[i] === "{") { depth++; i++; }
426
- else if (css[i] === "}") { depth--; if (depth > 0) i++; else break; }
427
- else { i++; }
428
- }
429
- return { content: css.substring(openBrace + 1, i), end: i + 1 };
430
- }
431
-
432
-
433
-
434
-
435
-
436
-
437
- // the HTML generator
438
-
439
22
  /**
440
23
  * CSS property names that are allowed as inline style shorthand attributes on
441
24
  * any Sinth component: Paragraph(color: "red", fontSize: "1.2rem") { "Hi" }
@@ -505,20 +88,29 @@ if (name === "model" && value?.kind === "str") {
505
88
 
506
89
  if (name === "delay") {
507
90
  if (value.kind === "num") {
508
- return `data-sinth-delay="${value.value}" style="display:none"`;
91
+ return `data-sinth-delay="${value.value}"`;
509
92
  }
510
93
  const v = litToString(value);
511
- if (/^\d+$/.test(v)) return `data-sinth-delay="${escAttr(v)}" style="display:none"`;
94
+ if (/^\d+$/.test(v)) return `data-sinth-delay="${escAttr(v)}"`;
512
95
  if (v.startsWith("__EXPR__")) {
513
96
  try {
514
97
  const expr: Expression = JSON.parse(v.substring(8));
515
98
  const id = registerExpr(ctx, expr);
516
- return `data-sinth-delay-expr-id="${id}" style="display:none"`;
99
+ return `data-sinth-delay-expr-id="${id}"`;
517
100
  } catch {}
518
101
  }
519
- // plain variable name – register as expression
520
102
  const id = registerExpr(ctx, { kind: "variable", name: v });
521
- return `data-sinth-delay-expr-id="${id}" style="display:none"`;
103
+ return `data-sinth-delay-expr-id="${id}"`;
104
+ }
105
+
106
+ if (name === "hide") {
107
+ if (value && (value as any).kind === "bool") {
108
+ if (!(value as any).value) {
109
+ return `data-sinth-delay-hide="false"`;
110
+ }
111
+ return "";
112
+ }
113
+ return "";
522
114
  }
523
115
 
524
116
  if (name === "checked") {
@@ -543,7 +135,7 @@ if (name === "delay") {
543
135
  const exprJson = raw.substring("__EXPR__".length);
544
136
  try {
545
137
  const expr: Expression = JSON.parse(exprJson);
546
- const jsExpr = compileExprToJS(expr);
138
+ const jsExpr = compileExprToJS(expr, ctx?.loopVars);
547
139
  const ev = eventAttrName(name);
548
140
  if (ev) return `${ev}="(function(){ ${jsExpr.replace(/"/g, "&quot;")}; sinthRender(); })()"`;
549
141
  return `${name}="${escAttr(jsExpr)}"`;
@@ -560,46 +152,37 @@ if (name === "delay") {
560
152
  return `${name}="${escAttr(raw)}"`;
561
153
  }
562
154
 
563
- export function renderText(text: string, params: Map<string, string>): string {
564
- const rawSlots = new Map<string, string>();
565
- let counter = 0;
566
155
 
567
- let s = text.replace(/\\\$/g, "\x00DOLLAR\x00");
568
156
 
569
- s = s.replace(/\$([a-zA-Z_][a-zA-Z0-9_]*)/g, (_, n) => {
570
- const val = params.get(n);
571
- if (val === undefined) return `$${n}`;
572
- if (n === "slot") {
573
- const ph = `\x00RAW${counter++}\x00`;
574
- rawSlots.set(ph, val);
575
- return ph;
576
- }
577
- return val;
578
- });
579
157
 
580
- s = esc(s);
581
158
 
582
- for (const [ph, val] of rawSlots) s = s.replace(ph, val);
583
- s = s.replace(/\x00DOLLAR\x00/g, "$");
584
159
 
585
- const braceRe = /\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g;
586
- let m: RegExpExecArray | null;
587
- while ((m = braceRe.exec(s)) !== null) {
588
- SinthWarning.emit(
589
- `Use $param for text interpolation; {param} is for attributes. Found '${m[0]}' in text.`
590
- );
160
+ function substituteParamsInExpr(expr: Expression, params: Map<string, string>): Expression {
161
+ if (expr.kind === "variable" && expr.name && params.has(expr.name)) {
162
+ const val = params.get(expr.name)!;
163
+ if (val.startsWith("__LIT__")) {
164
+ return { kind: "literal", value: { kind: "str", value: val.slice(7) } };
165
+ }
166
+ if (val.startsWith("__EXPR__")) {
167
+ try {
168
+ return JSON.parse(val.substring(8));
169
+ } catch { return expr; }
170
+ }
171
+ return { kind: "literal", value: { kind: "str", value: val } };
591
172
  }
592
-
593
- return s;
594
- }
595
-
596
- export function interpolateAttr(text: string, params: Map<string, string>): string {
597
- let s = text.replace(/\\\{/g, "\x00LB\x00");
598
- s = s.replace(/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g, (_, n) => params.get(n) ?? `{${n}}`);
599
- return s.replace(/\x00LB\x00/g, "{");
173
+ if (expr.kind === "binary") {
174
+ return {
175
+ ...expr,
176
+ left: expr.left ? substituteParamsInExpr(expr.left, params) : undefined,
177
+ right: expr.right ? substituteParamsInExpr(expr.right, params) : undefined,
178
+ };
179
+ }
180
+ if (expr.kind === "unary" && expr.operand) {
181
+ return { ...expr, operand: substituteParamsInExpr(expr.operand, params) };
182
+ }
183
+ return expr;
600
184
  }
601
185
 
602
-
603
186
  export function renderChild(
604
187
  child: Child,
605
188
  ctx: CompileCtx,
@@ -613,15 +196,28 @@ export function renderChild(
613
196
  return renderText(child.value, params);
614
197
 
615
198
  case "expr": {
616
- if (child.expression.kind === "variable" && params.has(child.expression.name!)) {
617
- const val = params.get(child.expression.name!)!;
199
+ if (!child.expression) return "";
200
+
201
+ if (child.expression.kind === "variable" && child.expression.name && params.has(child.expression.name)) {
202
+ const val = params.get(child.expression.name)!;
618
203
  if (val.startsWith("__LIT__")) {
619
204
  return esc(val.slice(7));
620
205
  }
206
+ if (val.startsWith("__RAW__")) {
207
+ return val.slice(7);
208
+ }
621
209
  if (val.startsWith("__VAR__")) {
622
210
  const exprId = registerExpr(ctx, { kind: "variable", name: val.slice(7) });
623
211
  return `<span class="sinth-expr" data-expr-id="${exprId}"></span>`;
624
212
  }
213
+ if (val.startsWith("__EXPR__")) {
214
+ try {
215
+ const expr: Expression = JSON.parse(val.substring(8));
216
+ const exprId = registerExpr(ctx, expr);
217
+ return `<span class="sinth-expr" data-expr-id="${exprId}"></span>`;
218
+ } catch { return esc(val); }
219
+ }
220
+ return esc(val);
625
221
  }
626
222
  if (child.expression.kind === "call" && child.expression.callee?.kind === "variable") {
627
223
  const fnName = child.expression.callee.name;
@@ -689,7 +285,11 @@ export function renderChild(
689
285
  const exprId = registerExpr(ctx, child.expression);
690
286
  return `<span class="sinth-expr" data-expr-id="${exprId}"></span>`;
691
287
  }
692
- const exprId = registerExpr(ctx, child.expression);
288
+ let expr = child.expression;
289
+ if (params.size > 0) {
290
+ expr = substituteParamsInExpr(expr, params);
291
+ }
292
+ const exprId = registerExpr(ctx, expr);
693
293
  return `<span class="sinth-expr" data-expr-id="${exprId}"></span>`;
694
294
  }
695
295
 
@@ -711,16 +311,14 @@ export function renderChild(
711
311
  return renderIfBlock(child, ctx, params, depth);
712
312
 
713
313
  case "for": {
714
- // collect loop‑variable names
715
314
  const loopVars = new Set<string>();
716
315
  loopVars.add(child.itemVar);
717
316
  if (child.keyVar) loopVars.add(child.keyVar);
718
317
  if (child.indexVar) loopVars.add(child.indexVar);
719
- // set them on ctx for compilation of the body
720
318
  const prev = ctx.loopVars;
721
319
  ctx.loopVars = loopVars;
722
320
  const bodyHTML = child.body.map(c => renderChild(c, ctx, params, depth + 1)).join("");
723
- ctx.loopVars = prev; // restore
321
+ ctx.loopVars = prev;
724
322
  const keyAttr = child.keyVar ? ` data-sinth-key="${escAttr(child.keyVar)}"` : "";
725
323
  const idxAttr = child.indexVar ? ` data-sinth-index="${escAttr(child.indexVar)}"` : "";
726
324
  return (
@@ -771,9 +369,40 @@ depth: number,
771
369
  replaceAttr = ` data-sinth-if-replace="${escAttr(idAttr.value.value)}"`;
772
370
  }
773
371
  }
372
+ let delayAttr = "";
373
+ let delayHideAttr = "";
374
+ if (firstComp) {
375
+ const delayA = firstComp.attrs.find(a => a.name === "delay");
376
+ const hideA = firstComp.attrs.find(a => a.name === "hide");
377
+ if (delayA && hideA && hideA.value && (hideA.value as any).kind === "bool" && !(hideA.value as any).value) {
378
+ if (delayA.value?.kind === "num") {
379
+ delayAttr = ` data-sinth-if-delay="${delayA.value.value}"`;
380
+ } else if (delayA.value?.kind === "str") {
381
+ const v = litToString(delayA.value);
382
+ if (/^\d+$/.test(v)) delayAttr = ` data-sinth-if-delay="${v}"`;
383
+ }
384
+ delayHideAttr = ` data-sinth-if-delay-hide="false"`;
385
+ }
386
+ }
387
+ let elseDelayAttr = "";
388
+ let elseDelayHideAttr = "";
389
+ const elseFirstComp = (ifBlock.elseBody ?? []).find(c => c.kind === "use") as CompUse | undefined;
390
+ if (elseFirstComp) {
391
+ const delayA = elseFirstComp.attrs.find(a => a.name === "delay");
392
+ const hideA = elseFirstComp.attrs.find(a => a.name === "hide");
393
+ if (delayA && hideA && hideA.value && (hideA.value as any).kind === "bool" && !(hideA.value as any).value) {
394
+ if (delayA.value?.kind === "num") {
395
+ elseDelayAttr = ` data-sinth-if-delay="${delayA.value.value}"`;
396
+ } else if (delayA.value?.kind === "str") {
397
+ const v = litToString(delayA.value);
398
+ if (/^\d+$/.test(v)) elseDelayAttr = ` data-sinth-if-delay="${v}"`;
399
+ }
400
+ elseDelayHideAttr = ` data-sinth-if-delay-hide="false"`;
401
+ }
402
+ }
774
403
  return (
775
- `<template data-sinth-if-id="${tplId}" data-sinth-if-expr="${condId}"${replaceAttr}>${bodyHTML}</template>` +
776
- (elseHTML ? `<template data-sinth-else data-sinth-if-id="${tplId}">${elseHTML}</template>` : "")
404
+ `<template data-sinth-if-id="${tplId}" data-sinth-if-expr="${condId}"${replaceAttr}${delayAttr}${delayHideAttr}>${bodyHTML}</template>` +
405
+ (elseHTML ? `<template data-sinth-else data-sinth-if-id="${tplId}"${elseDelayAttr}${elseDelayHideAttr}>${elseHTML}</template>` : "")
777
406
  );
778
407
  }
779
408
 
@@ -835,7 +464,6 @@ export function renderCompUse(
835
464
  params: Map<string, string>,
836
465
  depth: number,
837
466
  ): string {
838
- // transparent wrapper inserted by flattenIfToUses()
839
467
  if (use.name === "__IF_ROOT__") {
840
468
  return use.children.map(c => renderChild(c, ctx, params, depth)).join("");
841
469
  }
@@ -887,6 +515,12 @@ export function renderCompUse(
887
515
  continue;
888
516
  }
889
517
  if (use.name === "Checkbox" && (attr.name === "checked" || attr.name === "onChange" || attr.name === "label")) continue;
518
+ if (attr.name === "hide") {
519
+ if (attr.value && (attr.value as any).kind === "bool" && !(attr.value as any).value) {
520
+ attrParts.push(`data-sinth-delay-hide="false"`);
521
+ }
522
+ continue;
523
+ }
890
524
  const rendered = renderAttr(attr, params, ctx);
891
525
  if (rendered) attrParts.push(rendered);
892
526
  }
@@ -990,7 +624,7 @@ export function expandUserComp(
990
624
  params: Map<string, string>,
991
625
  depth: number,
992
626
  ): string {
993
- if (use.name === def.name && depth > 1) {
627
+ if (use.name === def.name && depth > 4) {
994
628
  throw new SinthError(`Recursive component '${def.name}' is not allowed.`, use.loc);
995
629
  }
996
630
 
@@ -1005,7 +639,11 @@ export function expandUserComp(
1005
639
  local.set(attr.name, "true");
1006
640
  } else if (attr.value.kind !== "null") {
1007
641
  const raw = litToString(attr.value);
1008
- local.set(attr.name, attr.value.kind === "str" ? interpolateAttr(raw, params) : raw);
642
+ if (raw.startsWith("__EXPR__")) {
643
+ local.set(attr.name, raw);
644
+ } else {
645
+ local.set(attr.name, attr.value.kind === "str" ? interpolateAttr(raw, params) : raw);
646
+ }
1009
647
  }
1010
648
  }
1011
649
 
@@ -1019,7 +657,7 @@ export function expandUserComp(
1019
657
  }
1020
658
 
1021
659
  const slotHTML = use.children.map(c => renderChild(c, ctx, params, depth)).join("");
1022
- local.set("slot", slotHTML);
660
+ local.set("slot", "__RAW__" + slotHTML);
1023
661
 
1024
662
  for (const block of def.styles) {
1025
663
  ctx.extraCSS.push(processStyleBlock(block, ctx.scopeHash, local));
@@ -1028,7 +666,7 @@ export function expandUserComp(
1028
666
  return def.body.map(c => renderChild(c, ctx, local, depth)).join("");
1029
667
  }
1030
668
 
1031
- // script collector
669
+
1032
670
 
1033
671
  export function collectScripts(
1034
672
  file: SinthFile,
@@ -1068,122 +706,10 @@ export function extractFunctionNames(js: string): string[] {
1068
706
  }
1069
707
 
1070
708
 
1071
- // head gen
1072
-
1073
- export interface HeadData {
1074
- title?: string; fav?: string;
1075
- lang: string; charset: string; viewport: string;
1076
- metaTags: { name: string; content: string }[];
1077
- metaProps: { property: string; content: string }[];
1078
- }
1079
-
1080
- export function buildHeadData(meta: MetaEntry[]): HeadData {
1081
- let title: string | undefined, fav: string | undefined;
1082
- let lang = "en", charset = "UTF-8", viewport = "width=device-width, initial-scale=1.0";
1083
- const metaTags: { name: string; content: string }[] = [];
1084
- const metaProps: { property: string; content: string }[] = [];
1085
-
1086
- for (const m of meta) {
1087
- const val = litToString(m.value);
1088
- switch (m.key) {
1089
- case "title": title = val; break;
1090
- case "fav": fav = val; break;
1091
- case "lang": lang = val; break;
1092
- case "charset": charset = val; break;
1093
- case "viewport": viewport = val; break;
1094
- case "descr": metaTags.push({ name: "description", content: val }); break;
1095
- case "author": metaTags.push({ name: "author", content: val }); break;
1096
- case "keywords": metaTags.push({ name: "keywords", content: val }); break;
1097
- case "robots": metaTags.push({ name: "robots", content: val }); break;
1098
- default:
1099
- if (m.key.startsWith("og") || m.key.startsWith("twitter")) {
1100
- const prop = m.key
1101
- .replace(/^og([A-Z])/, (_: string, c: string) => `og:${c.toLowerCase()}`)
1102
- .replace(/^twitter([A-Z])/, (_: string, c: string) => `twitter:${c.toLowerCase()}`);
1103
- metaProps.push({ property: prop, content: val });
1104
- } else {
1105
- metaTags.push({ name: camelToKebab(m.key), content: val });
1106
- }
1107
- }
1108
- }
1109
-
1110
- return { title, fav, lang, charset, viewport, metaTags, metaProps };
1111
- }
1112
-
1113
- export function faviconType(p: string): string {
1114
- switch (path.extname(p).toLowerCase()) {
1115
- case ".ico": return "image/x-icon";
1116
- case ".png": return "image/png";
1117
- case ".svg": return "image/svg+xml";
1118
- case ".gif": return "image/gif";
1119
- case ".webp": return "image/webp";
1120
- case ".jpg":
1121
- case ".jpeg": return "image/jpeg";
1122
- default:
1123
- SinthWarning.emit(`Unknown favicon extension '${path.extname(p)}', defaulting to image/x-icon`);
1124
- return "image/x-icon";
1125
- }
1126
- }
1127
-
1128
- export function renderHead(
1129
- hd: HeadData,
1130
- cssLinks: string[],
1131
- jsLinks: { src: string; attrs: Record<string, string> }[],
1132
- scopedCSS: string,
1133
- companionJS: string | undefined,
1134
- ): string {
1135
- const lines: string[] = [];
1136
- lines.push(` <meta charset="${escAttr(hd.charset)}">`);
1137
- lines.push(` <meta name="viewport" content="${escAttr(hd.viewport)}">`);
1138
- if (hd.title) lines.push(` <title>${esc(hd.title)}</title>`);
1139
- if (hd.fav) lines.push(` <link rel="icon" href="${escAttr(hd.fav)}" type="${faviconType(hd.fav)}">`);
1140
- for (const m of hd.metaTags) lines.push(` <meta name="${escAttr(m.name)}" content="${escAttr(m.content)}">`);
1141
- for (const m of hd.metaProps) lines.push(` <meta property="${escAttr(m.property)}" content="${escAttr(m.content)}">`);
1142
- for (const css of cssLinks) lines.push(` <link rel="stylesheet" href="${escAttr(css)}">`);
1143
- if (scopedCSS.trim()) lines.push(` <style>\n${scopedCSS}\n </style>`);
1144
- for (const js of jsLinks) {
1145
- const extra = Object.entries(js.attrs)
1146
- .map(([k, v]) => v === "true" ? k : `${k}="${escAttr(v)}"`)
1147
- .join(" ");
1148
- lines.push(` <script src="${escAttr(js.src)}"${extra ? " " + extra : ""}></script>`);
1149
- }
1150
- if (companionJS) lines.push(` <script src="${escAttr(companionJS)}"></script>`);
1151
- return `<head>\n${lines.join("\n")}\n</head>`;
1152
- }
1153
709
 
1154
710
 
1155
711
  // sinth runtime
1156
712
 
1157
- function compileFunctionDef(fn: FunctionDef, ctx: CompileCtx): string {
1158
- const paramsJS = fn.params.map(p => p.name).join(", ");
1159
-
1160
- if (fn.returnType === "ui") {
1161
- return "";
1162
- }
1163
-
1164
- const bodyStatements: string[] = [];
1165
- for (const child of fn.body) {
1166
- switch (child.kind) {
1167
- case "text":
1168
- break;
1169
- case "expr":
1170
- bodyStatements.push(`return ${compileExprToJS(child.expression)};`);
1171
- break;
1172
- case "assign_stmt":
1173
- bodyStatements.push(`${compileExprToJS(child.expression)};`);
1174
- break;
1175
- case "if":
1176
- bodyStatements.push(compileIfToJS(child as IfBlock));
1177
- break;
1178
- case "for":
1179
- break;
1180
- case "return":
1181
- bodyStatements.push(`return ${child.expression ? compileExprToJS(child.expression) : ""};`);
1182
- break;
1183
- }
1184
- }
1185
- return `function ${fn.name}(${paramsJS}) {\n${bodyStatements.map(s => ` ${s}`).join("\n")}\n}`;
1186
- }
1187
713
 
1188
714
  export function buildRuntime(opts: {
1189
715
  varDecls: VarDeclaration[];
@@ -1235,337 +761,18 @@ export function buildRuntime(opts: {
1235
761
  return varLines ? `// Sinth compiled runtime\n${varLines}` : "";
1236
762
  }
1237
763
 
1238
- let helpers = "";
1239
-
1240
- if (needsExpr || needsIf || needsFor) {
1241
- helpers += `
1242
- function sinthExpr(el) {
1243
- try {
1244
- var exprFn = __X[el.dataset.exprId];
1245
- if (exprFn) el.textContent = exprFn({});
1246
- } catch(e) {}
1247
- }
1248
- `;
1249
- }
1250
-
1251
- if (needsIf || needsMixed) {
1252
- helpers += `
1253
- function sinthReplaceInsert(t, anchor, ifId, replaceId) {
1254
- if (anchor) {
1255
- var cur = anchor.nextSibling;
1256
- while (cur && cur !== t) { var nx = cur.nextSibling; cur.remove(); cur = nx; }
1257
- } else {
1258
- anchor = document.createElement('span');
1259
- anchor.style.display = 'none';
1260
- anchor.dataset.sinthIfAnchor = ifId;
1261
- t.parentNode.insertBefore(anchor, t);
1262
- }
1263
- var _rp = null, _rpParent = null, _rpNext = null;
1264
- if (replaceId) {
1265
- _rp = document.getElementById(replaceId);
1266
- if (_rp) {
1267
- _rpParent = _rp.parentNode;
1268
- _rpNext = _rp.nextSibling;
1269
- _rp.parentNode.removeChild(_rp);
1270
- anchor._sinthReplaced = _rp;
1271
- anchor._sinthReplacedParent = _rpParent;
1272
- anchor._sinthReplacedNext = _rpNext;
1273
- }
1274
- }
1275
- var frag = document.createRange().createContextualFragment(t.innerHTML);
1276
- frag.querySelectorAll('.sinth-expr').forEach(sinthExpr);
1277
- if (${needsDelay}) {
1278
- frag.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
1279
- frag.querySelectorAll('[data-sinth-delay-expr-id]').forEach(function(el) { sinthDelayExpr(el, {}); });
1280
- }
1281
- var fragFirst = frag.firstChild;
1282
- var fragLast = frag.lastChild;
1283
- if (_rpParent && _rpNext) {
1284
- _rpParent.insertBefore(frag, _rpNext);
1285
- } else if (_rpParent) {
1286
- _rpParent.appendChild(frag);
1287
- } else {
1288
- t.parentNode.insertBefore(frag, t);
1289
- }
1290
- if (replaceId && anchor) {
1291
- anchor._sinthInsertedFirst = fragFirst;
1292
- anchor._sinthInsertedLast = fragLast;
1293
- }
1294
- return anchor;
1295
- }
1296
- `;
1297
- }
1298
-
1299
- if (needsDelay) {
1300
- helpers += `
1301
- function sinthDelay(el) {
1302
- if (el.dataset.sinthDelayDone) { el.style.display = ''; return; }
1303
- el.dataset.sinthDelayDone = '1';
1304
- var ms = parseInt(el.dataset.sinthDelay) || 0;
1305
- el.style.display = 'none';
1306
- var show = function() {
1307
- el.style.display = '';
1308
- el.querySelectorAll('.sinth-expr').forEach(sinthExpr);
1309
- };
1310
- if (ms > 0) setTimeout(show, ms);
1311
- else show();
1312
- }
1313
- function sinthDelayExpr(el, _ctx) {
1314
- _ctx = _ctx || {};
1315
- try {
1316
- var fn = __X[el.dataset.sinthDelayExprId];
1317
- var ms = fn ? parseInt(fn(_ctx)) || 0 : 0;
1318
- var show = function() {
1319
- el.style.display = '';
1320
- el.querySelectorAll('.sinth-expr').forEach(sinthExpr);
1321
- };
1322
- if (ms > 0) setTimeout(show, ms);
1323
- else show();
1324
- } catch(e) {}
1325
- }
1326
- `;
1327
- }
1328
764
 
1329
- if (needsIf) {
1330
- helpers += `
1331
- function sinthIfBlock(t) {
1332
- var ifId = t.dataset.sinthIfId;
1333
- var anchor = t.parentNode.querySelector('[data-sinth-if-anchor="' + ifId + '"]');
1334
- var condFn = __X[t.dataset.sinthIfExpr];
1335
- var cond = condFn ? condFn() : false;
1336
- if (cond) {
1337
- anchor = sinthReplaceInsert(t, anchor, ifId, t.dataset.sinthIfReplace);
1338
- } else {
1339
- if (anchor) {
1340
- if (anchor._sinthReplaced) {
1341
- var insFirst = anchor._sinthInsertedFirst;
1342
- var insLast = anchor._sinthInsertedLast;
1343
- var rpParent = anchor._sinthReplacedParent;
1344
- var rpNext = anchor._sinthReplacedNext;
1345
- if (insFirst && insLast) {
1346
- var cur = insFirst;
1347
- while (cur && cur !== insLast) {
1348
- var next = cur.nextSibling;
1349
- cur.remove();
1350
- cur = next;
1351
- }
1352
- if (insLast) insLast.remove();
1353
- }
1354
- if (rpParent && rpNext) {
1355
- rpParent.insertBefore(anchor._sinthReplaced, rpNext);
1356
- } else if (rpParent) {
1357
- rpParent.appendChild(anchor._sinthReplaced);
1358
- }
1359
- } else {
1360
- var cur2 = anchor.nextSibling;
1361
- while (cur2 && cur2 !== t) { var nx2 = cur2.nextSibling; cur2.remove(); cur2 = nx2; }
1362
- }
1363
- anchor.remove();
1364
- }
1365
- var elseT = t.nextElementSibling;
1366
- if (elseT && elseT.hasAttribute('data-sinth-else')) {
1367
- var elseIfId = elseT.dataset.sinthIfId;
1368
- var ea = t.parentNode.querySelector('[data-sinth-if-anchor="__else__' + elseIfId + '"]');
1369
- if (ea) {
1370
- var cur3 = ea.nextSibling;
1371
- while (cur3 && cur3 !== t) { var nx3 = cur3.nextSibling; cur3.remove(); cur3 = nx3; }
1372
- } else {
1373
- ea = document.createElement('span');
1374
- ea.style.display = 'none';
1375
- ea.dataset.sinthIfAnchor = '__else__' + elseIfId;
1376
- t.parentNode.insertBefore(ea, t);
1377
- }
1378
- var ef = document.createRange().createContextualFragment(elseT.innerHTML);
1379
- ef.querySelectorAll('.sinth-expr').forEach(sinthExpr);
1380
- if (${needsDelay}) {
1381
- ef.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
1382
- ef.querySelectorAll('[data-sinth-delay-expr-id]').forEach(function(el) { sinthDelayExpr(el, {}); });
1383
- }
1384
- t.parentNode.insertBefore(ef, t);
1385
- } else {
1386
- var ea2 = t.parentNode.querySelector('[data-sinth-if-anchor="__else__' + ifId + '"]');
1387
- if (ea2) {
1388
- var ec = ea2.nextSibling;
1389
- while (ec && ec !== t) { var en = ec.nextSibling; ec.remove(); ec = en; }
1390
- ea2.remove();
1391
- }
1392
- }
1393
- }
1394
- }
1395
- `;
1396
- }
765
+ const helpers = generateHelpers({ needsExpr, needsIf, needsFor, needsDelay, needsMixed });
1397
766
 
1398
- if (needsFor) {
1399
- helpers += `
1400
- function hashString(str) {
1401
- var hash = 0, i, chr;
1402
- for (i = 0; i < str.length; i++) {
1403
- chr = str.charCodeAt(i);
1404
- hash = ((hash << 5) - hash) + chr;
1405
- hash |= 0;
1406
- }
1407
- return String(hash);
1408
- }
1409
- function sinthForBlock(t) {
1410
- var source = window[t.dataset.sinthFor];
1411
- if (source === undefined) source = [];
1412
- var newHash = '';
1413
- try { newHash = hashString(JSON.stringify(source)); } catch(e) { newHash = ''; }
1414
- if (t.dataset.sinthForHash && t.dataset.sinthForHash === newHash) {
1415
- return;
1416
- }
1417
- t.dataset.sinthForHash = newHash;
1418
- var isObj = (typeof source === 'object' && source !== null && !Array.isArray(source));
1419
- var entries;
1420
- if (isObj) {
1421
- entries = Object.entries(source);
1422
- } else {
1423
- if (!Array.isArray(source)) source = [];
1424
- entries = source.map(function(item, index) { return [index, item]; });
1425
- }
1426
- var anchor = t.parentNode ? t.parentNode.querySelector('[data-sinth-for-anchor="' + t.dataset.sinthFor + '"]') : null;
1427
- if (anchor) {
1428
- var cur2 = anchor.nextSibling;
1429
- while (cur2 && cur2 !== t) { var nx2 = cur2.nextSibling; cur2.remove(); cur2 = nx2; }
1430
- anchor.remove();
1431
- }
1432
- var fa = document.createElement('span');
1433
- fa.style.display = 'none';
1434
- fa.dataset.sinthForAnchor = t.dataset.sinthFor;
1435
- t.parentNode && t.parentNode.insertBefore(fa, t);
1436
- var _loopIdx = 0;
1437
- entries.forEach(function(entry) {
1438
- var _k = entry[0];
1439
- var _v = entry[1];
1440
- var _item = (t.dataset && t.dataset.sinthItem) ? t.dataset.sinthItem : '__item__';
1441
- var _key = t.dataset && t.dataset.sinthKey ? t.dataset.sinthKey : null;
1442
- var _idx = t.dataset && t.dataset.sinthIndex ? t.dataset.sinthIndex : null;
1443
- _loopIdx++;
1444
- if (t.dataset.sinthIfReplace) {
1445
- var _rp = document.getElementById(t.dataset.sinthIfReplace);
1446
- if (_rp) _rp.parentNode.removeChild(_rp);
1447
- }
1448
- var loopCtx = {};
1449
- if (_item) loopCtx[_item] = _v;
1450
- if (_key) loopCtx[_key] = _k;
1451
- if (_idx) loopCtx[_idx] = _loopIdx - 1;
1452
- var frag = document.createRange().createContextualFragment(t.innerHTML);
1453
- frag.querySelectorAll('.sinth-expr').forEach(function(el) {
1454
- try {
1455
- var exprFn = __X[el.dataset.exprId];
1456
- if (exprFn) el.textContent = exprFn(loopCtx);
1457
- } catch(e) {}
1458
- el.classList.remove('sinth-expr');
1459
- });
1460
- frag.querySelectorAll('template[data-sinth-if-expr]').forEach(function(ifT) {
1461
- var condFn = __X[ifT.dataset.sinthIfExpr];
1462
- var cond = false;
1463
- try { if (condFn) cond = condFn(loopCtx); } catch(e) {}
1464
- if (cond) {
1465
- var ifContent = document.createRange().createContextualFragment(ifT.innerHTML);
1466
- ifContent.querySelectorAll('.sinth-expr').forEach(function(el2) {
1467
- try {
1468
- var exprFn2 = __X[el2.dataset.exprId];
1469
- if (exprFn2) el2.textContent = exprFn2(loopCtx);
1470
- } catch(e) {}
1471
- });
1472
- ifT.parentNode.insertBefore(ifContent, ifT);
1473
- } else {
1474
- var elseT = ifT.nextElementSibling;
1475
- if (elseT && elseT.hasAttribute('data-sinth-else')) {
1476
- var elseContent = document.createRange().createContextualFragment(elseT.innerHTML);
1477
- elseContent.querySelectorAll('.sinth-expr').forEach(function(el2) {
1478
- try {
1479
- var exprFn2 = __X[el2.dataset.exprId];
1480
- if (exprFn2) el2.textContent = exprFn2(loopCtx);
1481
- } catch(e) {}
1482
- });
1483
- ifT.parentNode.insertBefore(elseContent, ifT);
1484
- }
1485
- }
1486
- });
1487
- if (${needsDelay}) {
1488
- frag.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
1489
- frag.querySelectorAll('[data-sinth-delay-expr-id]').forEach(function(el) { sinthDelayExpr(el, loopCtx); });
1490
- }
1491
- t.parentNode && t.parentNode.insertBefore(frag, t);
767
+ const renderBody = buildRenderBody({
768
+ bodyHTML, logicBlocks, mixedBlocks,
769
+ needsLogic, needsMixed, needsIf, needsFor, needsExpr, needsDelay
1492
770
  });
1493
- }
1494
- `;
1495
- }
1496
-
1497
-
1498
771
 
1499
772
  const exprArrayJS = exprRegistry.length > 0
1500
773
  ? `var __X = [${exprRegistry.map((js) => `function(_ctx){ return ${js}; }`).join(",")}];\n`
1501
774
  : "";
1502
775
 
1503
- let renderBody = "";
1504
- renderBody += ` var _sx = window.scrollX, _sy = window.scrollY;\n`;
1505
-
1506
- if (needsLogic) {
1507
- renderBody += logicBlocks.map(b => b.replace(/^/gm, " ")).join("\n") + "\n";
1508
- }
1509
-
1510
- if (needsMixed) {
1511
- for (const mb of mixedBlocks) {
1512
- const ifJS = mb.ifJS ? mb.ifJS.trim() : "";
1513
- const elseJS = mb.elseJS ? mb.elseJS.trim() : "";
1514
- renderBody += ` (function() {
1515
- var __el = document.getElementById(${JSON.stringify(mb.replaceId || mb.id)});
1516
- if (__el) {
1517
- var __condFn = __X[${mb.conditionJS}];
1518
- if (__condFn ? __condFn() : false) {
1519
- ${ifJS}
1520
- __el.innerHTML = ${JSON.stringify(mb.ifHTML)};
1521
- } else {
1522
- ${elseJS}
1523
- __el.innerHTML = ${JSON.stringify(mb.elseHTML)};
1524
- }
1525
- __el.querySelectorAll('.sinth-expr').forEach(sinthExpr);
1526
- __el.querySelectorAll('template[data-sinth-if-expr]').forEach(sinthIfBlock);
1527
- ${needsDelay ? `__el.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
1528
- __el.querySelectorAll('[data-sinth-delay-expr-id]').forEach(function(el) { sinthDelayExpr(el, {}); });` : ""}
1529
- }
1530
- })();\n`;
1531
- }
1532
- }
1533
-
1534
- renderBody += ` document.querySelectorAll('[data-sinth-remove]').forEach(function(el) {
1535
- var target = document.getElementById(el.dataset.sinthRemove);
1536
- if (target) target.remove();
1537
- });\n`;
1538
-
1539
- if (needsIf) {
1540
- renderBody += ` document.querySelectorAll('template[data-sinth-if-expr]').forEach(sinthIfBlock);\n`;
1541
- }
1542
- if (needsFor) {
1543
- renderBody += ` document.querySelectorAll('template[data-sinth-for]').forEach(sinthForBlock);\n`;
1544
- }
1545
- renderBody += ` document.querySelectorAll('[data-sinth-value]').forEach(function(el) {
1546
- try { el.value = window[el.dataset.sinthValue] || ''; } catch(e) {}
1547
- });\n`;
1548
- renderBody += ` document.querySelectorAll('[data-sinth-checked]').forEach(function(el) {
1549
- try { el.checked = !!window[el.dataset.sinthChecked]; } catch(e) {}
1550
- });\n`;
1551
- if (bodyHTML.includes("data-sinth-checked-expr")) {
1552
- renderBody += ` document.querySelectorAll('[data-sinth-checked-expr]').forEach(function(el) {
1553
- try {
1554
- var exprFn = __X[el.dataset.sinthCheckedExpr];
1555
- if (exprFn) el.checked = !!exprFn({});
1556
- } catch(e) {}
1557
- });\n`;
1558
- }
1559
- if (needsExpr) {
1560
- renderBody += ` document.querySelectorAll('.sinth-expr').forEach(sinthExpr);\n`;
1561
- }
1562
- if (needsDelay) {
1563
- renderBody += ` setTimeout(function() {
1564
- document.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
1565
- }, 0);\n`;
1566
- }
1567
- renderBody += ` window.scrollTo(_sx, _sy);\n`;
1568
-
1569
776
  const renderFunc = needsRender ? `function sinthRender() {\n${renderBody}}\nsinthRender();` : "";
1570
777
 
1571
778
  const pageCode = `// Sinth page runtime
@@ -1606,7 +813,7 @@ export function compileFile(filePath: string, opts: CompileOptions): { html: str
1606
813
  const hash = fnv1a(absPath);
1607
814
 
1608
815
  const allVarDecls: VarDeclaration[] = file.varDecls;
1609
- const functionDefs: FunctionDef[] = file.functions; // ← new
816
+ const functionDefs: FunctionDef[] = file.functions;
1610
817
 
1611
818
  const ctx: CompileCtx = {
1612
819
  allDefs, functionDefs, customEls, cssLinks, jsLinks,