@yannosay/sinth 0.2.1 → 0.3.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.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/src/sinth.ts +98 -51
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yannosay/sinth",
3
- "version": "0.2.1",
3
+ "version": "0.3.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",
package/src/sinth.ts CHANGED
@@ -733,6 +733,8 @@ export class Parser {
733
733
  // += (only if next-next token is =)
734
734
  const nextTok = this.tokens[this.pos + 1];
735
735
  if (opTok.type === TT.OP_PLUS && nextTok && nextTok.type === TT.EQUALS) {
736
+ this.consume(TT.OP_PLUS); // consume '+'
737
+ this.consume(TT.EQUALS); // consume '='
736
738
  const right = this.parseExpression();
737
739
  if (!right) throw new SinthError("Expected expression after +=", this.peek().loc);
738
740
  return { kind: "assign", target: name, op: "+=", right };
@@ -836,7 +838,7 @@ export class Parser {
836
838
 
837
839
  // ── Component usages ──────────────────────────────────────
838
840
 
839
- private parseCompUse(): CompUse {
841
+ private parseCompUse(): CompUse {
840
842
  const loc = this.peek().loc;
841
843
  const name = this.consume(TT.IDENT).value;
842
844
  const attrs: Attr[] = [];
@@ -851,24 +853,40 @@ export class Parser {
851
853
  this.consume(TT.COLON);
852
854
  // For event attributes, try parsing the rest as an expression
853
855
  if (this.isEventAttribute(aname)) {
854
- const startTokens = this.pos;
855
- let expr = this.parseExpression();
856
- if (expr && !this.check(TT.COMMA) && !this.check(TT.RPAREN) && !this.check(TT.EOF)) {
857
- // If there are more tokens, it's probably not a simple expression
858
- this.pos = startTokens;
859
- expr = null;
856
+ // If the value is a quoted string, use it directly as handler code
857
+ if (this.check(TT.STRING)) {
858
+ value = this.parseLiteral();
859
+ } else {
860
+ const startTokens = this.pos;
861
+ let expr = this.parseExpression();
862
+ if (expr && !this.check(TT.COMMA) && !this.check(TT.RPAREN) && !this.check(TT.EOF)) {
863
+ // If there are more tokens, it's probably not a simple expression
864
+ this.pos = startTokens;
865
+ expr = null;
866
+ }
867
+ if (expr) {
868
+ value = { kind: "str", value: "__EXPR__" + JSON.stringify(expr) };
869
+ } else {
870
+ this.pos = startTokens;
871
+ value = this.parseLiteral();
872
+ }
860
873
  }
861
- if (expr) {
862
- value = { kind: "str", value: "__EXPR__" + JSON.stringify(expr) };
874
+ } else {
875
+ // Try literal first, then variable reference
876
+ if (this.check(TT.STRING) || this.check(TT.NUMBER) ||
877
+ this.check(TT.BOOL_TRUE) || this.check(TT.BOOL_FALSE) ||
878
+ this.check(TT.NULL_LIT) || this.check(TT.LBRACKET)) {
879
+ value = this.parseLiteral();
880
+ } else if (this.check(TT.IDENT)) {
881
+ const varName = this.consume(TT.IDENT).value;
882
+ value = { kind: "str", value: varName };
863
883
  } else {
864
- this.pos = startTokens;
865
884
  value = this.parseLiteral();
866
885
  }
867
- } else {
868
- value = this.parseLiteral();
869
886
  }
870
887
  }
871
888
  attrs.push({ name: aname, value, loc: aloc });
889
+
872
890
  if (!this.check(TT.RPAREN)) this.consume(TT.COMMA);
873
891
  }
874
892
  this.consume(TT.RPAREN);
@@ -1594,6 +1612,22 @@ function renderAttr(attr: Attr, paramMap: Map<string, string>): string {
1594
1612
  if (value === null) return name;
1595
1613
  if (value.kind === "null") return "";
1596
1614
  if (value.kind === "bool") return value.value ? name : "";
1615
+
1616
+ if (name === "delay") {
1617
+ // Support both numbers and variable references
1618
+ let delayVal: string;
1619
+ if (value.kind === "num") {
1620
+ delayVal = String(value.value);
1621
+ } else {
1622
+ delayVal = litToString(value);
1623
+ // If it looks like a variable name (not a number), treat it as a JS expression
1624
+ if (!/^\d+$/.test(delayVal)) {
1625
+ return `data-sinth-delay-expr="${escAttr(delayVal)}" style="display:none"`;
1626
+ }
1627
+ }
1628
+ return `data-sinth-delay="${escAttr(delayVal)}" style="display:none"`;
1629
+ }
1630
+
1597
1631
  if (value.kind === "num") return `${name}="${value.value}"`;
1598
1632
 
1599
1633
  let raw = value.value;
@@ -1606,20 +1640,21 @@ function renderAttr(attr: Attr, paramMap: Map<string, string>): string {
1606
1640
  const jsExpr = compileExprToJS(expr);
1607
1641
  const ev = eventAttrName(name);
1608
1642
  if (ev) {
1609
- return `${ev}="(function(){ ${jsExpr}; })()"`;
1643
+ return `${ev}="(function(){ ${jsExpr.replace(/"/g, '&quot;')}; })()"`;
1610
1644
  }
1611
1645
  return `${name}="${escAttr(jsExpr)}"`;
1612
1646
  } catch {
1613
1647
  // Fall through to normal handling
1614
1648
  }
1615
- }
1616
-
1649
+ }
1650
+
1617
1651
  raw = interpolateAttr(raw, paramMap);
1618
1652
 
1619
1653
  const ev = eventAttrName(name);
1620
1654
  if (ev) {
1621
- const call = raw.includes("(") ? raw : `${raw}(event)`;
1622
- return `${ev}="${escAttr(call)}"`;
1655
+ // Always append sinthRender() to event handlers
1656
+ const handler = raw.includes("(") ? raw : raw;
1657
+ return `${ev}="${escAttr(handler)};sinthRender()"`;
1623
1658
  }
1624
1659
  return `${name}="${escAttr(raw)}"`;
1625
1660
  }
@@ -2078,11 +2113,13 @@ function compileFile(filePath: string, opts: CompileOptions): string | null {
2078
2113
  if (componentScripts.length > 0) {
2079
2114
  scriptTags.push(`<script>\n${componentScripts.join("\n\n")}\n</script>`);
2080
2115
  }
2081
- for (const s of pageScripts) {
2116
+ for (const s of pageScripts) {
2082
2117
  const extra = Object.entries(s.attrs)
2083
2118
  .map(([k, v]) => v === "true" ? k : `${k}="${escAttr(v)}"`)
2084
2119
  .join(" ");
2085
- scriptTags.push(`<script${extra ? " " + extra : ""}>\n${s.raw}\n</script>`);
2120
+ // Convert let/const to var for global accessibility
2121
+ const globalRaw = s.raw.replace(/\b(let|const)\b/g, 'var');
2122
+ scriptTags.push(`<script${extra ? " " + extra : ""}>\n${globalRaw}\n</script>`);
2086
2123
  }
2087
2124
 
2088
2125
  const html = [
@@ -2092,53 +2129,49 @@ function compileFile(filePath: string, opts: CompileOptions): string | null {
2092
2129
  `<body data-s="${hash}">`,
2093
2130
  bodyHTML,
2094
2131
  `<script>
2095
- // v0.2.0: Sinth variable declarations
2132
+ // v0.2.0: Sinth variable declarations (global scope)
2096
2133
  ${file.varDecls.map(v => {
2097
- if (!v.value) return `let ${v.name};`; // uninitialized
2134
+ if (!v.value) return `var ${v.name};`;
2098
2135
  const val = litToString(v.value);
2099
2136
 
2100
- // Variable reference: __VAR__count → count
2101
2137
  if (v.varType !== "str[]" && val.startsWith("__VAR__")) {
2102
2138
  const refName = val.slice(7);
2103
- return `let ${v.name} = ${refName};`;
2139
+ return `var ${v.name} = ${refName};`;
2104
2140
  }
2105
2141
 
2106
- // Array literal: __ARR__["a","b"]
2107
2142
  if (val.startsWith("__ARR__")) {
2108
- return `let ${v.name} = ${val.slice(7)};`;
2143
+ return `var ${v.name} = ${val.slice(7)};`;
2109
2144
  }
2110
2145
 
2111
- if (v.varType === "str") return `let ${v.name} = ${JSON.stringify(val)};`;
2112
- return `let ${v.name} = ${val};`;
2146
+ if (v.varType === "str") return `var ${v.name} = ${JSON.stringify(val)};`;
2147
+ return `var ${v.name} = ${val};`;
2113
2148
  }).join("\n")}
2114
2149
 
2115
- // v0.2.0: Store original page HTML for full re-render
2116
- const _sinthBodyHTML = document.body.innerHTML;
2117
-
2118
2150
  function sinthRender() {
2119
- // Save current scroll position
2120
2151
  const scrollX = window.scrollX;
2121
2152
  const scrollY = window.scrollY;
2122
2153
 
2123
- // Re-render the entire body from the original HTML
2124
- document.body.innerHTML = _sinthBodyHTML;
2125
-
2126
- // Re-process all templates recursively
2127
2154
  function processTemplates(root) {
2128
2155
  root.querySelectorAll('template[data-sinth-if]').forEach(t => {
2129
- const cond = new Function('return ' + t.dataset.sinthIf)();
2156
+ const cond = eval(t.dataset.sinthIf);
2130
2157
  if (cond) {
2131
2158
  const frag = document.createRange().createContextualFragment(t.innerHTML);
2132
2159
  t.replaceWith(frag);
2133
- processTemplates(root); // Re-process in case templates were nested
2160
+ // Update expressions in the newly inserted fragment
2161
+ root.querySelectorAll('.sinth-expr').forEach(el => {
2162
+ try { el.textContent = eval(el.dataset.expr); } catch(e) {}
2163
+ });
2164
+ processTemplates(root);
2134
2165
  } else {
2135
2166
  const elseT = t.nextElementSibling;
2136
2167
  if (elseT && elseT.matches && elseT.matches('template[data-sinth-else]')) {
2137
2168
  const frag = document.createRange().createContextualFragment(elseT.innerHTML);
2138
2169
  elseT.replaceWith(frag);
2170
+ root.querySelectorAll('.sinth-expr').forEach(el => {
2171
+ try { el.textContent = eval(el.dataset.expr); } catch(e) {}
2172
+ });
2139
2173
  processTemplates(root);
2140
2174
  }
2141
- t.remove();
2142
2175
  }
2143
2176
  });
2144
2177
  root.querySelectorAll('template[data-sinth-for]').forEach(t => {
@@ -2147,41 +2180,55 @@ function sinthRender() {
2147
2180
  const itemName = t.dataset.sinthItem;
2148
2181
  const frag = document.createDocumentFragment();
2149
2182
  arr.forEach(item => {
2150
- // Fill the expression spans with the actual loop value BEFORE adding to DOM
2151
2183
  let itemHTML = t.innerHTML;
2152
2184
  const regex = new RegExp('<span class="sinth-expr" data-expr="' + itemName + '"></span>', 'g');
2153
2185
  itemHTML = itemHTML.replace(regex, '<span class="sinth-expr" data-expr="' + itemName + '">' + item + '</span>');
2154
2186
  frag.append(document.createRange().createContextualFragment(itemHTML));
2155
2187
  });
2156
2188
  t.replaceWith(frag);
2189
+ // Update expressions after for-loop expansion
2190
+ root.querySelectorAll('.sinth-expr').forEach(el => {
2191
+ try { el.textContent = eval(el.dataset.expr); } catch(e) {}
2192
+ });
2157
2193
  processTemplates(root);
2158
2194
  }
2159
2195
  });
2160
2196
  }
2161
2197
  processTemplates(document.body);
2162
2198
 
2163
- // Update all expression spans
2199
+ // Show delayed elements after DOM settles
2200
+ setTimeout(() => {
2201
+ // Handle static delays
2202
+ document.querySelectorAll('[data-sinth-delay]').forEach(el => {
2203
+ const delayMs = parseInt(el.dataset.sinthDelay) || 0;
2204
+ if (delayMs > 0) {
2205
+ setTimeout(() => { el.style.display = ''; }, delayMs);
2206
+ }
2207
+ });
2208
+ // Handle expression-based delays (variables)
2209
+ document.querySelectorAll('[data-sinth-delay-expr]').forEach(el => {
2210
+ try {
2211
+ const delayMs = parseInt(eval(el.dataset.sinthDelayExpr)) || 0;
2212
+ if (delayMs > 0) {
2213
+ setTimeout(() => { el.style.display = ''; }, delayMs);
2214
+ }
2215
+ } catch(e) {}
2216
+ });
2217
+ }, 0);
2218
+
2219
+ // Update any remaining expression spans (from initial render)
2164
2220
  document.querySelectorAll('.sinth-expr').forEach(el => {
2165
2221
  try { el.textContent = eval(el.dataset.expr); } catch(e) {}
2166
2222
  });
2167
2223
 
2168
- // Update onclick handlers
2169
- document.querySelectorAll('[onclick]').forEach(el => {
2170
- const oc = el.getAttribute('onclick');
2171
- if (oc && oc.startsWith('(function(){') && !oc.includes('sinthRender()')) {
2172
- const inner = oc.slice(12, -4);
2173
- el.setAttribute('onclick', '(function(){' + inner + ';sinthRender();})()');
2174
- }
2175
- });
2176
-
2177
- // Restore scroll
2178
2224
  window.scrollTo(scrollX, scrollY);
2179
2225
  }
2180
2226
 
2181
2227
  // Initial render
2182
2228
  sinthRender();
2183
2229
  </script>`,
2184
- scriptTags.join("\n"), "</body>",
2230
+ scriptTags.join("\n"),
2231
+ "</body>",
2185
2232
  "</html>",
2186
2233
  ].join("\n");
2187
2234