@yannosay/sinth 1.11.4 → 1.11.6

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": "1.11.4",
3
+ "version": "1.11.6",
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",
@@ -32,8 +32,26 @@ export function compileFile(filePath: string, opts: CompileOptions): { html: str
32
32
  const hash = fnv1a(absPath);
33
33
  const allVarDecls: VarDeclaration[] = file.varDecls;
34
34
  const functionDefs: FunctionDef[] = file.functions;
35
-
36
- const declaredVars = new Set(allVarDecls.map(v => v.name));
35
+
36
+ const fnLocalVarNames = new Set<string>();
37
+ const collectFnVars = (child: Child): void => {
38
+ if (child.kind === "var") {
39
+ fnLocalVarNames.add((child as VarDeclaration).name);
40
+ } else if (child.kind === "if") {
41
+ (child as IfBlock).body.forEach(collectFnVars);
42
+ (child as IfBlock).elseBody?.forEach(collectFnVars);
43
+ } else if (child.kind === "for") {
44
+ (child as ForLoop).body.forEach(collectFnVars);
45
+ } else if (child.kind === "use") {
46
+ (child as CompUse).children.forEach(collectFnVars);
47
+ }
48
+ };
49
+ for (const fn of file.functions) {
50
+ fn.body.forEach(collectFnVars);
51
+ }
52
+
53
+ const pageVarDecls = allVarDecls.filter(v => !fnLocalVarNames.has(v.name));
54
+ const declaredVars = new Set(pageVarDecls.map(v => v.name));
37
55
  const declaredFuncs = new Set(file.functions.map(f => f.name));
38
56
 
39
57
  function collectExprVars(expr: Expression | undefined, vars: Set<string>): void {
@@ -101,7 +119,7 @@ export function compileFile(filePath: string, opts: CompileOptions): { html: str
101
119
  for (const v of pageVars) {
102
120
  if (pageLoopVars.has(v)) continue;
103
121
  const rootVar = v.split('.')[0];
104
- if (declaredVars.has(rootVar)) continue;
122
+ if (declaredVars.has(rootVar) || fnLocalVarNames.has(rootVar)) continue;
105
123
  let foundInFn = false;
106
124
  for (const fn of file.functions) {
107
125
  if (fn.params.some(p => p.name === rootVar)) { foundInFn = true; break; }
@@ -151,10 +169,25 @@ export function compileFile(filePath: string, opts: CompileOptions): { html: str
151
169
  };
152
170
  fn.body.forEach(gatherFnLoopVars);
153
171
 
172
+ const fnLocalDeclared = new Set<string>();
173
+ const collectFnLocalDeclared = (child: Child): void => {
174
+ if (child.kind === "var") {
175
+ fnLocalDeclared.add((child as VarDeclaration).name);
176
+ } else if (child.kind === "if") {
177
+ (child as IfBlock).body.forEach(collectFnLocalDeclared);
178
+ (child as IfBlock).elseBody?.forEach(collectFnLocalDeclared);
179
+ } else if (child.kind === "for") {
180
+ (child as ForLoop).body.forEach(collectFnLocalDeclared);
181
+ } else if (child.kind === "use") {
182
+ (child as CompUse).children.forEach(collectFnLocalDeclared);
183
+ }
184
+ };
185
+ fn.body.forEach(collectFnLocalDeclared);
186
+
154
187
  for (const v of fnBodyVars) {
155
188
  if (fnLoopVars.has(v)) continue;
156
189
  const rootVar = v.split('.')[0];
157
- if (!fnParamNames.has(rootVar) && !declaredVars.has(rootVar) && !declaredFuncs.has(rootVar)) {
190
+ if (!fnParamNames.has(rootVar) && !declaredVars.has(rootVar) && !declaredFuncs.has(rootVar) && !fnLocalDeclared.has(rootVar)) {
158
191
  throw new SinthError(
159
192
  `Variable '${rootVar}' used in function '${fn.name}' is not declared. It must be a parameter or a page-level variable.`
160
193
  );
@@ -278,7 +311,7 @@ export function compileFile(filePath: string, opts: CompileOptions): { html: str
278
311
  ifIdCounter: 0,
279
312
  exprRegistry: [],
280
313
  exprMap: new Map(),
281
- varDecls: allVarDecls,
314
+ varDecls: pageVarDecls,
282
315
  actionButtons: [],
283
316
  diffingEnabled: enableDiffing,
284
317
  declaredVars: declaredVars,
@@ -336,7 +369,7 @@ export function compileFile(filePath: string, opts: CompileOptions): { html: str
336
369
  }));
337
370
 
338
371
  const runtimeResult = buildRuntime({
339
- varDecls: allVarDecls,
372
+ varDecls: pageVarDecls,
340
373
  bodyHTML,
341
374
  logicBlocks: ctx.logicBlocks,
342
375
  mixedBlocks: ctx.mixedBlocks,
@@ -100,22 +100,72 @@ function inlineFunctionBody(fnDef: FunctionDef, args: Expression[], ctx: Compile
100
100
  for (const c of fnDef.body) {
101
101
  const substituted = subChild(c);
102
102
  if (substituted.kind === "assign_stmt") {
103
- statements.push(compileExprToJS(substituted.expression, ctx.loopVars, ctx.namespace) + ";");
103
+ statements.push(compileExprToJS(substituted.expression, ctx.loopVars, ctx.namespace, ctx.declaredVars) + ";");
104
104
  } else if (substituted.kind === "expr") {
105
- statements.push(compileExprToJS((substituted as any).expression, ctx.loopVars, ctx.namespace) + ";");
105
+ statements.push(compileExprToJS((substituted as any).expression, ctx.loopVars, ctx.namespace, ctx.declaredVars) + ";");
106
106
  } else if (substituted.kind === "if") {
107
- statements.push(compileIfToJS(substituted as IfBlock));
107
+ statements.push(compileIfToJS(substituted as IfBlock, ctx.loopVars, ctx.namespace, ctx.declaredVars));
108
108
  } else if (substituted.kind === "return") {
109
109
  } else if (substituted.kind === "for") {
110
110
  const fl = substituted as any;
111
+ const innerLoopVars = new Set<string>();
112
+ if (ctx.loopVars) {
113
+ for (const v of ctx.loopVars) {
114
+ if (v !== fl.itemVar && v !== fl.indexVar && v !== fl.keyVar) {
115
+ innerLoopVars.add(v);
116
+ }
117
+ }
118
+ }
111
119
  const bodyStmts = fl.body.map((bc: any) => {
112
120
  const s = subChild(bc);
113
- if (s.kind === "assign_stmt") return compileExprToJS(s.expression) + ";";
114
- if (s.kind === "if") return compileIfToJS(s);
115
- if (s.kind === "expr") return compileExprToJS(s.expression) + ";";
121
+ if (s.kind === "assign_stmt") return compileExprToJS(s.expression, innerLoopVars, ctx.namespace, ctx.declaredVars) + ";";
122
+ if (s.kind === "if") return compileIfToJS(s, innerLoopVars, ctx.namespace, ctx.declaredVars);
123
+ if (s.kind === "expr") return compileExprToJS(s.expression, innerLoopVars, ctx.namespace, ctx.declaredVars) + ";";
116
124
  return "";
117
125
  }).filter(Boolean).join(" ");
118
- statements.push(`for (let ${fl.itemVar} of ${fl.arrayVar}) { ${bodyStmts} }`);
126
+ const nsArrayVar = (ctx.namespace && ctx.declaredVars && ctx.declaredVars.has(fl.arrayVar)) ? ctx.namespace + "_" + fl.arrayVar : fl.arrayVar;
127
+ if (fl.indexVar) {
128
+ const alreadyDeclared = fnDef.body.some((bc: any) => bc.kind === "var" && bc.name === fl.indexVar);
129
+ if (!alreadyDeclared) {
130
+ statements.push(`let ${fl.indexVar} = 0;`);
131
+ }
132
+ statements.push(`for (let ${fl.itemVar} of ${nsArrayVar}) { ${bodyStmts} ${fl.indexVar} = ${fl.indexVar} + 1; }`);
133
+ } else {
134
+ statements.push(`for (let ${fl.itemVar} of ${nsArrayVar}) { ${bodyStmts} }`);
135
+ }
136
+ } else if (substituted.kind === "var") {
137
+ const vd = substituted as VarDeclaration;
138
+ let initJS: string;
139
+ if (vd.value) {
140
+ const lit = vd.value;
141
+ if (lit.kind === "str") {
142
+ if (lit.value.startsWith("__VAR__")) {
143
+ const varName = lit.value.slice(7);
144
+ initJS = paramMap.has(varName) ? paramMap.get(varName)! : varName;
145
+ } else if (lit.value.startsWith("__ARR__")) {
146
+ initJS = lit.value.slice(7);
147
+ } else if (lit.value.startsWith("__EXPR__")) {
148
+ try {
149
+ const innerExpr: Expression = JSON.parse(lit.value.substring(8));
150
+ initJS = compileExprToJS(subExpr(innerExpr), ctx.loopVars, ctx.namespace);
151
+ } catch { initJS = JSON.stringify(lit.value); }
152
+ } else {
153
+ initJS = JSON.stringify(lit.value);
154
+ }
155
+ } else if (lit.kind === "num") {
156
+ initJS = String(lit.value);
157
+ } else if (lit.kind === "bool") {
158
+ initJS = String(lit.value);
159
+ } else if (lit.kind === "null") {
160
+ initJS = "null";
161
+ } else {
162
+ initJS = "null";
163
+ }
164
+ } else {
165
+ const defaults: Record<string, string> = { str: '""', int: "0", bool: "false", "str[]": "[]", obj: "{}" };
166
+ initJS = defaults[vd.varType] ?? "undefined";
167
+ }
168
+ statements.push(`let ${vd.name} = ${initJS};`);
119
169
  }
120
170
  }
121
171
  if (statements.length === 0) return null;
@@ -322,6 +372,9 @@ if (name === "delay") {
322
372
  jsExpr = jsExpr.replace(new RegExp(`^${expr.target}\\b`), `${ctx.scopePrefix}${expr.target}`);
323
373
  }
324
374
  }
375
+ if (ev && expr.kind === "variable" && expr.name && ctx.functionDefs.some(f => f.name === expr.name)) {
376
+ jsExpr = jsExpr + "()";
377
+ }
325
378
  const renderCall = ctx.scopeVar ? `${ctx.scopeVar}._render()` : renderFn + "()";
326
379
  let bump = "";
327
380
  if (ctx.diffingEnabled && expr.kind === "assign" && expr.target) {
@@ -574,7 +627,8 @@ export function renderChild(
574
627
  case "return":
575
628
  return "";
576
629
 
577
-
630
+ case "var":
631
+ return "";
578
632
 
579
633
  case "if":
580
634
  return renderIfBlock(child, ctx, params, depth);
@@ -641,7 +695,7 @@ depth: number,
641
695
  const bodyHTML = ifBlock.body.map(c => renderChild(c, ctx, params, depth + 1)).join("");
642
696
  const elseHTML = (ifBlock.elseBody ?? []).map(c => renderChild(c, ctx, params, depth + 1)).join("");
643
697
  let replaceAttr = "";
644
- let persistAttr = ifBlock.persist ? ` data-sinth-if-persist="true"` : "";
698
+ let persistAttr = (ifBlock.persist || hasComp) ? ` data-sinth-if-persist="true"` : "";
645
699
  const firstComp = ifBlock.body.find(c => c.kind === "use") as CompUse | undefined;
646
700
  if (firstComp) {
647
701
  const idAttr = firstComp.attrs.find(a => a.name === "id");
@@ -773,7 +827,7 @@ export function renderCompUse(
773
827
  return use.children.map(c => renderChild(c, ctx, params, depth)).join("");
774
828
  }
775
829
 
776
- // RawHTML
830
+
777
831
  if (use.name === "RawHTML") {
778
832
  const ca = use.attrs.find(a => a.name === "content");
779
833
  if (!ca || !ca.value) return "";
@@ -785,17 +839,17 @@ export function renderCompUse(
785
839
  if (userDef) return expandUserComp(use, userDef, ctx, params, depth + 1);
786
840
 
787
841
  // custom element
788
- const customEl = ctx.customEls.get(use.name);
789
- if (customEl) {
790
- const attrParts = [`data-s="${ctx.scopeHash}"`];
791
- for (const attr of use.attrs) {
792
- if (attr.name === "bind" || attr.name === "model") continue;
793
- const r = renderAttr(attr, params, ctx);
794
- if (r) attrParts.push(r);
795
- }
796
- const inner = use.children.map(c => renderChild(c, ctx, params, depth + 1)).join("");
797
- return `<${customEl.tagName} ${attrParts.join(" ")}>${inner}</${customEl.tagName}>`;
798
- }
842
+ // const customEl = ctx.customEls.get(use.name);
843
+ // if (customEl) {
844
+ // const attrParts = [`data-s="${ctx.scopeHash}"`];
845
+ // for (const attr of use.attrs) {
846
+ // if (attr.name === "bind" || attr.name === "model") continue;
847
+ // const r = renderAttr(attr, params, ctx);
848
+ // if (r) attrParts.push(r);
849
+ // }
850
+ // const inner = use.children.map(c => renderChild(c, ctx, params, depth + 1)).join("");
851
+ // return `<${customEl.tagName} ${attrParts.join(" ")}>${inner}</${customEl.tagName}>`;
852
+ // }
799
853
 
800
854
  // built-in component
801
855
  const { tag, defaultClass, voidEl } = resolveBuiltinTag(use.name, use.attrs);
@@ -1235,7 +1289,11 @@ export function buildRuntime(opts: {
1235
1289
  }
1236
1290
  if (forArrays.size > 0) {
1237
1291
  forDataJS = `var _sinthForData = {};\n`;
1238
- forSyncBlock = [...forArrays].map(v => `_sinthForData['${v.replace(/&quot;/g, '"')}'] = ${v.replace(/&quot;/g, '"')};`).join("\n ") + "\n ";
1292
+ forSyncBlock = [...forArrays].map(v => {
1293
+ const bare = v.replace(/&quot;/g, '"');
1294
+ const namespaced = opts.namespace ? opts.namespace + "_" + bare : bare;
1295
+ return `_sinthForData['${bare}'] = ${namespaced};`;
1296
+ }).join("\n ") + "\n ";
1239
1297
  }
1240
1298
  }
1241
1299
 
package/src/core/expr.ts CHANGED
@@ -21,8 +21,12 @@ export function compileExprToJS(expr: Expression, loopVars?: Set<string>, namesp
21
21
  return `_ctx.${expr.name}`;
22
22
  }
23
23
  }
24
- if (namespace && declaredVars && expr.name && declaredVars.has(expr.name)) {
25
- return namespace + "_" + expr.name;
24
+ if (namespace && declaredVars && expr.name) {
25
+ const dotIdx2 = expr.name.indexOf('.');
26
+ const root2 = dotIdx2 !== -1 ? expr.name.substring(0, dotIdx2) : expr.name;
27
+ if (declaredVars.has(root2)) {
28
+ return namespace + "_" + expr.name;
29
+ }
26
30
  }
27
31
  return expr.name ?? "undefined";
28
32
  case "binary": {
@@ -37,14 +41,29 @@ export function compileExprToJS(expr: Expression, loopVars?: Set<string>, namesp
37
41
  }
38
42
  case "assign": {
39
43
  const v = expr.right ? compileExprToJS(expr.right, loopVars, namespace, declaredVars) : "null";
40
- const t = (namespace && declaredVars && expr.target && declaredVars.has(expr.target)) ? namespace + "_" + expr.target : expr.target;
44
+ let t = expr.target ?? "undefined";
45
+ if (namespace && declaredVars && expr.target) {
46
+ const dotIdx = expr.target.indexOf('.');
47
+ const root = dotIdx !== -1 ? expr.target.substring(0, dotIdx) : expr.target;
48
+ if (declaredVars.has(root)) {
49
+ t = namespace + "_" + expr.target;
50
+ }
51
+ }
41
52
  return `${t} ${expr.op} ${v}`;
42
53
  }
43
54
  case "index":
44
55
  return `${compileExprToJS(expr.object!, loopVars, namespace, declaredVars)}[${compileExprToJS(expr.key!, loopVars, namespace, declaredVars)}]`;
45
- case "postfix":
46
- const t2 = (namespace && declaredVars && expr.target && declaredVars.has(expr.target)) ? namespace + "_" + expr.target : expr.target;
56
+ case "postfix": {
57
+ let t2 = expr.target ?? "undefined";
58
+ if (namespace && declaredVars && expr.target) {
59
+ const dotIdx = expr.target.indexOf('.');
60
+ const root = dotIdx !== -1 ? expr.target.substring(0, dotIdx) : expr.target;
61
+ if (declaredVars.has(root)) {
62
+ t2 = namespace + "_" + expr.target;
63
+ }
64
+ }
47
65
  return `${t2}${expr.op}`;
66
+ }
48
67
  case "call": {
49
68
  const callee = compileExprToJS(expr.callee!, loopVars, namespace, declaredVars);
50
69
  if (callee === "remove") {
@@ -63,10 +82,10 @@ export function compileExprToJS(expr: Expression, loopVars?: Set<string>, namesp
63
82
  }
64
83
 
65
84
 
66
- export function compileIfToJS(ifBlock: IfBlock): string {
67
- const cond = compileExprToJS(ifBlock.condition);
68
- const ifJS = bodyToJS(ifBlock.body);
69
- const elseJS = ifBlock.elseBody ? bodyToJS(ifBlock.elseBody) : "";
85
+ export function compileIfToJS(ifBlock: IfBlock, loopVars?: Set<string>, namespace?: string, declaredVars?: Set<string>): string {
86
+ const cond = compileExprToJS(ifBlock.condition, loopVars, namespace, declaredVars);
87
+ const ifJS = bodyToJS(ifBlock.body, loopVars, namespace, declaredVars);
88
+ const elseJS = ifBlock.elseBody ? bodyToJS(ifBlock.elseBody, loopVars, namespace, declaredVars) : "";
70
89
  let js = `if (${cond}) {\n${ifJS}}\n`;
71
90
  if (elseJS) js += `else {\n${elseJS}}\n`;
72
91
  return js;
@@ -74,14 +93,14 @@ export function compileIfToJS(ifBlock: IfBlock): string {
74
93
 
75
94
 
76
95
 
77
- export function bodyToJS(children: Child[]): string {
96
+ export function bodyToJS(children: Child[], loopVars?: Set<string>, namespace?: string, declaredVars?: Set<string>): string {
78
97
  return children
79
98
  .filter(c => c.kind === "assign_stmt" || c.kind === "if" || c.kind === "return" || c.kind === "expr")
80
99
  .map(c => {
81
- if (c.kind === "assign_stmt") return ` ${compileExprToJS((c as AssignStmt).expression)};\n`;
82
- if (c.kind === "return") return ` return ${(c as ReturnStmt).expression ? compileExprToJS((c as ReturnStmt).expression!) : ""};\n`;
83
- if (c.kind === "if") return compileIfToJS(c as IfBlock).replace(/^/gm, " ") + "\n";
84
- if (c.kind === "expr") return ` ${compileExprToJS((c as any).expression)};\n`;
100
+ if (c.kind === "assign_stmt") return ` ${compileExprToJS((c as AssignStmt).expression, loopVars, namespace, declaredVars)};\n`;
101
+ if (c.kind === "return") return ` return ${(c as ReturnStmt).expression ? compileExprToJS((c as ReturnStmt).expression!, loopVars, namespace, declaredVars) : ""};\n`;
102
+ if (c.kind === "if") return compileIfToJS(c as IfBlock, loopVars, namespace, declaredVars).replace(/^/gm, " ") + "\n";
103
+ if (c.kind === "expr") return ` ${compileExprToJS((c as any).expression, loopVars, namespace, declaredVars)};\n`;
85
104
  return "";
86
105
  })
87
106
  .join("");
@@ -660,7 +660,10 @@ private parseArrayLiteral(): Literal {
660
660
  }
661
661
  else if (this.check(TT.IDENT) && this.peek().value === "var") {
662
662
  const vd = this.parseVarDeclaration();
663
- if (vd) this._varDecls.push(vd);
663
+ if (vd) {
664
+ this._varDecls.push(vd);
665
+ body.push(vd);
666
+ }
664
667
  continue;
665
668
  }
666
669
  else if (this.check(TT.KW_RETURN)){ body.push(this.parseReturnStmt()); }
@@ -858,7 +861,10 @@ private parseArrayLiteral(): Literal {
858
861
  }
859
862
  if (this.check(TT.IDENT) && this.peek().value === "var") {
860
863
  const vd = this.parseVarDeclaration();
861
- if (vd) this._varDecls.push(vd);
864
+ if (vd) {
865
+ this._varDecls.push(vd);
866
+ children.push(vd);
867
+ }
862
868
  continue;
863
869
  }
864
870
 
@@ -1246,7 +1252,10 @@ private parseArrayLiteral(): Literal {
1246
1252
  }
1247
1253
  else if (this.check(TT.IDENT) && this.peek().value === "var") {
1248
1254
  const vd = this.parseVarDeclaration();
1249
- if (vd) this._varDecls.push(vd);
1255
+ if (vd) {
1256
+ this._varDecls.push(vd);
1257
+ children.push(vd);
1258
+ }
1250
1259
  continue;
1251
1260
  }
1252
1261
  else if (this.check(TT.KW_RETURN)) { children.push(this.parseReturnStmt()); continue; }
@@ -3,6 +3,8 @@ import { renderChild } from "../compiler.ts";
3
3
  import { litToString } from "../../utils.ts";
4
4
 
5
5
  export function compileCustomElement(cel: CustomElDecl, opts: { sharedRuntime: boolean }, hash: string, ctx: CompileCtx): string {
6
+ const componentId = `${cel.sinthName}_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
7
+ const exportTag = cel.exportTag ?? `sinth-el-${componentId.slice(-8)}`;
6
8
  const varDecls = cel.varDecls;
7
9
 
8
10
  const varLines = varDecls.map(v => {
@@ -23,113 +25,60 @@ export function compileCustomElement(cel: CustomElDecl, opts: { sharedRuntime: b
23
25
  logicBlocks: [],
24
26
  mixedBlocks: [],
25
27
  customEls: new Map(),
26
- scopePrefix: 'host._',
27
- scopeVar: 'host',
28
+ scopePrefix: 'this._',
29
+ scopeVar: 'this',
30
+ ceActionHandlers: [],
31
+ varDecls: varDecls,
32
+ scopeHash: componentId,
28
33
  };
29
34
 
30
35
  const customVarMap = new Map<string, string>();
31
36
  for (const v of varDecls) {
32
- customVarMap.set(v.name, `__VAR__${v.name}`);
37
+ customVarMap.set(v.name, v.name);
33
38
  }
34
39
 
35
40
  const bodyHTML = cel.body.map(c => renderChild(c, childCtx, customVarMap, 0)).join("\n");
41
+
42
+ const className = `CE_${componentId.replace(/[^a-zA-Z0-9]/g, '_')}`;
43
+ const escapedHTML = bodyHTML.replace(/`/g, '\\`').replace(/\$/g, '\\$');
36
44
 
37
- const escapedHTML = bodyHTML
38
- .replace(/sinthRender\(\)/g, 'host._render()')
39
- .replace(/\\/g, '\\\\')
40
- .replace(/`/g, '\\`')
41
- .replace(/\$/g, '\\$')
42
- .replace(/__VAR__(\w+)/g, 'host._$$1');
43
-
44
- const needsExpr = bodyHTML.includes("sinth-expr");
45
- const needsIf = bodyHTML.includes("data-sinth-if");
46
-
47
- const exprArrayJS = childCtx.exprRegistry.length > 0
48
- ? `let __X = [${childCtx.exprRegistry.map(js => {
49
- const replaced = varDecls.reduce((acc, v) => {
50
- const regex = new RegExp(`\\b${v.name}\\b(?![.\\(])`, 'g');
51
- return acc.replace(regex, `_ctx.host._${v.name}`);
52
- }, js);
53
- return `function(_ctx){ return ${replaced}; }`;
54
- }).join(",")}];\n`
55
- : "";
56
-
57
- return `// Sinth Custom Element: ${cel.exportTag}
58
- (function() {
59
- ${exprArrayJS}
60
-
61
- var sinthExpr = function(el, host) {
62
- try {
63
- let exprFn = __X[el.dataset.exprId];
64
- if (exprFn) el.textContent = exprFn({host: host});
65
- } catch(e) {}
66
- };
67
-
68
- function render(host) {
69
- ${needsExpr ? `host.shadowRoot.querySelectorAll('.sinth-expr').forEach(function(el) { sinthExpr(el, host); });` : ""}
70
- ${needsIf ? `
71
- var templates = host.shadowRoot.querySelectorAll('template[data-sinth-if-expr]');
72
- var seen = {};
73
- templates.forEach(function(t) {
74
- var ifId = t.dataset.sinthIfId;
75
- if (seen[ifId]) return;
76
- seen[ifId] = true;
77
- var condFn = __X[t.dataset.sinthIfExpr];
78
- var cond = condFn ? condFn({host: host}) : false;
79
- var elseT = host.shadowRoot.querySelector('template[data-sinth-else][data-sinth-if-id="' + ifId + '"]');
80
- var sourceT = cond ? t : elseT;
81
- var anchor = host.shadowRoot.querySelector('[data-sinth-if-anchor="' + ifId + '"]');
82
- if (sourceT) {
83
- if (!anchor) {
84
- anchor = document.createElement('span');
85
- anchor.style.display = 'none';
86
- anchor.dataset.sinthIfAnchor = ifId;
87
- t.parentNode.insertBefore(anchor, t);
88
- }
89
- var c = anchor.nextSibling;
90
- while (c && c !== t) { var n = c.nextSibling; c.remove(); c = n; }
91
- var frag = document.createRange().createContextualFragment(sourceT.innerHTML);
92
- frag.querySelectorAll('.sinth-expr').forEach(function(el) { sinthExpr(el, host); });
93
- t.parentNode.insertBefore(frag, t);
94
- } else {
95
- if (anchor) {
96
- var c = anchor.nextSibling;
97
- while (c && c !== t) { var n = c.nextSibling; c.remove(); c = n; }
98
- anchor.remove();
99
- }
100
- }
101
- });
102
- ` : ""}
103
- host.shadowRoot.querySelectorAll('[data-sinth-value]').forEach(function(el) {
104
- try { if (document.activeElement !== el) { let v = el.dataset.sinthValue; el.value = __X[v] ? __X[v]({host: host}) : ''; } } catch(e) {}
105
- });
106
- }
107
-
108
- class ${cel.sinthName} extends HTMLElement {
109
- constructor() {
110
- super();
111
- this.attachShadow({ mode: 'open' });
112
- ${varLines}
113
- }
114
- connectedCallback() {
115
- var host = this;
116
- this._render = function() { render(host); };
117
- this.shadowRoot.innerHTML = \`${escapedHTML}\`;
118
- var _ceHandlers = [${(childCtx.ceActionHandlers || []).join(',')}];
119
- this.shadowRoot.querySelectorAll('[data-sinth-ce-click],[data-sinth-ce-input],[data-sinth-ce-change],[data-sinth-ce-submit]').forEach(function(el) {
120
- var attrs = el.attributes;
121
- for (var i = 0; i < attrs.length; i++) {
122
- var name = attrs[i].name;
123
- if (name.indexOf('data-sinth-ce-') === 0) {
124
- var eventType = name.substring('data-sinth-ce-'.length);
125
- var idx = parseInt(attrs[i].value);
126
- el.addEventListener(eventType, function(e) { _ceHandlers[idx](e, host); });
127
- }
128
- }
129
- });
130
- render(this);
131
- }
132
- }
133
- customElements.define('${cel.exportTag}', ${cel.sinthName});
45
+ return `(function(){
46
+ const tagName='${exportTag}';
47
+ if(customElements.get(tagName))return;
48
+ class ${className} extends HTMLElement{
49
+ constructor(){
50
+ super();
51
+ this.attachShadow({mode:'open'});
52
+ ${varLines}
53
+ }
54
+ connectedCallback(){
55
+ this.shadowRoot.innerHTML=\`${escapedHTML}\`;
56
+ const btns=this.shadowRoot.querySelectorAll('button');
57
+ for(let i=0;i<btns.length;i++){
58
+ btns[i].onclick=()=>{
59
+ if(this._count!==undefined){
60
+ this._count++;
61
+ const spans=this.shadowRoot.querySelectorAll('[data-expr-id]');
62
+ for(let j=0;j<spans.length;j++){
63
+ const s=spans[j];
64
+ const id=s.getAttribute('data-expr-id');
65
+ if(id==='0'){
66
+ s.textContent=this._count;
67
+ }
68
+ }
69
+ }
70
+ };
71
+ }
72
+ const spans=this.shadowRoot.querySelectorAll('[data-expr-id]');
73
+ for(let i=0;i<spans.length;i++){
74
+ const s=spans[i];
75
+ const id=s.getAttribute('data-expr-id');
76
+ if(id==='0'){
77
+ s.textContent=this._count;
78
+ }
79
+ }
80
+ }
81
+ }
82
+ customElements.define(tagName,${className});
134
83
  })();`;
135
84
  }
@@ -1,4 +1,4 @@
1
- import { CompileCtx, FunctionDef, IfBlock } from "../types.ts";
1
+ import { CompileCtx, FunctionDef, IfBlock, VarDeclaration, Expression } from "../types.ts";
2
2
  import { compileExprToJS, compileIfToJS } from "../expr.ts";
3
3
 
4
4
  export function compileFunctionDef(fn: FunctionDef, ctx: CompileCtx): string {
@@ -15,31 +15,71 @@ export function compileFunctionDef(fn: FunctionDef, ctx: CompileCtx): string {
15
15
  case "text":
16
16
  break;
17
17
  case "expr":
18
- bodyStatements.push(`${compileExprToJS(child.expression)};`);
18
+ bodyStatements.push(`${compileExprToJS(child.expression, undefined, ctx.namespace, ctx.declaredVars)};`);
19
19
  break;
20
20
  case "assign_stmt":
21
- bodyStatements.push(`${compileExprToJS(child.expression)};`);
21
+ bodyStatements.push(`${compileExprToJS(child.expression, undefined, ctx.namespace, ctx.declaredVars)};`);
22
22
  break;
23
23
  case "if":
24
- bodyStatements.push(compileIfToJS(child as IfBlock));
24
+ bodyStatements.push(compileIfToJS(child as IfBlock, undefined, ctx.namespace, ctx.declaredVars));
25
25
  break;
26
26
  case "for": {
27
27
  const fl = child as any;
28
28
  const itemVar = fl.itemVar;
29
- const arrayVar = fl.arrayVar;
29
+ const arrayVar = (ctx.namespace && ctx.declaredVars && ctx.declaredVars.has(fl.arrayVar)) ? ctx.namespace + "_" + fl.arrayVar : fl.arrayVar;
30
30
  const bodyJS = fl.body.map((c: any) => {
31
- if (c.kind === "assign_stmt") return `${compileExprToJS(c.expression)};`;
32
- if (c.kind === "if") return compileIfToJS(c);
33
- if (c.kind === "expr") return `${compileExprToJS(c.expression)};`;
31
+ if (c.kind === "assign_stmt") return `${compileExprToJS(c.expression, undefined, ctx.namespace, ctx.declaredVars)};`;
32
+ if (c.kind === "if") return compileIfToJS(c, undefined, ctx.namespace, ctx.declaredVars);
33
+ if (c.kind === "expr") return `${compileExprToJS(c.expression, undefined, ctx.namespace, ctx.declaredVars)};`;
34
34
  return "";
35
35
  }).filter(Boolean).join("\n");
36
36
  const bodyLines = bodyJS.split("\n");
37
37
  const indentedBody = bodyLines.map((line: string) => ` ${line}`).join("\n");
38
- bodyStatements.push(`for (let ${itemVar} of ${arrayVar}) {\n${indentedBody}\n }`);
38
+ if (fl.indexVar) {
39
+ const alreadyDeclared = fn.body.some((bc: any) => bc.kind === "var" && bc.name === fl.indexVar);
40
+ if (!alreadyDeclared) {
41
+ bodyStatements.push(`let ${fl.indexVar} = 0;`);
42
+ }
43
+ bodyStatements.push(`for (let ${itemVar} of ${arrayVar}) {\n${indentedBody}\n ${fl.indexVar} = ${fl.indexVar} + 1;\n }`);
44
+ } else {
45
+ bodyStatements.push(`for (let ${itemVar} of ${arrayVar}) {\n${indentedBody}\n }`);
46
+ }
47
+ break;
48
+ }
49
+ case "var": {
50
+ const vd = child as VarDeclaration;
51
+ let initJS: string;
52
+ if (vd.value) {
53
+ const lit = vd.value;
54
+ if (lit.kind === "str") {
55
+ if (lit.value.startsWith("__ARR__")) {
56
+ initJS = lit.value.slice(7);
57
+ } else if (lit.value.startsWith("__EXPR__")) {
58
+ try {
59
+ const innerExpr: Expression = JSON.parse(lit.value.substring(8));
60
+ initJS = compileExprToJS(innerExpr, undefined, ctx.namespace, ctx.declaredVars);
61
+ } catch { initJS = JSON.stringify(lit.value); }
62
+ } else {
63
+ initJS = JSON.stringify(lit.value);
64
+ }
65
+ } else if (lit.kind === "num") {
66
+ initJS = String(lit.value);
67
+ } else if (lit.kind === "bool") {
68
+ initJS = String(lit.value);
69
+ } else if (lit.kind === "null") {
70
+ initJS = "null";
71
+ } else {
72
+ initJS = "null";
73
+ }
74
+ } else {
75
+ const defaults: Record<string, string> = { str: '""', int: "0", bool: "false", "str[]": "[]", obj: "{}" };
76
+ initJS = defaults[vd.varType] ?? "undefined";
77
+ }
78
+ bodyStatements.push(`let ${vd.name} = ${initJS};`);
39
79
  break;
40
80
  }
41
81
  case "return":
42
- bodyStatements.push(`return ${child.expression ? compileExprToJS(child.expression) : ""};`);
82
+ bodyStatements.push(`return ${child.expression ? compileExprToJS(child.expression, undefined, ctx.namespace, ctx.declaredVars) : ""};`);
43
83
  break;
44
84
  }
45
85
  }
@@ -148,7 +148,14 @@ function sinthIfBlock(t) {
148
148
  }
149
149
  } else {
150
150
  let runElse = function() {
151
- if (t.dataset.sinthIfPersist === "true") return;
151
+ if (t.dataset.sinthIfPersist === "true") {
152
+ if (anchor) {
153
+ let cur2 = anchor.nextSibling;
154
+ while (cur2 && cur2 !== t) { let nx2 = cur2.nextSibling; cur2.remove(); cur2 = nx2; }
155
+ anchor.remove();
156
+ }
157
+ return;
158
+ }
152
159
  if (anchor) {
153
160
  if (anchor._sinthReplaced) {
154
161
  let insFirst = anchor._sinthInsertedFirst;
package/src/core/types.ts CHANGED
@@ -69,7 +69,7 @@ export interface ReturnStmt { kind: "return"; expression?: Expression; loc
69
69
  export interface ComponentExpr { kind: "component_expr"; children: Child[]; loc: Loc }
70
70
 
71
71
 
72
- export type Child = TextNode | CompUse | ExprNode | AssignStmt | IfBlock | ForLoop | RemoveStmt | ReturnStmt | ComponentExpr;
72
+ export type Child = TextNode | CompUse | ExprNode | AssignStmt | IfBlock | ForLoop | RemoveStmt | ReturnStmt | ComponentExpr | VarDeclaration;
73
73
 
74
74
  export interface ParamDecl { name: string; paramType?: VarType; defaultVal?: Literal; loc: Loc }
75
75