@yannosay/sinth 0.7.1 → 0.8.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.
Files changed (3) hide show
  1. package/README.md +31 -6
  2. package/package.json +1 -1
  3. package/src/sinth.ts +426 -383
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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yannosay/sinth",
3
- "version": "0.7.1",
3
+ "version": "0.8.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",
package/src/sinth.ts CHANGED
@@ -21,22 +21,20 @@ enum TT {
21
21
  KW_COMPONENT, KW_STYLE, KW_SCRIPT,
22
22
  KW_GLOBAL, KW_PAGE, KW_LANG,
23
23
  KW_CUSTOM_EL, KW_CUSTOM,
24
- KW_IF, KW_ELSE, KW_FOR, KW_IN,
25
- OP_PLUS, OP_MINUS, OP_STAR, OP_SLASH,
24
+ KW_IF, KW_ELSE, KW_FOR, KW_IN, KW_REMOVE,
25
+ OP_PLUS, OP_MINUS, OP_STAR, OP_SLASH, OP_SEMI,
26
26
  OP_LT, OP_GT, OP_NEQ, OP_EQEQ, OP_LTEQ, OP_GTEQ,
27
27
  EOF,
28
28
  }
29
29
 
30
30
  interface Token { type: TT; value: string; loc: Loc }
31
31
 
32
- // literal types
33
32
  type LitStr = { kind: "str"; value: string };
34
33
  type LitNum = { kind: "num"; value: number };
35
34
  type LitBool = { kind: "bool"; value: boolean };
36
35
  type LitNull = { kind: "null" };
37
36
  type Literal = LitStr | LitNum | LitBool | LitNull;
38
37
 
39
- // expression AST
40
38
  type UnaryOp = "not" | "-";
41
39
  type BinaryOp = "+" | "-" | "*" | "/" | "==" | "!=" | "<" | ">" | "<=" | ">=" | "and" | "or";
42
40
  type AssignOp = "=" | "+=" | "-=";
