@yannosay/sinth 0.15.3 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,9 +1,10 @@
1
1
  # Sinth
2
2
 
3
- The language that fixes HTML. Declarative. Reactive. Compiles to pure HTML.
3
+ The language that makes HTML feel SO easy. Declarative. Reactive. Compiles to pure HTML.
4
4
 
5
- Find out more: https://www.youtube.com/watch?v=W0tOMTiIF0Q
6
- Discord: [Join here!](https://discord.gg/SUvcrafTQm)
5
+ * Introduction: https://www.youtube.com/watch?v=W0tOMTiIF0Q
6
+ * Discord: [Join here!](https://discord.gg/SUvcrafTQm)
7
+ * Documentation: [sinth.yannosay.com/docs](https://sinth.yannosay.com/docs)
7
8
 
8
9
 
9
10
  [![npm version](https://img.shields.io/npm/v/@yannosay/sinth)](https://www.npmjs.com/package/@yannosay/sinth)
@@ -132,6 +133,25 @@ Button(onClick: isFullscreen = !isFullscreen, fullscreen: isFullscreen, fullscre
132
133
  Without fullscreenSync, pressing Escape exits fullscreen but the variable stays true.
133
134
  With it, Escape resets the variable to false — button text updates automatically.
134
135
 
136
+ ### Opt-in DOM Diffing
137
+
138
+ Skip re-executing expressions when their variables haven't changed. Perfect for expensive calculations or side effects you only want to fire once.
139
+
140
+ ```ts
141
+ page
142
+ domdiffing = true -- enables expression memoization
143
+
144
+ var int count = 0
145
+
146
+ Main {
147
+ Heading(level: 1) { count }
148
+ (alert("Fires only once!")) -- no dependencies, runs once and never again
149
+ Button(onClick: count = += 1) { "Increment" }
150
+ }
151
+ ```
152
+ Count updates every click because count changed. The alert fires only on page load — zero dependencies means it's cached forever. No library import. No window pollution. Just a meta flag.
153
+
154
+
135
155
 
136
156
  #### Animations that make sense.
137
157
  ```ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yannosay/sinth",
3
- "version": "0.15.3",
3
+ "version": "0.16.0",
4
4
  "description": "A declarative & reactive language that compiles to pure HTML, CSS, and JavaScript.",
5
5
  "author": "Yannosay Productions",
6
6
  "license": "AGPL-3.0",
@@ -36,7 +36,7 @@
36
36
  "ts-node": "^10.9.0"
37
37
  },
38
38
  "devDependencies": {
39
- "@types/node": "^20.19.40",
39
+ "@types/node": "^20.19.41",
40
40
  "typescript": "^5.3.0"
41
41
  },
42
42
  "engines": {
package/src/cli.ts CHANGED
@@ -317,7 +317,7 @@ component Card(title, color = "blue") {
317
317
  name: path.basename(root).toLowerCase().replace(/\s+/g, "-"),
318
318
  version: "1.0.0",
319
319
  scripts: { build: "sinth build", dev: "sinth dev" },
320
- devDependencies: { "ts-node": "^10.0.0", typescript: "^5.0.0", sass: "^1.70.0" },
320
+ dependencies: { "ts-node": "^10.0.0", "sass": "^1.70.0" },
321
321
  }, null, 2));
322
322
 
323
323
  process.stdout.write(`
@@ -254,7 +254,15 @@ if (name === "delay") {
254
254
  const exprs: Expression[] = JSON.parse(exprJson);
255
255
  const jsExprs = exprs.map(e => compileExprToJS(e)).join("; ");
256
256
  const ev = eventAttrName(name);
257
- if (ev) return `${ev}="(function(){ ${jsExprs.replace(/"/g, """)}; sinthRender(); })()"`;
257
+ let bumps = "";
258
+ if (ctx.diffingEnabled) {
259
+ const targets: string[] = [];
260
+ for (const e of exprs) {
261
+ if (e.kind === "assign" && e.target) targets.push(e.target);
262
+ }
263
+ if (targets.length) bumps = ";" + targets.map(t => `window._bump&&window._bump('${t.replace(/'/g, "\\'")}')`).join(";");
264
+ }
265
+ if (ev) return `${ev}="(function(){ ${jsExprs.replace(/"/g, """)}${bumps}; sinthRender(); })()"`;
258
266
  return `${name}="${escAttr(jsExprs)}"`;
259
267
  } catch { }
260
268
  }
@@ -274,7 +282,11 @@ if (name === "delay") {
274
282
  }
275
283
  }
276
284
  const jsExpr = compileExprToJS(expr, ctx?.loopVars);
277
- if (ev) return `${ev}="(function(){ ${jsExpr.replace(/"/g, """)}; sinthRender(); })()"`;
285
+ let bump = "";
286
+ if (ctx.diffingEnabled && expr.kind === "assign" && expr.target) {
287
+ bump = `;window._bump&&window._bump('${expr.target.replace(/'/g, "\\'")}')`;
288
+ }
289
+ if (ev) return `${ev}="(function(){ ${jsExpr.replace(/"/g, """)}${bump}; sinthRender(); })()"`;
278
290
  return `${name}="${escAttr(jsExpr)}"`;
279
291
  } catch { }
280
292
  }
@@ -320,6 +332,21 @@ function substituteParamsInExpr(expr: Expression, params: Map<string, string>):
320
332
  return expr;
321
333
  }
322
334
 
335
+ function exprDeps(expr: Expression, declaredVars: Set<string>): string {
336
+ const deps = new Set<string>();
337
+ function walk(e: Expression | undefined): void {
338
+ if (!e) return;
339
+ if (e.kind === "variable" && e.name && declaredVars.has(e.name)) deps.add(e.name);
340
+ if (e.kind === "binary") { walk(e.left); walk(e.right); }
341
+ if (e.kind === "unary") walk(e.operand);
342
+ if (e.kind === "call") { e.args?.forEach(walk); }
343
+ if (e.kind === "index") { walk(e.object); walk(e.key); }
344
+ if (e.kind === "assign") { if (e.target && declaredVars.has(e.target)) deps.add(e.target); walk(e.right); }
345
+ }
346
+ walk(expr);
347
+ return [...deps].join(",");
348
+ }
349
+
323
350
  export function renderChild(
324
351
  child: Child,
325
352
  ctx: CompileCtx,
@@ -345,13 +372,13 @@ export function renderChild(
345
372
  }
346
373
  if (val.startsWith("__VAR__")) {
347
374
  const exprId = registerExpr(ctx, { kind: "variable", name: val.slice(7) });
348
- return `<span class="sinth-expr" data-expr-id="${exprId}"></span>`;
375
+ return `<span class="sinth-expr" data-expr-id="${exprId}"${ctx.diffingEnabled ? ` data-sinth-deps="${exprDeps(child.expression, ctx.declaredVars ?? new Set())}"` : ""}></span>`;
349
376
  }
350
377
  if (val.startsWith("__EXPR__")) {
351
378
  try {
352
379
  const expr: Expression = JSON.parse(val.substring(8));
353
380
  const exprId = registerExpr(ctx, expr);
354
- return `<span class="sinth-expr" data-expr-id="${exprId}"></span>`;
381
+ return `<span class="sinth-expr" data-expr-id="${exprId}"${ctx.diffingEnabled ? ` data-sinth-deps="${exprDeps(child.expression, ctx.declaredVars ?? new Set())}"` : ""}></span>`;
355
382
  } catch { return esc(val); }
356
383
  }
357
384
  return esc(val);
@@ -456,14 +483,14 @@ export function renderChild(
456
483
  }
457
484
  if (child.expression.kind === "variable" && child.expression.name && !ctx.loopVars?.has(child.expression.name)) {
458
485
  const exprId = registerExpr(ctx, child.expression);
459
- return `<span class="sinth-expr" data-expr-id="${exprId}"></span>`;
486
+ return `<span class="sinth-expr" data-expr-id="${exprId}"${ctx.diffingEnabled ? ` data-sinth-deps="${exprDeps(child.expression, ctx.declaredVars ?? new Set())}"` : ""}></span>`;
460
487
  }
461
488
  let expr = child.expression;
462
489
  if (params.size > 0) {
463
490
  expr = substituteParamsInExpr(expr, params);
464
491
  }
465
492
  const exprId = registerExpr(ctx, expr);
466
- return `<span class="sinth-expr" data-expr-id="${exprId}"></span>`;
493
+ return `<span class="sinth-expr" data-expr-id="${exprId}"${ctx.diffingEnabled ? ` data-sinth-deps="${exprDeps(child.expression, ctx.declaredVars ?? new Set())}"` : ""}></span>`;
467
494
  }
468
495
 
469
496
  case "assign_stmt": {
@@ -585,7 +612,15 @@ depth: number,
585
612
 
586
613
  const ifAssignJS = ifBlock.body
587
614
  .filter(c => c.kind === "assign_stmt")
588
- .map(c => ` ${compileExprToJS((c as AssignStmt).expression)};`)
615
+ .map(c => {
616
+ const e = (c as AssignStmt).expression;
617
+ const js = compileExprToJS(e);
618
+ let bump = "";
619
+ if (ctx.diffingEnabled && e.kind === "assign" && e.target) {
620
+ bump = `;window._bump&&window._bump('${e.target.replace(/'/g, "\\'")}')`;
621
+ }
622
+ return ` ${js};${bump}`;
623
+ })
589
624
  .join("\n");
590
625
 
591
626
  const ifHTML = ifBlock.body
@@ -595,7 +630,15 @@ depth: number,
595
630
 
596
631
  const elseAssignJS = (ifBlock.elseBody ?? [])
597
632
  .filter(c => c.kind === "assign_stmt")
598
- .map(c => ` ${compileExprToJS((c as AssignStmt).expression)};`)
633
+ .map(c => {
634
+ const e = (c as AssignStmt).expression;
635
+ const js = compileExprToJS(e);
636
+ let bump = "";
637
+ if (ctx.diffingEnabled && e.kind === "assign" && e.target) {
638
+ bump = `;window._bump&&window._bump('${e.target.replace(/'/g, "\\'")}')`;
639
+ }
640
+ return ` ${js};${bump}`;
641
+ })
599
642
  .join("\n");
600
643
 
601
644
  const elseHTML = (ifBlock.elseBody ?? [])
@@ -1140,6 +1183,10 @@ export function compileFile(filePath: string, opts: CompileOptions): { html: str
1140
1183
  }
1141
1184
  }
1142
1185
  }
