@yannosay/sinth 0.13.7 → 0.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -153,7 +153,7 @@ if done == true {
153
153
  remove "myElement"
154
154
  }
155
155
  ```
156
- Delete elements for good. No virtual DOM diffing.
156
+ Delete elements. No virtual DOM diffing!
157
157
 
158
158
  Compiles to pure HTML.
159
159
 
@@ -176,6 +176,7 @@ Main {
176
176
  ```
177
177
 
178
178
 
179
+
179
180
  ```ts
180
181
  page
181
182
  title = "Counter Demo"
@@ -199,7 +200,27 @@ Main {
199
200
  Input(bind: stepSize, step: 1)
200
201
  }
201
202
  ```
203
+ ##### NEW! (0.14.0):
204
+ Sinth now supports Reactivity in Functions!
205
+ ```ts
206
+ page
207
+ title = "Reactive Counter"
202
208
 
209
+ var int apples = 1
210
+ var int bananas = 2
211
+ var int oranges = -6
212
+
213
+ function Counter(int value) -> ui {
214
+ Heading(level: 1) {"Count is at: " + (value) + "!"}
215
+ Button(onClick: value = value + 1) {"Increment"}
216
+ }
217
+
218
+ Main {
219
+ (Counter(apples))
220
+ (Counter(bananas))
221
+ (Counter(oranges))
222
+ }
223
+ ```
203
224
 
204
225
 
205
226
  # Install
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yannosay/sinth",
3
- "version": "0.13.7",
3
+ "version": "0.14.1",
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",
@@ -73,7 +73,7 @@ export function registerExpr(ctx: CompileCtx, expr: Expression): number {
73
73
  }
74
74
 
75
75
 