@@ -62,11 +60,11 @@ interface ExprNode { kind: "expr"; expression: Expression;
62
60
  interface AssignStmt { kind: "assign_stmt"; expression: Expression; loc: Loc }
63
61
  interface IfBlock { kind: "if"; condition: Expression; body: Child[]; elseBody?: Child[]; loc: Loc }
64
62
  interface ForLoop { kind: "for"; keyVar?: string; itemVar: string; indexVar?: string; arrayVar: string; body: Child[]; loc: Loc }
63
+ interface RemoveStmt { kind: "remove"; target: string; loc: Loc }
65
64
 
66
- // assignStmt is a first-class child so if bodies can be mixed
67
- type Child = TextNode | CompUse | ExprNode | AssignStmt | IfBlock | ForLoop;
68
65
 
69
- // component / file structure
66
+ type Child = TextNode | CompUse | ExprNode | AssignStmt | IfBlock | ForLoop | RemoveStmt;
67
+
70
68
  interface ParamDecl { name: string; defaultVal?: Literal; loc: Loc }
71
69
 
72
70
  interface StyleBlock {
@@ -228,6 +226,7 @@ const KEYWORDS: Record<string, TT> = {
228
226
  "else": TT.KW_ELSE,
229
227
  "for": TT.KW_FOR,
230
228
  "in": TT.KW_IN,
229
+ "remove": TT.KW_REMOVE,
231
230
  };
232
231
 
233
232
  export class Lexer {
@@ -266,6 +265,7 @@ export class Lexer {
266
265
  if (ch === "+") { tokens.push(this.single(TT.OP_PLUS, loc)); continue; }
267
266
  if (ch === "*") { tokens.push(this.single(TT.OP_STAR, loc)); continue; }
268
267
  if (ch === "/") { tokens.push(this.single(TT.OP_SLASH, loc)); continue; }
268
+ if (ch === ";") { tokens.push(this.single(TT.OP_SEMI, loc)); continue; }
269
269
  if (ch === "<") { tokens.push(this.single(TT.OP_LT, loc)); continue; }
270
270
  if (ch === ">") { tokens.push(this.single(TT.OP_GT, loc)); continue; }
271
271
  if (ch === "-" && !this.isDigit(this.src[this.pos + 1] ?? "")) {
@@ -954,6 +954,19 @@ private parseArrayLiteral(): Literal {
954
954
  continue;
955
955
  }
956
956
 
957
+ if (this.check(TT.KW_REMOVE)) {
958
+ const loc = this.consume(TT.KW_REMOVE).loc;
959
+ if (this.check(TT.STRING)) {
960
+ const target = this.consume(TT.STRING).value;
961
+ children.push({ kind: "remove", target, loc });
962
+ } else {
963
+ throw new SinthError(
964
+ `Expected a string after 'remove', got '${this.peek().value}'. Use remove "id".`,
965
+ this.peek().loc,
966
+ );
967
+ }
968
+ continue;
969
+ }
957
970
  if (this.check(TT.IDENT) && this.peek().value === "var") {
958
971
  const vd = this.parseVarDeclaration();
959
972
  if (vd) this._varDecls.push(vd);
@@ -1141,12 +1154,23 @@ private parseArrayLiteral(): Literal {
1141
1154
  value = this.parseLiteral();
1142
1155
  } else {
1143
1156
  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) };
1157
+ const expr = this.parseExpression();
1158
+ if (expr && (this.check(TT.COMMA) || this.check(TT.RPAREN) || this.check(TT.OP_SEMI))) {
1159
+ const exprs: Expression[] = [expr];
1160
+ while (this.check(TT.OP_SEMI)) {
1161
+ this.consume(TT.OP_SEMI);
1162
+ const next = this.parseExpression();
1163
+ if (next) exprs.push(next);
1164
+ else break;
1165
+ }
1166
+ if (exprs.length === 1) {
1167
+ value = { kind: "str", value: "__EXPR__" + JSON.stringify(exprs[0]) };
1168
+ } else {
1169
+ value = { kind: "str", value: "__MULTI_EXPR__" + JSON.stringify(exprs) };
1170
+ }
1147
1171
  } else {
1148
1172
  this.pos = savedPos;
1149
- value = this.parseLiteral();
1173
+ value = this.parseLiteral();
1150
1174
  }
1151
1175
  }
1152
1176
  } else {
@@ -2173,21 +2197,34 @@ if (name === "delay") {
2173
2197
 
2174
2198
  let raw = value.value;
2175
2199
 
2200
+ if (raw.startsWith("__MULTI_EXPR__")) {
2201
+ const exprJson = raw.substring("__MULTI_EXPR__".length);
2202
+ try {
2203
+ const exprs: Expression[] = JSON.parse(exprJson);
2204
+ const jsExprs = exprs.map(e => compileExprToJS(e)).join("; ");
2205
+ const ev = eventAttrName(name);
2206
+ if (ev) return `${ev}="(function(){ ${jsExprs.replace(/"/g, "&quot;")}; sinthRender(); })()"`;
2207
+ return `${name}="${escAttr(jsExprs)}"`;
2208
+ } catch { }
2209
+ }
2176
2210
  if (raw.startsWith("__EXPR__")) {
2177
2211
  const exprJson = raw.substring("__EXPR__".length);
2178
2212
  try {
2179
2213
  const expr: Expression = JSON.parse(exprJson);
2180
2214
  const jsExpr = compileExprToJS(expr);
2181
2215
  const ev = eventAttrName(name);
2182
- if (ev) return `${ev}="(function(){ ${jsExpr.replace(/"/g, "&quot;")}; })()"`;
2216
+ if (ev) return `${ev}="(function(){ ${jsExpr.replace(/"/g, "&quot;")}; sinthRender(); })()"`;
2183
2217
  return `${name}="${escAttr(jsExpr)}"`;
2184
- } catch { /* fall through */ }
2218
+ } catch { }
2185
2219
  }
2186
2220
 
2187
2221
  raw = interpolateAttr(raw, paramMap);
2188
2222
 
2189
2223
  const ev = eventAttrName(name);
2190
- if (ev) return `${ev}="${escAttr(raw)};sinthRender()"`;
2224
+ if (ev) {
2225
+ const call = raw.includes("(") ? raw : raw + "()";
2226
+ return `${ev}="${escAttr(call)};sinthRender()"`;
2227
+ }
2191
2228
  return `${name}="${escAttr(raw)}"`;
2192
2229
  }
2193
2230
 
@@ -2260,6 +2297,10 @@ function renderChild(
2260
2297
  return "";
2261
2298
  }
2262
2299
 
2300
+ case "remove": {
2301
+ return `<span data-sinth-remove="${esc((child as RemoveStmt).target)}"></span>`;
2302
+ }
2303
+
2263
2304
  case "if":
2264
2305
  return renderIfBlock(child, ctx, params, depth);
2265
2306
 
@@ -2316,7 +2357,7 @@ depth: number,
2316
2357
  if (firstComp) {
2317
2358
  const idAttr = firstComp.attrs.find(a => a.name === "id");
2318
2359
  const replAttr = firstComp.attrs.find(a => a.name === "replace");
2319
- const wantsReplace = !replAttr || replAttr.value === null || (replAttr.value?.kind === "bool" && replAttr.value.value === true);
2360
+ const wantsReplace = replAttr && (replAttr.value === null || (replAttr.value?.kind === "bool" && replAttr.value.value));
2320
2361
  if (idAttr && idAttr.value?.kind === "str" && wantsReplace) {
2321
2362
  replaceAttr = ` data-sinth-if-replace="${escAttr(idAttr.value.value)}"`;
2322
2363
  }
@@ -2357,14 +2398,14 @@ depth: number,
2357
2398
  const ifId = ifFirstComp.attrs.find(a => a.name === "id")?.value;
2358
2399
  const ifReplace = ifFirstComp.attrs.find(a => a.name === "replace");
2359
2400
  const ifReplaceVal = ifReplace?.value;
2360
- const ifWantsReplace = !ifReplace || (ifReplaceVal?.kind === "bool" && ifReplaceVal.value === true) || (ifReplaceVal === null);
2401
+ const ifWantsReplace = ifReplace && (ifReplaceVal === null || (ifReplaceVal?.kind === "bool" && ifReplaceVal.value));
2361
2402
 
2362
2403
  if (ifId && ifId.kind === "str" && ifWantsReplace) {
2363
2404
  if (elseFirstComp) {
2364
2405
  const elseId = elseFirstComp.attrs.find(a => a.name === "id")?.value;
2365
2406
  const elseReplace = elseFirstComp.attrs.find(a => a.name === "replace");
2366
2407
  const elseReplaceVal = elseReplace?.value;
2367
- const elseWantsReplace = !elseReplace || (elseReplaceVal?.kind === "bool" && elseReplaceVal.value === true) || (elseReplaceVal === null);
2408
+ const elseWantsReplace = elseReplace && (elseReplaceVal === null || (elseReplaceVal?.kind === "bool" && elseReplaceVal.value));
2368
2409
 
2369
2410
  if (elseId && elseId.kind === "str" && elseId.value === ifId.value && elseWantsReplace) {
2370
2411
  replaceId = ifId.value;
@@ -2666,19 +2707,18 @@ function buildRuntime(opts: {
2666
2707
  mixedBlocks: MixedBlockEntry[];
2667
2708
  assignedVars: Set<string>;
2668
2709
  exprRegistry: string[];
2669
- }): string {
2710
+ sharedRuntime: boolean;
2711
+ }): string | { page: string; shared: string } {
2670
2712
  const { varDecls, bodyHTML, logicBlocks, mixedBlocks, assignedVars, exprRegistry } = opts;
2671
2713
 
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;
2714
+ const needsExpr = bodyHTML.includes("sinth-expr");
2715
+ const needsIf = bodyHTML.includes("data-sinth-if");
2716
+ const needsFor = bodyHTML.includes("data-sinth-for");
2717
+ 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"));
2718
+ const needsMixed = mixedBlocks.length > 0;
2719
+ const needsLogic = logicBlocks.length > 0;
2679
2720
  const needsRender = needsExpr || needsIf || needsFor || needsMixed || needsLogic;
2680
2721
 
2681
- // var decls with type defaults
2682
2722
  const varLines = varDecls.map(v => {
2683
2723
  if (!v.value) {
2684
2724
  if (!assignedVars.has(v.name)) {
@@ -2696,378 +2736,362 @@ const needsLogic = logicBlocks.length > 0;
2696
2736
  if (val.startsWith("__ARR__")) return `var ${v.name} = ${val.slice(7)};`;
2697
2737
  if (v.varType === "obj") return `var ${v.name} = ${val};`;
2698
2738
  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};`;
2739
+ if (v.varType === "str[]" && typeof val === 'string' && val.startsWith("__ARR__")) {
2740
+ try {
2741
+ const arr = JSON.parse(val.slice(7));
2742
+ return `var ${v.name} = ${JSON.stringify(arr)};`;
2743
+ } catch { return `var ${v.name} = ${val.slice(7)};`; }
2744
+ }
2745
+ return `var ${v.name} = ${val};`;
2706
2746
  }).join("\n");
2707
2747
 
2708
2748
  if (!needsRender && !needsDelay) {
2709
- return varLines ? `// Sinth v1.0.0\n${varLines}` : "";
2749
+ return varLines ? `// Sinth compiled runtime\n${varLines}` : "";
2710
2750
  }
2711
2751
 
2712
- let renderBody = "";
2752
+ let helpers = "";
2713
2753
 
2714
- renderBody += ` var _sx = window.scrollX, _sy = window.scrollY;\n`;
2754
+ if (needsExpr || needsIf || needsFor) {
2755
+ helpers += `
2756
+ function sinthExpr(el) {
2757
+ try {
2758
+ var exprFn = __X[el.dataset.exprId];
2759
+ if (exprFn) el.textContent = exprFn({});
2760
+ } catch(e) {}
2761
+ }
2762
+ `;
2763
+ }
2715
2764
 
2716
- if (needsLogic) {
2717
- renderBody += logicBlocks.map(b => b.replace(/^/gm, " ")).join("\n") + "\n";
2765
+ if (needsIf || needsMixed) {
2766
+ helpers += `
2767
+ function sinthReplaceInsert(t, anchor, ifId, replaceId) {
2768
+ if (anchor) {
2769
+ var cur = anchor.nextSibling;
2770
+ while (cur && cur !== t) { var nx = cur.nextSibling; cur.remove(); cur = nx; }
2771
+ } else {
2772
+ anchor = document.createElement('span');
2773
+ anchor.style.display = 'none';
2774
+ anchor.dataset.sinthIfAnchor = ifId;
2775
+ t.parentNode.insertBefore(anchor, t);
2776
+ }
2777
+ var _rp = null, _rpParent = null, _rpNext = null;
2778
+ if (replaceId) {
2779
+ _rp = document.getElementById(replaceId);
2780
+ if (_rp) {
2781
+ _rpParent = _rp.parentNode;
2782
+ _rpNext = _rp.nextSibling;
2783
+ _rp.parentNode.removeChild(_rp);
2784
+ anchor._sinthReplaced = _rp;
2785
+ anchor._sinthReplacedParent = _rpParent;
2786
+ anchor._sinthReplacedNext = _rpNext;
2787
+ }
2788
+ }
2789
+ var frag = document.createRange().createContextualFragment(t.innerHTML);
2790
+ frag.querySelectorAll('.sinth-expr').forEach(sinthExpr);
2791
+ if (${needsDelay}) {
2792
+ frag.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
2793
+ frag.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
2794
+ }
2795
+ var fragFirst = frag.firstChild;
2796
+ var fragLast = frag.lastChild;
2797
+ if (_rpParent && _rpNext) {
2798
+ _rpParent.insertBefore(frag, _rpNext);
2799
+ } else if (_rpParent) {
2800
+ _rpParent.appendChild(frag);
2801
+ } else {
2802
+ t.parentNode.insertBefore(frag, t);
2803
+ }
2804
+ if (replaceId && anchor) {
2805
+ anchor._sinthInsertedFirst = fragFirst;
2806
+ anchor._sinthInsertedLast = fragLast;
2807
+ }
2808
+ return anchor;
2809
+ }
2810
+ `;
2718
2811
  }
2719
2812
 
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;
2813
+ if (needsDelay) {
2814
+ helpers += `
2815
+ function sinthDelay(el) {
2816
+ if (el.dataset.sinthDelayDone) { el.style.display = ''; return; }
2817
+ el.dataset.sinthDelayDone = '1';
2818
+ var ms = parseInt(el.dataset.sinthDelay) || 0;
2819
+ el.style.display = 'none';
2820
+ if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
2821
+ else el.style.display = '';
2822
+ }
2823
+ function sinthDelayExpr(el) {
2824
+ try {
2825
+ var fn = __X[el.dataset.sinthDelayExprId];
2826
+ var ms = fn ? parseInt(fn()) || 0 : 0;
2827
+ el.style.display = '';
2828
+ if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
2829
+ } catch(e) {}
2830
+ }
2831
+ `;
2832
+ }
2833
+
2834
+ if (needsIf) {
2835
+ helpers += `
2836
+ function sinthIfBlock(t) {
2837
+ var ifId = t.dataset.sinthIfId;
2838
+ var anchor = t.parentNode.querySelector('[data-sinth-if-anchor="' + ifId + '"]');
2839
+ var condFn = __X[t.dataset.sinthIfExpr];
2840
+ var cond = condFn ? condFn() : false;
2841
+ if (cond) {
2842
+ anchor = sinthReplaceInsert(t, anchor, ifId, t.dataset.sinthIfReplace);
2843
+ } else {
2740
2844
  if (anchor) {
2741
- var cur2 = anchor.nextSibling;
2742
- while (cur2 && cur2 !== t) { var nx2 = cur2.nextSibling; cur2.remove(); cur2 = nx2; }
2845
+ if (anchor._sinthReplaced) {
2846
+ var insFirst = anchor._sinthInsertedFirst;
2847
+ var insLast = anchor._sinthInsertedLast;
2848
+ var rpParent = anchor._sinthReplacedParent;
2849
+ var rpNext = anchor._sinthReplacedNext;
2850
+ if (insFirst && insLast) {
2851
+ var cur = insFirst;
2852
+ while (cur && cur !== insLast) {
2853
+ var next = cur.nextSibling;
2854
+ cur.remove();
2855
+ cur = next;
2856
+ }
2857
+ if (insLast) insLast.remove();
2858
+ }
2859
+ if (rpParent && rpNext) {
2860
+ rpParent.insertBefore(anchor._sinthReplaced, rpNext);
2861
+ } else if (rpParent) {
2862
+ rpParent.appendChild(anchor._sinthReplaced);
2863
+ }
2864
+ } else {
2865
+ var cur2 = anchor.nextSibling;
2866
+ while (cur2 && cur2 !== t) { var nx2 = cur2.nextSibling; cur2.remove(); cur2 = nx2; }
2867
+ }
2743
2868
  anchor.remove();
2744
2869
  }
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];
2870
+ var elseT = t.nextElementSibling;
2871
+ if (elseT && elseT.hasAttribute('data-sinth-else')) {
2872
+ var elseIfId = elseT.dataset.sinthIfId;
2873
+ var ea = t.parentNode.querySelector('[data-sinth-if-anchor="__else__' + elseIfId + '"]');
2874
+ if (ea) {
2875
+ var cur3 = ea.nextSibling;
2876
+ while (cur3 && cur3 !== t) { var nx3 = cur3.nextSibling; cur3.remove(); cur3 = nx3; }
2877
+ } else {
2878
+ ea = document.createElement('span');
2879
+ ea.style.display = 'none';
2880
+ ea.dataset.sinthIfAnchor = '__else__' + elseIfId;
2881
+ t.parentNode.insertBefore(ea, t);
2882
+ }
2883
+ var ef = document.createRange().createContextualFragment(elseT.innerHTML);
2884
+ ef.querySelectorAll('.sinth-expr').forEach(sinthExpr);
2885
+ if (${needsDelay}) {
2886
+ ef.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
2887
+ ef.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
2888
+ }
2889
+ t.parentNode.insertBefore(ef, t);
2890
+ } else {
2891
+ var ea2 = t.parentNode.querySelector('[data-sinth-if-anchor="__else__' + ifId + '"]');
2892
+ if (ea2) {
2893
+ var ec = ea2.nextSibling;
2894
+ while (ec && ec !== t) { var en = ec.nextSibling; ec.remove(); ec = en; }
2895
+ ea2.remove();
2896
+ }
2897
+ }
2898
+ }
2899
+ }
2900
+ `;
2901
+ }
2902
+
2903
+ if (needsFor) {
2904
+ helpers += `
2905
+ function hashString(str) {
2906
+ var hash = 0, i, chr;
2907
+ for (i = 0; i < str.length; i++) {
2908
+ chr = str.charCodeAt(i);
2909
+ hash = ((hash << 5) - hash) + chr;
2910
+ hash |= 0;
2911
+ }
2912
+ return String(hash);
2913
+ }
2914
+ function sinthForBlock(t) {
2915
+ var source = window[t.dataset.sinthFor];
2916
+ if (source === undefined) source = [];
2917
+ var newHash = '';
2918
+ try { newHash = hashString(JSON.stringify(source)); } catch(e) { newHash = ''; }
2919
+ if (t.dataset.sinthForHash && t.dataset.sinthForHash === newHash) {
2920
+ return;
2921
+ }
2922
+ t.dataset.sinthForHash = newHash;
2923
+ var isObj = (typeof source === 'object' && source !== null && !Array.isArray(source));
2924
+ var entries;
2925
+ if (isObj) {
2926
+ entries = Object.entries(source);
2927
+ } else {
2928
+ if (!Array.isArray(source)) source = [];
2929
+ entries = source.map(function(item, index) { return [index, item]; });
2930
+ }
2931
+ var anchor = t.parentNode ? t.parentNode.querySelector('[data-sinth-for-anchor="' + t.dataset.sinthFor + '"]') : null;
2932
+ if (anchor) {
2933
+ var cur2 = anchor.nextSibling;
2934
+ while (cur2 && cur2 !== t) { var nx2 = cur2.nextSibling; cur2.remove(); cur2 = nx2; }
2935
+ anchor.remove();
2936
+ }
2937
+ var fa = document.createElement('span');
2938
+ fa.style.display = 'none';
2939
+ fa.dataset.sinthForAnchor = t.dataset.sinthFor;
2940
+ t.parentNode && t.parentNode.insertBefore(fa, t);
2941
+ var _loopIdx = 0;
2942
+ entries.forEach(function(entry) {
2943
+ var _k = entry[0];
2944
+ var _v = entry[1];
2945
+ var _item = (t.dataset && t.dataset.sinthItem) ? t.dataset.sinthItem : '__item__';
2946
+ var _key = t.dataset && t.dataset.sinthKey ? t.dataset.sinthKey : null;
2947
+ var _idx = t.dataset && t.dataset.sinthIndex ? t.dataset.sinthIndex : null;
2948
+ _loopIdx++;
2949
+ if (t.dataset.sinthIfReplace) {
2950
+ var _rp = document.getElementById(t.dataset.sinthIfReplace);
2951
+ if (_rp) _rp.parentNode.removeChild(_rp);
2952
+ }
2953
+ var frag = document.createRange().createContextualFragment(t.innerHTML);
2954
+ frag.querySelectorAll('.sinth-expr').forEach(function(el) {
2955
+ try {
2956
+ var exprFn = __X[el.dataset.exprId];
2957
+ if (!exprFn) return;
2778
2958
  var _ctx = {};
2779
2959
  if (_item) _ctx[_item] = _v;
2780
2960
  if (_key) _ctx[_key] = _k;
2781
2961
  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);
2962
+ el.textContent = exprFn(_ctx);
2963
+ el.classList.remove('sinth-expr');
2964
+ } catch(e) {}
2831
2965
  });
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) {
2966
+ frag.querySelectorAll('template[data-sinth-if-expr]').forEach(function(ifT) {
2967
+ var condFn = __X[ifT.dataset.sinthIfExpr];
2968
+ var _ctx = {};
2969
+ if (_item) _ctx[_item] = _v;
2970
+ if (_key) _ctx[_key] = _k;
2971
+ if (_idx) _ctx[_idx] = _loopIdx - 1;
2972
+ var cond = false;
2973
+ try { if (condFn) cond = condFn(_ctx); } catch(e) {}
2974
+ if (cond) {
2975
+ var ifContent = document.createRange().createContextualFragment(ifT.innerHTML);
2976
+ ifContent.querySelectorAll('.sinth-expr').forEach(function(el2) {
2900
2977
  try {
2901
- var exprFn = __X[el.dataset.exprId];
2902
- if (exprFn) el.textContent = exprFn();
2978
+ var exprFn2 = __X[el2.dataset.exprId];
2979
+ if (exprFn2) el2.textContent = exprFn2(_ctx);
2903
2980
  } catch(e) {}
2904
2981
  });
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);
2982
+ ifT.parentNode.insertBefore(ifContent, ifT);
2920
2983
  } 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();
2984
+ var elseT = ifT.nextElementSibling;
2985
+ if (elseT && elseT.hasAttribute('data-sinth-else')) {
2986
+ var elseContent = document.createRange().createContextualFragment(elseT.innerHTML);
2987
+ elseContent.querySelectorAll('.sinth-expr').forEach(function(el2) {
2988
+ try {
2989
+ var exprFn2 = __X[el2.dataset.exprId];
2990
+ if (exprFn2) el2.textContent = exprFn2(_ctx);
2991
+ } catch(e) {}
2992
+ });
2993
+ ifT.parentNode.insertBefore(elseContent, ifT);
2926
2994
  }
2927
2995
  }
2996
+ });
2997
+ if (${needsDelay}) {
2998
+ frag.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
2999
+ frag.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
2928
3000
  }
3001
+ t.parentNode && t.parentNode.insertBefore(frag, t);
2929
3002
  });
3003
+ }
2930
3004
  `;
2931
3005
  }
2932
3006
 
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);
3007
+ if (needsMixed) {
3008
+ helpers += `
3009
+ function sinthMixedBlock(el, condId, ifJS, ifHTML, elseJS, elseHTML) {
3010
+ var condFn = __X[condId];
3011
+ var cond = condFn ? condFn() : false;
3012
+ if (cond) {
3013
+ if (ifJS) eval(ifJS);
3014
+ el.innerHTML = ifHTML;
2968
3015
  } 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
- ` : ""}
3016
+ if (elseJS) eval(elseJS);
3017
+ el.innerHTML = elseHTML;
3018
+ }
3019
+ el.querySelectorAll('.sinth-expr').forEach(sinthExpr);
3020
+ el.querySelectorAll('template[data-sinth-if-expr]').forEach(sinthIfBlock);
3021
+ if (${needsDelay}) {
3022
+ el.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
3023
+ el.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
3024
+ }
2999
3025
  }
3000
- })();
3001
3026
  `;
3002
- }
3003
- }
3027
+ }
3004
3028
 
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
- `;
3029
+ const exprArrayJS = exprRegistry.length > 0
3030
+ ? `var __X = [${exprRegistry.map((js) => `function(_ctx){ return ${js}; }`).join(",")}];\n`
3031
+ : "";
3014
3032
 
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
- `;
3033
+ let renderBody = "";
3034
+ renderBody += ` var _sx = window.scrollX, _sy = window.scrollY;\n`;
3035
+
3036
+ if (needsLogic) {
3037
+ renderBody += logicBlocks.map(b => b.replace(/^/gm, " ")).join("\n") + "\n";
3038
+ }
3039
+
3040
+ if (needsMixed) {
3041
+ for (const mb of mixedBlocks) {
3042
+ renderBody += ` (function() {
3043
+ var __el = document.getElementById(${JSON.stringify(mb.replaceId || mb.id)});
3044
+ if (__el) sinthMixedBlock(__el, ${mb.conditionJS}, ${JSON.stringify(mb.ifJS)}, ${JSON.stringify(mb.ifHTML)}, ${JSON.stringify(mb.elseJS)}, ${JSON.stringify(mb.elseHTML)});
3045
+ })();\n`;
3046
+ }
3025
3047
  }
3026
3048
 
3049
+ renderBody += ` document.querySelectorAll('[data-sinth-remove]').forEach(function(el) {
3050
+ var target = document.getElementById(el.dataset.sinthRemove);
3051
+ if (target) target.remove();
3052
+ });\n`;
3027
3053
 
3054
+ if (needsIf) {
3055
+ renderBody += ` document.querySelectorAll('template[data-sinth-if-expr]').forEach(sinthIfBlock);\n`;
3056
+ }
3057
+ if (needsFor) {
3058
+ renderBody += ` document.querySelectorAll('template[data-sinth-for]').forEach(sinthForBlock);\n`;
3059
+ }
3060
+ renderBody += ` document.querySelectorAll('[data-sinth-value]').forEach(function(el) {
3061
+ try { el.value = window[el.dataset.sinthValue] || ''; } catch(e) {}
3062
+ });\n`;
3063
+ renderBody += ` document.querySelectorAll('[data-sinth-checked]').forEach(function(el) {
3064
+ try { el.checked = !!window[el.dataset.sinthChecked]; } catch(e) {}
3065
+ });\n`;
3066
+ if (needsExpr) {
3067
+ renderBody += ` document.querySelectorAll('.sinth-expr').forEach(sinthExpr);\n`;
3068
+ }
3069
+ if (needsDelay) {
3070
+ renderBody += ` setTimeout(function() {
3071
+ document.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
3072
+ document.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
3073
+ }, 0);\n`;
3074
+ }
3028
3075
  renderBody += ` window.scrollTo(_sx, _sy);\n`;
3029
3076
 
3077
+ const renderFunc = needsRender ? `function sinthRender() {\n${renderBody}}\nsinthRender();` : "";
3030
3078
 
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
- : "";
3079
+ const pageCode = `// Sinth page runtime
3080
+ ${varLines}
3081
+ ${exprArrayJS}
3082
+ ${renderFunc}`;
3083
+
3084
+ if (opts.sharedRuntime && helpers.trim()) {
3085
+ const sharedCode = `// Sinth shared runtime
3086
+ ${helpers}`;
3087
+ return { page: pageCode, shared: sharedCode };
3088
+ }
3055
3089
 
3056
3090
  return `// Sinth compiled runtime
3057
3091
  ${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
- ` : ""}
3092
+ ${helpers}
3068
3093
  ${exprArrayJS}
3069
- ${needsRender ? `function sinthRender() {\n${renderBody}}\nsinthRender();` : ""}
3070
- ${delayBlock}`;
3094
+ ${renderFunc}`;
3071
3095
  }
3072
3096
 
3073
3097
  // main compilation pipeline
@@ -3078,9 +3102,10 @@ interface CompileOptions {
3078
3102
  libraryPaths: string[];
3079
3103
  minify: boolean;
3080
3104
  checkOnly: boolean;
3105
+ sharedRuntime: boolean;
3081
3106
  }
3082
3107
 
3083
- function compileFile(filePath: string, opts: CompileOptions): string | null {
3108
+ function compileFile(filePath: string, opts: CompileOptions): { html: string; shared?: string } | null {
3084
3109
  const absPath = path.resolve(filePath);
3085
3110
  const file = parseFile(absPath);
3086
3111
 
@@ -3107,7 +3132,7 @@ function compileFile(filePath: string, opts: CompileOptions): string | null {
3107
3132
  const body = file.uses.map(u => renderCompUse(u, ctx, new Map(), 0)).join("\n");
3108
3133
  const pageCSS = file.styles.map(s => processStyleBlock(s, hash)).join("\n");
3109
3134
  const allCSS = [pageCSS, ...ctx.extraCSS].join("\n");
3110
- return `${body}\n<style>\n${allCSS}\n</style>`;
3135
+ return { html: `${body}\n<style>\n${allCSS}\n</style>` };
3111
3136
  }
3112
3137
 
3113
3138
  const headData = buildHeadData(file.meta);
@@ -3141,18 +3166,23 @@ function compileFile(filePath: string, opts: CompileOptions): string | null {
3141
3166
  })(),
3142
3167
  }));
3143
3168
 
3144
- const head = renderHead(headData, relativeCssLinks, relativeJsLinks, scopedCSS, companionJS);
3145
-
3146
- // build tree-shaken runtime
3147
- const runtimeJS = buildRuntime({
3169
+ const runtimeResult = buildRuntime({
3148
3170
  varDecls: allVarDecls,
3149
3171
  bodyHTML,
3150
3172
  logicBlocks: ctx.logicBlocks,
3151
3173
  mixedBlocks: ctx.mixedBlocks,
3152
3174
  assignedVars,
3153
3175
  exprRegistry: ctx.exprRegistry,
3176
+ sharedRuntime: opts.sharedRuntime,
3154
3177
  });
3178
+ const runtimeJS = typeof runtimeResult === 'string' ? runtimeResult : runtimeResult.page;
3179
+ const sharedJS = typeof runtimeResult === 'string' ? null : runtimeResult.shared;
3180
+
3181
+ const sharedRuntimeTag = opts.sharedRuntime && sharedJS
3182
+ ? `<script src="./sinth-runtime.js"></script>`
3183
+ : "";
3155
3184
 
3185
+ const head = renderHead(headData, relativeCssLinks, relativeJsLinks, scopedCSS, companionJS);
3156
3186
  const scriptTags: string[] = [];
3157
3187
  if (componentScripts.length > 0) {
3158
3188
  scriptTags.push(`<script>\n${componentScripts.join("\n\n")}\n</script>`);
@@ -3172,13 +3202,15 @@ function compileFile(filePath: string, opts: CompileOptions): string | null {
3172
3202
  head,
3173
3203
  `<body data-s="${hash}">`,
3174
3204
  bodyHTML,
3205
+ sharedRuntimeTag,
3175
3206
  runtimeJS.trim() ? `<script>\n${runtimeJS}\n</script>` : "",
3176
3207
  scriptTags.join("\n"),
3177
3208
  "</body>",
3178
3209
  "</html>",
3179
3210
  ].filter(Boolean).join("\n");
3180
3211
 
3181
- return opts.minify ? minifyHTML(html) : html;
3212
+ const finalHTML = opts.minify ? minifyHTML(html) : html;
3213
+ return sharedJS ? { html: finalHTML, shared: sharedJS } : { html: finalHTML };
3182
3214
  }
3183
3215
 
3184
3216
  function minifyHTML(html: string): string {
@@ -3348,6 +3380,7 @@ async function main(): Promise<void> {
3348
3380
  const portIdx = args.indexOf("--port");
3349
3381
  const port = portIdx !== -1 ? parseInt(args[portIdx + 1], 10) : (cfg.port as number | undefined) ?? 3000;
3350
3382
  const minify = args.includes("--prod") || Boolean(cfg.minify);
3383
+ const sharedRuntime = args.includes("--shared-runtime") || Boolean(cfg.sharedRuntime);
3351
3384
  const libraryPaths = (cfg.libraryPaths as string[] | undefined) ?? [path.join(cwd, "libraries")];
3352
3385
 
3353
3386
  const flagValues = new Set<string>();
@@ -3355,7 +3388,7 @@ async function main(): Promise<void> {
3355
3388
  if (portIdx !== -1) flagValues.add(args[portIdx + 1]);
3356
3389
  const cleanArgs = args.filter(a => !a.startsWith("--") && !flagValues.has(a));
3357
3390
 
3358
- const opts: CompileOptions = { projectRoot: cwd, outDir, libraryPaths, minify, checkOnly: false };
3391
+ const opts: CompileOptions = { projectRoot: cwd, outDir, libraryPaths, minify, checkOnly: false, sharedRuntime };
3359
3392
 
3360
3393
  switch (command) {
3361
3394
  case "build": {
@@ -3371,10 +3404,15 @@ async function main(): Promise<void> {
3371
3404
 
3372
3405
  let hadError = false, built = 0;
3373
3406
 
3407
+ const sharedRuntimes: string[] = [];
3374
3408
  for (const p of pages) {
3375
3409
  try {
3376
- const html = compileFile(p, opts);
3377
- if (!html) continue;
3410
+ const result = compileFile(p, opts);
3411
+ if (!result) continue;
3412
+ const html = result.html;
3413
+ if (result.shared) {
3414
+ sharedRuntimes.push(result.shared);
3415
+ }
3378
3416
  const rel = path.relative(cwd, p).replace(/\.sinth$/, ".html");
3379
3417
  const out = path.join(outDir, rel);
3380
3418
  fs.mkdirSync(path.dirname(out), { recursive: true });
@@ -3387,6 +3425,12 @@ async function main(): Promise<void> {
3387
3425
  }
3388
3426
  }
3389
3427
 
3428
+ if (sharedRuntimes.length > 0) {
3429
+ const combined = sharedRuntimes.join("\n");
3430
+ fs.writeFileSync(path.join(outDir, "sinth-runtime.js"), combined);
3431
+ process.stdout.write(` \x1b[32m✓\x1b[0m sinth-runtime.js (shared)\n`);
3432
+ }
3433
+
3390
3434
  // copies to output
3391
3435
  const assetsIn = path.join(cwd, "assets"), assetsOut = path.join(outDir, "assets");
3392
3436
  if (fs.existsSync(assetsIn)) {
@@ -3457,8 +3501,24 @@ async function main(): Promise<void> {
3457
3501
  }
3458
3502
 
3459
3503
  default: {
3504
+ let version = "1.0.0";
3505
+ const paths = [
3506
+ path.resolve(__dirname, "..", "package.json"),
3507
+ path.resolve(__dirname, "package.json"),
3508
+ path.resolve(process.cwd(), "package.json"),
3509
+ path.resolve(process.cwd(), "..", "package.json"),
3510
+ ];
3511
+ for (const p of paths) {
3512
+ if (fs.existsSync(p)) {
3513
+ try {
3514
+ const pkg = JSON.parse(fs.readFileSync(p, "utf-8"));
3515
+ version = pkg.version;
3516
+ break;
3517
+ } catch {}
3518
+ }
3519
+ }
3460
3520
  process.stdout.write(`
3461
- \x1b[1mSinth Compiler v1.0.0\x1b[0m
3521
+ \x1b[1mSinth Compiler v${version}\x1b[0m
3462
3522
 
3463
3523
  \x1b[1mCommands:\x1b[0m
3464
3524
  sinth build [files] [--out ./dist] [--prod] Compile .sinth pages
@@ -3466,23 +3526,6 @@ async function main(): Promise<void> {
3466
3526
  sinth check Lint without emitting
3467
3527
  sinth init [name] Scaffold a new project
3468
3528
  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
3529
  `);
3487
3530
  break;
3488
3531
  }