@yannosay/sinth 0.5.2 → 0.5.4

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 +21 -18
  2. package/package.json +1 -1
  3. package/src/sinth.ts +109 -40
package/README.md CHANGED
@@ -2,29 +2,32 @@
2
2
 
3
3
  A declarative language that compiles to pure HTML, CSS, and JavaScript. Zero runtime, maximum control.
4
4
 
5
- ## Install
6
- @'
7
- # Sinth
5
+ ##
8
6
 
9
- A declarative language that compiles to pure HTML, CSS, and JavaScript. Zero runtime, maximum control.
7
+ ### Install ( Recommended Way)
8
+
9
+ * `npm install -g sinth`
10
+
11
+ ##
12
+
13
+ ### Quick start
10
14
 
11
- ## Install
12
- npm install -g sinth
15
+ * `sinth init`
16
+ * `sinth dev pages/index.sinth`
13
17
 
14
- text
15
18
 
16
- ## Quick start
17
- sinth init
18
- sinth dev
19
19
 
20
- text
21
20
 
22
- ## Commands
23
- - `sinth init` — scaffold a new project
24
- - `sinth dev` — start dev server with live reload
25
- - `sinth build` — compile to static files
26
- - `sinth check` — lint without output
27
- - `sinth version` — print version
21
+ ##
22
+
23
+ ### Commands
24
+
25
+ * `sinth init` — scaffold a new project
26
+ * `sinth dev` — start dev server with live reload
27
+ * `sinth build` — compile to static files
28
+ * `sinth check` — lint without output
29
+ * `sinth version` — print version
28
30
 
29
31
  ## License
