@yannosay/sinth 0.10.0 → 0.12.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/README.md CHANGED
@@ -1,7 +1,9 @@
1
1
  # Sinth
2
2
 
3
3
  The language that fixes HTML. Declarative. Reactive. Compiles to pure HTML.
4
+
4
5
  Find out more: https://www.youtube.com/watch?v=W0tOMTiIF0Q
6
+ Discord: [Join here!](https://discord.gg/SUvcrafTQm)
5
7
 
6
8
 
7
9
  [![npm version](https://img.shields.io/npm/v/@yannosay/sinth)](https://www.npmjs.com/package/@yannosay/sinth)
@@ -25,22 +27,60 @@ Button(onClick: "deletePost()") { "Delete" }
25
27
  }
26
28
  ```
27
29
 
30
+ No JSX ternaries. No v-if. No separate script tags. Mixed logic. Clean.
31
+
28
32
  #### Functions - easy as you know it
29
33
  ```ts
30
34
  page
31
35
 
32
- title = "Function test"
36
+ title = "Full Test"
33
37
 
34
- function greet(str name) -> str { -- New! (0.10.0)
38
+ var str userName = "Sinths User"
39
+
40
+ function greet(str name) -> str {
35
41
  "Hello, " + name
36
42
  }
37
43
 
44
+ function renderHeading(str label) -> ui {
45
+ Heading(level: 2) {
46
+ (label)
47
+ }
48
+ }
49
+
38
50
  Div {
39
- (greet("Sinth")) + " - welcome!"
51
+ (greet(userName)) + " — welcome back!"
52
+ }
53
+
54
+ (renderHeading(userName))
55
+ (renderHeading("This renders!"))
56
+ ```
57
+ or
58
+
59
+ ```ts
60
+ page
61
+
62
+ title = "Checkbox Test"
63
+
64
+ var bool isAdmin = false
65
+
66
+ function toggleAdmin() {
67
+ isAdmin = not isAdmin
68
+ }
69
+
70
+ function getStatus() -> str {
71
+ if (isAdmin) {
72
+ return "ON"
73
+ }
74
+ return "OFF"
75
+ }
76
+
77
+ Checkbox(checked: isAdmin, onChange: toggleAdmin(), label: "Admin mode?")
78
+
79
+ Paragraph {
80
+ "Admin mode is " + (getStatus()) + "! :D"
40
81
  }
41
82
  ```
42
83
 
43
- No JSX ternaries. No v-if. No separate script tags. Mixed logic. Clean.
44
84
 
45
85
  #### Animations that make sense.
46
86
  ```ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yannosay/sinth",
3
- "version": "0.10.0",
3
+ "version": "0.12.0",
4
4
  "description": "A declarative language that compiles to pure HTML, CSS, and JavaScript.",
5
5
  "author": "Yannosay Productions",
6
6
  "license": "AGPL-3.0",
@@ -613,6 +613,41 @@ export function renderChild(
613
613
  return renderText(child.value, params);
614
614
 
615
615
  case "expr": {
616
+ if (child.expression.kind === "variable" && params.has(child.expression.name!)) {
617
+ const val = params.get(child.expression.name!)!;
618
+ if (val.startsWith("__LIT__")) {
619
+ return esc(val.slice(7));
620
+ }
621
+ if (val.startsWith("__VAR__")) {
622
+ const exprId = registerExpr(ctx, { kind: "variable", name: val.slice(7) });
623
+ return `<span class="sinth-expr" data-expr-id="${exprId}"></span>`;
624
+ }
625
+ }
626
+ if (child.expression.kind === "call" && child.expression.callee?.kind === "variable") {
627
+ const fnName = child.expression.callee.name;
628
+ const fnDef = fnName ? ctx.functionDefs.find(f => f.name === fnName) : undefined;
629
+ if (fnDef && fnDef.returnType === "ui") {
630
+ const callArgs = child.expression.args ?? [];
631
+ const localParams = new Map<string, string>();
632
+ for (let i = 0; i < fnDef.params.length && i < callArgs.length; i++) {
633
+ const arg = callArgs[i];
634
+ if (arg.kind === "literal" && arg.value?.kind === "str") {
635
+ localParams.set(fnDef.params[i].name, "__LIT__" + arg.value.value);
636
+ } else if (arg.kind === "variable" && arg.name) {
637
+ localParams.set(fnDef.params[i].name, "__VAR__" + arg.name);
638
+ }
639
+ }
640
+ return fnDef.body.map(c => {
641
+ if (c.kind === "expr" && c.expression.kind === "variable" && localParams.has(c.expression.name!)) {
642
+ return localParams.get(c.expression.name!)!;
643
+ }
644
+ if (c.kind === "use") {
645
+ return renderCompUse(c, ctx, localParams, depth + 1);
646
+ }
647
+ return renderChild(c, ctx, localParams, depth + 1);
648
+ }).join("");
649
+ }
650
+ }
616
651
  if (child.expression.kind === "literal" && child.expression.value) {
617
652
  return esc(litToString(child.expression.value));
618
653
  }
@@ -631,7 +666,12 @@ export function renderChild(
631
666
 
632
667
  case "remove": {
633
668
  return `<span data-sinth-remove="${esc((child as RemoveStmt).target)}"></span>`;
634
- }
669
+ }
670
+
671
+ case "return":
672
+ return "";
673
+
674
+
635
675
 
636
676
  case "if":
637
677
  return renderIfBlock(child, ctx, params, depth);
@@ -656,6 +696,9 @@ export function renderChild(
656
696
 
657
697
  case "use":
658
698
  return renderCompUse(child, ctx, params, depth);
699
+
700
+ case "component_expr":
701
+ return child.children.map(c => renderChild(c, ctx, params, depth + 1)).join("");
659
702
  }
660
703
  }
661
704
 
@@ -809,6 +852,7 @@ export function renderCompUse(
809
852
  if (attr.value?.kind === "str") userClass = interpolateAttr(attr.value.value, params);
810
853
  continue;
811
854
  }
855
+ if (use.name === "Checkbox" && (attr.name === "checked" || attr.name === "onChange" || attr.name === "label")) continue;
812
856
  const rendered = renderAttr(attr, params, ctx);
813
857
  if (rendered) attrParts.push(rendered);
814
858
  }
@@ -836,17 +880,61 @@ export function renderCompUse(
836
880
  }
837
881
  if (use.name === "Checkbox") {
838
882
  if (!use.attrs.some(a => a.name === "type")) attrParts.push(`type="checkbox"`);
839
- const bindAttr = use.attrs.find(a => a.name === "bind");
840
- if (bindAttr?.value?.kind === "str") {
841
- let vName = bindAttr.value.value;
842
- if (vName.startsWith("__EXPR__")) {
883
+
884
+ const checkedAttr = use.attrs.find(a => a.name === "checked");
885
+ if (checkedAttr && checkedAttr.value) {
886
+ if (checkedAttr.value.kind === "bool") {
887
+ if (checkedAttr.value.value) attrParts.push(`checked`);
888
+ } else if (checkedAttr.value.kind === "str") {
889
+ let raw = checkedAttr.value.value;
890
+ if (raw.startsWith("__EXPR__")) {
891
+ try {
892
+ const expr: Expression = JSON.parse(raw.substring(8));
893
+ if (expr.kind === "variable" && expr.name) {
894
+ attrParts.push(`data-sinth-checked="${escAttr(expr.name)}"`);
895
+ } else {
896
+ const exprId = registerExpr(ctx, expr);
897
+ attrParts.push(`data-sinth-checked-expr="${exprId}"`);
898
+ }
899
+ } catch {}
900
+ } else {
901
+ attrParts.push(`data-sinth-checked="${escAttr(raw)}"`);
902
+ }
903
+ }
904
+ }
905
+
906
+ const onChangeAttr = use.attrs.find(a => a.name === "onChange");
907
+ if (onChangeAttr && onChangeAttr.value?.kind === "str") {
908
+ let raw = onChangeAttr.value.value;
909
+ if (raw.startsWith("__EXPR__")) {
843
910
  try {
844
- const expr: Expression = JSON.parse(vName.substring(8));
845
- if (expr.kind === "variable" && expr.name) vName = expr.name;
911
+ const expr: Expression = JSON.parse(raw.substring(8));
912
+ const jsExpr = compileExprToJS(expr);
913
+ attrParts.push(`onchange="(function(){ ${jsExpr}; sinthRender(); })(event)"`);
846
914
  } catch {}
915
+ } else {
916
+ attrParts.push(`onchange="${escAttr(raw)};sinthRender()"`);
917
+ }
918
+ } else if (!onChangeAttr && checkedAttr) {
919
+ const raw = checkedAttr.value?.kind === "str" ? checkedAttr.value.value : "";
920
+ if (raw.startsWith("__EXPR__")) {
921
+ try {
922
+ const expr: Expression = JSON.parse(raw.substring(8));
923
+ if (expr.kind === "variable" && expr.name) {
924
+ attrParts.push(`onchange="(function(e){ ${expr.name} = e.target.checked; sinthRender(); })(event)"`);
925
+ }
926
+ } catch {}
927
+ } else if (raw.match(/^[a-zA-Z_][a-zA-Z0-9_]*$/)) {
928
+ attrParts.push(`onchange="(function(e){ ${raw} = e.target.checked; sinthRender(); })(event)"`);
847
929
  }
848
- attrParts.push(`onchange="(function(e){ ${vName} = e.target.checked; sinthRender(); })(event)"`);
849
- attrParts.push(`data-sinth-checked="${escAttr(vName)}"`);
930
+ }
931
+
932
+ const labelAttr = use.attrs.find(a => a.name === "label");
933
+ const labelText = labelAttr?.value?.kind === "str" ? esc(interpolateAttr(labelAttr.value.value, params)) : "";
934
+
935
+ if (labelText) {
936
+ const checkAttrStr = attrParts.length ? " " + attrParts.join(" ") : "";
937
+ return `<label data-s="${ctx.scopeHash}"><input${checkAttrStr}> ${labelText}</label>`;
850
938
  }
851
939
  }
852
940
 
@@ -1032,8 +1120,14 @@ export function renderHead(
1032
1120
 
1033
1121
  // sinth runtime
1034
1122
 
1035
- function compileFunctionDef(fn: FunctionDef): string {
1123
+ function compileFunctionDef(fn: FunctionDef, ctx: CompileCtx): string {
1036
1124
  const paramsJS = fn.params.map(p => p.name).join(", ");
1125
+
1126
+ if (fn.returnType === "ui") {
1127
+ const childHTMLs = fn.body.map(c => renderChild(c, ctx, new Map(), 0));
1128
+ return `function ${fn.name}(${paramsJS}) {\n return [${childHTMLs.map(h => JSON.stringify(h)).join(", ")}];\n}`;
1129
+ }
1130
+
1037
1131
  const bodyStatements: string[] = [];
1038
1132
  for (const child of fn.body) {
1039
1133
  switch (child.kind) {
@@ -1050,6 +1144,9 @@ function compileFunctionDef(fn: FunctionDef): string {
1050
1144
  break;
1051
1145
  case "for":
1052
1146
  break;
1147
+ case "return":
1148
+ bodyStatements.push(`return ${child.expression ? compileExprToJS(child.expression) : ""};`);
1149
+ break;
1053
1150
  }
1054
1151
  }
1055
1152
  return `function ${fn.name}(${paramsJS}) {\n${bodyStatements.map(s => ` ${s}`).join("\n")}\n}`;
@@ -1360,27 +1457,7 @@ function sinthForBlock(t) {
1360
1457
  `;
1361
1458
  }
1362
1459
 
1363
- if (needsMixed) {
1364
- helpers += `
1365
- function sinthMixedBlock(el, condId, ifJS, ifHTML, elseJS, elseHTML) {
1366
- var condFn = __X[condId];
1367
- var cond = condFn ? condFn() : false;
1368
- if (cond) {
1369
- if (ifJS) eval(ifJS);
1370
- el.innerHTML = ifHTML;
1371
- } else {
1372
- if (elseJS) eval(elseJS);
1373
- el.innerHTML = elseHTML;
1374
- }
1375
- el.querySelectorAll('.sinth-expr').forEach(sinthExpr);
1376
- el.querySelectorAll('template[data-sinth-if-expr]').forEach(sinthIfBlock);
1377
- if (${needsDelay}) {
1378
- el.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
1379
- el.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
1380
- }
1381
- }
1382
- `;
1383
- }
1460
+
1384
1461
 
1385
1462
  const exprArrayJS = exprRegistry.length > 0
1386
1463
  ? `var __X = [${exprRegistry.map((js) => `function(_ctx){ return ${js}; }`).join(",")}];\n`
@@ -1395,9 +1472,24 @@ function sinthMixedBlock(el, condId, ifJS, ifHTML, elseJS, elseHTML) {
1395
1472
 
1396
1473
  if (needsMixed) {
1397
1474
  for (const mb of mixedBlocks) {
1475
+ const ifJS = mb.ifJS ? mb.ifJS.trim() : "";
1476
+ const elseJS = mb.elseJS ? mb.elseJS.trim() : "";
1398
1477
  renderBody += ` (function() {
1399
1478
  var __el = document.getElementById(${JSON.stringify(mb.replaceId || mb.id)});
1400
- if (__el) sinthMixedBlock(__el, ${mb.conditionJS}, ${JSON.stringify(mb.ifJS)}, ${JSON.stringify(mb.ifHTML)}, ${JSON.stringify(mb.elseJS)}, ${JSON.stringify(mb.elseHTML)});
1479
+ if (__el) {
1480
+ var __condFn = __X[${mb.conditionJS}];
1481
+ if (__condFn ? __condFn() : false) {
1482
+ ${ifJS}
1483
+ __el.innerHTML = ${JSON.stringify(mb.ifHTML)};
1484
+ } else {
1485
+ ${elseJS}
1486
+ __el.innerHTML = ${JSON.stringify(mb.elseHTML)};
1487
+ }
1488
+ __el.querySelectorAll('.sinth-expr').forEach(sinthExpr);
1489
+ __el.querySelectorAll('template[data-sinth-if-expr]').forEach(sinthIfBlock);
1490
+ ${needsDelay ? `__el.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
1491
+ __el.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);` : ""}
1492
+ }
1401
1493
  })();\n`;
1402
1494
  }
1403
1495
  }
@@ -1419,6 +1511,14 @@ function sinthMixedBlock(el, condId, ifJS, ifHTML, elseJS, elseHTML) {
1419
1511
  renderBody += ` document.querySelectorAll('[data-sinth-checked]').forEach(function(el) {
1420
1512
  try { el.checked = !!window[el.dataset.sinthChecked]; } catch(e) {}
1421
1513
  });\n`;
1514
+ if (bodyHTML.includes("data-sinth-checked-expr")) {
1515
+ renderBody += ` document.querySelectorAll('[data-sinth-checked-expr]').forEach(function(el) {
1516
+ try {
1517
+ var exprFn = __X[el.dataset.sinthCheckedExpr];
1518
+ if (exprFn) el.checked = !!exprFn({});
1519
+ } catch(e) {}
1520
+ });\n`;
1521
+ }
1422
1522
  if (needsExpr) {
1423
1523
  renderBody += ` document.querySelectorAll('.sinth-expr').forEach(sinthExpr);\n`;
1424
1524
  }
@@ -1473,7 +1573,7 @@ export function compileFile(filePath: string, opts: CompileOptions): { html: str
1473
1573
  const functionDefs: FunctionDef[] = file.functions; // ← new
1474
1574
 
1475
1575
  const ctx: CompileCtx = {
1476
- allDefs, customEls, cssLinks, jsLinks,
1576
+ allDefs, functionDefs, customEls, cssLinks, jsLinks,
1477
1577
  scopeHash: hash,
1478
1578
  pageFile: absPath,
1479
1579
  extraCSS: [],
@@ -1506,8 +1606,16 @@ export function compileFile(filePath: string, opts: CompileOptions): { html: str
1506
1606
  }
1507
1607
  for (const v of file.varDecls) { if (v.value) assignedVars.add(v.name); }
1508
1608
 
1609
+ // warn about reserved browser globals
1610
+ const RESERVED_GLOBALS = new Set(["name", "location", "history", "status", "closed", "length", "top", "self", "parent", "frames", "origin"]);
1611
+ for (const v of file.varDecls) {
1612
+ if (RESERVED_GLOBALS.has(v.name)) {
1613
+ SinthWarning.emit(`Variable '${v.name}' shadows a reserved browser global. This may cause unexpected behavior. Consider renaming.`, v.loc);
1614
+ }
1615
+ }
1616
+
1509
1617
  // compile function definitions to JS
1510
- const compiledFunctions = functionDefs.map(f => compileFunctionDef(f)).join("\n");
1618
+ const compiledFunctions = functionDefs.map(f => compileFunctionDef(f, ctx)).join("\n");
1511
1619
 
1512
1620
  // companion JS file (needs same name as .sinth, adds support for JS libraries)
1513
1621
  const companionJS = (() => {
package/src/core/expr.ts CHANGED
@@ -1,4 +1,5 @@
1
- import { Expression, Child, AssignStmt, IfBlock, LitStr, LitNum, LitBool } from "./types.ts";
1
+ import { Expression, Child, AssignStmt, IfBlock, ReturnStmt, LitStr, LitNum, LitBool } from "./types.ts";
2
+
2
3
 
3
4
  export function compileExprToJS(expr: Expression, loopVars?: Set<string>): string {
4
5
  switch (expr.kind) {
@@ -55,9 +56,10 @@ export function compileIfToJS(ifBlock: IfBlock): string {
55
56
 
56
57
  export function bodyToJS(children: Child[]): string {
57
58
  return children
58
- .filter(c => c.kind === "assign_stmt" || c.kind === "if")
59
+ .filter(c => c.kind === "assign_stmt" || c.kind === "if" || c.kind === "return")
59
60
  .map(c => {
60
61
  if (c.kind === "assign_stmt") return ` ${compileExprToJS((c as AssignStmt).expression)};\n`;
62
+ if (c.kind === "return") return ` return ${(c as ReturnStmt).expression ? compileExprToJS((c as ReturnStmt).expression!) : ""};\n`;
61
63
  if (c.kind === "if") return compileIfToJS(c as IfBlock).replace(/^/gm, " ") + "\n";
62
64
  return "";
63
65
  })
package/src/core/lexer.ts CHANGED
@@ -22,6 +22,7 @@ const KEYWORDS: Record<string, TT> = {
22
22
  "in": TT.KW_IN,
23
23
  "remove": TT.KW_REMOVE,
24
24
  "function": TT.KW_FUNCTION,
25
+ "return": TT.KW_RETURN,
25
26
  };
26
27
 
27
28
  export class Lexer {
@@ -53,6 +54,7 @@ export class Lexer {
53
54
  // two-character operators ->
54
55
  if (ch === "=" && this.src[this.pos + 1] === "=") { this.adv(); this.adv(); tokens.push({ type: TT.OP_EQEQ, value: "==", loc }); continue; }
55
56
  if (ch === "!" && this.src[this.pos + 1] === "=") { this.adv(); this.adv(); tokens.push({ type: TT.OP_NEQ, value: "!=", loc }); continue; }
57
+ if (ch === "!") { tokens.push(this.single(TT.OP_NOT, loc)); continue; }
56
58
  if (ch === ">" && this.src[this.pos + 1] === "=") { this.adv(); this.adv(); tokens.push({ type: TT.OP_GTEQ, value: ">=", loc }); continue; }
57
59
  if (ch === "<" && this.src[this.pos + 1] === "=") { this.adv(); this.adv(); tokens.push({ type: TT.OP_LTEQ, value: "<=", loc }); continue; }
58
60
 
@@ -1,4 +1,4 @@
1
- import { TT, Token, Loc, Literal, Expression, Attr, Child, CompUse, IfBlock, ForLoop, RemoveStmt, ParamDecl, StyleBlock, ScriptBlock, CompDef, CustomElDecl, VarDeclaration, ImportNode, MetaEntry, FunctionDef, SinthFile, SinthError, SinthWarning, AssignOp, VarType, BinaryOp } from "./types.ts";
1
+ import { TT, Token, Loc, Literal, Expression, Attr, Child, CompUse, IfBlock, ForLoop, RemoveStmt, ReturnStmt, ParamDecl, StyleBlock, ScriptBlock, CompDef, CustomElDecl, VarDeclaration, ImportNode, MetaEntry, FunctionDef, SinthFile, SinthError, SinthWarning, AssignOp, VarType, BinaryOp } from "./types.ts";
2
2
  import { Lexer } from "./lexer.ts";
3
3
  import { compileExprToJS, compileIfToJS } from "./expr.ts";
4
4
  import { tagNameToPascal } from "../utils.ts";
@@ -61,6 +61,15 @@ export class Parser {
61
61
  const forNode = this.parseForLoop();
62
62
  uses.push({ kind: "use", name: "__IF_ROOT__", attrs: [], children: [forNode], loc: forNode.loc });
63
63
  }
64
+ else if (this.check(TT.LPAREN)) {
65
+ const loc = this.peek().loc;
66
+ this.consume(TT.LPAREN);
67
+ const expr = this.parseExpression();
68
+ if (!expr) throw new SinthError("Expected expression after '('", loc);
69
+ if (!this.check(TT.RPAREN)) throw new SinthError("Expected ')'", loc);
70
+ this.consume(TT.RPAREN);
71
+ uses.push({ kind: "use", name: "__IF_ROOT__", attrs: [], children: [{ kind: "expr", expression: expr, loc }], loc });
72
+ }
64
73
  else if (this.check(TT.IDENT)) {
65
74
  const savedPos = this.pos;
66
75
  const identName = this.peek().value;
@@ -171,8 +180,8 @@ uses.push(this.parseCompUse());
171
180
  this.consume(TT.LBRACKET); this.consume(TT.RBRACKET);
172
181
  typeStr = "str[]";
173
182
  }
174
- if (!["int", "str", "bool", "str[]", "obj"].includes(typeStr)) {
175
- throw new SinthError(`Unknown type '${typeStr}'. Expected: int, str, bool, str[], obj`, typeTok.loc);
183
+ if (!["int", "str", "bool", "str[]", "obj", "ui"].includes(typeStr)) {
184
+ throw new SinthError(`Unknown type '${typeStr}'. Expected: int, str, bool, str[], obj, component`, typeTok.loc);
176
185
  }
177
186
 
178
187
  const nameTok = this.consume(TT.IDENT);
@@ -253,8 +262,8 @@ private parseArrayLiteral(): Literal {
253
262
  const tok = this.peek();
254
263
 
255
264
  // Unary 'not'
256
- if (tok.type === TT.IDENT && tok.value === "not") {
257
- this.consume(TT.IDENT);
265
+ if ((tok.type === TT.IDENT && tok.value === "not") || tok.type === TT.OP_NOT) {
266
+ if (tok.type === TT.IDENT) this.consume(TT.IDENT); else this.consume(TT.OP_NOT);
258
267
  const operand = this.parseExpression();
259
268
  if (!operand) throw new SinthError("Expected expression after 'not'", tok.loc);
260
269
  const unaryExpr: Expression = { kind: "unary", op: "not", operand };
@@ -393,8 +402,8 @@ private parseArrayLiteral(): Literal {
393
402
  if (this.check(TT.OP_ARROW)) {
394
403
  this.consume(TT.OP_ARROW);
395
404
  const typeTok = this.consume(TT.IDENT);
396
- if (!["int","str","bool","str[]","obj"].includes(typeTok.value)) {
397
- throw new SinthError(`Unknown return type '${typeTok.value}'. Expected: int, str, bool, str[], obj`, typeTok.loc);
405
+ if (!["int","str","bool","str[]","obj","ui"].includes(typeTok.value)) {
406
+ throw new SinthError(`Unknown return type '${typeTok.value}'. Expected: int, str, bool, str[], obj, ui`, typeTok.loc);
398
407
  }
399
408
  returnType = typeTok.value as VarType;
400
409
  }
@@ -424,6 +433,15 @@ private parseArrayLiteral(): Literal {
424
433
  return { sinthName, tagName, params, loc };
425
434
  }
426
435
 
436
+ private parseReturnStmt(): ReturnStmt {
437
+ const loc = this.consume(TT.KW_RETURN).loc;
438
+ let expression: Expression | undefined;
439
+ if (!this.check(TT.RBRACE) && !this.check(TT.EOF) && !this.check(TT.KW_IF) && !this.check(TT.KW_FOR) && !this.check(TT.KW_RETURN)) {
440
+ expression = this.parseExpression() ?? undefined;
441
+ }
442
+ return { kind: "return", expression, loc };
443
+ }
444
+
427
445
  private parseParamDecls(): ParamDecl[] {
428
446
  const params: ParamDecl[] = [];
429
447
  if (!this.check(TT.LPAREN)) return params;
@@ -472,6 +490,7 @@ private parseArrayLiteral(): Literal {
472
490
  if (vd) this._varDecls.push(vd);
473
491
  continue;
474
492
  }
493
+ else if (this.check(TT.KW_RETURN)){ body.push(this.parseReturnStmt()); }
475
494
  else if (this.check(TT.KW_IF)) { body.push(this.parseIfBlock()); }
476
495
  else if (this.check(TT.KW_FOR)) { body.push(this.parseForLoop()); }
477
496
  else if (this.check(TT.IDENT)) { body.push(this.parseCompUse()); }
@@ -515,6 +534,7 @@ private parseArrayLiteral(): Literal {
515
534
  const children: Child[] = [];
516
535
 
517
536
  while (!this.check(TT.RBRACE) && !this.check(TT.EOF)) {
537
+ if (this.check(TT.KW_RETURN)) { children.push(this.parseReturnStmt()); continue; }
518
538
  if (this.check(TT.KW_IF)) { children.push(this.parseIfBlock()); continue; }
519
539
  if (this.check(TT.KW_FOR)) { children.push(this.parseForLoop()); continue; }
520
540
  if (this.check(TT.LPAREN)) {
@@ -525,6 +545,23 @@ private parseArrayLiteral(): Literal {
525
545
  }
526
546
  continue;
527
547
  }
548
+ if (this.check(TT.IDENT)) {
549
+ const savedPos = this.pos;
550
+ const name = this.peek().value;
551
+ const nextType = this.tokens[this.pos + 1]?.type;
552
+ if (nextType === TT.EQUALS || (nextType === TT.OP_PLUS && this.tokens[this.pos + 2]?.type === TT.EQUALS) || (nextType === TT.OP_MINUS && this.tokens[this.pos + 2]?.type === TT.EQUALS)) {
553
+ this.consume(TT.IDENT);
554
+ let op: AssignOp = "=";
555
+ if (this.check(TT.OP_PLUS)) { this.consume(TT.OP_PLUS); op = "+="; }
556
+ else if (this.check(TT.OP_MINUS)) { this.consume(TT.OP_MINUS); op = "-="; }
557
+ this.consume(TT.EQUALS);
558
+ const rhs = this.parseExpression();
559
+ if (!rhs) throw new SinthError("Expected expression after assignment", this.peek().loc);
560
+ children.push({ kind: "assign_stmt", expression: { kind: "assign", target: name, op, right: rhs }, loc: this.peek().loc });
561
+ continue;
562
+ }
563
+ this.pos = savedPos;
564
+ }
528
565
  if (this.check(TT.STRING)) {
529
566
  const loc = this.peek().loc;
530
567
  children.push({ kind: "text", value: this.consume(TT.STRING).value, loc });
@@ -804,32 +841,34 @@ private parseArrayLiteral(): Literal {
804
841
  while (!this.check(TT.EOF) && !this.check(TT.RBRACE)) {
805
842
  if (this.check(TT.LPAREN)) {
806
843
  const loc = this.peek().loc;
844
+ this.consume(TT.LPAREN);
807
845
  let expr = this.parseExpression();
808
- if (expr) {
809
- while (this.check(TT.OP_PLUS)) {
810
- this.consume(TT.OP_PLUS);
811
- let rhs: Expression | null = null;
812
- if (this.check(TT.STRING)) {
813
- rhs = { kind: "literal", value: { kind: "str", value: this.consume(TT.STRING).value } };
814
- } else if (this.check(TT.IDENT)) {
815
- const rhsName = this.consume(TT.IDENT).value;
816
- if (this.check(TT.DOT)) {
817
- this.consume(TT.DOT);
818
- rhs = { kind: "variable", name: rhsName + "." + this.consume(TT.IDENT).value };
819
- } else if (this.check(TT.LBRACKET)) {
820
- const rhsVar: Expression = { kind: "variable", name: rhsName };
821
- rhs = this.parsePostfix(rhsVar);
822
- } else {
823
- rhs = { kind: "variable", name: rhsName };
824
- }
846
+ if (!expr) throw new SinthError("Expected expression after '('", this.peek().loc);
847
+ if (!this.check(TT.RPAREN)) throw new SinthError("Expected ')'", this.peek().loc);
848
+ this.consume(TT.RPAREN);
849
+ while (this.check(TT.OP_PLUS)) {
850
+ this.consume(TT.OP_PLUS);
851
+ let rhs: Expression | null = null;
852
+ if (this.check(TT.STRING)) {
853
+ rhs = { kind: "literal", value: { kind: "str", value: this.consume(TT.STRING).value } };
854
+ } else if (this.check(TT.IDENT)) {
855
+ const rhsName = this.consume(TT.IDENT).value;
856
+ if (this.check(TT.DOT)) {
857
+ this.consume(TT.DOT);
858
+ rhs = { kind: "variable", name: rhsName + "." + this.consume(TT.IDENT).value };
859
+ } else if (this.check(TT.LBRACKET)) {
860
+ const rhsVar: Expression = { kind: "variable", name: rhsName };
861
+ rhs = this.parsePostfix(rhsVar);
825
862
  } else {
826
- rhs = this.parseExpression();
863
+ rhs = { kind: "variable", name: rhsName };
827
864
  }
828
- if (!rhs) throw new SinthError("Expected expression after +", this.peek().loc);
829
- expr = { kind: "binary", left: expr, op: "+", right: rhs };
865
+ } else {
866
+ rhs = this.parseExpression();
830
867
  }
831
- children.push({ kind: "expr", expression: expr, loc });
868
+ if (!rhs) throw new SinthError("Expected expression after +", this.peek().loc);
869
+ expr = { kind: "binary", left: expr, op: "+", right: rhs };
832
870
  }
871
+ children.push({ kind: "expr", expression: expr, loc });
833
872
  continue;
834
873
  }
835
874
  if (this.check(TT.STRING)) {
@@ -864,6 +903,7 @@ private parseArrayLiteral(): Literal {
864
903
  if (vd) this._varDecls.push(vd);
865
904
  continue;
866
905
  }
906
+ else if (this.check(TT.KW_RETURN)) { children.push(this.parseReturnStmt()); continue; }
867
907
  else if (this.check(TT.KW_IF)) { children.push(this.parseIfBlock()); }
868
908
  else if (this.check(TT.KW_FOR)) { children.push(this.parseForLoop()); }
869
909
  else if (this.check(TT.IDENT)) {
@@ -871,6 +911,18 @@ private parseArrayLiteral(): Literal {
871
911
  const rawName = this.peek().value;
872
912
  const nextType = this.tokens[this.pos + 1]?.type;
873
913
 
914
+ if (nextType === TT.EQUALS || (nextType === TT.OP_PLUS && this.tokens[this.pos + 2]?.type === TT.EQUALS) || (nextType === TT.OP_MINUS && this.tokens[this.pos + 2]?.type === TT.EQUALS)) {
915
+ this.consume(TT.IDENT);
916
+ let op: AssignOp = "=";
917
+ if (this.check(TT.OP_PLUS)) { this.consume(TT.OP_PLUS); op = "+="; }
918
+ else if (this.check(TT.OP_MINUS)) { this.consume(TT.OP_MINUS); op = "-="; }
919
+ this.consume(TT.EQUALS);
920
+ const rhs = this.parseExpression();
921
+ if (!rhs) throw new SinthError("Expected expression after assignment", this.peek().loc);
922
+ children.push({ kind: "assign_stmt", expression: { kind: "assign", target: rawName, op, right: rhs }, loc });
923
+ continue;
924
+ }
925
+
874
926
  if (nextType === TT.DOT) {
875
927
  let fullName = this.consume(TT.IDENT).value;
876
928
  this.consume(TT.DOT);
package/src/core/types.ts CHANGED
@@ -19,10 +19,11 @@ export enum TT {
19
19
  KW_GLOBAL, KW_PAGE, KW_LANG,
20
20
  KW_CUSTOM_EL, KW_CUSTOM,
21
21
  KW_IF, KW_ELSE, KW_FOR, KW_IN, KW_REMOVE,
22
- KW_FUNCTION,
22
+ KW_FUNCTION, KW_RETURN,
23
23
  OP_PLUS, OP_MINUS, OP_STAR, OP_SLASH, OP_SEMI,
24
24
  OP_LT, OP_GT, OP_NEQ, OP_EQEQ, OP_LTEQ, OP_GTEQ,
25
25
  OP_ARROW,
26
+ OP_NOT,
26
27
  EOF,
27
28
  }
28
29
 
@@ -62,9 +63,11 @@ export interface AssignStmt { kind: "assign_stmt"; expression: Expression;
62
63
  export interface IfBlock { kind: "if"; condition: Expression; body: Child[]; elseBody?: Child[]; loc: Loc }
63
64
  export interface ForLoop { kind: "for"; keyVar?: string; itemVar: string; indexVar?: string; arrayVar: string; body: Child[]; loc: Loc }
64
65
  export interface RemoveStmt { kind: "remove"; target: string; loc: Loc }
66
+ export interface ReturnStmt { kind: "return"; expression?: Expression; loc: Loc }
67
+ export interface ComponentExpr { kind: "component_expr"; children: Child[]; loc: Loc }
65
68
 
66
69
 
67
- export type Child = TextNode | CompUse | ExprNode | AssignStmt | IfBlock | ForLoop | RemoveStmt;
70
+ export type Child = TextNode | CompUse | ExprNode | AssignStmt | IfBlock | ForLoop | RemoveStmt | ReturnStmt | ComponentExpr;
68
71
 
69
72
  export interface ParamDecl { name: string; defaultVal?: Literal; loc: Loc }
70
73
 
@@ -82,7 +85,7 @@ export interface CompDef { name: string; params: ParamDecl[]; body: Child[]
82
85
  export interface CustomElDecl { sinthName: string; tagName: string; params: ParamDecl[]; loc: Loc }
83
86
  export interface CustomElInfo { tagName: string; params: ParamDecl[] }
84
87
 
85
- export type VarType = "int" | "str" | "bool" | "str[]" | "obj";
88
+ export type VarType = "int" | "str" | "bool" | "str[]" | "obj" | "ui";
86
89
  export interface VarDeclaration { kind: "var"; name: string; varType: VarType; value: Literal | null; loc: Loc }
87
90
 
88
91
  export type ImportNode =
@@ -126,6 +129,7 @@ export interface MixedBlockEntry {
126
129
 
127
130
  export interface CompileCtx {
128
131
  allDefs: Map<string, CompDef>;
132
+ functionDefs: FunctionDef[];
129
133
  customEls: Map<string, CustomElInfo>;
130
134
  cssLinks: string[];
131
135
  jsLinks: { src: string; attrs: Record<string, string> }[];
@@ -1,399 +0,0 @@
1
- import { VarDeclaration, MixedBlockEntry, SinthWarning } from "./types.ts";
2
- import { litToString } from "../utils.ts";
3
-
4
-
5
-
6
- export function buildRuntime(opts: {
7
- varDecls: VarDeclaration[];
8
- bodyHTML: string;
9
- logicBlocks: string[];
10
- mixedBlocks: MixedBlockEntry[];
11
- assignedVars: Set<string>;
12
- exprRegistry: string[];
13
- sharedRuntime: boolean;
14
- functionsJS: string; // ← new
15
- }): string | { page: string; shared: string } {
16
- const { varDecls, bodyHTML, logicBlocks, mixedBlocks, assignedVars, exprRegistry, functionsJS } = opts;
17
-
18
- const needsExpr = bodyHTML.includes("sinth-expr");
19
- const needsIf = bodyHTML.includes("data-sinth-if");
20
- const needsFor = bodyHTML.includes("data-sinth-for");
21
- const needsDelay = bodyHTML.includes("data-sinth-delay") || bodyHTML.includes("data-sinth-delay-expr-id") || mixedBlocks.some(mb => mb.ifHTML.includes("data-sinth-delay") || mb.ifHTML.includes("data-sinth-delay-expr-id") || mb.elseHTML.includes("data-sinth-delay") || mb.elseHTML.includes("data-sinth-delay-expr-id"));
22
- const needsMixed = mixedBlocks.length > 0;
23
- const needsLogic = logicBlocks.length > 0;
24
- const needsRender = needsExpr || needsIf || needsFor || needsMixed || needsLogic;
25
-
26
- const varLines = varDecls.map(v => {
27
- if (!v.value) {
28
- if (!assignedVars.has(v.name)) {
29
- const defaults: Record<string, string> = { str: '""', int: "0", bool: "false", "str[]": "[]" };
30
- SinthWarning.emit(
31
- `Variable '${v.name}' is declared but never assigned. Defaulting to ${defaults[v.varType] ?? "undefined"}.`,
32
- v.loc,
33
- );
34
- }
35
- const defaults: Record<string, string> = { str: '""', int: "0", bool: "false", "str[]": "[]" };
36
- return `var ${v.name} = ${defaults[v.varType] ?? "undefined"};`;
37
- }
38
- const val = litToString(v.value);
39
- if (val.startsWith("__VAR__")) return `var ${v.name} = ${val.slice(7)};`;
40
- if (val.startsWith("__ARR__")) return `var ${v.name} = ${val.slice(7)};`;
41
- if (v.varType === "obj") return `var ${v.name} = ${val};`;
42
- if (v.varType === "str") return `var ${v.name} = ${JSON.stringify(val)};`;
43
- if (v.varType === "str[]" && typeof val === 'string' && val.startsWith("__ARR__")) {
44
- try {
45
- const arr = JSON.parse(val.slice(7));
46
- return `var ${v.name} = ${JSON.stringify(arr)};`;
47
- } catch { return `var ${v.name} = ${val.slice(7)};`; }
48
- }
49
- return `var ${v.name} = ${val};`;
50
- }).join("\n");
51
-
52
- if (!needsRender && !needsDelay) {
53
- return varLines ? `// Sinth compiled runtime\n${varLines}` : "";
54
- }
55
-
56
- let helpers = "";
57
-
58
- if (needsExpr || needsIf || needsFor) {
59
- helpers += `
60
- function sinthExpr(el) {
61
- try {
62
- var exprFn = __X[el.dataset.exprId];
63
- if (exprFn) el.textContent = exprFn({});
64
- } catch(e) {}
65
- }
66
- `;
67
- }
68
-
69
- if (needsIf || needsMixed) {
70
- helpers += `
71
- function sinthReplaceInsert(t, anchor, ifId, replaceId) {
72
- if (anchor) {
73
- var cur = anchor.nextSibling;
74
- while (cur && cur !== t) { var nx = cur.nextSibling; cur.remove(); cur = nx; }
75
- } else {
76
- anchor = document.createElement('span');
77
- anchor.style.display = 'none';
78
- anchor.dataset.sinthIfAnchor = ifId;
79
- t.parentNode.insertBefore(anchor, t);
80
- }
81
- var _rp = null, _rpParent = null, _rpNext = null;
82
- if (replaceId) {
83
- _rp = document.getElementById(replaceId);
84
- if (_rp) {
85
- _rpParent = _rp.parentNode;
86
- _rpNext = _rp.nextSibling;
87
- _rp.parentNode.removeChild(_rp);
88
- anchor._sinthReplaced = _rp;
89
- anchor._sinthReplacedParent = _rpParent;
90
- anchor._sinthReplacedNext = _rpNext;
91
- }
92
- }
93
- var frag = document.createRange().createContextualFragment(t.innerHTML);
94
- frag.querySelectorAll('.sinth-expr').forEach(sinthExpr);
95
- if (${needsDelay}) {
96
- frag.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
97
- frag.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
98
- }
99
- var fragFirst = frag.firstChild;
100
- var fragLast = frag.lastChild;
101
- if (_rpParent && _rpNext) {
102
- _rpParent.insertBefore(frag, _rpNext);
103
- } else if (_rpParent) {
104
- _rpParent.appendChild(frag);
105
- } else {
106
- t.parentNode.insertBefore(frag, t);
107
- }
108
- if (replaceId && anchor) {
109
- anchor._sinthInsertedFirst = fragFirst;
110
- anchor._sinthInsertedLast = fragLast;
111
- }
112
- return anchor;
113
- }
114
- `;
115
- }
116
-
117
- if (needsDelay) {
118
- helpers += `
119
- function sinthDelay(el) {
120
- if (el.dataset.sinthDelayDone) { el.style.display = ''; return; }
121
- el.dataset.sinthDelayDone = '1';
122
- var ms = parseInt(el.dataset.sinthDelay) || 0;
123
- el.style.display = 'none';
124
- if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
125
- else el.style.display = '';
126
- }
127
- function sinthDelayExpr(el) {
128
- try {
129
- var fn = __X[el.dataset.sinthDelayExprId];
130
- var ms = fn ? parseInt(fn()) || 0 : 0;
131
- el.style.display = '';
132
- if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
133
- } catch(e) {}
134
- }
135
- `;
136
- }
137
-
138
- if (needsIf) {
139
- helpers += `
140
- function sinthIfBlock(t) {
141
- var ifId = t.dataset.sinthIfId;
142
- var anchor = t.parentNode.querySelector('[data-sinth-if-anchor="' + ifId + '"]');
143
- var condFn = __X[t.dataset.sinthIfExpr];
144
- var cond = condFn ? condFn() : false;
145
- if (cond) {
146
- anchor = sinthReplaceInsert(t, anchor, ifId, t.dataset.sinthIfReplace);
147
- } else {
148
- if (anchor) {
149
- if (anchor._sinthReplaced) {
150
- var insFirst = anchor._sinthInsertedFirst;
151
- var insLast = anchor._sinthInsertedLast;
152
- var rpParent = anchor._sinthReplacedParent;
153
- var rpNext = anchor._sinthReplacedNext;
154
- if (insFirst && insLast) {
155
- var cur = insFirst;
156
- while (cur && cur !== insLast) {
157
- var next = cur.nextSibling;
158
- cur.remove();
159
- cur = next;
160
- }
161
- if (insLast) insLast.remove();
162
- }
163
- if (rpParent && rpNext) {
164
- rpParent.insertBefore(anchor._sinthReplaced, rpNext);
165
- } else if (rpParent) {
166
- rpParent.appendChild(anchor._sinthReplaced);
167
- }
168
- } else {
169
- var cur2 = anchor.nextSibling;
170
- while (cur2 && cur2 !== t) { var nx2 = cur2.nextSibling; cur2.remove(); cur2 = nx2; }
171
- }
172
- anchor.remove();
173
- }
174
- var elseT = t.nextElementSibling;
175
- if (elseT && elseT.hasAttribute('data-sinth-else')) {
176
- var elseIfId = elseT.dataset.sinthIfId;
177
- var ea = t.parentNode.querySelector('[data-sinth-if-anchor="__else__' + elseIfId + '"]');
178
- if (ea) {
179
- var cur3 = ea.nextSibling;
180
- while (cur3 && cur3 !== t) { var nx3 = cur3.nextSibling; cur3.remove(); cur3 = nx3; }
181
- } else {
182
- ea = document.createElement('span');
183
- ea.style.display = 'none';
184
- ea.dataset.sinthIfAnchor = '__else__' + elseIfId;
185
- t.parentNode.insertBefore(ea, t);
186
- }
187
- var ef = document.createRange().createContextualFragment(elseT.innerHTML);
188
- ef.querySelectorAll('.sinth-expr').forEach(sinthExpr);
189
- if (${needsDelay}) {
190
- ef.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
191
- ef.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
192
- }
193
- t.parentNode.insertBefore(ef, t);
194
- } else {
195
- var ea2 = t.parentNode.querySelector('[data-sinth-if-anchor="__else__' + ifId + '"]');
196
- if (ea2) {
197
- var ec = ea2.nextSibling;
198
- while (ec && ec !== t) { var en = ec.nextSibling; ec.remove(); ec = en; }
199
- ea2.remove();
200
- }
201
- }
202
- }
203
- }
204
- `;
205
- }
206
-
207
- if (needsFor) {
208
- helpers += `
209
- function hashString(str) {
210
- var hash = 0, i, chr;
211
- for (i = 0; i < str.length; i++) {
212
- chr = str.charCodeAt(i);
213
- hash = ((hash << 5) - hash) + chr;
214
- hash |= 0;
215
- }
216
- return String(hash);
217
- }
218
- function sinthForBlock(t) {
219
- var source = window[t.dataset.sinthFor];
220
- if (source === undefined) source = [];
221
- var newHash = '';
222
- try { newHash = hashString(JSON.stringify(source)); } catch(e) { newHash = ''; }
223
- if (t.dataset.sinthForHash && t.dataset.sinthForHash === newHash) {
224
- return;
225
- }
226
- t.dataset.sinthForHash = newHash;
227
- var isObj = (typeof source === 'object' && source !== null && !Array.isArray(source));
228
- var entries;
229
- if (isObj) {
230
- entries = Object.entries(source);
231
- } else {
232
- if (!Array.isArray(source)) source = [];
233
- entries = source.map(function(item, index) { return [index, item]; });
234
- }
235
- var anchor = t.parentNode ? t.parentNode.querySelector('[data-sinth-for-anchor="' + t.dataset.sinthFor + '"]') : null;
236
- if (anchor) {
237
- var cur2 = anchor.nextSibling;
238
- while (cur2 && cur2 !== t) { var nx2 = cur2.nextSibling; cur2.remove(); cur2 = nx2; }
239
- anchor.remove();
240
- }
241
- var fa = document.createElement('span');
242
- fa.style.display = 'none';
243
- fa.dataset.sinthForAnchor = t.dataset.sinthFor;
244
- t.parentNode && t.parentNode.insertBefore(fa, t);
245
- var _loopIdx = 0;
246
- entries.forEach(function(entry) {
247
- var _k = entry[0];
248
- var _v = entry[1];
249
- var _item = (t.dataset && t.dataset.sinthItem) ? t.dataset.sinthItem : '__item__';
250
- var _key = t.dataset && t.dataset.sinthKey ? t.dataset.sinthKey : null;
251
- var _idx = t.dataset && t.dataset.sinthIndex ? t.dataset.sinthIndex : null;
252
- _loopIdx++;
253
- if (t.dataset.sinthIfReplace) {
254
- var _rp = document.getElementById(t.dataset.sinthIfReplace);
255
- if (_rp) _rp.parentNode.removeChild(_rp);
256
- }
257
- var frag = document.createRange().createContextualFragment(t.innerHTML);
258
- frag.querySelectorAll('.sinth-expr').forEach(function(el) {
259
- try {
260
- var exprFn = __X[el.dataset.exprId];
261
- if (!exprFn) return;
262
- var _ctx = {};
263
- if (_item) _ctx[_item] = _v;
264
- if (_key) _ctx[_key] = _k;
265
- if (_idx) _ctx[_idx] = _loopIdx - 1;
266
- el.textContent = exprFn(_ctx);
267
- el.classList.remove('sinth-expr');
268
- } catch(e) {}
269
- });
270
- frag.querySelectorAll('template[data-sinth-if-expr]').forEach(function(ifT) {
271
- var condFn = __X[ifT.dataset.sinthIfExpr];
272
- var _ctx = {};
273
- if (_item) _ctx[_item] = _v;
274
- if (_key) _ctx[_key] = _k;
275
- if (_idx) _ctx[_idx] = _loopIdx - 1;
276
- var cond = false;
277
- try { if (condFn) cond = condFn(_ctx); } catch(e) {}
278
- if (cond) {
279
- var ifContent = document.createRange().createContextualFragment(ifT.innerHTML);
280
- ifContent.querySelectorAll('.sinth-expr').forEach(function(el2) {
281
- try {
282
- var exprFn2 = __X[el2.dataset.exprId];
283
- if (exprFn2) el2.textContent = exprFn2(_ctx);
284
- } catch(e) {}
285
- });
286
- ifT.parentNode.insertBefore(ifContent, ifT);
287
- } else {
288
- var elseT = ifT.nextElementSibling;
289
- if (elseT && elseT.hasAttribute('data-sinth-else')) {
290
- var elseContent = document.createRange().createContextualFragment(elseT.innerHTML);
291
- elseContent.querySelectorAll('.sinth-expr').forEach(function(el2) {
292
- try {
293
- var exprFn2 = __X[el2.dataset.exprId];
294
- if (exprFn2) el2.textContent = exprFn2(_ctx);
295
- } catch(e) {}
296
- });
297
- ifT.parentNode.insertBefore(elseContent, ifT);
298
- }
299
- }
300
- });
301
- if (${needsDelay}) {
302
- frag.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
303
- frag.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
304
- }
305
- t.parentNode && t.parentNode.insertBefore(frag, t);
306
- });
307
- }
308
- `;
309
- }
310
-
311
- if (needsMixed) {
312
- helpers += `
313
- function sinthMixedBlock(el, condId, ifJS, ifHTML, elseJS, elseHTML) {
314
- var condFn = __X[condId];
315
- var cond = condFn ? condFn() : false;
316
- if (cond) {
317
- if (ifJS) eval(ifJS);
318
- el.innerHTML = ifHTML;
319
- } else {
320
- if (elseJS) eval(elseJS);
321
- el.innerHTML = elseHTML;
322
- }
323
- el.querySelectorAll('.sinth-expr').forEach(sinthExpr);
324
- el.querySelectorAll('template[data-sinth-if-expr]').forEach(sinthIfBlock);
325
- if (${needsDelay}) {
326
- el.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
327
- el.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
328
- }
329
- }
330
- `;
331
- }
332
-
333
- const exprArrayJS = exprRegistry.length > 0
334
- ? `var __X = [${exprRegistry.map((js) => `function(_ctx){ return ${js}; }`).join(",")}];\n`
335
- : "";
336
-
337
- let renderBody = "";
338
- renderBody += ` var _sx = window.scrollX, _sy = window.scrollY;\n`;
339
-
340
- if (needsLogic) {
341
- renderBody += logicBlocks.map(b => b.replace(/^/gm, " ")).join("\n") + "\n";
342
- }
343
-
344
- if (needsMixed) {
345
- for (const mb of mixedBlocks) {
346
- renderBody += ` (function() {
347
- var __el = document.getElementById(${JSON.stringify(mb.replaceId || mb.id)});
348
- if (__el) sinthMixedBlock(__el, ${mb.conditionJS}, ${JSON.stringify(mb.ifJS)}, ${JSON.stringify(mb.ifHTML)}, ${JSON.stringify(mb.elseJS)}, ${JSON.stringify(mb.elseHTML)});
349
- })();\n`;
350
- }
351
- }
352
-
353
- renderBody += ` document.querySelectorAll('[data-sinth-remove]').forEach(function(el) {
354
- var target = document.getElementById(el.dataset.sinthRemove);
355
- if (target) target.remove();
356
- });\n`;
357
-
358
- if (needsIf) {
359
- renderBody += ` document.querySelectorAll('template[data-sinth-if-expr]').forEach(sinthIfBlock);\n`;
360
- }
361
- if (needsFor) {
362
- renderBody += ` document.querySelectorAll('template[data-sinth-for]').forEach(sinthForBlock);\n`;
363
- }
364
- renderBody += ` document.querySelectorAll('[data-sinth-value]').forEach(function(el) {
365
- try { el.value = window[el.dataset.sinthValue] || ''; } catch(e) {}
366
- });\n`;
367
- renderBody += ` document.querySelectorAll('[data-sinth-checked]').forEach(function(el) {
368
- try { el.checked = !!window[el.dataset.sinthChecked]; } catch(e) {}
369
- });\n`;
370
- if (needsExpr) {
371
- renderBody += ` document.querySelectorAll('.sinth-expr').forEach(sinthExpr);\n`;
372
- }
373
- if (needsDelay) {
374
- renderBody += ` setTimeout(function() {
375
- document.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
376
- document.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
377
- }, 0);\n`;
378
- }
379
- renderBody += ` window.scrollTo(_sx, _sy);\n`;
380
-
381
- const renderFunc = needsRender ? `function sinthRender() {\n${renderBody}}\nsinthRender();` : "";
382
-
383
- const pageCode = `// Sinth page runtime
384
- ${varLines}
385
- ${functionsJS ? functionsJS + "\n" : ""}${exprArrayJS}
386
- ${renderFunc}`;
387
-
388
- if (opts.sharedRuntime && helpers.trim()) {
389
- const sharedCode = `// Sinth shared runtime
390
- ${helpers}`;
391
- return { page: pageCode, shared: sharedCode };
392
- }
393
-
394
- return `// Sinth compiled runtime
395
- ${varLines}
396
- ${functionsJS ? functionsJS + "\n" : ""}${helpers}
397
- ${exprArrayJS}
398
- ${renderFunc}`;
399
- }