1186
+ const enableDiffing = file.meta.some(m =>
1187
+ m.key === "domdiffing" &&
1188
+ (m.value.kind === "bool" ? m.value.value === true : (m.value.kind === "str" && m.value.value === "true"))
1189
+ );
1143
1190
  const ctx: CompileCtx = {
1144
1191
  allDefs, functionDefs, customEls, cssLinks, jsLinks,
1145
1192
  scopeHash: hash,
@@ -1153,6 +1200,8 @@ export function compileFile(filePath: string, opts: CompileOptions): { html: str
1153
1200
  exprMap: new Map(),
1154
1201
  varDecls: allVarDecls,
1155
1202
  actionButtons: [],
1203
+ diffingEnabled: enableDiffing,
1204
+ declaredVars: declaredVars,
1156
1205
  };
1157
1206
 
1158
1207
  if (!file.isPage) {
@@ -1213,10 +1262,38 @@ export function compileFile(filePath: string, opts: CompileOptions): { html: str
1213
1262
  assignedVars,
1214
1263
  exprRegistry: ctx.exprRegistry,
1215
1264
  sharedRuntime: opts.sharedRuntime,
1216
- functionsJS: compiledFunctions, // ← pass compiled functions
1265
+ functionsJS: compiledFunctions,
1217
1266
  });
1218
1267
  const runtimeJS = typeof runtimeResult === 'string' ? runtimeResult : runtimeResult.page;
1219
1268
  const sharedJS = typeof runtimeResult === 'string' ? null : runtimeResult.shared;
1269
+ let finalRuntimeJS = runtimeJS;
1270
+ if (enableDiffing) {
1271
+ finalRuntimeJS = runtimeJS.replace('sinthRender();',
1272
+ 'var _bump=function(v){_bump._v[v]=(_bump._v[v]||0)+1;};' +
1273
+ '_bump._v={};' +
1274
+ 'window._bump=_bump;' +
1275
+ 'var _exprCache=new WeakMap();' +
1276
+ 'var _origSinthExpr=sinthExpr;' +
1277
+ 'sinthExpr=function(el){' +
1278
+ 'var deps=el.dataset.sinthDeps;' +
1279
+ 'if(deps!=null){' +
1280
+ 'var list=deps.split(",").filter(Boolean);' +
1281
+ 'if(list.length){' +
1282
+ 'var h="";' +
1283
+ 'for(var i=0;i<list.length;i++){var v=list[i].trim();h+=v+":"+(_bump._v[v]||0)+";";}' +
1284
+ 'var old=_exprCache.get(el);' +
1285
+ 'if(old===h)return;' +
1286
+ '_exprCache.set(el,h);' +
1287
+ '}else{' +
1288
+ 'if(_exprCache.has(el))return;' +
1289
+ '_exprCache.set(el,1);' +
1290
+ '}' +
1291
+ '}' +
1292
+ '_origSinthExpr(el);' +
1293
+ '};' +
1294
+ 'sinthRender();'
1295
+ );
1296
+ }
1220
1297
 
1221
1298
 
1222
1299
  const head = renderHead(headData, relativeCssLinks, relativeJsLinks, scopedCSS, companionJS);
@@ -1262,7 +1339,7 @@ const sharedRuntimeTag = (() => {
1262
1339
  bodyHTML,
1263
1340
  actionInitScript,
1264
1341
  sharedRuntimeTag,
1265
- runtimeJS.trim() ? `<script>\n${runtimeJS}\n</script>` : "",
1342
+ finalRuntimeJS.trim() ? `<script>\n${finalRuntimeJS}\n</script>` : "",
1266
1343
  scriptTags.join("\n"),
1267
1344
  "</body>",
1268
1345
  "</html>",
@@ -804,8 +804,28 @@ private parseArrayLiteral(): Literal {
804
804
  continue;
805
805
  }
806
806
 
807
- // Component usage: ident( or ident{ or ident RAW_BLOCK
808
- if (nextType === TT.LPAREN || nextType === TT.LBRACE || nextType === TT.RAW_BLOCK) {
807
+ if (nextType === TT.LPAREN) {
808
+ const identName = this.peek().value;
809
+ if (identName[0] === identName[0].toUpperCase() && identName[0] !== identName[0].toLowerCase()) {
810
+ children.push(this.parseCompUse());
811
+ } else {
812
+ this.consume(TT.IDENT);
813
+ this.consume(TT.LPAREN);
814
+ const args: Expression[] = [];
815
+ if (!this.check(TT.RPAREN)) {
816
+ args.push(this.parseExpression()!);
817
+ while (this.check(TT.COMMA)) {
818
+ this.consume(TT.COMMA);
819
+ args.push(this.parseExpression()!);
820
+ }
821
+ }
822
+ this.consume(TT.RPAREN);
823
+ const callExpr: Expression = { kind: "call", callee: { kind: "variable", name: identName }, args };
824
+ children.push({ kind: "expr", expression: callExpr, loc });
825
+ }
826
+ continue;
827
+ }
828
+ if (nextType === TT.LBRACE || nextType === TT.RAW_BLOCK) {
809
829
  children.push(this.parseCompUse());
810
830
  continue;
811
831
  }
@@ -836,11 +856,6 @@ private parseArrayLiteral(): Literal {
836
856
  continue;
837
857
  }
838
858
 
839
- throw new SinthError(
840
- `Unexpected token '${this.peek().value}' in if/else body`,
841
- this.peek().loc,
842
- );
843
-
844
859
  // reject implicit concatenation only after expression children
845
860
  if (children.length > 0) {
846
861
  const lastChild = children[children.length - 1];
@@ -855,7 +870,8 @@ private parseArrayLiteral(): Literal {
855
870
  this.tokens[this.pos]?.value !== "for" &&
856
871
  this.tokens[this.pos]?.value !== "else" &&
857
872
  this.tokens[this.pos]?.value !== "and" &&
858
- this.tokens[this.pos]?.value !== "or")
873
+ this.tokens[this.pos]?.value !== "or" &&
874
+ this.tokens[this.pos]?.value[0] !== this.tokens[this.pos]?.value[0]?.toUpperCase())
859
875
  ) {
860
876
  throw new SinthError(
861
877
  `Unexpected ${TT[nextTT]}. Use '+' to concatenate values.`,
@@ -977,7 +993,7 @@ private parseArrayLiteral(): Literal {
977
993
  this.check(TT.BOOL_TRUE) || this.check(TT.BOOL_FALSE) ||
978
994
  this.check(TT.NULL_LIT) || this.check(TT.LBRACKET) || this.check(TT.LBRACE)) {
979
995
  value = this.parseLiteral();
980
- } else if (this.check(TT.IDENT) || this.check(TT.LPAREN)) {
996
+ } else if (this.check(TT.IDENT) || this.check(TT.LPAREN) || this.check(TT.NUMBER)) {
981
997
  const savedPos = this.pos;
982
998
  const expr = this.parseExpression();
983
999
  if (expr && (this.check(TT.COMMA) || this.check(TT.RPAREN))) {
@@ -1024,6 +1040,7 @@ private parseArrayLiteral(): Literal {
1024
1040
  private parseChildList(): Child[] {
1025
1041
  const children: Child[] = [];
1026
1042
  while (!this.check(TT.EOF) && !this.check(TT.RBRACE)) {
1043
+
1027
1044
  if (this.check(TT.LPAREN)) {
1028
1045
  const loc = this.peek().loc;
1029
1046
  this.consume(TT.LPAREN);
@@ -1207,14 +1224,35 @@ private parseArrayLiteral(): Literal {
1207
1224
  } else {
1208
1225
  children.push({ kind: "expr", expression: indexedExpr, loc });
1209
1226
  }
1210
- } else if (nextType === TT.LPAREN || nextType === TT.LBRACE || nextType === TT.RAW_BLOCK) {
1227
+ } else if (nextType === TT.LPAREN) {
1228
+ const identName = this.peek().value;
1229
+ if (identName[0] === identName[0].toUpperCase() && identName[0] !== identName[0].toLowerCase()) {
1230
+ children.push(this.parseCompUse());
1231
+ continue;
1232
+ } else {
1233
+ this.consume(TT.IDENT);
1234
+ this.consume(TT.LPAREN);
1235
+ const args: Expression[] = [];
1236
+ if (!this.check(TT.RPAREN)) {
1237
+ args.push(this.parseExpression()!);
1238
+ while (this.check(TT.COMMA)) {
1239
+ this.consume(TT.COMMA);
1240
+ args.push(this.parseExpression()!);
1241
+ }
1242
+ }
1243
+ this.consume(TT.RPAREN);
1244
+ const callExpr: Expression = { kind: "call", callee: { kind: "variable", name: identName }, args };
1245
+ children.push({ kind: "expr", expression: callExpr, loc });
1246
+ continue;
1247
+ }
1248
+ } else if (nextType === TT.LBRACE || nextType === TT.RAW_BLOCK) {
1211
1249
  children.push(this.parseCompUse());
1250
+ continue;
1212
1251
  } else {
1213
1252
  const name = this.consume(TT.IDENT).value;
1214
1253
  children.push({ kind: "expr", expression: { kind: "variable", name }, loc });
1215
1254
  }
1216
1255
  }
1217
- else throw new SinthError(`Unexpected token '${this.peek().value}' in children`, this.peek().loc);
1218
1256
  // reject implicit concatenation only after expression children
1219
1257
  if (children.length > 0) {
1220
1258
  const lastChild = children[children.length - 1];
@@ -1229,7 +1267,8 @@ private parseArrayLiteral(): Literal {
1229
1267
  this.tokens[this.pos]?.value !== "for" &&
1230
1268
  this.tokens[this.pos]?.value !== "else" &&
1231
1269
  this.tokens[this.pos]?.value !== "and" &&
1232
- this.tokens[this.pos]?.value !== "or")
1270
+ this.tokens[this.pos]?.value !== "or" &&
1271
+ this.tokens[this.pos]?.value[0] !== this.tokens[this.pos]?.value[0]?.toUpperCase())
1233
1272
  ) {
1234
1273
  throw new SinthError(
1235
1274
  `Unexpected ${TT[nextTT]}. Use '+' to concatenate values.`,
@@ -1238,6 +1277,9 @@ private parseArrayLiteral(): Literal {
1238
1277
  }
1239
1278
  }
1240
1279
  }
1280
+ if (!this.check(TT.RBRACE) && !this.check(TT.EOF)) {
1281
+ throw new SinthError(`Unexpected token '${this.peek().value}' in children`, this.peek().loc);
1282
+ }
1241
1283
  }
1242
1284
  return children;
1243
1285
  }
@@ -10,12 +10,12 @@ export function generateHelpers(opts: {
10
10
 
11
11
  if (needsExpr || needsIf || needsFor) {
12
12
  helpers += `
13
- function sinthExpr(el) {
13
+ var sinthExpr = function(el) {
14
14
  try {
15
15
  let exprFn = __X[el.dataset.exprId];
16
16
  if (exprFn) el.textContent = exprFn({});
17
17
  } catch(e) {}
18
- }
18
+ };
19
19
  `;
20
20
  }
21
21
 
package/src/core/types.ts CHANGED
@@ -147,6 +147,8 @@ export interface CompileCtx {
147
147
  varDecls?: VarDeclaration[];
148
148
  actionButtons: { qid: string; delayMs: number; hide: boolean }[];
149
149
  loopVars?: Set<string>;
150
+ diffingEnabled?: boolean;
151
+ declaredVars?: Set<string>;
150
152
  }
151
153
 
152
154
  export class SinthError extends Error {