@yannosay/sinth 0.7.1 → 0.8.1

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,13 +1,16 @@
1
- # Sinth
1
+ # Sinth
2
2
 
3
3
  The language that fixes HTML. Declarative. Reactive. Compiles to pure HTML.
4
4
 
5
5
 
6
+ [![npm version](https://img.shields.io/npm/v/@yannosay/sinth)](https://www.npmjs.com/package/@yannosay/sinth)
7
+ [![npm downloads](https://img.shields.io/npm/dw/@yannosay/sinth)](https://www.npmjs.com/package/@yannosay/sinth)
8
+ [![license](https://img.shields.io/npm/l/@yannosay/sinth)](https://github.com/Yannosay/sinth/blob/main/LICENSE)
6
9
 
7
10
  ## Why Sinth?
8
11
 
9
12
  #### Reactive forms in one line.
10
- ```
13
+ ```ts
11
14
  Input(bind: userName, placeholder: "Enter your name")
12
15
  Paragraph { "Hello, " + userName }
13
16
  ```
@@ -15,7 +18,7 @@ Paragraph { "Hello, " + userName }
15
18
  No useState. No onChange. No e.target.value. Just bind.
16
19
 
17
20
  #### Logic and UI live together.
18
- ```TS
21
+ ```ts
19
22
  if user.isAdmin {
20
23
  Button(onClick: "deletePost()") { "Delete" }
21
24
  }
@@ -32,11 +35,22 @@ Paragraph(delay: index * 300) { item.name }
32
35
 
33
36
  Staggered animations. One expression. No useEffect. No setTimeout chains.
34
37
 
35
- #### Compiles to pure HTML.
36
- Ready to upload wherever you want.
38
+ #### Multiple actions, single handler.
39
+ ```ts
40
+ Button(onClick: show = not show; deleted = true) { "Toggle & Delete" }
41
+ Chain statements with ;. No wrapper functions. No script blocks.
42
+ ```
37
43
 
44
+ ```ts
45
+ if done == true {
46
+ remove "myElement"
47
+ }
48
+ ```
49
+ Delete elements for good. No virtual DOM diffing.
38
50
 
51
+ Compiles to pure HTML.
39
52
 
53
+ #### Ready to upload wherever you want.
40
54
 
41
55
 
42
56
  # Install
@@ -56,7 +70,7 @@ Open your browser. Edit your .sinth file. Watch it update live.
56
70
 
57
71
 
58
72
  ## Your First Sinth File
59
- ```TS
73
+ ```ts
60
74
  page
61
75
  title = "My Sinth Project"
62
76
 
@@ -89,6 +103,16 @@ Main {
89
103
 
90
104
  ###### Nothing you like? Give us feedback on our [Discord Server](https://discord.gg/SUvcrafTQm)!
91
105
 
106
+ ## Shared Runtime
107
+
108
+ For multi-page projects, extract helpers into a cached file:
109
+ `sinth build --shared-runtime`
110
+
111
+
112
+ This creates a `sinth-runtime.js` file shared across all pages. Each page shrinks to ~25 lines of render logic. The browser caches the helpers once.
113
+
114
+ Helpful when working on big projects.
115
+
92
116
  ## Security
93
117
 
94
118
  Sinth's reactive runtime does not use eval(). Every expression is pre-compiled into optimized JavaScript functions at build time. No code injection possible. No runtime string evaluation. The most secure way to power reactive UI.
@@ -100,6 +124,7 @@ Sinth's reactive runtime does not use eval(). Every expression is pre-compiled i
100
124
  - sinth init — scaffold a new project
101
125
  - sinth dev [file] — start dev server with live reload
102
126
  - sinth build — compile to static files
127
+ - sinth build --shared-runtime — build with shared runtime (useful when using a heavier runtime)
103
128
  - sinth check — lint without output
104
129
  - sinth version — print version
105
130
 
package/bin/sinth.js CHANGED
@@ -1,4 +1,4 @@
1
- #!/usr/bin/env node
1
+ #!/usr/bin/env node
2
2
  const path = require('path');
3
3
  const tsSource = path.join(__dirname, '..', 'src', 'sinth.ts');
4
4
  require('ts-node').register({ project: path.join(__dirname, '..', 'tsconfig.json') });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yannosay/sinth",
3
- "version": "0.7.1",
3
+ "version": "0.8.1",
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",
@@ -32,7 +32,6 @@
32
32
  "LICENSE"
33
33
  ],
34
34
  "dependencies": {
35
- "@yannosay/sinth": "^0.0.9",
36
35
  "sass": "^1.70.0",
37
36
  "ts-node": "^10.9.0"
38
37
  },
package/src/sinth.ts CHANGED
@@ -1,7 +1,5 @@
1
1
  #!/usr/bin/env node
2
- // Sinth Compiler 0.5.4 — Unified if/else, Sinth Style language, tree-shaken runtime
3
- // Single-file TypeScript compiler for the Sinth declarative web language.
4
- // Run with: npx ts-node sinth.ts build | sinth build | sinth dev
2
+ // Sinth Compiler
5
3
 
6
4
  import * as fs from "fs";
7
5
  import * as path from "path";
@@ -10,7 +8,6 @@ import * as http from "http";
10
8
 
11
9
  interface Loc { file: string; line: number; col: number }
12
10
 
13
- // plain `enum TT` so TT[t] string-indexing works at runtime.
14
11
  enum TT {
15
12
  LBRACE, RBRACE, LPAREN, RPAREN, COLON, COMMA, EQUALS, DOT,
16
13
  LBRACKET, RBRACKET,
@@ -21,22 +18,20 @@ enum TT {
21
18
  KW_COMPONENT, KW_STYLE, KW_SCRIPT,
22
19
  KW_GLOBAL, KW_PAGE, KW_LANG,
23
20
  KW_CUSTOM_EL, KW_CUSTOM,
24
- KW_IF, KW_ELSE, KW_FOR, KW_IN,
25
- OP_PLUS, OP_MINUS, OP_STAR, OP_SLASH,
21
+ KW_IF, KW_ELSE, KW_FOR, KW_IN, KW_REMOVE,
22
+ OP_PLUS, OP_MINUS, OP_STAR, OP_SLASH, OP_SEMI,
26
23
  OP_LT, OP_GT, OP_NEQ, OP_EQEQ, OP_LTEQ, OP_GTEQ,
27
24
  EOF,
28
25
  }
29
26
 
30
27
  interface Token { type: TT; value: string; loc: Loc }
31
28
 
32
- // literal types
33
29
  type LitStr = { kind: "str"; value: string };
34
30
  type LitNum = { kind: "num"; value: number };
35
31
  type LitBool = { kind: "bool"; value: boolean };
36
32
  type LitNull = { kind: "null" };
37
33
  type Literal = LitStr | LitNum | LitBool | LitNull;
38
34
 
39
- // expression AST
40
35
  type UnaryOp = "not" | "-";
41
36
  type BinaryOp = "+" | "-" | "*" | "/" | "==" | "!=" | "<" | ">" | "<=" | ">=" | "and" | "or";
42
37
  type AssignOp = "=" | "+=" | "-=";
@@ -62,11 +57,11 @@ interface ExprNode { kind: "expr"; expression: Expression;
62
57
  interface AssignStmt { kind: "assign_stmt"; expression: Expression; loc: Loc }
63
58
  interface IfBlock { kind: "if"; condition: Expression; body: Child[]; elseBody?: Child[]; loc: Loc }
64
59
  interface ForLoop { kind: "for"; keyVar?: string; itemVar: string; indexVar?: string; arrayVar: string; body: Child[]; loc: Loc }
60
+ interface RemoveStmt { kind: "remove"; target: string; loc: Loc }
65
61
 
66
- // assignStmt is a first-class child so if bodies can be mixed
67
- type Child = TextNode | CompUse | ExprNode | AssignStmt | IfBlock | ForLoop;
68
62
 
69
- // component / file structure
63
+ type Child = TextNode | CompUse | ExprNode | AssignStmt | IfBlock | ForLoop | RemoveStmt;
64
+
70
65
  interface ParamDecl { name: string; defaultVal?: Literal; loc: Loc }
71
66
 
72
67
  interface StyleBlock {
@@ -170,7 +165,6 @@ class SinthWarning {
170
165
  }
171
166
  }
172
167
 
173
- // FNV-1a 32-bit hash → 8-char hex scope id
174
168
  function fnv1a(s: string): string {
175
169
  let h = 0x811c9dc5;
176
170
  for (let i = 0; i < s.length; i++) {
@@ -186,7 +180,6 @@ function camelToKebab(s: string): string {
186
180
  return s.replace(/([A-Z])/g, m => `-${m.toLowerCase()}`);
187
181
  }
188
182
 
189
- // "w-counter" → "WCounter"
190
183
  function tagNameToPascal(tag: string): string {
191
184
  return tag.split("-").map(p => p.charAt(0).toUpperCase() + p.slice(1)).join("");
192
185
  }
@@ -228,6 +221,7 @@ const KEYWORDS: Record<string, TT> = {
228
221
  "else": TT.KW_ELSE,
229
222
  "for": TT.KW_FOR,
230
223
  "in": TT.KW_IN,
224
+ "remove": TT.KW_REMOVE,
231
225
  };
232
226
 
233
227
  export class Lexer {
@@ -266,6 +260,7 @@ export class Lexer {
266
260
  if (ch === "+") { tokens.push(this.single(TT.OP_PLUS, loc)); continue; }
267
261
  if (ch === "*") { tokens.push(this.single(TT.OP_STAR, loc)); continue; }
268
262
  if (ch === "/") { tokens.push(this.single(TT.OP_SLASH, loc)); continue; }
263
+ if (ch === ";") { tokens.push(this.single(TT.OP_SEMI, loc)); continue; }
269
264
  if (ch === "<") { tokens.push(this.single(TT.OP_LT, loc)); continue; }
270
265
  if (ch === ">") { tokens.push(this.single(TT.OP_GT, loc)); continue; }
271
266
  if (ch === "-" && !this.isDigit(this.src[this.pos + 1] ?? "")) {
@@ -314,7 +309,7 @@ export class Lexer {
314
309
  const ch = this.src[this.pos];
315
310
  if (ch === " " || ch === "\t" || ch === "\r" || ch === "\n") { this.adv(); continue; }
316
311
 
317
- // sinth comments: -- line or --[ nestable block ]--
312
+ // sinth comments: -- line or --[ nestable block for when doing longgerrr comments]--
318
313
  if (ch === "-" && this.src[this.pos + 1] === "-") {
319
314
  if (this.src[this.pos + 2] === "[") {
320
315
  this.adv(); this.adv(); this.adv();
@@ -954,6 +949,19 @@ private parseArrayLiteral(): Literal {
954
949
  continue;
955
950
  }
956
951
 
952
+ if (this.check(TT.KW_REMOVE)) {
953
+ const loc = this.consume(TT.KW_REMOVE).loc;
954
+ if (this.check(TT.STRING)) {
955
+ const target = this.consume(TT.STRING).value;
956
+ children.push({ kind: "remove", target, loc });
957
+ } else {
958
+ throw new SinthError(
959
+ `Expected a string after 'remove', got '${this.peek().value}'. Use remove "id".`,
960
+ this.peek().loc,
961
+ );
962
+ }
963
+ continue;
964
+ }
957
965
  if (this.check(TT.IDENT) && this.peek().value === "var") {
958
966
  const vd = this.parseVarDeclaration();
959
967
  if (vd) this._varDecls.push(vd);
@@ -1141,12 +1149,23 @@ private parseArrayLiteral(): Literal {
1141
1149
  value = this.parseLiteral();
1142
1150
  } else {
1143
1151
  const savedPos = this.pos;
1144
- const expr = this.parseExpression();
1145
- if (expr && (this.check(TT.COMMA) || this.check(TT.RPAREN))) {
1146
- value = { kind: "str", value: "__EXPR__" + JSON.stringify(expr) };
1152
+ const expr = this.parseExpression();
1153
+ if (expr && (this.check(TT.COMMA) || this.check(TT.RPAREN) || this.check(TT.OP_SEMI))) {
1154
+ const exprs: Expression[] = [expr];
1155
+ while (this.check(TT.OP_SEMI)) {
1156
+ this.consume(TT.OP_SEMI);
1157
+ const next = this.parseExpression();
1158
+ if (next) exprs.push(next);
1159
+ else break;
1160
+ }
1161
+ if (exprs.length === 1) {
1162
+ value = { kind: "str", value: "__EXPR__" + JSON.stringify(exprs[0]) };
1163
+ } else {
1164
+ value = { kind: "str", value: "__MULTI_EXPR__" + JSON.stringify(exprs) };
1165
+ }
1147
1166
  } else {
1148
1167
  this.pos = savedPos;
1149
- value = this.parseLiteral();
1168
+ value = this.parseLiteral();
1150
1169
  }
1151
1170
  }
1152
1171
  } else {
@@ -2173,21 +2192,34 @@ if (name === "delay") {
2173
2192
 
2174
2193
  let raw = value.value;
2175
2194
 
2195
+ if (raw.startsWith("__MULTI_EXPR__")) {
2196
+ const exprJson = raw.substring("__MULTI_EXPR__".length);
2197
+ try {
2198
+ const exprs: Expression[] = JSON.parse(exprJson);
2199
+ const jsExprs = exprs.map(e => compileExprToJS(e)).join("; ");
2200
+ const ev = eventAttrName(name);
2201
+ if (ev) return `${ev}="(function(){ ${jsExprs.replace(/"/g, "&quot;")}; sinthRender(); })()"`;
2202
+ return `${name}="${escAttr(jsExprs)}"`;
2203
+ } catch { }
2204
+ }
2176
2205
  if (raw.startsWith("__EXPR__")) {
2177
2206
  const exprJson = raw.substring("__EXPR__".length);
2178
2207
  try {
2179
2208
  const expr: Expression = JSON.parse(exprJson);
2180
2209
  const jsExpr = compileExprToJS(expr);
2181
2210
  const ev = eventAttrName(name);
2182
- if (ev) return `${ev}="(function(){ ${jsExpr.replace(/"/g, "&quot;")}; })()"`;
2211
+ if (ev) return `${ev}="(function(){ ${jsExpr.replace(/"/g, "&quot;")}; sinthRender(); })()"`;
2183
2212
  return `${name}="${escAttr(jsExpr)}"`;
2184
- } catch { /* fall through */ }
2213
+ } catch { }
2185
2214
  }