30
- AGPL-3.0
32
+
33
+ AGPL-3.0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yannosay/sinth",
3
- "version": "0.5.2",
3
+ "version": "0.5.4",
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
@@ -63,7 +63,7 @@ interface CompUse { kind: "use"; name: string; attrs: Attr[]; childre
63
63
  interface ExprNode { kind: "expr"; expression: Expression; loc: Loc }
64
64
  interface AssignStmt { kind: "assign_stmt"; expression: Expression; loc: Loc }
65
65
  interface IfBlock { kind: "if"; condition: Expression; body: Child[]; elseBody?: Child[]; loc: Loc }
66
- interface ForLoop { kind: "for"; itemVar: string; arrayVar: string; body: Child[]; loc: Loc }
66
+ interface ForLoop { kind: "for"; keyVar?: string; itemVar: string; indexVar?: string; arrayVar: string; body: Child[]; loc: Loc }
67
67
 
68
68
  // v1.0.0: AssignStmt is a first-class Child so if bodies can be mixed.
69
69
  type Child = TextNode | CompUse | ExprNode | AssignStmt | IfBlock | ForLoop;
@@ -85,7 +85,7 @@ interface CompDef { name: string; params: ParamDecl[]; body: Child[]; style
85
85
  interface CustomElDecl { sinthName: string; tagName: string; params: ParamDecl[]; loc: Loc }
86
86
  interface CustomElInfo { tagName: string; params: ParamDecl[] }
87
87
 
88
- type VarType = "int" | "str" | "bool" | "str[]";
88
+ type VarType = "int" | "str" | "bool" | "str[]" | "obj";
89
89
  interface VarDeclaration { kind: "var"; name: string; varType: VarType; value: Literal | null; loc: Loc }
90
90
 
91
91
  type ImportNode =
@@ -112,10 +112,11 @@ interface SinthFile {
112
112
  interface MixedBlockEntry {
113
113
  id: string;
114
114
  conditionJS: string;
115
- ifJS: string; // assignment JS in if-branch
116
- ifHTML: string; // pre-rendered component HTML in if-branch
115
+ ifJS: string;
116
+ ifHTML: string;
117
117
  elseJS: string;
118
118
  elseHTML: string;
119
+ replaceId?: string;
119
120
  }
120
121
 
121
122
  interface CompileCtx {
@@ -126,9 +127,9 @@ interface CompileCtx {
126
127
  scopeHash: string;
127
128
  pageFile: string;
128
129
  extraCSS: string[];
129
- mixedBlocks: MixedBlockEntry[]; // v1.0.0: mixed if/else anchors
130
+ mixedBlocks: MixedBlockEntry[];
130
131
  mixedCounter: number;
131
- logicBlocks: string[]; // v1.0.0: pure-logic if JS fragments
132
+ logicBlocks: string[];
132
133
  }
133
134
 
134
135
  // ═══════════════════════════════════════════════════════════════════════════
@@ -516,7 +517,7 @@ export class Parser {
516
517
  // Variable declarations
517
518
  while (this.check(TT.IDENT) && this.peek().value === "var") {
518
519
  const vd = this.parseVarDeclaration();
519
- if (vd) { varDecls.push(vd); this._varDecls.push(vd); }
520
+ if (vd) { varDecls.push(vd); }
520
521
  }
521
522
 
522
523
  // Body
@@ -530,10 +531,13 @@ export class Parser {
530
531
  if (vd) varDecls.push(vd);
531
532
  }
532
533
  else if (this.check(TT.KW_IF)) {
533
- // v1.0.0: Top-level if blocks in a page are parsed via unified body
534
534
  const ifNode = this.parseIfBlock();
535
535
  uses.push(...this.flattenIfToUses(ifNode, scripts));
536
536
  }
537
+ else if (this.check(TT.KW_FOR)) {
538
+ const forNode = this.parseForLoop();
539
+ uses.push({ kind: "use", name: "__IF_ROOT__", attrs: [], children: [forNode], loc: forNode.loc });
540
+ }
537
541
  else if (this.check(TT.IDENT)) {
538
542
  const savedPos = this.pos;
539
543
  const identName = this.peek().value;
@@ -651,8 +655,8 @@ uses.push(this.parseCompUse());
651
655
  this.consume(TT.LBRACKET); this.consume(TT.RBRACKET);
652
656
  typeStr = "str[]";
653
657
  }
654
- if (!["int", "str", "bool", "str[]"].includes(typeStr)) {
655
- throw new SinthError(`Unknown type '${typeStr}'. Expected: int, str, bool, str[]`, typeTok.loc);
658
+ if (!["int", "str", "bool", "str[]", "obj"].includes(typeStr)) {
659
+ throw new SinthError(`Unknown type '${typeStr}'. Expected: int, str, bool, str[], obj`, typeTok.loc);
656
660
  }
657
661
 
658
662
  const nameTok = this.consume(TT.IDENT);
@@ -1064,7 +1068,25 @@ private parseArrayLiteral(): Literal {
1064
1068
 
1065
1069
  private parseForLoop(): ForLoop {
1066
1070
  const loc = this.consume(TT.KW_FOR).loc;
1067
- const itemVar = this.consume(TT.IDENT).value;
1071
+ const firstVar = this.consume(TT.IDENT).value;
1072
+ let keyVar: string | undefined;
1073
+ let itemVar: string;
1074
+ let indexVar: string | undefined;
1075
+ if (this.check(TT.COMMA)) {
1076
+ this.consume(TT.COMMA);
1077
+ keyVar = firstVar;
1078
+ itemVar = this.consume(TT.IDENT).value;
1079
+ if (this.check(TT.COMMA)) {
1080
+ this.consume(TT.COMMA);
1081
+ indexVar = this.consume(TT.IDENT).value;
1082
+ }
1083
+ } else {
1084
+ itemVar = firstVar;
1085
+ if (this.check(TT.COMMA)) {
1086
+ this.consume(TT.COMMA);
1087
+ indexVar = this.consume(TT.IDENT).value;
1088
+ }
1089
+ }
1068
1090
  if (!this.check(TT.KW_IN)) throw new SinthError("Expected 'in' after loop variable", this.peek().loc);
1069
1091
  this.consume(TT.KW_IN);
1070
1092
  const arrayVar = this.consume(TT.IDENT).value;
@@ -1076,7 +1098,7 @@ private parseArrayLiteral(): Literal {
1076
1098
  this.loopVar = null;
1077
1099
  this.consume(TT.RBRACE);
1078
1100
 
1079
- return { kind: "for", itemVar, arrayVar, body, loc };
1101
+ return { kind: "for", keyVar, itemVar, indexVar, arrayVar, body, loc };
1080
1102
  }
1081
1103
 
1082
1104
  // ── Component usages ─────────────────────────────────────────────────────
@@ -1112,7 +1134,7 @@ private parseArrayLiteral(): Literal {
1112
1134
  this.check(TT.BOOL_TRUE) || this.check(TT.BOOL_FALSE) ||
1113
1135
  this.check(TT.NULL_LIT) || this.check(TT.LBRACKET) || this.check(TT.LBRACE)) {
1114
1136
  value = this.parseLiteral();
1115
- } else if (this.check(TT.IDENT)) {
1137
+ } else if (this.check(TT.IDENT) || this.check(TT.LPAREN)) {
1116
1138
  // Try to parse as expression (handles user.age, user.age * 20, etc.)
1117
1139
  const savedPos = this.pos;
1118
1140
  const expr = this.parseExpression();
@@ -1121,7 +1143,11 @@ private parseArrayLiteral(): Literal {
1121
1143
  } else {
1122
1144
  // Not a full expression, treat as simple variable reference
1123
1145
  this.pos = savedPos;
1124
- value = { kind: "str", value: this.consume(TT.IDENT).value };
1146
+ if (this.check(TT.IDENT)) {
1147
+ value = { kind: "str", value: this.consume(TT.IDENT).value };
1148
+ } else {
1149
+ value = this.parseLiteral();
1150
+ }
1125
1151
  }
1126
1152
  } else {
1127
1153
  value = this.parseLiteral();
@@ -2165,8 +2191,10 @@ function renderChild(
2165
2191
 
2166
2192
  case "for": {
2167
2193
  const bodyHTML = child.body.map(c => renderChild(c, ctx, params, depth + 1)).join("");
2194
+ const keyAttr = child.keyVar ? ` data-sinth-key="${escAttr(child.keyVar)}"` : "";
2195
+ const idxAttr = child.indexVar ? ` data-sinth-index="${escAttr(child.indexVar)}"` : "";
2168
2196
  return (
2169
- `<template data-sinth-for="${escAttr(child.arrayVar)}" data-sinth-item="${escAttr(child.itemVar)}">${bodyHTML}</template>`
2197
+ `<template data-sinth-for="${escAttr(child.arrayVar)}" data-sinth-item="${escAttr(child.itemVar)}"${keyAttr}${idxAttr}>${bodyHTML}</template>`
2170
2198
  );
2171
2199
  }
2172
2200
 
@@ -2237,9 +2265,33 @@ depth: number,
2237
2265
  .map(c => renderChild(c, ctx, params, depth + 1))
2238
2266
  .join("");
2239
2267
 
2240
- ctx.mixedBlocks.push({ id, conditionJS: condJS, ifJS: ifAssignJS, ifHTML, elseJS: elseAssignJS, elseHTML });
2268
+ // Detect if both branches have a component with the same id — use it as replace anchor
2269
+ let replaceId: string | undefined;
2270
+ const ifFirstComp = ifBlock.body.find(c => c.kind === "use") as CompUse | undefined;
2271
+ const elseFirstComp = (ifBlock.elseBody ?? []).find(c => c.kind === "use") as CompUse | undefined;
2272
+ if (ifFirstComp) {
2273
+ const ifId = ifFirstComp.attrs.find(a => a.name === "id")?.value;
2274
+ const ifReplace = ifFirstComp.attrs.find(a => a.name === "replace");
2275
+ const ifReplaceVal = ifReplace?.value;
2276
+ const ifWantsReplace = !ifReplace || (ifReplaceVal?.kind === "bool" && ifReplaceVal.value === true) || (ifReplaceVal === null);
2277
+
2278
+ if (ifId && ifId.kind === "str" && ifWantsReplace) {
2279
+ if (elseFirstComp) {
2280
+ const elseId = elseFirstComp.attrs.find(a => a.name === "id")?.value;
2281
+ const elseReplace = elseFirstComp.attrs.find(a => a.name === "replace");
2282
+ const elseReplaceVal = elseReplace?.value;
2283
+ const elseWantsReplace = !elseReplace || (elseReplaceVal?.kind === "bool" && elseReplaceVal.value === true) || (elseReplaceVal === null);
2284
+
2285
+ if (elseId && elseId.kind === "str" && elseId.value === ifId.value && elseWantsReplace) {
2286
+ replaceId = ifId.value;
2287
+ }
2288
+ }
2289
+ }
2290
+ }
2291
+
2292
+ ctx.mixedBlocks.push({ id, conditionJS: condJS, ifJS: ifAssignJS, ifHTML, elseJS: elseAssignJS, elseHTML, replaceId });
2241
2293
 
2242
- return `<span id="${id}" data-sinth-mixed></span>`;
2294
+ return `<span id="${replaceId || id}" data-sinth-mixed></span>`;
2243
2295
  }
2244
2296
 
2245
2297
  function renderCompUse(
@@ -2534,7 +2586,8 @@ const needsLogic = logicBlocks.length > 0;
2534
2586
  const val = litToString(v.value);
2535
2587
  if (val.startsWith("__VAR__")) return `var ${v.name} = ${val.slice(7)};`;
2536
2588
  if (val.startsWith("__ARR__")) return `var ${v.name} = ${val.slice(7)};`;
2537
- if (v.varType === "str") return `var ${v.name} = ${JSON.stringify(val)};`;
2589
+ if (v.varType === "obj") return `var ${v.name} = ${val};`;
2590
+ if (v.varType === "str") return `var ${v.name} = ${JSON.stringify(val)};`;
2538
2591
  if (v.varType === "str[]" && typeof val === 'string' && val.startsWith("__ARR__")) {
2539
2592
  try {
2540
2593
  const arr = JSON.parse(val.slice(7));
@@ -2558,13 +2611,21 @@ return `var ${v.name} = ${val};`;
2558
2611
  renderBody += logicBlocks.map(b => b.replace(/^/gm, " ")).join("\n") + "\n";
2559
2612
  }
2560
2613
 
2614
+ // data-sinth-for templates (MUST run before if-templates)
2561
2615
  // data-sinth-for templates (MUST run before if-templates)
2562
2616
  if (needsFor) {
2563
2617
  renderBody += `
2564
2618
  document.querySelectorAll('template[data-sinth-for]').forEach(function(t) {
2565
- var arr;
2566
- try { arr = eval(t.dataset.sinthFor); } catch(e) { arr = []; }
2567
- if (!Array.isArray(arr)) arr = [];
2619
+ var source;
2620
+ try { source = eval(t.dataset.sinthFor); } catch(e) { source = []; }
2621
+ var isObj = (typeof source === 'object' && source !== null && !Array.isArray(source));
2622
+ var entries;
2623
+ if (isObj) {
2624
+ entries = Object.entries(source);
2625
+ } else {
2626
+ if (!Array.isArray(source)) source = [];
2627
+ entries = source.map(function(item, index) { return [index, item]; });
2628
+ }
2568
2629
  var anchor = t.parentNode ? t.parentNode.querySelector('[data-sinth-for-anchor="' + t.dataset.sinthFor + '"]') : null;
2569
2630
  if (anchor) {
2570
2631
  var cur2 = anchor.nextSibling;
@@ -2575,32 +2636,39 @@ return `var ${v.name} = ${val};`;
2575
2636
  fa.style.display = 'none';
2576
2637
  fa.dataset.sinthForAnchor = t.dataset.sinthFor;
2577
2638
  t.parentNode && t.parentNode.insertBefore(fa, t);
2578
- arr.forEach(function(item) {
2639
+ var _loopIdx = 0;
2640
+ entries.forEach(function(entry) {
2641
+ var _k = entry[0];
2642
+ var _v = entry[1];
2579
2643
  var _item = (t.dataset && t.dataset.sinthItem) ? t.dataset.sinthItem : '__item__';
2580
- var _user = item; // Capture in closure
2581
- window['_sinth_item_'] = _user;
2644
+ var _key = t.dataset && t.dataset.sinthKey ? t.dataset.sinthKey : null;
2645
+ var _idx = t.dataset && t.dataset.sinthIndex ? t.dataset.sinthIndex : null;
2646
+
2647
+ _loopIdx++;
2648
+ var _user = _v;
2582
2649
  var frag = document.createRange().createContextualFragment(t.innerHTML);
2583
- // Replace expressions with actual values BEFORE inserting into DOM
2584
2650
  frag.querySelectorAll('.sinth-expr').forEach(function(el) {
2585
2651
  try {
2586
2652
  if (el.dataset.expr === _item) {
2587
- el.textContent = _user;
2588
- } else if (el.dataset.expr && el.dataset.expr.indexOf(_item) !== -1) {
2589
- var expr = el.dataset.expr;
2590
- // Replace variable name with the captured closure variable
2653
+ el.textContent = _v;
2654
+ } else if (_key && el.dataset.expr === _key) {
2655
+ el.textContent = _k;
2656
+ } else if (el.dataset.expr && (el.dataset.expr.indexOf(_item) !== -1 || (_key && el.dataset.expr.indexOf(_key) !== -1) || (_idx && el.dataset.expr.indexOf(_idx) !== -1))) {
2591
2657
  eval('var ' + _item + ' = _user;');
2592
- el.textContent = eval(expr);
2658
+ if (_key) eval('var ' + _key + ' = _k;');
2659
+ if (_idx) eval('var ' + _idx + ' = _loopIdx - 1;');
2660
+ el.textContent = eval(el.dataset.expr);
2661
+ el.classList.remove('sinth-expr'); // Mark as processed
2593
2662
  }
2594
2663
  } catch(e) {}
2595
2664
  });
2596
- // Process if-templates
2597
2665
  frag.querySelectorAll('template[data-sinth-if]').forEach(function(ifT) {
2598
2666
  var cond = false;
2599
- try { eval('var ' + _item + ' = _user;'); cond = eval(ifT.dataset.sinthIf); } catch(e) {}
2667
+ try { eval('var ' + _item + ' = _user;'); if (_key) eval('var ' + _key + ' = _k;'); if (_idx) eval('var ' + _idx + ' = _loopIdx - 1;'); cond = eval(ifT.dataset.sinthIf); } catch(e) {}
2600
2668
  if (cond) {
2601
2669
  var ifContent = document.createRange().createContextualFragment(ifT.innerHTML);
2602
2670
  ifContent.querySelectorAll('.sinth-expr').forEach(function(el2) {
2603
- try { eval('var ' + _item + ' = _user;'); el2.textContent = eval(el2.dataset.expr); } catch(e) {}
2671
+ try { eval('var ' + _item + ' = _user;'); if (_key) eval('var ' + _key + ' = _k;'); if (_idx) eval('var ' + _idx + ' = _loopIdx - 1;'); el2.textContent = eval(el2.dataset.expr); } catch(e) {}
2604
2672
  });
2605
2673
  ifT.parentNode.insertBefore(ifContent, ifT);
2606
2674
  } else {
@@ -2608,13 +2676,12 @@ return `var ${v.name} = ${val};`;
2608
2676
  if (elseT && elseT.hasAttribute('data-sinth-else')) {
2609
2677
  var elseContent = document.createRange().createContextualFragment(elseT.innerHTML);
2610
2678
  elseContent.querySelectorAll('.sinth-expr').forEach(function(el2) {
2611
- try { eval('var ' + _item + ' = _user;'); el2.textContent = eval(el2.dataset.expr); } catch(e) {}
2679
+ try { eval('var ' + _item + ' = _user;'); if (_key) eval('var ' + _key + ' = _k;'); if (_idx) eval('var ' + _idx + ' = _loopIdx - 1;'); el2.textContent = eval(el2.dataset.expr); } catch(e) {}
2612
2680
  });
2613
2681
  ifT.parentNode.insertBefore(elseContent, ifT);
2614
2682
  }
2615
2683
  }
2616
2684
  });
2617
- // Handle delays
2618
2685
  frag.querySelectorAll('[data-sinth-delay]').forEach(function(el) {
2619
2686
  var ms = parseInt(el.dataset.sinthDelay) || 0;
2620
2687
  el.style.display = 'none';
@@ -2624,9 +2691,12 @@ return `var ${v.name} = ${val};`;
2624
2691
  frag.querySelectorAll('[data-sinth-delay-expr]').forEach(function(el) {
2625
2692
  try {
2626
2693
  eval('var ' + _item + ' = _user;');
2694
+ if (_key) eval('var ' + _key + ' = _k;');
2695
+ if (_idx) eval('var ' + _idx + ' = _loopIdx - 1;');
2627
2696
  var ms = eval(el.dataset.sinthDelayExpr) || 0;
2628
- el.style.display = '';
2697
+ el.style.display = 'none';
2629
2698
  if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
2699
+ else el.style.display = '';
2630
2700
  } catch(e) {}
2631
2701
  });
2632
2702
  t.parentNode && t.parentNode.insertBefore(frag, t);
@@ -2634,7 +2704,6 @@ return `var ${v.name} = ${val};`;
2634
2704
  });
2635
2705
  `;
2636
2706
  }
2637
-
2638
2707
  // data-sinth-if / data-sinth-else templates (run AFTER for-loops)
2639
2708
  if (needsIf) {
2640
2709
  renderBody += `
@@ -2728,14 +2797,14 @@ const elseHTMLJS = JSON.stringify(mb.elseHTML);
2728
2797
  const hasDelay = mb.ifHTML.includes("data-sinth-delay") || mb.elseHTML.includes("data-sinth-delay");
2729
2798
  renderBody += `
2730
2799
  (function() {
2731
- var __el = document.getElementById(${JSON.stringify(mb.id)});
2800
+ var __el = document.getElementById(${JSON.stringify(mb.replaceId || mb.id)});
2732
2801
  if (__el) {
2733
2802
  var __cond;
2734
2803
  try { __cond = (${mb.conditionJS}); } catch(e) { __cond = false; }
2735
2804
  if (__cond) {
2736
- ${mb.ifJS ? mb.ifJS + "\n" : ""} __el.innerHTML = ${ifHTMLJS};
2805
+ ${mb.ifJS ? mb.ifJS : ""} __el.innerHTML = ${ifHTMLJS};
2737
2806
  } else {
2738
- ${mb.elseJS ? mb.elseJS + "\n" : ""} __el.innerHTML = ${elseHTMLJS};
2807
+ ${mb.elseJS ? mb.elseJS : ""} __el.innerHTML = ${elseHTMLJS};
2739
2808
  }
2740
2809
  __el.querySelectorAll('.sinth-expr').forEach(function(e) {
2741
2810
  try { e.textContent = eval(e.dataset.expr); } catch(ex) {}