76
- export function renderAttr(attr: Attr, paramMap: Map<string, string>, ctx?: CompileCtx): string {
76
+ export function renderAttr(attr: Attr, paramMap: Map<string, string>, ctx: CompileCtx): string {
77
77
  const { name, value } = attr;
78
78
  if (value === null) return name;
79
79
  if (value.kind === "null") return "";
@@ -287,19 +287,35 @@ export function renderChild(
287
287
  localParams.set(fnDef.params[i].name, "__LIT__" + arg.value.value);
288
288
  } else if (arg.kind === "variable" && arg.name) {
289
289
  localParams.set(fnDef.params[i].name, "__VAR__" + arg.name);
290
+ } else {
291
+ const exprId = registerExpr(ctx, arg);
292
+ localParams.set(fnDef.params[i].name, "__EXPRID__" + exprId);
290
293
  }
291
294
  }
292
295
  const substituteExpr = (expr: Expression, pm: Map<string, string>): Expression => {
293
296
  if (expr.kind === "variable" && pm.has(expr.name!)) {
294
297
  const pv = pm.get(expr.name!)!;
295
298
  if (pv.startsWith("__LIT__")) return { kind: "literal", value: { kind: "str", value: pv.slice(7) } };
299
+ if (pv.startsWith("__EXPRID__")) {
300
+ const id = parseInt(pv.slice(10), 10);
301
+ return { kind: "expr_ref", exprId: id };
302
+ }
296
303
  return { kind: "variable", name: pv.slice(7) };
297
304
  }
298
305
  if (expr.kind === "binary") return { ...expr, left: substituteExpr(expr.left!, pm), right: substituteExpr(expr.right!, pm) };
299
306
  if (expr.kind === "unary") return { ...expr, operand: substituteExpr(expr.operand!, pm) };
300
307
  if (expr.kind === "call") return { ...expr, callee: substituteExpr(expr.callee!, pm), args: expr.args?.map(a => substituteExpr(a, pm)) };
301
308
  if (expr.kind === "index") return { ...expr, object: substituteExpr(expr.object!, pm), key: substituteExpr(expr.key!, pm) };
302
- if (expr.kind === "assign") return { ...expr, right: expr.right ? substituteExpr(expr.right, pm) : undefined };
309
+ if (expr.kind === "assign") {
310
+ const target = expr.target;
311
+ if (target && pm.has(target)) {
312
+ const pv = pm.get(target)!;
313
+ if (pv.startsWith("__VAR__")) {
314
+ return { ...expr, target: pv.slice(7), right: expr.right ? substituteExpr(expr.right, pm) : undefined };
315
+ }
316
+ }
317
+ return { ...expr, right: expr.right ? substituteExpr(expr.right, pm) : undefined };
318
+ }
303
319
  return expr;
304
320
  };
305
321
  const substituteChild = (c: Child, pm: Map<string, string>): Child => {
@@ -319,6 +335,20 @@ export function renderChild(
319
335
  const sa: Attr[] = u.attrs.map(a => {
320
336
  if (a.value?.kind === "str") {
321
337
  let raw = a.value.value;
338
+ if (raw.startsWith("__EXPR__")) {
339
+ try {
340
+ const expr: Expression = JSON.parse(raw.substring(8));
341
+ const substituted = substituteExpr(expr, pm);
342
+ return { ...a, value: { kind: "str" as const, value: "__EXPR__" + JSON.stringify(substituted) } };
343
+ } catch {}
344
+ }
345
+ if (raw.startsWith("__MULTI_EXPR__")) {
346
+ try {
347
+ const exprs: Expression[] = JSON.parse(raw.substring("__MULTI_EXPR__".length));
348
+ const substituted = exprs.map(e => substituteExpr(e, pm));
349
+ return { ...a, value: { kind: "str" as const, value: "__MULTI_EXPR__" + JSON.stringify(substituted) } };
350
+ } catch {}
351
+ }
322
352
  for (const [pn, pv] of pm) {
323
353
  if (pv.startsWith("__LIT__")) raw = raw.replace(new RegExp(`\\b${pn}\\b`, 'g'), pv.slice(7));
324
354
  if (pv.startsWith("__VAR__")) raw = raw.replace(new RegExp(`\\b${pn}\\b`, 'g'), pv.slice(7));
@@ -334,6 +364,9 @@ export function renderChild(
334
364
  return fnDef.body.map(c => renderChild(substituteChild(c, localParams), ctx, localParams, depth + 1)).join("");
335
365
  }
336
366
  }
367
+ if (child.expression.kind === "expr_ref" && child.expression.exprId !== undefined) {
368
+ return `<span class="sinth-expr" data-expr-id="${child.expression.exprId}"></span>`;
369
+ }
337
370
  if (child.expression.kind === "literal" && child.expression.value) {
338
371
  return esc(litToString(child.expression.value));
339
372
  }
@@ -584,6 +617,18 @@ export function renderCompUse(
584
617
  if (classes) attrParts.push(`class="${escAttr(classes)}"`);
585
618
  if (inlineStyleParts.length > 0) attrParts.push(`style="${escAttr(inlineStyleParts.join("; "))}"`);
586
619
  if (tag === "button" && !use.attrs.some(a => a.name === "type")) attrParts.push(`type="button"`);
620
+ if (use.attrs.some(a => a.name === "delay") && use.attrs.some(a => a.name === "hide")) {
621
+ const hideAttr = use.attrs.find(a => a.name === "hide")!;
622
+ const hideVal = hideAttr.value;
623
+ const isHidden = (hideVal === null) ||
624
+ (hideVal?.kind === "bool" && hideVal.value) ||
625
+ (hideVal?.kind === "str" && hideVal.value !== "false");
626
+ attrParts.push(`data-sinth-delay-hide="${isHidden ? "true" : "false"}"`);
627
+ if (!isHidden) {
628
+ // hide: false → show initial content immediately, delay only on updates
629
+ attrParts.push(`data-sinth-delay-done="1"`);
630
+ }
631
+ }
587
632
  if (use.name === "Input") {
588
633
  const bindAttr = use.attrs.find(a => a.name === "bind");
589
634
  const modelAttr = use.attrs.find(a => a.name === "model");
@@ -880,7 +925,6 @@ ${exprArrayJS}
880
925
  ${renderFunc}`;
881
926
  }
882
927
 
883
- // main compilation pipeline
884
928
 
885
929
  export interface CompileOptions {
886
930
  projectRoot: string;
@@ -894,14 +938,77 @@ export interface CompileOptions {
894
938
  export function compileFile(filePath: string, opts: CompileOptions): { html: string; shared?: string } | null {
895
939
  const absPath = path.resolve(filePath);
896
940
  const file = parseFile(absPath);
897
-
898
941
  const cfg: ResolverConfig = { projectRoot: opts.projectRoot, libraryPaths: opts.libraryPaths };
899
942
  const { allDefs, customEls, cssLinks, jsLinks } = resolveImports(file, cfg);
900
943
  const hash = fnv1a(absPath);
901
-
902
944
  const allVarDecls: VarDeclaration[] = file.varDecls;
903
945
  const functionDefs: FunctionDef[] = file.functions;
946
+
947
+ const declaredVars = new Set(allVarDecls.map(v => v.name));
948
+ const declaredFuncs = new Set(file.functions.map(f => f.name));
949
+
950
+ function collectExprVars(expr: Expression | undefined, vars: Set<string>): void {
951
+ if (!expr) return;
952
+ if (expr.kind === "variable" && expr.name && !declaredFuncs.has(expr.name)) vars.add(expr.name);
953
+ if (expr.kind === "assign" && expr.target) vars.add(expr.target);
954
+ if (expr.left) collectExprVars(expr.left, vars);
955
+ if (expr.right) collectExprVars(expr.right, vars);
956
+ if (expr.operand) collectExprVars(expr.operand, vars);
957
+ if (expr.object) collectExprVars(expr.object, vars);
958
+ if (expr.key) collectExprVars(expr.key, vars);
959
+ if (expr.args) expr.args.forEach(a => collectExprVars(a, vars));
960
+ }
904
961
 
962
+ function collectChildVars(child: Child, vars: Set<string>): void {
963
+ if (child.kind === "expr" || child.kind === "assign_stmt" || child.kind === "return") {
964
+ collectExprVars(child.expression, vars);
965
+ }
966
+ if (child.kind === "if") {
967
+ collectExprVars((child as IfBlock).condition, vars);
968
+ (child as IfBlock).body.forEach(c => collectChildVars(c, vars));
969
+ (child as IfBlock).elseBody?.forEach(c => collectChildVars(c, vars));
970
+ }
971
+ if (child.kind === "for") {
972
+ (child as ForLoop).body.forEach(c => collectChildVars(c, vars));
973
+ }
974
+ if (child.kind === "use") {
975
+ (child as CompUse).attrs.forEach(a => {
976
+ if (a.value?.kind === "str") {
977
+ const v = a.value.value;
978
+ if (v.startsWith("__EXPR__") || v.startsWith("__MULTI_EXPR__")) {
979
+ try {
980
+ const exprs: Expression[] = v.startsWith("__MULTI_EXPR__")
981
+ ? JSON.parse(v.substring("__MULTI_EXPR__".length))
982
+ : [JSON.parse(v.substring(8))];
983
+ exprs.forEach(e => collectExprVars(e, vars));
984
+ } catch {}
985
+ }
986
+ }
987
+ });
988
+ (child as CompUse).children.forEach(c => collectChildVars(c, vars));
989
+ }
990
+ }
991
+ const pageVars = new Set<string>();
992
+ file.uses.forEach(u => collectChildVars(u, pageVars));
993
+ for (const v of pageVars) {
994
+ if (!declaredVars.has(v)) {
995
+ throw new SinthError(
996
+ `Variable '${v}' is used but never declared. Add 'var str ${v}' or 'var int ${v}' before using it.`
997
+ );
998
+ }
999
+ }
1000
+ for (const fn of file.functions) {
1001
+ const fnParamNames = new Set(fn.params.map(p => p.name));
1002
+ const fnBodyVars = new Set<string>();
1003
+ fn.body.forEach(c => collectChildVars(c, fnBodyVars));
1004
+ for (const v of fnBodyVars) {
1005
+ if (!fnParamNames.has(v) && !declaredVars.has(v) && !declaredFuncs.has(v)) {
1006
+ throw new SinthError(
1007
+ `Variable '${v}' used in function '${fn.name}' is not declared. It must be a parameter or a page-level variable.`
1008
+ );
1009
+ }
1010
+ }
1011
+ }
905
1012
  const ctx: CompileCtx = {
906
1013
  allDefs, functionDefs, customEls, cssLinks, jsLinks,
907
1014
  scopeHash: hash,
@@ -73,15 +73,19 @@ function sinthDelay(el) {
73
73
  if (el.dataset.sinthDelayDone) { return; }
74
74
  el.dataset.sinthDelayDone = '1';
75
75
  var ms = parseInt(el.dataset.sinthDelay) || 0;
76
- if (el.dataset.sinthDelayHide !== 'false') {
77
- el.style.display = 'none';
78
- }
76
+ var hideEl = el.dataset.sinthDelayHide !== 'false';
79
77
  var show = function() {
80
- el.style.display = '';
78
+ if (hideEl) el.style.display = '';
81
79
  el.querySelectorAll('.sinth-expr').forEach(sinthExpr);
82
80
  };
83
- if (ms > 0) setTimeout(show, ms);
84
- else show();
81
+ if (hideEl) {
82
+ el.style.display = 'none';
83
+ if (ms > 0) setTimeout(show, ms);
84
+ else show();
85
+ } else {
86
+ if (ms > 0) setTimeout(show, ms);
87
+ else show();
88
+ }
85
89
  }
86
90
  function sinthDelayExpr(el, _ctx) {
87
91
  _ctx = _ctx || {};
@@ -43,14 +43,13 @@ export function buildRenderBody(opts: {
43
43
  }
44
44
  }
45
45
 
46
+ if (needsIf) {
47
+ renderBody += ` document.querySelectorAll('template[data-sinth-if-expr]').forEach(sinthIfBlock);\n`;
48
+ }
46
49
  renderBody += ` document.querySelectorAll('[data-sinth-remove]').forEach(function(el) {
47
50
  var target = document.getElementById(el.dataset.sinthRemove);
48
51
  if (target) target.remove();
49
52
  });\n`;
50
-
51
- if (needsIf) {
52
- renderBody += ` document.querySelectorAll('template[data-sinth-if-expr]').forEach(sinthIfBlock);\n`;
53
- }
54
53
  if (needsFor) {
55
54
  renderBody += ` document.querySelectorAll('template[data-sinth-for]').forEach(sinthForBlock);\n`;
56
55
  }
@@ -71,8 +70,28 @@ export function buildRenderBody(opts: {
71
70
  } catch(e) {}
72
71
  });\n`;
73
72
  }
73
+ if (needsDelay) {
74
+ renderBody += ` document.querySelectorAll('[data-sinth-delay]').forEach(function(el) {
75
+ var newContent = '';
76
+ el.querySelectorAll('.sinth-expr').forEach(function(exprEl) {
77
+ var exprFn = __X[exprEl.dataset.exprId];
78
+ if (exprFn) newContent += exprFn({});
79
+ });
80
+ if (el._sinthLastContent === undefined) {
81
+ el._sinthLastContent = newContent;
82
+ } else if (el._sinthLastContent !== newContent) {
83
+ el._sinthLastContent = newContent;
84
+ delete el.dataset.sinthDelayDone;
85
+ }
86
+ });\n`;
87
+ }
74
88
  if (needsExpr) {
75
- renderBody += ` document.querySelectorAll('.sinth-expr').forEach(sinthExpr);\n`;
89
+ renderBody += ` document.querySelectorAll('.sinth-expr').forEach(function(el) {
90
+ var delayParent = el.closest('[data-sinth-delay]');
91
+ if (!delayParent || delayParent.dataset.sinthDelayDone) {
92
+ sinthExpr(el);
93
+ }
94
+ });\n`;
76
95
  }
77
96
  renderBody += ` document.querySelectorAll('[data-sinth-hide]').forEach(function(el) {
78
97
  var exprId = el.dataset.sinthHide;
package/src/core/types.ts CHANGED
@@ -41,7 +41,7 @@ export type AssignOp = "=" | "+=" | "-=";
41
41
  export type PostfixOp = "++" | "--";
42
42
 
43
43
  export interface Expression {
44
- kind: "literal" | "variable" | "unary" | "binary" | "assign" | "postfix" | "index" | "call";
44
+ kind: "literal" | "variable" | "unary" | "binary" | "assign" | "postfix" | "index" | "call" | "expr_ref";
45
45
  value?: Literal;
46
46
  name?: string;
47
47
  op?: UnaryOp | BinaryOp | AssignOp | PostfixOp;
@@ -53,6 +53,7 @@ export interface Expression {
53
53
  key?: Expression;
54
54
  callee?: Expression;
55
55
  args?: Expression[];
56
+ exprId?: number; // for "expr_ref" kind
56
57
  }
57
58
 
58
59
  export interface Attr { name: string; value: Literal | null; loc: Loc }
package/tsconfig.json CHANGED
@@ -5,11 +5,11 @@
5
5
  "lib": ["ES2020"],
6
6
  "outDir": "./dist",
7
7
  "rootDir": "./src",
8
- "strict": false,
8
+ "strict": true,
9
9
  "esModuleInterop": true,
10
10
  "skipLibCheck": true,
11
- "noImplicitAny": false,
12
- "strictNullChecks": false,
11
+ "noImplicitAny": true,
12
+ "strictNullChecks": true,
13
13
  "allowImportingTsExtensions": true,
14
14
  "noEmit": true,
15
15
  "types": ["node"],