@yannosay/sinth 0.14.1 → 0.14.3

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yannosay/sinth",
3
- "version": "0.14.1",
3
+ "version": "0.14.3",
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",
@@ -46,6 +46,71 @@ export const INLINE_STYLE_PROPS = new Set([
46
46
  "content","quotes",
47
47
  ]);
48
48
 
49
+ function inlineFunctionBody(fnDef: FunctionDef, args: Expression[], ctx: CompileCtx): string | null {
50
+ const paramMap = new Map<string, string>();
51
+ for (let i = 0; i < fnDef.params.length && i < args.length; i++) {
52
+ paramMap.set(fnDef.params[i].name, compileExprToJS(args[i]));
53
+ }
54
+ const subExpr = (expr: Expression): Expression => {
55
+ if (expr.kind === "variable" && expr.name && paramMap.has(expr.name)) {
56
+ return { kind: "variable", name: paramMap.get(expr.name)! };
57
+ }
58
+ if (expr.kind === "binary") {
59
+ return { ...expr, left: expr.left ? subExpr(expr.left) : undefined, right: expr.right ? subExpr(expr.right) : undefined };
60
+ }
61
+ if (expr.kind === "unary") {
62
+ return { ...expr, operand: expr.operand ? subExpr(expr.operand) : undefined };
63
+ }
64
+ if (expr.kind === "assign") {
65
+ if (expr.target && paramMap.has(expr.target)) {
66
+ return { ...expr, target: paramMap.get(expr.target)!, right: expr.right ? subExpr(expr.right) : undefined };
67
+ }
68
+ return { ...expr, right: expr.right ? subExpr(expr.right) : undefined };
69
+ }
70
+ if (expr.kind === "postfix" && expr.target && paramMap.has(expr.target)) {
71
+ return { ...expr, target: paramMap.get(expr.target)!, op: expr.op };
72
+ }
73
+ if (expr.kind === "index") {
74
+ return { ...expr, object: expr.object ? subExpr(expr.object) : undefined, key: expr.key ? subExpr(expr.key) : undefined };
75
+ }
76
+ if (expr.kind === "call") {
77
+ return { ...expr, callee: expr.callee ? subExpr(expr.callee) : undefined, args: expr.args?.map(a => subExpr(a)) };
78
+ }
79
+ return expr;
80
+ };
81
+ const subChild = (child: Child): Child => {
82
+ switch (child.kind) {
83
+ case "assign_stmt":
84
+ return { ...child, expression: subExpr(child.expression) as Expression };
85
+ case "if": {
86
+ const ib = child as IfBlock;
87
+ return {
88
+ ...ib,
89
+ condition: subExpr(ib.condition),
90
+ body: ib.body.map(subChild),
91
+ elseBody: ib.elseBody?.map(subChild),
92
+ };
93
+ }
94
+ case "return":
95
+ return { ...child, expression: child.expression ? subExpr(child.expression) : undefined };
96
+ default:
97
+ return child;
98
+ }
99
+ };
100
+ const statements: string[] = [];
101
+ for (const c of fnDef.body) {
102
+ const substituted = subChild(c);
103
+ if (substituted.kind === "assign_stmt") {
104
+ statements.push(compileExprToJS(substituted.expression) + ";");
105
+ } else if (substituted.kind === "if") {
106
+ statements.push(compileIfToJS(substituted as IfBlock));
107
+ } else if (substituted.kind === "return") {
108
+ }
109
+ }
110
+ if (statements.length === 0) return null;
111
+ return statements.join(" ");
112
+ }
113
+
49
114
  export function resolveBuiltinTag(
50
115
  name: string,
51
116
  attrs: Attr[],
@@ -177,6 +242,12 @@ if (name === "delay") {
177
242
 
178
243
  let raw = value.value;
179
244
 
245
+ if (raw.startsWith("__ACTION_JS__")) {
246
+ const js = raw.substring("__ACTION_JS__".length);
247
+ const ev = eventAttrName(name);
248
+ if (ev) return `${ev}="(function(){ ${js.replace(/"/g, "&quot;")}; sinthRender(); })()"`;
249
+ return `${name}="${escAttr(js)}"`;
250
+ }
180
251
  if (raw.startsWith("__MULTI_EXPR__")) {
181
252
  const exprJson = raw.substring("__MULTI_EXPR__".length);
182
253
  try {
@@ -191,8 +262,18 @@ if (name === "delay") {
191
262
  const exprJson = raw.substring("__EXPR__".length);
192
263
  try {
193
264
  const expr: Expression = JSON.parse(exprJson);
194
- const jsExpr = compileExprToJS(expr, ctx?.loopVars);
195
265
  const ev = eventAttrName(name);
266
+ if (ev && expr.kind === "call" && expr.callee?.kind === "variable") {
267
+ const fnName = expr.callee.name;
268
+ const fnDef = fnName ? ctx.functionDefs.find(f => f.name === fnName) : undefined;
269
+ if (fnDef) {
270
+ const inlinedJS = inlineFunctionBody(fnDef, expr.args ?? [], ctx);
271
+ if (inlinedJS) {
272
+ return `${ev}="(function(){ ${inlinedJS.replace(/"/g, "&quot;")}; sinthRender(); })()"`;
273
+ }
274
+ }
275
+ }
276
+ const jsExpr = compileExprToJS(expr, ctx?.loopVars);
196
277
  if (ev) return `${ev}="(function(){ ${jsExpr.replace(/"/g, "&quot;")}; sinthRender(); })()"`;
197
278
  return `${name}="${escAttr(jsExpr)}"`;
198
279
  } catch { }
@@ -342,6 +423,9 @@ export function renderChild(
342
423
  return { ...a, value: { kind: "str" as const, value: "__EXPR__" + JSON.stringify(substituted) } };
343
424
  } catch {}
344
425
  }
426
+ if (raw.startsWith("__ACTION_JS__")) {
427
+ return { ...a, value: { kind: "str" as const, value: raw } };
428
+ }
345
429
  if (raw.startsWith("__MULTI_EXPR__")) {
346
430
  try {
347
431
  const exprs: Expression[] = JSON.parse(raw.substring("__MULTI_EXPR__".length));
@@ -617,16 +701,59 @@ export function renderCompUse(
617
701
  if (classes) attrParts.push(`class="${escAttr(classes)}"`);
618
702
  if (inlineStyleParts.length > 0) attrParts.push(`style="${escAttr(inlineStyleParts.join("; "))}"`);
619
703
  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"`);
704
+
705
+ const delayAttrVal = use.attrs.find(a => a.name === "delay");
706
+ if (delayAttrVal) {
707
+ const delayMs = delayAttrVal.value?.kind === "num" ? delayAttrVal.value.value : 1000;
708
+ const eventNames = ["onClick", "onChange", "onInput", "onSubmit"];
709
+ let hasEvent = false;
710
+ for (const en of eventNames) {
711
+ const evName = en.toLowerCase();
712
+ const idx = attrParts.findIndex(p => p.startsWith(evName + "="));
713
+ if (idx >= 0) {
714
+ hasEvent = true;
715
+ const current = attrParts[idx];
716
+ const match = current.match(/\(function\(\)\{\s*(.+?);\s*sinthRender\(\)/);
717
+ if (match) {
718
+ const action = match[1];
719
+ const qid = `__sq${ctx.ifIdCounter++}`;
720
+ const hideAttr = use.attrs.find(a => a.name === "hide");
721
+ const hideVal = hideAttr
722
+ ? (hideAttr.value === null
723
+ ? true
724
+ : (hideAttr.value.kind === "bool"
725
+ ? hideAttr.value.value
726
+ : (hideAttr.value.kind === "str" && hideAttr.value.value !== "false")))
727
+ : true;
728
+ ctx.actionButtons.push({ qid, delayMs, hide: hideVal });
729
+ const delayIdx = attrParts.findIndex(p => p.startsWith("data-sinth-delay"));
730
+ if (delayIdx >= 0) attrParts.splice(delayIdx, 1);
731
+ const hideIdx = attrParts.findIndex(p => p.startsWith("data-sinth-delay-hide"));
732
+ if (hideIdx >= 0) attrParts.splice(hideIdx, 1);
733
+ const doneIdx = attrParts.findIndex(p => p.startsWith("data-sinth-delay-done"));
734
+ if (doneIdx >= 0) attrParts.splice(doneIdx, 1);
735
+ attrParts.push(`data-sinth-queue-id="${qid}"`);
736
+ if (hideVal) {
737
+ attrParts.push(`style="display:none"`);
738
+ }
739
+ attrParts[idx] = `${evName}="${escAttr(`(function(e){ var el=document.querySelector('[data-sinth-queue-id=${qid}]'); if(!el)return; var hide=${hideVal}; if(hide)el.style.display='none'; var q=window._sinthQ=q||{}; var sq=q.${qid}=q.${qid}||[]; sq.push(function(){ if(hide)el.style.display=''; ${action}; sinthRender(); }); if(sq.length===1){ (function p(first){ if(!sq||sq.length===0){delete q.${qid};return;} var a=sq[0]; sq.shift(); var d=first?${delayMs}:0; setTimeout(function(){ a(); if(sq.length>0)setTimeout(function(){p(false)},${delayMs}); },d); })(true); } })()`)}"`;
740
+ }
741
+ }
742
+ }
743
+ if (!hasEvent) {
744
+ if (use.attrs.some(a => a.name === "hide")) {
745
+ const hideAttr = use.attrs.find(a => a.name === "hide")!;
746
+ const hideVal = hideAttr.value;
747
+ const isHidden = (hideVal === null) ||
748
+ (hideVal?.kind === "bool" && hideVal.value) ||
749
+ (hideVal?.kind === "str" && hideVal.value !== "false");
750
+ attrParts.push(`data-sinth-delay-hide="${isHidden ? "true" : "false"}"`);
751
+ if (!isHidden) {
752
+ attrParts.push(`data-sinth-delay-done="1"`);
753
+ }
754
+ } else {
755
+ attrParts.push(`data-sinth-delay-hide="true"`);
756
+ }
630
757
  }
631
758
  }
632
759
  if (use.name === "Input") {
@@ -974,7 +1101,7 @@ export function compileFile(filePath: string, opts: CompileOptions): { html: str
974
1101
  if (child.kind === "use") {
975
1102
  (child as CompUse).attrs.forEach(a => {
976
1103
  if (a.value?.kind === "str") {
977
- const v = a.value.value;
1104
+ const v = a.value.value;
978
1105
  if (v.startsWith("__EXPR__") || v.startsWith("__MULTI_EXPR__")) {
979
1106
  try {
980
1107
  const exprs: Expression[] = v.startsWith("__MULTI_EXPR__")
@@ -1021,6 +1148,7 @@ export function compileFile(filePath: string, opts: CompileOptions): { html: str
1021
1148
  exprRegistry: [],
1022
1149
  exprMap: new Map(),
1023
1150
  varDecls: allVarDecls,
1151
+ actionButtons: [],
1024
1152
  };
1025
1153
 
1026
1154
  if (!file.isPage) {
@@ -1113,12 +1241,22 @@ const sharedRuntimeTag = (() => {
1113
1241
  return `<script src="${runtimeSrc}"></script>`;
1114
1242
  })();
1115
1243
 
1244
+ let actionInitScript = '';
1245
+ if (ctx.actionButtons.length > 0) {
1246
+ actionInitScript = '<script>' +
1247
+ ctx.actionButtons.map(b =>
1248
+ `setTimeout(function(){ var el=document.querySelector('[data-sinth-queue-id="${b.qid}"]'); if(el)el.style.display=''; },${b.delayMs});`
1249
+ ).join('') +
1250
+ '</script>';
1251
+ }
1252
+
1116
1253
  const html = [
1117
1254
  "<!DOCTYPE html>",
1118
1255
  `<html lang="${escAttr(headData.lang)}">`,
1119
1256
  head,
1120
1257
  `<body data-s="${hash}">`,
1121
1258
  bodyHTML,
1259
+ actionInitScript,
1122
1260
  sharedRuntimeTag,
1123
1261
  runtimeJS.trim() ? `<script>\n${runtimeJS}\n</script>` : "",
1124
1262
  scriptTags.join("\n"),
package/src/core/expr.ts CHANGED
@@ -39,6 +39,9 @@ export function compileExprToJS(expr: Expression, loopVars?: Set<string>): strin
39
39
  case "call": {
40
40
  const callee = compileExprToJS(expr.callee!, loopVars);
41
41
  const args = (expr.args ?? []).map(a => compileExprToJS(a, loopVars)).join(", ");
42
+ if (expr.args && expr.args.length === 0 && /\.length$/.test(callee)) {
43
+ return callee;
44
+ }
42
45
  return `${callee}(${args})`;
43
46
  }
44
47
  default:
@@ -256,9 +256,7 @@ private parseArrayLiteral(): Literal {
256
256
  return obj;
257
257
  }
258
258
 
259
- // expression parsing
260
-
261
- parseExpression(): Expression | null {
259
+ parseExpression(skipBinary: boolean = false): Expression | null {
262
260
  const tok = this.peek();
263
261
 
264
262
  // Unary 'not'
@@ -276,10 +274,10 @@ private parseArrayLiteral(): Literal {
276
274
  if (!inner) throw new SinthError("Expected expression after '('", this.peek().loc);
277
275
  if (!this.check(TT.RPAREN)) throw new SinthError("Expected closing ')'", this.peek().loc);
278
276
  this.consume(TT.RPAREN);
279
- return this.parseBinaryRHS(this.parseCallExpr(this.parsePostfix(inner)));
277
+ const result = this.parseCallExpr(this.parsePostfix(inner));
278
+ return skipBinary ? result : this.parseBinaryRHS(result);
280
279
  }
281
280
 
282
- // literal
283
281
  if (this.check(TT.STRING) || this.check(TT.NUMBER) || this.check(TT.BOOL_TRUE) ||
284
282
  this.check(TT.BOOL_FALSE) || this.check(TT.NULL_LIT)) {
285
283
  const lit = this.parseLiteral();
@@ -582,7 +580,7 @@ private parseArrayLiteral(): Literal {
582
580
  rhs = { kind: "variable", name: rhsName };
583
581
  }
584
582
  } else {
585
- rhs = this.parseExpression();
583
+ rhs = this.parseExpression(true);
586
584
  }
587
585
  if (!rhs) throw new SinthError("Expected expression after +", this.peek().loc);
588
586
  leftExpr = { kind: "binary", left: leftExpr, op: "+", right: rhs };
@@ -791,18 +789,33 @@ private parseArrayLiteral(): Literal {
791
789
  } else {
792
790
  const savedPos = this.pos;
793
791
  const expr = this.parseExpression();
794
- if (expr && (this.check(TT.COMMA) || this.check(TT.RPAREN) || this.check(TT.OP_SEMI))) {
795
- const exprs: Expression[] = [expr];
792
+ if (expr && (this.check(TT.COMMA) || this.check(TT.RPAREN) || this.check(TT.OP_SEMI) || this.check(TT.KW_IF))) {
793
+ const actions: (Expression | { kind: "if"; js: string })[] = [{ kind: "expr", expr } as any];
796
794
  while (this.check(TT.OP_SEMI)) {
797
795
  this.consume(TT.OP_SEMI);
798
- const next = this.parseExpression();
799
- if (next) exprs.push(next);
800
- else break;
796
+ if (this.check(TT.KW_IF)) {
797
+ const ifBlock = this.parseIfBlock();
798
+ actions.push({ kind: "if", js: compileIfToJS(ifBlock) });
799
+ } else {
800
+ const next = this.parseExpression();
801
+ if (next) actions.push({ kind: "expr", expr: next } as any);
802
+ else break;
803
+ }
801
804
  }
802
- if (exprs.length === 1) {
803
- value = { kind: "str", value: "__EXPR__" + JSON.stringify(exprs[0]) };
805
+ const hasIf = actions.some(a => a.kind === "if");
806
+ if (actions.length === 1 && !hasIf) {
807
+ const single = (actions[0] as any).expr as Expression;
808
+ value = { kind: "str", value: "__EXPR__" + JSON.stringify(single) };
804
809
  } else {
805
- value = { kind: "str", value: "__MULTI_EXPR__" + JSON.stringify(exprs) };
810
+ const partsJS: string[] = [];
811
+ for (const a of actions) {
812
+ if (a.kind === "if") {
813
+ partsJS.push((a as any).js as string);
814
+ } else {
815
+ partsJS.push(compileExprToJS((a as any).expr as Expression) + ";");
816
+ }
817
+ }
818
+ value = { kind: "str", value: "__ACTION_JS__" + partsJS.join(" ") };
806
819
  }
807
820
  } else {
808
821
  this.pos = savedPos;
@@ -864,7 +877,7 @@ private parseArrayLiteral(): Literal {
864
877
  if (this.check(TT.LPAREN)) {
865
878
  const loc = this.peek().loc;
866
879
  this.consume(TT.LPAREN);
867
- let expr = this.parseExpression();
880
+ let expr = this.parseExpression(true);
868
881
  if (!expr) throw new SinthError("Expected expression after '('", this.peek().loc);
869
882
  if (!this.check(TT.RPAREN)) throw new SinthError("Expected ')'", this.peek().loc);
870
883
  this.consume(TT.RPAREN);
@@ -885,7 +898,7 @@ private parseArrayLiteral(): Literal {
885
898
  rhs = { kind: "variable", name: rhsName };
886
899
  }
887
900
  } else {
888
- rhs = this.parseExpression();
901
+ rhs = this.parseExpression(true);
889
902
  }
890
903
  if (!rhs) throw new SinthError("Expected expression after +", this.peek().loc);
891
904
  expr = { kind: "binary", left: expr, op: "+", right: rhs };
@@ -913,7 +926,7 @@ private parseArrayLiteral(): Literal {
913
926
  rhs = { kind: "variable", name: rhsName };
914
927
  }
915
928
  } else {
916
- rhs = this.parseExpression();
929
+ rhs = this.parseExpression(true);
917
930
  }
918
931
  if (!rhs) throw new SinthError("Expected expression after +", this.peek().loc);
919
932
  leftExpr = { kind: "binary", left: leftExpr, op: "+", right: rhs };
@@ -970,7 +983,7 @@ private parseArrayLiteral(): Literal {
970
983
  rhs = { kind: "variable", name: rhsName };
971
984
  }
972
985
  } else {
973
- rhs = this.parseExpression();
986
+ rhs = this.parseExpression(true);
974
987
  }
975
988
  if (!rhs) throw new SinthError("Expected expression after +", this.peek().loc);
976
989
  leftExpr = { kind: "binary", left: leftExpr, op: "+", right: rhs };
@@ -1003,7 +1016,7 @@ private parseArrayLiteral(): Literal {
1003
1016
  rhs = { kind: "variable", name: rhsName };
1004
1017
  }
1005
1018
  } else {
1006
- rhs = this.parseExpression();
1019
+ rhs = this.parseExpression(true);
1007
1020
  }
1008
1021
  if (!rhs) throw new SinthError("Expected expression after +", this.peek().loc);
1009
1022
  leftExpr = { kind: "binary", left: leftExpr, op: "+", right: rhs };
@@ -1035,7 +1048,7 @@ private parseArrayLiteral(): Literal {
1035
1048
  rhs = { kind: "variable", name: rhsName };
1036
1049
  }
1037
1050
  } else {
1038
- rhs = this.parseExpression();
1051
+ rhs = this.parseExpression(true);
1039
1052
  }
1040
1053
  if (!rhs) throw new SinthError("Expected expression after +", this.peek().loc);
1041
1054
  leftExpr = { kind: "binary", left: leftExpr, op: "+", right: rhs };
package/src/core/types.ts CHANGED
@@ -144,6 +144,7 @@ export interface CompileCtx {
144
144
  exprRegistry: string[];
145
145
  exprMap: Map<string, number>;
146
146
  varDecls?: VarDeclaration[];
147
+ actionButtons: { qid: string; delayMs: number; hide: boolean }[];
147
148
  loopVars?: Set<string>;
148
149
  }
149
150
 
package/src/utils.ts CHANGED
@@ -25,7 +25,7 @@ export function esc(s: string): string {
25
25
  }
26
26
 
27
27
  export function escAttr(s: string): string {
28
- return esc(s).replace(/"/g, "&quot;");
28
+ return s.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
29
29
  }
30
30
 
31
31
  export function litToString(lit: Literal): string {