2186
2215
 
2187
2216
  raw = interpolateAttr(raw, paramMap);
2188
2217
 
2189
2218
  const ev = eventAttrName(name);
2190
- if (ev) return `${ev}="${escAttr(raw)};sinthRender()"`;
2219
+ if (ev) {
2220
+ const call = raw.includes("(") ? raw : raw + "()";
2221
+ return `${ev}="${escAttr(call)};sinthRender()"`;
2222
+ }
2191
2223
  return `${name}="${escAttr(raw)}"`;
2192
2224
  }
2193
2225
 
@@ -2260,6 +2292,10 @@ function renderChild(
2260
2292
  return "";
2261
2293
  }
2262
2294
 
2295
+ case "remove": {
2296
+ return `<span data-sinth-remove="${esc((child as RemoveStmt).target)}"></span>`;
2297
+ }
2298
+
2263
2299
  case "if":
2264
2300
  return renderIfBlock(child, ctx, params, depth);
2265
2301
 
@@ -2316,7 +2352,7 @@ depth: number,
2316
2352
  if (firstComp) {
2317
2353
  const idAttr = firstComp.attrs.find(a => a.name === "id");
2318
2354
  const replAttr = firstComp.attrs.find(a => a.name === "replace");
2319
- const wantsReplace = !replAttr || replAttr.value === null || (replAttr.value?.kind === "bool" && replAttr.value.value === true);
2355
+ const wantsReplace = replAttr && (replAttr.value === null || (replAttr.value?.kind === "bool" && replAttr.value.value));
2320
2356
  if (idAttr && idAttr.value?.kind === "str" && wantsReplace) {
2321
2357
  replaceAttr = ` data-sinth-if-replace="${escAttr(idAttr.value.value)}"`;
2322
2358
  }
@@ -2357,14 +2393,14 @@ depth: number,
2357
2393
  const ifId = ifFirstComp.attrs.find(a => a.name === "id")?.value;
2358
2394
  const ifReplace = ifFirstComp.attrs.find(a => a.name === "replace");
2359
2395
  const ifReplaceVal = ifReplace?.value;
2360
- const ifWantsReplace = !ifReplace || (ifReplaceVal?.kind === "bool" && ifReplaceVal.value === true) || (ifReplaceVal === null);
2396
+ const ifWantsReplace = ifReplace && (ifReplaceVal === null || (ifReplaceVal?.kind === "bool" && ifReplaceVal.value));
2361
2397
 
2362
2398
  if (ifId && ifId.kind === "str" && ifWantsReplace) {
2363
2399
  if (elseFirstComp) {
2364
2400
  const elseId = elseFirstComp.attrs.find(a => a.name === "id")?.value;
2365
2401
  const elseReplace = elseFirstComp.attrs.find(a => a.name === "replace");
2366
2402
  const elseReplaceVal = elseReplace?.value;
2367
- const elseWantsReplace = !elseReplace || (elseReplaceVal?.kind === "bool" && elseReplaceVal.value === true) || (elseReplaceVal === null);
2403
+ const elseWantsReplace = elseReplace && (elseReplaceVal === null || (elseReplaceVal?.kind === "bool" && elseReplaceVal.value));
2368
2404
 
2369
2405
  if (elseId && elseId.kind === "str" && elseId.value === ifId.value && elseWantsReplace) {
2370
2406
  replaceId = ifId.value;
@@ -2666,19 +2702,18 @@ function buildRuntime(opts: {
2666
2702
  mixedBlocks: MixedBlockEntry[];
2667
2703
  assignedVars: Set<string>;
2668
2704
  exprRegistry: string[];
2669
- }): string {
2705
+ sharedRuntime: boolean;
2706
+ }): string | { page: string; shared: string } {
2670
2707
  const { varDecls, bodyHTML, logicBlocks, mixedBlocks, assignedVars, exprRegistry } = opts;
2671
2708
 
2672
-
2673
- const needsExpr = bodyHTML.includes("sinth-expr");
2674
- const needsIf = bodyHTML.includes("data-sinth-if");
2675
- const needsFor = bodyHTML.includes("data-sinth-for");
2676
- 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"));
2677
- const needsMixed = mixedBlocks.length > 0;
2678
- const needsLogic = logicBlocks.length > 0;
2709
+ const needsExpr = bodyHTML.includes("sinth-expr");
2710
+ const needsIf = bodyHTML.includes("data-sinth-if");
2711
+ const needsFor = bodyHTML.includes("data-sinth-for");
2712
+ 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"));
2713
+ const needsMixed = mixedBlocks.length > 0;
2714
+ const needsLogic = logicBlocks.length > 0;
2679
2715
  const needsRender = needsExpr || needsIf || needsFor || needsMixed || needsLogic;
2680
2716
 
2681
- // var decls with type defaults
2682
2717
  const varLines = varDecls.map(v => {
2683
2718
  if (!v.value) {
2684
2719
  if (!assignedVars.has(v.name)) {
@@ -2696,378 +2731,362 @@ const needsLogic = logicBlocks.length > 0;
2696
2731
  if (val.startsWith("__ARR__")) return `var ${v.name} = ${val.slice(7)};`;
2697
2732
  if (v.varType === "obj") return `var ${v.name} = ${val};`;
2698
2733
  if (v.varType === "str") return `var ${v.name} = ${JSON.stringify(val)};`;
2699
- if (v.varType === "str[]" && typeof val === 'string' && val.startsWith("__ARR__")) {
2700
- try {
2701
- const arr = JSON.parse(val.slice(7));
2702
- return `var ${v.name} = ${JSON.stringify(arr)};`;
2703
- } catch { return `var ${v.name} = ${val.slice(7)};`; }
2704
- }
2705
- return `var ${v.name} = ${val};`;
2734
+ if (v.varType === "str[]" && typeof val === 'string' && val.startsWith("__ARR__")) {
2735
+ try {
2736
+ const arr = JSON.parse(val.slice(7));
2737
+ return `var ${v.name} = ${JSON.stringify(arr)};`;
2738
+ } catch { return `var ${v.name} = ${val.slice(7)};`; }
2739
+ }
2740
+ return `var ${v.name} = ${val};`;
2706
2741
  }).join("\n");
2707
2742
 
2708
2743
  if (!needsRender && !needsDelay) {
2709
- return varLines ? `// Sinth v1.0.0\n${varLines}` : "";
2744
+ return varLines ? `// Sinth compiled runtime\n${varLines}` : "";
2710
2745
  }
2711
2746
 
2712
- let renderBody = "";
2747
+ let helpers = "";
2713
2748
 
2714
- renderBody += ` var _sx = window.scrollX, _sy = window.scrollY;\n`;
2749
+ if (needsExpr || needsIf || needsFor) {
2750
+ helpers += `
2751
+ function sinthExpr(el) {
2752
+ try {
2753
+ var exprFn = __X[el.dataset.exprId];
2754
+ if (exprFn) el.textContent = exprFn({});
2755
+ } catch(e) {}
2756
+ }
2757
+ `;
2758
+ }
2715
2759
 
2716
- if (needsLogic) {
2717
- renderBody += logicBlocks.map(b => b.replace(/^/gm, " ")).join("\n") + "\n";
2760
+ if (needsIf || needsMixed) {
2761
+ helpers += `
2762
+ function sinthReplaceInsert(t, anchor, ifId, replaceId) {
2763
+ if (anchor) {
2764
+ var cur = anchor.nextSibling;
2765
+ while (cur && cur !== t) { var nx = cur.nextSibling; cur.remove(); cur = nx; }
2766
+ } else {
2767
+ anchor = document.createElement('span');
2768
+ anchor.style.display = 'none';
2769
+ anchor.dataset.sinthIfAnchor = ifId;
2770
+ t.parentNode.insertBefore(anchor, t);
2771
+ }
2772
+ var _rp = null, _rpParent = null, _rpNext = null;
2773
+ if (replaceId) {
2774
+ _rp = document.getElementById(replaceId);
2775
+ if (_rp) {
2776
+ _rpParent = _rp.parentNode;
2777
+ _rpNext = _rp.nextSibling;
2778
+ _rp.parentNode.removeChild(_rp);
2779
+ anchor._sinthReplaced = _rp;
2780
+ anchor._sinthReplacedParent = _rpParent;
2781
+ anchor._sinthReplacedNext = _rpNext;
2782
+ }
2783
+ }
2784
+ var frag = document.createRange().createContextualFragment(t.innerHTML);
2785
+ frag.querySelectorAll('.sinth-expr').forEach(sinthExpr);
2786
+ if (${needsDelay}) {
2787
+ frag.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
2788
+ frag.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
2789
+ }
2790
+ var fragFirst = frag.firstChild;
2791
+ var fragLast = frag.lastChild;
2792
+ if (_rpParent && _rpNext) {
2793
+ _rpParent.insertBefore(frag, _rpNext);
2794
+ } else if (_rpParent) {
2795
+ _rpParent.appendChild(frag);
2796
+ } else {
2797
+ t.parentNode.insertBefore(frag, t);
2798
+ }
2799
+ if (replaceId && anchor) {
2800
+ anchor._sinthInsertedFirst = fragFirst;
2801
+ anchor._sinthInsertedLast = fragLast;
2802
+ }
2803
+ return anchor;
2804
+ }
2805
+ `;
2718
2806
  }
2719
2807
 
2720
- if (needsFor) {
2721
- renderBody += `
2722
- document.querySelectorAll('template[data-sinth-for]').forEach(function(t) {
2723
- var source = window[t.dataset.sinthFor];
2724
- if (source === undefined) source = [];
2725
- var newHash = '';
2726
- try { newHash = hashString(JSON.stringify(source)); } catch(e) { newHash = ''; }
2727
- if (t.dataset.sinthForHash && t.dataset.sinthForHash === newHash) {
2728
- return;
2729
- }
2730
- t.dataset.sinthForHash = newHash;
2731
- var isObj = (typeof source === 'object' && source !== null && !Array.isArray(source));
2732
- var entries;
2733
- if (isObj) {
2734
- entries = Object.entries(source);
2735
- } else {
2736
- if (!Array.isArray(source)) source = [];
2737
- entries = source.map(function(item, index) { return [index, item]; });
2738
- }
2739
- var anchor = t.parentNode ? t.parentNode.querySelector('[data-sinth-for-anchor="' + t.dataset.sinthFor + '"]') : null;
2808
+ if (needsDelay) {
2809
+ helpers += `
2810
+ function sinthDelay(el) {
2811
+ if (el.dataset.sinthDelayDone) { el.style.display = ''; return; }
2812
+ el.dataset.sinthDelayDone = '1';
2813
+ var ms = parseInt(el.dataset.sinthDelay) || 0;
2814
+ el.style.display = 'none';
2815
+ if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
2816
+ else el.style.display = '';
2817
+ }
2818
+ function sinthDelayExpr(el) {
2819
+ try {
2820
+ var fn = __X[el.dataset.sinthDelayExprId];
2821
+ var ms = fn ? parseInt(fn()) || 0 : 0;
2822
+ el.style.display = '';
2823
+ if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
2824
+ } catch(e) {}
2825
+ }
2826
+ `;
2827
+ }
2828
+
2829
+ if (needsIf) {
2830
+ helpers += `
2831
+ function sinthIfBlock(t) {
2832
+ var ifId = t.dataset.sinthIfId;
2833
+ var anchor = t.parentNode.querySelector('[data-sinth-if-anchor="' + ifId + '"]');
2834
+ var condFn = __X[t.dataset.sinthIfExpr];
2835
+ var cond = condFn ? condFn() : false;
2836
+ if (cond) {
2837
+ anchor = sinthReplaceInsert(t, anchor, ifId, t.dataset.sinthIfReplace);
2838
+ } else {
2740
2839
  if (anchor) {
2741
- var cur2 = anchor.nextSibling;
2742
- while (cur2 && cur2 !== t) { var nx2 = cur2.nextSibling; cur2.remove(); cur2 = nx2; }
2840
+ if (anchor._sinthReplaced) {
2841
+ var insFirst = anchor._sinthInsertedFirst;
2842
+ var insLast = anchor._sinthInsertedLast;
2843
+ var rpParent = anchor._sinthReplacedParent;
2844
+ var rpNext = anchor._sinthReplacedNext;
2845
+ if (insFirst && insLast) {
2846
+ var cur = insFirst;
2847
+ while (cur && cur !== insLast) {
2848
+ var next = cur.nextSibling;
2849
+ cur.remove();
2850
+ cur = next;
2851
+ }
2852
+ if (insLast) insLast.remove();
2853
+ }
2854
+ if (rpParent && rpNext) {
2855
+ rpParent.insertBefore(anchor._sinthReplaced, rpNext);
2856
+ } else if (rpParent) {
2857
+ rpParent.appendChild(anchor._sinthReplaced);
2858
+ }
2859
+ } else {
2860
+ var cur2 = anchor.nextSibling;
2861
+ while (cur2 && cur2 !== t) { var nx2 = cur2.nextSibling; cur2.remove(); cur2 = nx2; }
2862
+ }
2743
2863
  anchor.remove();
2744
2864
  }
2745
- var fa = document.createElement('span');
2746
- fa.style.display = 'none';
2747
- fa.dataset.sinthForAnchor = t.dataset.sinthFor;
2748
- t.parentNode && t.parentNode.insertBefore(fa, t);
2749
- var _loopIdx = 0;
2750
- entries.forEach(function(entry) {
2751
- var _k = entry[0];
2752
- var _v = entry[1];
2753
- var _item = (t.dataset && t.dataset.sinthItem) ? t.dataset.sinthItem : '__item__';
2754
- var _key = t.dataset && t.dataset.sinthKey ? t.dataset.sinthKey : null;
2755
- var _idx = t.dataset && t.dataset.sinthIndex ? t.dataset.sinthIndex : null;
2756
-
2757
- _loopIdx++;
2758
- var _user = _v;
2759
- if (t.dataset.sinthIfReplace) {
2760
- var _rp = document.getElementById(t.dataset.sinthIfReplace);
2761
- if (_rp) _rp.parentNode.removeChild(_rp);
2762
- }
2763
- var frag = document.createRange().createContextualFragment(t.innerHTML);
2764
- frag.querySelectorAll('.sinth-expr').forEach(function(el) {
2765
- try {
2766
- var exprFn = __X[el.dataset.exprId];
2767
- if (!exprFn) return;
2768
- var _ctx = {};
2769
- if (_item) _ctx[_item] = _v;
2770
- if (_key) _ctx[_key] = _k;
2771
- if (_idx) _ctx[_idx] = _loopIdx - 1;
2772
- el.textContent = exprFn(_ctx);
2773
- el.classList.remove('sinth-expr');
2774
- } catch(e) {}
2775
- });
2776
- frag.querySelectorAll('template[data-sinth-if-expr]').forEach(function(ifT) {
2777
- var condFn = __X[ifT.dataset.sinthIfExpr];
2865
+ var elseT = t.nextElementSibling;
2866
+ if (elseT && elseT.hasAttribute('data-sinth-else')) {
2867
+ var elseIfId = elseT.dataset.sinthIfId;
2868
+ var ea = t.parentNode.querySelector('[data-sinth-if-anchor="__else__' + elseIfId + '"]');
2869
+ if (ea) {
2870
+ var cur3 = ea.nextSibling;
2871
+ while (cur3 && cur3 !== t) { var nx3 = cur3.nextSibling; cur3.remove(); cur3 = nx3; }
2872
+ } else {
2873
+ ea = document.createElement('span');
2874
+ ea.style.display = 'none';
2875
+ ea.dataset.sinthIfAnchor = '__else__' + elseIfId;
2876
+ t.parentNode.insertBefore(ea, t);
2877
+ }
2878
+ var ef = document.createRange().createContextualFragment(elseT.innerHTML);
2879
+ ef.querySelectorAll('.sinth-expr').forEach(sinthExpr);
2880
+ if (${needsDelay}) {
2881
+ ef.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
2882
+ ef.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
2883
+ }
2884
+ t.parentNode.insertBefore(ef, t);
2885
+ } else {
2886
+ var ea2 = t.parentNode.querySelector('[data-sinth-if-anchor="__else__' + ifId + '"]');
2887
+ if (ea2) {
2888
+ var ec = ea2.nextSibling;
2889
+ while (ec && ec !== t) { var en = ec.nextSibling; ec.remove(); ec = en; }
2890
+ ea2.remove();
2891
+ }
2892
+ }
2893
+ }
2894
+ }
2895
+ `;
2896
+ }
2897
+
2898
+ if (needsFor) {
2899
+ helpers += `
2900
+ function hashString(str) {
2901
+ var hash = 0, i, chr;
2902
+ for (i = 0; i < str.length; i++) {
2903
+ chr = str.charCodeAt(i);
2904
+ hash = ((hash << 5) - hash) + chr;
2905
+ hash |= 0;
2906
+ }
2907
+ return String(hash);
2908
+ }
2909
+ function sinthForBlock(t) {
2910
+ var source = window[t.dataset.sinthFor];
2911
+ if (source === undefined) source = [];
2912
+ var newHash = '';
2913
+ try { newHash = hashString(JSON.stringify(source)); } catch(e) { newHash = ''; }
2914
+ if (t.dataset.sinthForHash && t.dataset.sinthForHash === newHash) {
2915
+ return;
2916
+ }
2917
+ t.dataset.sinthForHash = newHash;
2918
+ var isObj = (typeof source === 'object' && source !== null && !Array.isArray(source));
2919
+ var entries;
2920
+ if (isObj) {
2921
+ entries = Object.entries(source);
2922
+ } else {
2923
+ if (!Array.isArray(source)) source = [];
2924
+ entries = source.map(function(item, index) { return [index, item]; });
2925
+ }
2926
+ var anchor = t.parentNode ? t.parentNode.querySelector('[data-sinth-for-anchor="' + t.dataset.sinthFor + '"]') : null;
2927
+ if (anchor) {
2928
+ var cur2 = anchor.nextSibling;
2929
+ while (cur2 && cur2 !== t) { var nx2 = cur2.nextSibling; cur2.remove(); cur2 = nx2; }
2930
+ anchor.remove();
2931
+ }
2932
+ var fa = document.createElement('span');
2933
+ fa.style.display = 'none';
2934
+ fa.dataset.sinthForAnchor = t.dataset.sinthFor;
2935
+ t.parentNode && t.parentNode.insertBefore(fa, t);
2936
+ var _loopIdx = 0;
2937
+ entries.forEach(function(entry) {
2938
+ var _k = entry[0];
2939
+ var _v = entry[1];
2940
+ var _item = (t.dataset && t.dataset.sinthItem) ? t.dataset.sinthItem : '__item__';
2941
+ var _key = t.dataset && t.dataset.sinthKey ? t.dataset.sinthKey : null;
2942
+ var _idx = t.dataset && t.dataset.sinthIndex ? t.dataset.sinthIndex : null;
2943
+ _loopIdx++;
2944
+ if (t.dataset.sinthIfReplace) {
2945
+ var _rp = document.getElementById(t.dataset.sinthIfReplace);
2946
+ if (_rp) _rp.parentNode.removeChild(_rp);
2947
+ }
2948
+ var frag = document.createRange().createContextualFragment(t.innerHTML);
2949
+ frag.querySelectorAll('.sinth-expr').forEach(function(el) {
2950
+ try {
2951
+ var exprFn = __X[el.dataset.exprId];
2952
+ if (!exprFn) return;
2778
2953
  var _ctx = {};
2779
2954
  if (_item) _ctx[_item] = _v;
2780
2955
  if (_key) _ctx[_key] = _k;
2781
2956
  if (_idx) _ctx[_idx] = _loopIdx - 1;
2782
- var cond = false;
2783
- try { if (condFn) cond = condFn(_ctx); } catch(e) {}
2784
- if (cond) {
2785
- var ifContent = document.createRange().createContextualFragment(ifT.innerHTML);
2786
- ifContent.querySelectorAll('.sinth-expr').forEach(function(el2) {
2787
- try {
2788
- var exprFn2 = __X[el2.dataset.exprId];
2789
- if (exprFn2) el2.textContent = exprFn2(_ctx);
2790
- } catch(e) {}
2791
- });
2792
- ifT.parentNode.insertBefore(ifContent, ifT);
2793
- } else {
2794
- var elseT = ifT.nextElementSibling;
2795
- if (elseT && elseT.hasAttribute('data-sinth-else')) {
2796
- var elseContent = document.createRange().createContextualFragment(elseT.innerHTML);
2797
- elseContent.querySelectorAll('.sinth-expr').forEach(function(el2) {
2798
- try {
2799
- var exprFn2 = __X[el2.dataset.exprId];
2800
- if (exprFn2) el2.textContent = exprFn2(_ctx);
2801
- } catch(e) {}
2802
- });
2803
- ifT.parentNode.insertBefore(elseContent, ifT);
2804
- }
2805
- }
2806
- });
2807
- frag.querySelectorAll('[data-sinth-delay]').forEach(function(el) {
2808
- if (el.dataset.sinthDelayDone) { el.style.display = ''; return; }
2809
- el.dataset.sinthDelayDone = '1';
2810
- var ms = parseInt(el.dataset.sinthDelay) || 0;
2811
- el.style.display = 'none';
2812
- if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
2813
- else el.style.display = '';
2814
- });
2815
- frag.querySelectorAll('[data-sinth-delay-expr-id]').forEach(function(el) {
2816
- if (el.dataset.sinthDelayDone) { el.style.display = ''; return; }
2817
- el.dataset.sinthDelayDone = '1';
2818
- try {
2819
- var fn = __X[el.dataset.sinthDelayExprId];
2820
- var _ctx = {};
2821
- if (_item) _ctx[_item] = _v;
2822
- if (_key) _ctx[_key] = _k;
2823
- if (_idx) _ctx[_idx] = _loopIdx - 1;
2824
- var ms = fn ? parseInt(fn(_ctx)) || 0 : 0;
2825
- el.style.display = 'none';
2826
- if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
2827
- else el.style.display = '';
2828
- } catch(e) {}
2829
- });
2830
- t.parentNode && t.parentNode.insertBefore(frag, t);
2957
+ el.textContent = exprFn(_ctx);
2958
+ el.classList.remove('sinth-expr');
2959
+ } catch(e) {}
2831
2960
  });
2832
- });
2833
- `;
2834
- }
2835
- if (needsIf) {
2836
- renderBody += `
2837
- document.querySelectorAll('template[data-sinth-if-expr]').forEach(function(t) {
2838
- var ifId = t.dataset.sinthIfId;
2839
- var anchor = t.parentNode.querySelector('[data-sinth-if-anchor="' + ifId + '"]');
2840
- var condFn = __X[t.dataset.sinthIfExpr];
2841
- var cond = condFn ? condFn() : false;
2842
- if (cond) {
2843
- if (t.dataset.sinthIfReplace) {
2844
- var _rp = document.getElementById(t.dataset.sinthIfReplace);
2845
- if (_rp) _rp.parentNode.removeChild(_rp);
2846
- }
2847
- if (anchor) {
2848
- var cur = anchor.nextSibling;
2849
- while (cur && cur !== t) { var nx = cur.nextSibling; cur.remove(); cur = nx; }
2850
- } else {
2851
- anchor = document.createElement('span');
2852
- anchor.style.display = 'none';
2853
- anchor.dataset.sinthIfAnchor = ifId;
2854
- t.parentNode.insertBefore(anchor, t);
2855
- }
2856
- var frag = document.createRange().createContextualFragment(t.innerHTML);
2857
- frag.querySelectorAll('.sinth-expr').forEach(function(el) {
2858
- try {
2859
- var exprFn = __X[el.dataset.exprId];
2860
- if (exprFn) el.textContent = exprFn();
2861
- } catch(e) {}
2862
- });
2863
- frag.querySelectorAll('[data-sinth-delay]').forEach(function(el) {
2864
- if (el.dataset.sinthDelayDone) { el.style.display = ''; return; }
2865
- el.dataset.sinthDelayDone = '1';
2866
- var ms = parseInt(el.dataset.sinthDelay) || 0;
2867
- el.style.display = 'none';
2868
- if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
2869
- else el.style.display = '';
2870
- });
2871
- frag.querySelectorAll('[data-sinth-delay-expr-id]').forEach(function(el) {
2872
- try {
2873
- var fn = __X[el.dataset.sinthDelayExprId];
2874
- var ms = fn ? parseInt(fn()) || 0 : 0;
2875
- el.style.display = '';
2876
- if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
2877
- } catch(e) {}
2878
- });
2879
- t.parentNode.insertBefore(frag, t);
2880
- } else {
2881
- if (anchor) {
2882
- var cur2 = anchor.nextSibling;
2883
- while (cur2 && cur2 !== t) { var nx2 = cur2.nextSibling; cur2.remove(); cur2 = nx2; }
2884
- anchor.remove();
2885
- }
2886
- var elseT = t.nextElementSibling;
2887
- if (elseT && elseT.dataset && elseT.hasAttribute('data-sinth-else')) {
2888
- var ea = t.parentNode.querySelector('[data-sinth-if-anchor="__else__' + ifId + '"]');
2889
- if (ea) {
2890
- var cur3 = ea.nextSibling;
2891
- while (cur3 && cur3 !== t) { var nx3 = cur3.nextSibling; cur3.remove(); cur3 = nx3; }
2892
- } else {
2893
- ea = document.createElement('span');
2894
- ea.style.display = 'none';
2895
- ea.dataset.sinthIfAnchor = '__else__' + ifId;
2896
- t.parentNode.insertBefore(ea, t);
2897
- }
2898
- var ef = document.createRange().createContextualFragment(elseT.innerHTML);
2899
- ef.querySelectorAll('.sinth-expr').forEach(function(el) {
2961
+ frag.querySelectorAll('template[data-sinth-if-expr]').forEach(function(ifT) {
2962
+ var condFn = __X[ifT.dataset.sinthIfExpr];
2963
+ var _ctx = {};
2964
+ if (_item) _ctx[_item] = _v;
2965
+ if (_key) _ctx[_key] = _k;
2966
+ if (_idx) _ctx[_idx] = _loopIdx - 1;
2967
+ var cond = false;
2968
+ try { if (condFn) cond = condFn(_ctx); } catch(e) {}
2969
+ if (cond) {
2970
+ var ifContent = document.createRange().createContextualFragment(ifT.innerHTML);
2971
+ ifContent.querySelectorAll('.sinth-expr').forEach(function(el2) {
2900
2972
  try {
2901
- var exprFn = __X[el.dataset.exprId];
2902
- if (exprFn) el.textContent = exprFn();
2973
+ var exprFn2 = __X[el2.dataset.exprId];
2974
+ if (exprFn2) el2.textContent = exprFn2(_ctx);
2903
2975
  } catch(e) {}
2904
2976
  });
2905
- ef.querySelectorAll('[data-sinth-delay]').forEach(function(el) {
2906
- var ms = parseInt(el.dataset.sinthDelay) || 0;
2907
- el.style.display = 'none';
2908
- if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
2909
- else el.style.display = '';
2910
- });
2911
- ef.querySelectorAll('[data-sinth-delay-expr-id]').forEach(function(el) {
2912
- try {
2913
- var fn = __X[el.dataset.sinthDelayExprId];
2914
- var ms = fn ? parseInt(fn()) || 0 : 0;
2915
- el.style.display = '';
2916
- if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
2917
- } catch(e) {}
2918
- });
2919
- t.parentNode.insertBefore(ef, t);
2977
+ ifT.parentNode.insertBefore(ifContent, ifT);
2920
2978
  } else {
2921
- var ea2 = t.parentNode ? t.parentNode.querySelector('[data-sinth-if-anchor="__else__' + ifId + '"]') : null;
2922
- if (ea2) {
2923
- var ec = ea2.nextSibling;
2924
- while (ec && ec !== t) { var en = ec.nextSibling; ec.remove(); ec = en; }
2925
- ea2.remove();
2979
+ var elseT = ifT.nextElementSibling;
2980
+ if (elseT && elseT.hasAttribute('data-sinth-else')) {
2981
+ var elseContent = document.createRange().createContextualFragment(elseT.innerHTML);
2982
+ elseContent.querySelectorAll('.sinth-expr').forEach(function(el2) {
2983
+ try {
2984
+ var exprFn2 = __X[el2.dataset.exprId];
2985
+ if (exprFn2) el2.textContent = exprFn2(_ctx);
2986
+ } catch(e) {}
2987
+ });
2988
+ ifT.parentNode.insertBefore(elseContent, ifT);
2926
2989
  }
2927
2990
  }
2991
+ });
2992
+ if (${needsDelay}) {
2993
+ frag.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
2994
+ frag.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
2928
2995
  }
2996
+ t.parentNode && t.parentNode.insertBefore(frag, t);
2929
2997
  });
2998
+ }
2930
2999
  `;
2931
3000
  }
2932
3001
 
2933
- // mixed if/else blocks
2934
- if (needsMixed) {
2935
- for (const mb of mixedBlocks) {
2936
- const ifHTMLJS = JSON.stringify(mb.ifHTML);
2937
- const elseHTMLJS = JSON.stringify(mb.elseHTML);
2938
- const hasDelay = mb.ifHTML.includes("data-sinth-delay") || mb.elseHTML.includes("data-sinth-delay") || mb.ifHTML.includes("data-sinth-delay-expr-id") || mb.elseHTML.includes("data-sinth-delay-expr-id");
2939
- renderBody += `
2940
- (function() {
2941
- var __el = document.getElementById(${JSON.stringify(mb.replaceId || mb.id)});
2942
- if (__el) {
2943
- var condFn = __X[${mb.conditionJS}];
2944
- var __cond = condFn ? condFn() : false;
2945
- if (__cond) {
2946
- ${mb.ifJS ? mb.ifJS : ""} __el.innerHTML = ${ifHTMLJS};
2947
- } else {
2948
- ${mb.elseJS ? mb.elseJS : ""} __el.innerHTML = ${elseHTMLJS};
2949
- }
2950
- __el.querySelectorAll('.sinth-expr').forEach(function(e) {
2951
- try {
2952
- var exprFn = __X[e.dataset.exprId];
2953
- if (exprFn) e.textContent = exprFn();
2954
- } catch(ex) {}
2955
- });
2956
- __el.querySelectorAll('template[data-sinth-if-expr]').forEach(function(innerT) {
2957
- var innerCondFn = __X[innerT.dataset.sinthIfExpr];
2958
- var innerCond = innerCondFn ? innerCondFn() : false;
2959
- if (innerCond) {
2960
- var innerFrag = document.createRange().createContextualFragment(innerT.innerHTML);
2961
- innerFrag.querySelectorAll('.sinth-expr').forEach(function(e2) {
2962
- try {
2963
- var exprFn2 = __X[e2.dataset.exprId];
2964
- if (exprFn2) e2.textContent = exprFn2();
2965
- } catch(ex) {}
2966
- });
2967
- innerT.parentNode.insertBefore(innerFrag, innerT);
3002
+ if (needsMixed) {
3003
+ helpers += `
3004
+ function sinthMixedBlock(el, condId, ifJS, ifHTML, elseJS, elseHTML) {
3005
+ var condFn = __X[condId];
3006
+ var cond = condFn ? condFn() : false;
3007
+ if (cond) {
3008
+ if (ifJS) eval(ifJS);
3009
+ el.innerHTML = ifHTML;
2968
3010
  } else {
2969
- var innerElse = innerT.nextElementSibling;
2970
- if (innerElse && innerElse.hasAttribute('data-sinth-else')) {
2971
- var innerElseFrag = document.createRange().createContextualFragment(innerElse.innerHTML);
2972
- innerElseFrag.querySelectorAll('.sinth-expr').forEach(function(e2) {
2973
- try {
2974
- var exprFn2 = __X[e2.dataset.exprId];
2975
- if (exprFn2) e2.textContent = exprFn2();
2976
- } catch(ex) {}
2977
- });
2978
- innerT.parentNode.insertBefore(innerElseFrag, innerT);
2979
- }
2980
- }
2981
- });
2982
- ${hasDelay ? `
2983
- __el.querySelectorAll('[data-sinth-delay]').forEach(function(el) {
2984
- var ms = parseInt(el.dataset.sinthDelay) || 0;
2985
- el.style.display = 'none';
2986
- if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
2987
- else el.style.display = '';
2988
- });
2989
- __el.querySelectorAll('[data-sinth-delay-expr-id]').forEach(function(el) {
2990
- try {
2991
- var fn = __X[el.dataset.sinthDelayExprId];
2992
- var ms = fn ? parseInt(fn()) || 0 : 0;
2993
- el.style.display = 'none';
2994
- if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
2995
- else el.style.display = '';
2996
- } catch(e) {}
2997
- });
2998
- ` : ""}
3011
+ if (elseJS) eval(elseJS);
3012
+ el.innerHTML = elseHTML;
3013
+ }
3014
+ el.querySelectorAll('.sinth-expr').forEach(sinthExpr);
3015
+ el.querySelectorAll('template[data-sinth-if-expr]').forEach(sinthIfBlock);
3016
+ if (${needsDelay}) {
3017
+ el.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
3018
+ el.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
3019
+ }
2999
3020
  }
3000
- })();
3001
3021
  `;
3002
- }
3003
- }
3022
+ }
3004
3023
 
3005
- // set input vals from bound vars
3006
- renderBody += `
3007
- document.querySelectorAll('[data-sinth-value]').forEach(function(el) {
3008
- try { el.value = window[el.dataset.sinthValue] || ''; } catch(e) {}
3009
- });
3010
- document.querySelectorAll('[data-sinth-checked]').forEach(function(el) {
3011
- try { el.checked = !!window[el.dataset.sinthChecked]; } catch(e) {}
3012
- });
3013
- `;
3024
+ const exprArrayJS = exprRegistry.length > 0
3025
+ ? `var __X = [${exprRegistry.map((js) => `function(_ctx){ return ${js}; }`).join(",")}];\n`
3026
+ : "";
3014
3027
 
3015
- // expression spans
3016
- if (needsExpr) {
3017
- renderBody += `
3018
- document.querySelectorAll('.sinth-expr').forEach(function(el) {
3019
- try {
3020
- var exprFn = __X[el.dataset.exprId];
3021
- if (exprFn) el.textContent = exprFn({});
3022
- } catch(e) {}
3023
- });
3024
- `;
3028
+ let renderBody = "";
3029
+ renderBody += ` var _sx = window.scrollX, _sy = window.scrollY;\n`;
3030
+
3031
+ if (needsLogic) {
3032
+ renderBody += logicBlocks.map(b => b.replace(/^/gm, " ")).join("\n") + "\n";
3025
3033
  }
3026
3034
 
3035
+ if (needsMixed) {
3036
+ for (const mb of mixedBlocks) {
3037
+ renderBody += ` (function() {
3038
+ var __el = document.getElementById(${JSON.stringify(mb.replaceId || mb.id)});
3039
+ if (__el) sinthMixedBlock(__el, ${mb.conditionJS}, ${JSON.stringify(mb.ifJS)}, ${JSON.stringify(mb.ifHTML)}, ${JSON.stringify(mb.elseJS)}, ${JSON.stringify(mb.elseHTML)});
3040
+ })();\n`;
3041
+ }
3042
+ }
3027
3043
 
3044
+ renderBody += ` document.querySelectorAll('[data-sinth-remove]').forEach(function(el) {
3045
+ var target = document.getElementById(el.dataset.sinthRemove);
3046
+ if (target) target.remove();
3047
+ });\n`;
3048
+
3049
+ if (needsIf) {
3050
+ renderBody += ` document.querySelectorAll('template[data-sinth-if-expr]').forEach(sinthIfBlock);\n`;
3051
+ }
3052
+ if (needsFor) {
3053
+ renderBody += ` document.querySelectorAll('template[data-sinth-for]').forEach(sinthForBlock);\n`;
3054
+ }
3055
+ renderBody += ` document.querySelectorAll('[data-sinth-value]').forEach(function(el) {
3056
+ try { el.value = window[el.dataset.sinthValue] || ''; } catch(e) {}
3057
+ });\n`;
3058
+ renderBody += ` document.querySelectorAll('[data-sinth-checked]').forEach(function(el) {
3059
+ try { el.checked = !!window[el.dataset.sinthChecked]; } catch(e) {}
3060
+ });\n`;
3061
+ if (needsExpr) {
3062
+ renderBody += ` document.querySelectorAll('.sinth-expr').forEach(sinthExpr);\n`;
3063
+ }
3064
+ if (needsDelay) {
3065
+ renderBody += ` setTimeout(function() {
3066
+ document.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
3067
+ document.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
3068
+ }, 0);\n`;
3069
+ }
3028
3070
  renderBody += ` window.scrollTo(_sx, _sy);\n`;
3029
3071
 
3072
+ const renderFunc = needsRender ? `function sinthRender() {\n${renderBody}}\nsinthRender();` : "";
3030
3073
 
3031
- const delayBlock = needsDelay ? `
3032
- setTimeout(function() {
3033
- document.querySelectorAll('[data-sinth-delay]').forEach(function(el) {
3034
- var ms = parseInt(el.dataset.sinthDelay) || 0;
3035
- if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
3036
- else el.style.display = '';
3037
- });
3038
- document.querySelectorAll('[data-sinth-delay-expr-id]').forEach(function(el) {
3039
- try {
3040
- var fn = __X[el.dataset.sinthDelayExprId];
3041
- var ms = fn ? parseInt(fn()) || 0 : 0;
3042
- if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
3043
- else el.style.display = '';
3044
- } catch(e) {}
3045
- });
3046
- }, 0);
3047
- ` : "";
3048
-
3049
- // Build the expression registry as a JS array
3050
- const exprArrayJS = opts.exprRegistry && opts.exprRegistry.length > 0
3051
- ? `var __X = [${opts.exprRegistry.map((js) => {
3052
- return `function(_ctx){ return ${js}; }`;
3053
- }).join(",")}];\n`
3054
- : "";
3074
+ const pageCode = `// Sinth page runtime
3075
+ ${varLines}
3076
+ ${exprArrayJS}
3077
+ ${renderFunc}`;
3078
+
3079
+ if (opts.sharedRuntime && helpers.trim()) {
3080
+ const sharedCode = `// Sinth shared runtime
3081
+ ${helpers}`;
3082
+ return { page: pageCode, shared: sharedCode };
3083
+ }
3055
3084
 
3056
3085
  return `// Sinth compiled runtime
3057
3086
  ${varLines}
3058
- ${needsFor ? `function hashString(str) {
3059
- var hash = 0, i, chr;
3060
- for (i = 0; i < str.length; i++) {
3061
- chr = str.charCodeAt(i);
3062
- hash = ((hash << 5) - hash) + chr;
3063
- hash |= 0;
3064
- }
3065
- return String(hash);
3066
- }
3067
- ` : ""}
3087
+ ${helpers}
3068
3088
  ${exprArrayJS}
3069
- ${needsRender ? `function sinthRender() {\n${renderBody}}\nsinthRender();` : ""}
3070
- ${delayBlock}`;
3089
+ ${renderFunc}`;
3071
3090
  }
3072
3091
 
3073
3092
  // main compilation pipeline
@@ -3078,9 +3097,10 @@ interface CompileOptions {
3078
3097
  libraryPaths: string[];
3079
3098
  minify: boolean;
3080
3099
  checkOnly: boolean;
3100
+ sharedRuntime: boolean;
3081
3101
  }
3082
3102
 
3083
- function compileFile(filePath: string, opts: CompileOptions): string | null {
3103
+ function compileFile(filePath: string, opts: CompileOptions): { html: string; shared?: string } | null {
3084
3104
  const absPath = path.resolve(filePath);
3085
3105
  const file = parseFile(absPath);
3086
3106
 
@@ -3107,7 +3127,8 @@ function compileFile(filePath: string, opts: CompileOptions): string | null {
3107
3127
  const body = file.uses.map(u => renderCompUse(u, ctx, new Map(), 0)).join("\n");
3108
3128
  const pageCSS = file.styles.map(s => processStyleBlock(s, hash)).join("\n");
3109
3129
  const allCSS = [pageCSS, ...ctx.extraCSS].join("\n");
3110
- return `${body}\n<style>\n${allCSS}\n</style>`;
3130
+ const h = `${body}\n<style>\n${allCSS}\n</style>`;
3131
+ return { html: h };
3111
3132
  }
3112
3133
 
3113
3134
  const headData = buildHeadData(file.meta);
@@ -3141,18 +3162,23 @@ function compileFile(filePath: string, opts: CompileOptions): string | null {
3141
3162
  })(),
3142
3163
  }));
3143
3164
 
3144
- const head = renderHead(headData, relativeCssLinks, relativeJsLinks, scopedCSS, companionJS);
3145
-
3146
- // build tree-shaken runtime
3147
- const runtimeJS = buildRuntime({
3165
+ const runtimeResult = buildRuntime({
3148
3166
  varDecls: allVarDecls,
3149
3167
  bodyHTML,
3150
3168
  logicBlocks: ctx.logicBlocks,
3151
3169
  mixedBlocks: ctx.mixedBlocks,
3152
3170
  assignedVars,
3153
3171
  exprRegistry: ctx.exprRegistry,
3172
+ sharedRuntime: opts.sharedRuntime,
3154
3173
  });
3174
+ const runtimeJS = typeof runtimeResult === 'string' ? runtimeResult : runtimeResult.page;
3175
+ const sharedJS = typeof runtimeResult === 'string' ? null : runtimeResult.shared;
3155
3176
 
3177
+ const sharedRuntimeTag = opts.sharedRuntime && sharedJS
3178
+ ? `<script src="./sinth-runtime.js"></script>`
3179
+ : "";
3180
+
3181
+ const head = renderHead(headData, relativeCssLinks, relativeJsLinks, scopedCSS, companionJS);
3156
3182
  const scriptTags: string[] = [];
3157
3183
  if (componentScripts.length > 0) {
3158
3184
  scriptTags.push(`<script>\n${componentScripts.join("\n\n")}\n</script>`);
@@ -3172,13 +3198,15 @@ function compileFile(filePath: string, opts: CompileOptions): string | null {
3172
3198
  head,
3173
3199
  `<body data-s="${hash}">`,
3174
3200
  bodyHTML,
3201
+ sharedRuntimeTag,
3175
3202
  runtimeJS.trim() ? `<script>\n${runtimeJS}\n</script>` : "",
3176
3203
  scriptTags.join("\n"),
3177
3204
  "</body>",
3178
3205
  "</html>",
3179
3206
  ].filter(Boolean).join("\n");
3180
3207
 
3181
- return opts.minify ? minifyHTML(html) : html;
3208
+ const finalHTML = opts.minify ? minifyHTML(html) : html;
3209
+ return sharedJS ? { html: finalHTML, shared: sharedJS } : { html: finalHTML };
3182
3210
  }
3183
3211
 
3184
3212
  function minifyHTML(html: string): string {
@@ -3236,8 +3264,9 @@ async function startDevServer(opts: CompileOptions & { port: number; files?: str
3236
3264
  : findSinthPages(opts.projectRoot, opts.outDir);
3237
3265
  for (const p of pages) {
3238
3266
  try {
3239
- const html = compileFile(p, { ...opts, checkOnly: false });
3240
- if (!html) continue;
3267
+ const result = compileFile(p, { ...opts, checkOnly: false });
3268
+ if (!result) continue;
3269
+ const html = result.html;
3241
3270
  const rel = path.relative(opts.projectRoot, p).replace(/\.sinth$/, ".html").replace(/\\/g, "/");
3242
3271
  const url = "/" + rel;
3243
3272
  cache.set(url, html + LIVE_RELOAD_SCRIPT);
@@ -3254,13 +3283,22 @@ async function startDevServer(opts: CompileOptions & { port: number; files?: str
3254
3283
 
3255
3284
  const resolvedOut = path.resolve(opts.outDir);
3256
3285
  let watchReady = false;
3286
+ const pending = new Map<string, NodeJS.Timeout>();
3287
+ const DEBOUNCE_MS = 300;
3288
+
3257
3289
  try {
3258
3290
  fs.watch(opts.projectRoot, { recursive: true }, (_, filename) => {
3259
3291
  if (!filename) return;
3260
3292
  const abs = path.resolve(opts.projectRoot, filename);
3261
3293
  if (abs.startsWith(resolvedOut + path.sep) || abs === resolvedOut) return;
3262
- process.stdout.write(`\x1b[36m[sinth]\x1b[0m Changed: ${filename}\n`);
3263
- compileAll(); notify();
3294
+ if (pending.has(abs)) {
3295
+ clearTimeout(pending.get(abs)!);
3296
+ }
3297
+ pending.set(abs, setTimeout(() => {
3298
+ pending.delete(abs);
3299
+ process.stdout.write(`\x1b[36m[sinth]\x1b[0m Changed: ${filename}\n`);
3300
+ compileAll(); notify();
3301
+ }, DEBOUNCE_MS));
3264
3302
  });
3265
3303
  watchReady = true;
3266
3304
  } catch {}
@@ -3348,6 +3386,7 @@ async function main(): Promise<void> {
3348
3386
  const portIdx = args.indexOf("--port");
3349
3387
  const port = portIdx !== -1 ? parseInt(args[portIdx + 1], 10) : (cfg.port as number | undefined) ?? 3000;
3350
3388
  const minify = args.includes("--prod") || Boolean(cfg.minify);
3389
+ const sharedRuntime = args.includes("--shared-runtime") || Boolean(cfg.sharedRuntime);
3351
3390
  const libraryPaths = (cfg.libraryPaths as string[] | undefined) ?? [path.join(cwd, "libraries")];
3352
3391
 
3353
3392
  const flagValues = new Set<string>();
@@ -3355,7 +3394,7 @@ async function main(): Promise<void> {
3355
3394
  if (portIdx !== -1) flagValues.add(args[portIdx + 1]);
3356
3395
  const cleanArgs = args.filter(a => !a.startsWith("--") && !flagValues.has(a));
3357
3396
 
3358
- const opts: CompileOptions = { projectRoot: cwd, outDir, libraryPaths, minify, checkOnly: false };
3397
+ const opts: CompileOptions = { projectRoot: cwd, outDir, libraryPaths, minify, checkOnly: false, sharedRuntime };
3359
3398
 
3360
3399
  switch (command) {
3361
3400
  case "build": {
@@ -3371,10 +3410,15 @@ async function main(): Promise<void> {
3371
3410
 
3372
3411
  let hadError = false, built = 0;
3373
3412
 
3413
+ const sharedRuntimes: string[] = [];
3374
3414
  for (const p of pages) {
3375
3415
  try {
3376
- const html = compileFile(p, opts);
3377
- if (!html) continue;
3416
+ const result = compileFile(p, opts);
3417
+ if (!result) continue;
3418
+ const html = result.html;
3419
+ if (result.shared) {
3420
+ sharedRuntimes.push(result.shared);
3421
+ }
3378
3422
  const rel = path.relative(cwd, p).replace(/\.sinth$/, ".html");
3379
3423
  const out = path.join(outDir, rel);
3380
3424
  fs.mkdirSync(path.dirname(out), { recursive: true });
@@ -3387,6 +3431,12 @@ async function main(): Promise<void> {
3387
3431
  }
3388
3432
  }
3389
3433
 
3434
+ if (sharedRuntimes.length > 0) {
3435
+ const combined = sharedRuntimes.join("\n");
3436
+ fs.writeFileSync(path.join(outDir, "sinth-runtime.js"), combined);
3437
+ process.stdout.write(` \x1b[32m✓\x1b[0m sinth-runtime.js (shared)\n`);
3438
+ }
3439
+
3390
3440
  // copies to output
3391
3441
  const assetsIn = path.join(cwd, "assets"), assetsOut = path.join(outDir, "assets");
3392
3442
  if (fs.existsSync(assetsIn)) {
@@ -3457,8 +3507,24 @@ async function main(): Promise<void> {
3457
3507
  }
3458
3508
 
3459
3509
  default: {
3510
+ let version = "1.0.0";
3511
+ const paths = [
3512
+ path.resolve(__dirname, "..", "package.json"),
3513
+ path.resolve(__dirname, "package.json"),
3514
+ path.resolve(process.cwd(), "package.json"),
3515
+ path.resolve(process.cwd(), "..", "package.json"),
3516
+ ];
3517
+ for (const p of paths) {
3518
+ if (fs.existsSync(p)) {
3519
+ try {
3520
+ const pkg = JSON.parse(fs.readFileSync(p, "utf-8"));
3521
+ version = pkg.version;
3522
+ break;
3523
+ } catch {}
3524
+ }
3525
+ }
3460
3526
  process.stdout.write(`
3461
- \x1b[1mSinth Compiler v1.0.0\x1b[0m
3527
+ \x1b[1mSinth Compiler v${version}\x1b[0m
3462
3528
 
3463
3529
  \x1b[1mCommands:\x1b[0m
3464
3530
  sinth build [files] [--out ./dist] [--prod] Compile .sinth pages
@@ -3466,23 +3532,6 @@ async function main(): Promise<void> {
3466
3532
  sinth check Lint without emitting
3467
3533
  sinth init [name] Scaffold a new project
3468
3534
  sinth version Print version
3469
-
3470
- \x1b[1mConfig:\x1b[0m sinth.config.json
3471
- { "outDir": "./dist", "libraryPaths": ["./libraries"], "minify": false }
3472
-
3473
- \x1b[1mSinth Style v1.0.0:\x1b[0m
3474
- style Paragraph { color: "red"; onHover { color: "blue" } }
3475
- style { Hero { padding: "4rem"; media(maxWidth: "600px") { padding: "1rem" } } }
3476
- Paragraph(color: "red", fontSize: "1.2rem") { "Inline shorthand" }
3477
-
3478
- \x1b[1mMixed if/else:\x1b[0m
3479
- if guess == target {
3480
- result = "Correct!"
3481
- Paragraph(id: "msg") { result }
3482
- } else {
3483
- result = "Wrong!"
3484
- Paragraph(id: "msg") { "Nope!" }
3485
- }
3486
3535
  `);
3487
3536
  break;
3488
3537
  }