@yannosay/sinth 1.3.0 → 1.5.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
@@ -2,6 +2,8 @@
2
2
 
3
3
  The language that makes HTML feel SO easy. Declarative. Reactive. Compiles to pure HTML.
4
4
 
5
+ **I need YOUR Help to improve Sinth, please consider joining the Discord so Sinth can be optimized more easy, currently I am doing this alone!**
6
+
5
7
  * Introduction: https://www.youtube.com/watch?v=W0tOMTiIF0Q
6
8
  * Discord: [Join here!](https://discord.gg/SUvcrafTQm)
7
9
  * Documentation: [sinth.yannosay.com/docs](https://sinth.yannosay.com/docs)
@@ -19,7 +21,7 @@ Input(bind: userName, placeholder: "Enter your name")
19
21
  Paragraph { "Hello, " + userName }
20
22
  ```
21
23
 
22
- No useState. No onChange. No e.target.value.
24
+ No useState, onChange or e.target.value!
23
25
 
24
26
  ```ts
25
27
  page
@@ -56,7 +58,42 @@ Button(onClick: "deletePost()") { "Delete" }
56
58
  }
57
59
  ```
58
60
 
59
- No JSX ternaries. No v-if. No separate script tags. Mixed logic. Clean.
61
+ No JSX ternaries or v-if. No separate script tags. Mixed logic there where you need it.
62
+
63
+ #### Sinth Language Syntax Reference
64
+
65
+ | Syntax | Description |
66
+ |-------------------------------------------------|------------------------------------------------|
67
+ | `--` or --[Hello]-- | Comment |
68
+ | `page` | Declares a full Sinth page |
69
+ | `title = "..."` | Sets the page title |
70
+ | `function myFunction` | Creates a reusable & reactive function |
71
+ | `var str myVar = ""` | Declares a string variable |
72
+ | `var int myVar` | Declares an integer variable |
73
+ | `var bool myVar` | Declares a boolean variable |
74
+ | `var str[] myVar` | Declares a string array |
75
+ | `var obj myVar` | Declares an object variable |
76
+ | `import "./file.sinth"` | Imports another Sinth file |
77
+ | `import css "./file.css"` | Imports a CSS file |
78
+ | `import js "./file.js"` | Imports a JS file |
79
+ | `Heading(level: 1) { "..." }` | Renders a heading (h1-h6) |
80
+ | `Paragraph { "..." }` | Renders a paragraph |
81
+ | `Button(onClick: fn) { "..." }` | Renders a clickable button |
82
+ | `Input(bind: myVar)` | Renders a bound input field |
83
+ | `Checkbox(checked: myBool)` | Renders a checkbox |
84
+ | `if condition { ... }` | Conditional rendering |
85
+ | `if condition { ... } else { ... }` | Conditional with else branch |
86
+ | `for item in array { ... }` | Loops over an array |
87
+ | `for item, index in array { ... }` | Loops with index |
88
+ | `delay: ms` | Delays rendering of an element |
89
+ | `hide: bool` | Conditionally hides an element |
90
+ | `style { ... }` | Defines scoped CSS styles |
91
+ | `script { ... }` | Defines page-level JavaScript |
92
+ | `component MyComp { ... }` | Defines a reusable component |
93
+ | `custom el "my-tag" { ... }` | Defines a custom element |
94
+ | `custom MyCounter(export: <awesome-counter />)` | Exports a custom element tag |
95
+
96
+
60
97
 
61
98
  #### Functions - easy as you know it
62
99
  ```ts
@@ -83,8 +120,6 @@ Div {
83
120
  renderHeading(userName)
84
121
  renderHeading("This renders!")
85
122
  ```
86
- or
87
-
88
123
  ```ts
89
124
  page
90
125
 
@@ -109,7 +144,56 @@ Paragraph {
109
144
  "Admin mode is " + getStatus() + "!"
110
145
  }
111
146
  ```
112
- #### NEW (0.13.5): Fullscreen activation + if-else inside Component
147
+ #### Code what you need
148
+ ```ts
149
+ page
150
+ title = "For Loop Variable Test"
151
+
152
+ var obj historyList = []
153
+ var int kickCount = 0
154
+ var str userName = ""
155
+ var obj newList = []
156
+ var int i = 0
157
+
158
+ function kickUser() {
159
+ if userName != "" {
160
+ historyList.push(userName)
161
+ kickCount = kickCount + 1
162
+ userName = ""
163
+ }
164
+ }
165
+
166
+ function removeUser(index) {
167
+ newList = []
168
+ i = 0
169
+ for user in historyList {
170
+ if i != index {
171
+ newList.push(user)
172
+ }
173
+ i = i + 1
174
+ }
175
+ historyList = newList
176
+ kickCount = kickCount - 1
177
+ }
178
+
179
+ Main {
180
+ Heading(level: 1) { "For Loop Test" }
181
+
182
+ Input(bind: userName, placeholder: "Enter username to kick")
183
+ Button(onClick: kickUser()) { "Add User" }
184
+
185
+ Paragraph { "Count: " + kickCount }
186
+
187
+ Heading(level: 2) { "Users:" }
188
+ for kickedUser, index in historyList {
189
+ Paragraph { kickedUser }
190
+ Button(onClick: removeUser(index)) { "Remove" }
191
+ }
192
+ }
193
+ ```
194
+
195
+
196
+ #### Fullscreen activation + if-else inside Component
113
197
 
114
198
  ```ts
115
199
  page
@@ -137,7 +221,7 @@ Main {
137
221
  }
138
222
  ```
139
223
 
140
- #### Fullscreen Sync (0.13.6)
224
+ #### Fullscreen Sync
141
225
 
142
226
  Opt-in Escape key handling. `fullscreenSync` keeps your variable in sync with the browser's fullscreen state.
143
227
 
@@ -147,11 +231,11 @@ Button(onClick: isFullscreen = !isFullscreen, fullscreen: isFullscreen, fullscre
147
231
  }
148
232
  ```
149
233
  Without fullscreenSync, pressing Escape exits fullscreen but the variable stays true.
150
- With it, Escape resets the variable to false — button text updates automatically.
234
+ With it, Escape resets the variable to false and the button text updates automatically.
151
235
 
152
236
  #### Opt-in DOM Diffing
153
237
 
154
- Skip re-executing expressions when their variables haven't changed. Perfect for expensive calculations or side effects you only want to fire once.
238
+ Skip re-executing expressions when their variables haven't changed. Perfect for expensive calculations or side effects you only want to fire once. No one
155
239
 
156
240
  ```ts
157
241
  page
@@ -169,8 +253,12 @@ Count updates every click because count changed. The alert fires only on page lo
169
253
 
170
254
  #### Animations that make sense.
171
255
  ```ts
256
+ page
257
+
258
+ var str[] items = ["First", "Second", "Third", "Fourth", "Fifth"]
259
+
172
260
  for item, index in items {
173
- Paragraph(delay: index * 300) { item.name }
261
+ Paragraph(delay: (index + 1) * 1000) { item }
174
262
  }
175
263
  ```
176
264
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yannosay/sinth",
3
- "version": "1.3.0",
3
+ "version": "1.5.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",
@@ -49,7 +49,7 @@ export const INLINE_STYLE_PROPS = new Set([
49
49
  function inlineFunctionBody(fnDef: FunctionDef, args: Expression[], ctx: CompileCtx): string | null {
50
50
  const paramMap = new Map<string, string>();
51
51
  for (let i = 0; i < fnDef.params.length && i < args.length; i++) {
52
- paramMap.set(fnDef.params[i].name, compileExprToJS(args[i]));
52
+ paramMap.set(fnDef.params[i].name, compileExprToJS(args[i], ctx.loopVars));
53
53
  }
54
54
  const subExpr = (expr: Expression): Expression => {
55
55
  if (expr.kind === "variable" && expr.name && paramMap.has(expr.name)) {
@@ -98,13 +98,26 @@ function inlineFunctionBody(fnDef: FunctionDef, args: Expression[], ctx: Compile
98
98
  }
99
99
  };
100
100
  const statements: string[] = [];
101
+
101
102
  for (const c of fnDef.body) {
102
103
  const substituted = subChild(c);
103
104
  if (substituted.kind === "assign_stmt") {
104
105
  statements.push(compileExprToJS(substituted.expression) + ";");
106
+ } else if (substituted.kind === "expr") {
107
+ statements.push(compileExprToJS((substituted as any).expression) + ";");
105
108
  } else if (substituted.kind === "if") {
106
109
  statements.push(compileIfToJS(substituted as IfBlock));
107
110
  } else if (substituted.kind === "return") {
111
+ } else if (substituted.kind === "for") {
112
+ const fl = substituted as any;
113
+ const bodyStmts = fl.body.map((bc: any) => {
114
+ const s = subChild(bc);
115
+ if (s.kind === "assign_stmt") return compileExprToJS(s.expression) + ";";
116
+ if (s.kind === "if") return compileIfToJS(s);
117
+ if (s.kind === "expr") return compileExprToJS(s.expression) + ";";
118
+ return "";
119
+ }).filter(Boolean).join(" ");
120
+ statements.push(`for (let ${fl.itemVar} of ${fl.arrayVar}) { ${bodyStmts} }`);
108
121
  }
109
122
  }
110
123
  if (statements.length === 0) return null;
@@ -128,7 +141,10 @@ export function resolveBuiltinTag(
128
141
  }
129
142
 
130
143
  export function registerExpr(ctx: CompileCtx, expr: Expression): number {
131
- const jsExpr = compileExprToJS(expr, ctx.loopVars);
144
+ let jsExpr = compileExprToJS(expr, ctx.loopVars);
145
+ if (ctx.scopePrefix && ctx.scopeVar && expr.kind === "variable" && expr.name && ctx.varDecls?.some(v => v.name === expr.name)) {
146
+ jsExpr = `_ctx.${ctx.scopePrefix}${expr.name}`;
147
+ }
132
148
  const existing = ctx.exprMap.get(jsExpr);
133
149
  if (existing !== undefined) return existing;
134
150
  const id = ctx.exprRegistry.length;
@@ -137,6 +153,13 @@ export function registerExpr(ctx: CompileCtx, expr: Expression): number {
137
153
  return id;
138
154
  }
139
155
 
156
+ function emitCEAction(ctx: CompileCtx, eventName: string, handlerBody: string): string {
157
+ if (!ctx.ceActionHandlers) ctx.ceActionHandlers = [];
158
+ const idx = ctx.ceActionHandlers.length;
159
+ ctx.ceActionHandlers.push(`function(e, host) { ${handlerBody} }`);
160
+ return `data-sinth-ce-${eventName}="${idx}"`;
161
+ }
162
+
140
163
 
141
164
  export function renderAttr(attr: Attr, paramMap: Map<string, string>, ctx: CompileCtx): string {
142
165
  const { name, value } = attr;
@@ -145,12 +168,21 @@ export function renderAttr(attr: Attr, paramMap: Map<string, string>, ctx: Compi
145
168
  if (value.kind === "bool") return value.value ? name : "";
146
169
 
147
170
  if (name === "model" && value?.kind === "str") {
148
- const vName = interpolateAttr(value.value, paramMap);
171
+ let vName = interpolateAttr(value.value, paramMap);
172
+ if (ctx.scopePrefix && ctx.scopeVar && ctx.varDecls?.some(v => v.name === vName)) {
173
+ vName = `${ctx.scopePrefix}${vName}`;
174
+ }
149
175
  const varDecl = ctx?.varDecls?.find(v => v.name === vName);
150
176
  const rhs = (varDecl && varDecl.varType === "int")
151
177
  ? `Number(e.target.value) || 0`
152
178
  : `e.target.value`;
153
- return `oninput="(function(e){ ${vName} = ${rhs}; sinthRender(); })(event)" value="${escAttr(vName)}"`;
179
+ const renderCall = ctx.scopeVar ? `${ctx.scopeVar}._render()` : 'sinthRender()';
180
+ const handlerBody = `${vName} = ${rhs}; ${renderCall}`;
181
+ if (ctx.scopePrefix) {
182
+ const oninputAttr = emitCEAction(ctx, 'input', handlerBody);
183
+ return `${oninputAttr} value="${escAttr(vName)}"`;
184
+ }
185
+ return `oninput="(function(e){ ${handlerBody} })(event)" value="${escAttr(vName)}"`;
154
186
  }
155
187
 
156
188
  if (name === "step" && value?.kind === "str") {
@@ -282,12 +314,26 @@ if (name === "delay") {
282
314
  }
283
315
  }
284
316
  }
285
- const jsExpr = compileExprToJS(expr, ctx?.loopVars);
317
+ let jsExpr = compileExprToJS(expr, ctx?.loopVars);
318
+ if (ctx.scopePrefix && ctx.scopeVar) {
319
+ if (expr.kind === "variable" && expr.name && ctx.varDecls?.some(v => v.name === expr.name)) {
320
+ jsExpr = `${ctx.scopePrefix}${expr.name}`;
321
+ } else if (expr.kind === "assign" && expr.target && ctx.varDecls?.some(v => v.name === expr.target)) {
322
+ jsExpr = jsExpr.replace(new RegExp(`^${expr.target}\\b`), `${ctx.scopePrefix}${expr.target}`);
323
+ }
324
+ }
325
+ const renderCall = ctx.scopeVar ? `${ctx.scopeVar}._render()` : 'sinthRender()';
286
326
  let bump = "";
287
327
  if (ctx.diffingEnabled && expr.kind === "assign" && expr.target) {
288
328
  bump = `;window._bump&&window._bump('${expr.target.replace(/'/g, "\\'")}')`;
289
329
  }
290
- if (ev) return `${ev}="(function(){ ${jsExpr.replace(/"/g, "&quot;")}${bump}; sinthRender(); })()"`;
330
+ if (ev) {
331
+ const handlerBody = `${jsExpr}${bump}; ${renderCall}`;
332
+ if (ctx.scopePrefix) {
333
+ return emitCEAction(ctx, ev, handlerBody);
334
+ }
335
+ return `${ev}="(function(){ ${handlerBody.replace(/"/g, "&quot;")} })()"`;
336
+ }
291
337
  return `${name}="${escAttr(jsExpr)}"`;
292
338
  } catch { }
293
339
  }
@@ -386,6 +432,10 @@ export function renderChild(
386
432
  }
387
433
  if (child.expression.kind === "call" && child.expression.callee?.kind === "variable") {
388
434
  const fnName = child.expression.callee.name;
435
+ if (fnName && fnName.includes(".")) {
436
+ ctx.logicBlocks.push(compileExprToJS(child.expression) + ";");
437
+ return "";
438
+ }
389
439
  if (fnName === "remove" && child.expression.args && child.expression.args.length === 1) {
390
440
  const arg = child.expression.args[0];
391
441
  if (arg.kind === "literal" && arg.value?.kind === "str") {
@@ -708,6 +758,7 @@ export function renderCompUse(
708
758
  if (customEl) {
709
759
  const attrParts = [`data-s="${ctx.scopeHash}"`];
710
760
  for (const attr of use.attrs) {
761
+ if (attr.name === "bind" || attr.name === "model") continue;
711
762
  const r = renderAttr(attr, params, ctx);
712
763
  if (r) attrParts.push(r);
713
764
  }
@@ -834,7 +885,17 @@ export function renderCompUse(
834
885
  ? `Number(e.target.value) || 0`
835
886
  : `e.target.value`;
836
887
  const initialVal = varDecl?.value ? litToString(varDecl.value).replace(/"/g, '&quot;') : "";
837
- attrParts.push(`oninput="(function(e){ ${vName} = ${rhs}; sinthRender(); })(event)"`);
888
+ let resolvedName = vName;
889
+ if (ctx.scopePrefix && ctx.scopeVar && ctx.varDecls?.some(v => v.name === vName)) {
890
+ resolvedName = `${ctx.scopePrefix}${vName}`;
891
+ }
892
+ const renderCall = ctx.scopeVar ? `${ctx.scopeVar}._render()` : 'sinthRender()';
893
+ const handlerBody = `${resolvedName} = ${rhs}; ${renderCall}`;
894
+ if (ctx.scopePrefix) {
895
+ attrParts.push(emitCEAction(ctx, 'input', handlerBody));
896
+ } else {
897
+ attrParts.push(`oninput="(function(e){ ${handlerBody} })(event)"`);
898
+ }
838
899
  attrParts.push(`value="${escAttr(initialVal)}"`);
839
900
  const valueExprId = registerExpr(ctx, { kind: "variable", name: vName });
840
901
  attrParts.push(`data-sinth-value="${valueExprId}"`);
@@ -1022,12 +1083,11 @@ export function buildRuntime(opts: {
1022
1083
  const needsMixed = mixedBlocks.length > 0;
1023
1084
  const needsExpr = bodyHTML.includes("sinth-expr") || needsMixed;
1024
1085
  const needsIf = bodyHTML.includes("data-sinth-if") || needsMixed;
1025
- const needsFor = bodyHTML.includes("data-sinth-for");
1026
- const needsDelay = bodyHTML.includes("data-sinth-delay") || bodyHTML.includes("data-sinth-delay-expr-id") || mixedBlocks.some(mb => mb.ifHTML.includes("data-sinth-delay") || mb.ifHTML.includes("data-sinth-delay-expr-id") || mb.elseHTML.includes("data-sinth-delay") || mb.elseHTML.includes("data-sinth-delay-expr-id"));
1086
+ const needsFor = bodyHTML.includes("data-sinth-for") || bodyHTML.includes("data-sinth-for-expr"); const needsDelay = bodyHTML.includes("data-sinth-delay") || bodyHTML.includes("data-sinth-delay-expr-id") || mixedBlocks.some(mb => mb.ifHTML.includes("data-sinth-delay") || mb.ifHTML.includes("data-sinth-delay-expr-id") || mb.elseHTML.includes("data-sinth-delay") || mb.elseHTML.includes("data-sinth-delay-expr-id"));
1027
1087
  const needsLogic = logicBlocks.length > 0;
1028
1088
  const needsFullscreen = bodyHTML.includes("data-sinth-fullscreen");
1029
1089
  const needsFullscreenSync = bodyHTML.includes("data-sinth-fullscreen-sync");
1030
- const needsRender = needsExpr || needsIf || needsFor || needsMixed || needsLogic || bodyHTML.includes("data-sinth-hide") || needsFullscreen || needsFullscreenSync;
1090
+ const needsRender = needsExpr || needsIf || needsFor || needsMixed || needsLogic || bodyHTML.includes("data-sinth-hide") || needsFullscreen || needsFullscreenSync || needsDelay;
1031
1091
 
1032
1092
  const varLines = varDecls.map(v => {
1033
1093
  if (!v.value) {
@@ -1055,7 +1115,7 @@ export function buildRuntime(opts: {
1055
1115
  return `let ${v.name} = ${val};`;
1056
1116
  }).join("\n");
1057
1117
 
1058
- if (!needsRender && !needsDelay) {
1118
+ if (!needsRender) {
1059
1119
  return varLines ? `// Sinth compiled runtime\n${varLines}` : "";
1060
1120
  }
1061
1121
 
@@ -1067,11 +1127,29 @@ export function buildRuntime(opts: {
1067
1127
  needsLogic, needsMixed, needsIf, needsFor, needsExpr, needsDelay
1068
1128
  });
1069
1129
 
1130
+ let forDataJS = "";
1131
+ let forSyncBlock = "";
1132
+ if (needsFor) {
1133
+ const forArrays = new Set<string>();
1134
+ const forRegex = /data-sinth-for="([^"]+)"/g;
1135
+ let m;
1136
+ while ((m = forRegex.exec(bodyHTML)) !== null) {
1137
+ forArrays.add(m[1]);
1138
+ }
1139
+ if (forArrays.size > 0) {
1140
+ forDataJS = `var _sinthForData = {};\n`;
1141
+ forSyncBlock = [...forArrays].map(v => `_sinthForData['${v.replace(/&quot;/g, '"')}'] = ${v.replace(/&quot;/g, '"')};`).join("\n ") + "\n ";
1142
+ }
1143
+ }
1144
+
1070
1145
  const exprArrayJS = exprRegistry.length > 0
1071
1146
  ? `let __X = [${exprRegistry.map((js) => `function(_ctx){ return ${js}; }`).join(",")}];\n`
1072
1147
  : "";
1073
1148
 
1074
- let renderFunc = needsRender ? `function sinthRender() {\n${renderBody.replace(/^/gm, " ")}\n}\nsinthRender();` : "";
1149
+ let renderFunc = '';
1150
+ if (needsRender) {
1151
+ renderFunc = `function sinthRender() {\n ${forSyncBlock}${renderBody.replace(/^/gm, " ")}\n}\nsinthRender();`;
1152
+ }
1075
1153
 
1076
1154
  if (needsFullscreenSync) {
1077
1155
  renderFunc += `
@@ -1095,6 +1173,7 @@ export function buildRuntime(opts: {
1095
1173
 
1096
1174
  const pageCode = `// Sinth Page Runtime
1097
1175
  ${varLines}
1176
+ ${forDataJS}
1098
1177
  ${exprArrayJS}
1099
1178
  ${renderFunc}`;
1100
1179
 
@@ -1106,6 +1185,7 @@ ${helpers}`;
1106
1185
 
1107
1186
  return `// Sinth compiled runtime
1108
1187
  ${varLines}
1188
+ ${forDataJS}
1109
1189
  ${functionsJS ? functionsJS + "\n" : ""}${helpers}
1110
1190
  ${exprArrayJS}
1111
1191
  ${renderFunc}`;
@@ -1177,9 +1257,50 @@ export function compileFile(filePath: string, opts: CompileOptions): { html: str
1177
1257
  }
1178
1258
  const pageVars = new Set<string>();
1179
1259
  file.uses.forEach(u => collectChildVars(u, pageVars));
1260
+
1261
+ const pageLoopVars = new Set<string>();
1262
+ const gatherLoopVars = (child: Child): void => {
1263
+ if (child.kind === "for") {
1264
+ const fl = child as ForLoop;
1265
+ if (fl.itemVar) pageLoopVars.add(fl.itemVar);
1266
+ if (fl.keyVar) pageLoopVars.add(fl.keyVar);
1267
+ if (fl.indexVar) pageLoopVars.add(fl.indexVar);
1268
+ fl.body.forEach(gatherLoopVars);
1269
+ } else if (child.kind === "if") {
1270
+ (child as IfBlock).body.forEach(gatherLoopVars);
1271
+ (child as IfBlock).elseBody?.forEach(gatherLoopVars);
1272
+ } else if (child.kind === "use") {
1273
+ (child as CompUse).children.forEach(gatherLoopVars);
1274
+ }
1275
+ };
1276
+ file.uses.forEach(gatherLoopVars);
1277
+
1180
1278
  for (const v of pageVars) {
1279
+ if (pageLoopVars.has(v)) continue;
1181
1280
  const rootVar = v.split('.')[0];
1182
- if (!declaredVars.has(rootVar)) {
1281
+ if (declaredVars.has(rootVar)) continue;
1282
+ let foundInFn = false;
1283
+ for (const fn of file.functions) {
1284
+ if (fn.params.some(p => p.name === rootVar)) { foundInFn = true; break; }
1285
+ const fnLoopVars = new Set<string>();
1286
+ const gatherFnLoopVars = (child: Child): void => {
1287
+ if (child.kind === "for") {
1288
+ const fl = child as ForLoop;
1289
+ if (fl.itemVar) fnLoopVars.add(fl.itemVar);
1290
+ if (fl.keyVar) fnLoopVars.add(fl.keyVar);
1291
+ if (fl.indexVar) fnLoopVars.add(fl.indexVar);
1292
+ fl.body.forEach(gatherFnLoopVars);
1293
+ } else if (child.kind === "if") {
1294
+ (child as IfBlock).body.forEach(gatherFnLoopVars);
1295
+ (child as IfBlock).elseBody?.forEach(gatherFnLoopVars);
1296
+ } else if (child.kind === "use") {
1297
+ (child as CompUse).children.forEach(gatherFnLoopVars);
1298
+ }
1299
+ };
1300
+ fn.body.forEach(gatherFnLoopVars);
1301
+ if (fnLoopVars.has(rootVar)) { foundInFn = true; break; }
1302
+ }
1303
+ if (!foundInFn) {
1183
1304
  throw new SinthError(
1184
1305
  `Variable '${rootVar}' is used but never declared. Add 'var str ${rootVar}' or 'var int ${rootVar}' before using it.`
1185
1306
  );
@@ -1189,7 +1310,26 @@ export function compileFile(filePath: string, opts: CompileOptions): { html: str
1189
1310
  const fnParamNames = new Set(fn.params.map(p => p.name));
1190
1311
  const fnBodyVars = new Set<string>();
1191
1312
  fn.body.forEach(c => collectChildVars(c, fnBodyVars));
1313
+
1314
+ const fnLoopVars = new Set<string>();
1315
+ const gatherFnLoopVars = (child: Child): void => {
1316
+ if (child.kind === "for") {
1317
+ const fl = child as ForLoop;
1318
+ if (fl.itemVar) fnLoopVars.add(fl.itemVar);
1319
+ if (fl.keyVar) fnLoopVars.add(fl.keyVar);
1320
+ if (fl.indexVar) fnLoopVars.add(fl.indexVar);
1321
+ fl.body.forEach(gatherFnLoopVars);
1322
+ } else if (child.kind === "if") {
1323
+ (child as IfBlock).body.forEach(gatherFnLoopVars);
1324
+ (child as IfBlock).elseBody?.forEach(gatherFnLoopVars);
1325
+ } else if (child.kind === "use") {
1326
+ (child as CompUse).children.forEach(gatherFnLoopVars);
1327
+ }
1328
+ };
1329
+ fn.body.forEach(gatherFnLoopVars);
1330
+
1192
1331
  for (const v of fnBodyVars) {
1332
+ if (fnLoopVars.has(v)) continue;
1193
1333
  const rootVar = v.split('.')[0];
1194
1334
  if (!fnParamNames.has(rootVar) && !declaredVars.has(rootVar) && !declaredFuncs.has(rootVar)) {
1195
1335
  throw new SinthError(
package/src/core/expr.ts CHANGED
@@ -1,11 +1,15 @@
1
- import { Expression, Child, AssignStmt, IfBlock, ReturnStmt, LitStr, LitNum, LitBool } from "./types.ts";
2
-
1
+ import { Expression, Child, AssignStmt, IfBlock, ReturnStmt, LitStr, LitNum, LitBool, CompileCtx } from "./types.ts";
3
2
 
4
3
  export function compileExprToJS(expr: Expression, loopVars?: Set<string>): string {
5
4
  switch (expr.kind) {
6
5
  case "literal":
7
6
  if (!expr.value) return "null";
8
- if (expr.value.kind === "str") return JSON.stringify((expr.value as LitStr).value);
7
+ if (expr.value.kind === "str") {
8
+ const sv = (expr.value as LitStr).value;
9
+ if (sv.startsWith("__ARR__")) return sv.slice(7);
10
+ if (sv.startsWith("__VAR__")) return sv.slice(7);
11
+ return JSON.stringify(sv);
12
+ }
9
13
  if (expr.value.kind === "num") return String((expr.value as LitNum).value);
10
14
  if (expr.value.kind === "bool") return String((expr.value as LitBool).value);
11
15
  return "null";
@@ -67,12 +71,19 @@ export function compileIfToJS(ifBlock: IfBlock): string {
67
71
 
68
72
  export function bodyToJS(children: Child[]): string {
69
73
  return children
70
- .filter(c => c.kind === "assign_stmt" || c.kind === "if" || c.kind === "return")
74
+ .filter(c => c.kind === "assign_stmt" || c.kind === "if" || c.kind === "return" || c.kind === "expr")
71
75
  .map(c => {
72
76
  if (c.kind === "assign_stmt") return ` ${compileExprToJS((c as AssignStmt).expression)};\n`;
73
77
  if (c.kind === "return") return ` return ${(c as ReturnStmt).expression ? compileExprToJS((c as ReturnStmt).expression!) : ""};\n`;
74
78
  if (c.kind === "if") return compileIfToJS(c as IfBlock).replace(/^/gm, " ") + "\n";
79
+ if (c.kind === "expr") return ` ${compileExprToJS((c as any).expression)};\n`;
75
80
  return "";
76
81
  })
77
82
  .join("");
83
+ }
84
+ export function scopeVariableName(name: string, ctx?: CompileCtx): string {
85
+ if (ctx?.scopePrefix && ctx?.scopeVar && ctx?.varDecls?.some(v => v.name === name)) {
86
+ return `${ctx.scopePrefix}${name}`;
87
+ }
88
+ return name;
78
89
  }
@@ -129,6 +129,7 @@ if (nextType === TT.LPAREN && identName[0] === identName[0].toLowerCase()) {
129
129
  );
130
130
  }
131
131
 
132
+ this._visited.clear();
132
133
  return { filePath: this.file, isPage, imports, meta, defs, functions, uses, styles, scripts, customEls, varDecls };
133
134
  }
134
135
 
@@ -262,6 +263,8 @@ private parseArrayLiteral(): Literal {
262
263
  } else if (this.check(TT.NULL_LIT)) {
263
264
  this.consume(TT.NULL_LIT);
264
265
  obj[key] = null;
266
+ } else if (this.check(TT.IDENT)) {
267
+ obj[key] = `__VAR__${this.consume(TT.IDENT).value}`;
265
268
  } else {
266
269
  throw new SinthError(`Expected literal value for key '${key}'`, this.peek().loc);
267
270
  }
@@ -271,7 +274,10 @@ private parseArrayLiteral(): Literal {
271
274
  return obj;
272
275
  }
273
276
 
277
+ private _visited: Set<number> = new Set();
274
278
  parseExpression(skipBinary: boolean = false): Expression | null {
279
+ if (this._visited.has(this.pos)) throw new SinthError("Circular expression reference", this.peek().loc);
280
+ this._visited.add(this.pos);
275
281
  const tok = this.peek();
276
282
 
277
283
 
@@ -295,7 +301,7 @@ private parseArrayLiteral(): Literal {
295
301
  }
296
302
 
297
303
  if (this.check(TT.STRING) || this.check(TT.NUMBER) || this.check(TT.BOOL_TRUE) ||
298
- this.check(TT.BOOL_FALSE) || this.check(TT.NULL_LIT)) {
304
+ this.check(TT.BOOL_FALSE) || this.check(TT.NULL_LIT) || this.check(TT.LBRACE) || this.check(TT.LBRACKET)) {
299
305
  const lit = this.parseLiteral();
300
306
  const base: Expression = { kind: "literal", value: lit };
301
307
  return this.parseBinaryRHS(this.parseCallExpr(this.parsePostfix(base)));
@@ -382,6 +388,10 @@ private parseArrayLiteral(): Literal {
382
388
  this.consume(TT.RPAREN);
383
389
  return inner!;
384
390
  }
391
+ if (tok.type === TT.LBRACE) {
392
+ const obj = this.parseObjectLiteral();
393
+ return { kind: "literal", value: { kind: "str", value: JSON.stringify(obj) } };
394
+ }
385
395
  throw new SinthError(`Expected expression`, this.peek().loc);
386
396
  }
387
397
 
@@ -405,7 +415,8 @@ private parseArrayLiteral(): Literal {
405
415
  this.pos = savedPos;
406
416
  return left;
407
417
  }
408
- return this.parseComparison({ kind: "binary", left, op, right });
418
+ if (this.pos === savedPos) return { kind: "binary", left, op, right };
419
+ return { kind: "binary", left, op, right };
409
420
  }
410
421
 
411
422
  private parseLogical(left: Expression): Expression {
@@ -438,7 +449,7 @@ private parseArrayLiteral(): Literal {
438
449
  const rightPrimary = this.parsePrimary();
439
450
  const rightWithPostfix = this.parsePostfix(rightPrimary);
440
451
  const rightWithCall = this.parseCallExpr(rightWithPostfix);
441
- const right = this.parseArithmetic(rightWithCall);
452
+ const right = rightWithCall;
442
453
  if (!right) throw new SinthError(`Expected expression after '${op}'`, this.peek().loc);
443
454
  left = { kind: "binary", left, op, right };
444
455
  }
@@ -800,15 +811,7 @@ private parseArrayLiteral(): Literal {
800
811
  rhs = { kind: "literal", value: { kind: "str", value: this.consume(TT.STRING).value } };
801
812
  } else if (this.check(TT.IDENT)) {
802
813
  const rhsName = this.consume(TT.IDENT).value;
803
- if (this.check(TT.DOT)) {
804
- this.consume(TT.DOT);
805
- rhs = { kind: "variable", name: rhsName + "." + this.consume(TT.IDENT).value };
806
- } else if (this.check(TT.LBRACKET)) {
807
- const rhsVar: Expression = { kind: "variable", name: rhsName };
808
- rhs = this.parsePostfix(rhsVar);
809
- } else {
810
- rhs = { kind: "variable", name: rhsName };
811
- }
814
+ rhs = { kind: "variable", name: rhsName };
812
815
  } else {
813
816
  rhs = this.parseExpression(true);
814
817
  }
@@ -916,7 +919,21 @@ private parseArrayLiteral(): Literal {
916
919
  let fullName = this.consume(TT.IDENT).value;
917
920
  this.consume(TT.DOT);
918
921
  fullName = fullName + "." + this.consume(TT.IDENT).value;
919
- children.push({ kind: "expr", expression: { kind: "variable", name: fullName }, loc });
922
+ if (this.check(TT.LPAREN)) {
923
+ this.consume(TT.LPAREN);
924
+ const args: Expression[] = [];
925
+ if (!this.check(TT.RPAREN)) {
926
+ args.push(this.parseExpression()!);
927
+ while (this.check(TT.COMMA)) {
928
+ this.consume(TT.COMMA);
929
+ args.push(this.parseExpression()!);
930
+ }
931
+ }
932
+ this.consume(TT.RPAREN);
933
+ children.push({ kind: "expr", expression: { kind: "call", callee: { kind: "variable", name: fullName }, args }, loc });
934
+ } else {
935
+ children.push({ kind: "expr", expression: { kind: "variable", name: fullName }, loc });
936
+ }
920
937
  continue;
921
938
  }
922
939
 
@@ -989,7 +1006,28 @@ private parseArrayLiteral(): Literal {
989
1006
  }
990
1007
  if (!this.check(TT.KW_IN)) throw new SinthError("Expected 'in' after loop variable", this.peek().loc);
991
1008
  this.consume(TT.KW_IN);
992
- const arrayVar = this.consume(TT.IDENT).value;
1009
+ let arrayVar = this.consume(TT.IDENT).value;
1010
+ while (this.check(TT.DOT)) {
1011
+ this.consume(TT.DOT);
1012
+ const propName = this.consume(TT.IDENT).value;
1013
+ if (this.check(TT.LPAREN)) {
1014
+ this.consume(TT.LPAREN);
1015
+ const args: string[] = [];
1016
+ if (!this.check(TT.RPAREN)) {
1017
+ if (this.check(TT.STRING)) args.push(this.consume(TT.STRING).value);
1018
+ else if (this.check(TT.NUMBER)) args.push(this.consume(TT.NUMBER).value);
1019
+ while (this.check(TT.COMMA)) {
1020
+ this.consume(TT.COMMA);
1021
+ if (this.check(TT.STRING)) args.push(this.consume(TT.STRING).value);
1022
+ else if (this.check(TT.NUMBER)) args.push(this.consume(TT.NUMBER).value);
1023
+ }
1024
+ }
1025
+ this.consume(TT.RPAREN);
1026
+ arrayVar = arrayVar + "." + propName + "(" + args.map(a => JSON.stringify(a)).join(",") + ")";
1027
+ } else {
1028
+ arrayVar = arrayVar + "." + propName;
1029
+ }
1030
+ }
993
1031
 
994
1032
  if (keyVar === undefined && indexVar !== undefined) {
995
1033
  const srcDecl = this._varDecls.find(d => d.name === arrayVar);
@@ -1119,7 +1157,9 @@ private parseArrayLiteral(): Literal {
1119
1157
 
1120
1158
  private parseChildList(): Child[] {
1121
1159
  const children: Child[] = [];
1160
+ let _iter = 0;
1122
1161
  while (!this.check(TT.EOF) && !this.check(TT.RBRACE)) {
1162
+ if (++_iter > 1000) throw new SinthError("Infinite loop in children", this.peek().loc);
1123
1163
 
1124
1164
  if (this.check(TT.LPAREN)) {
1125
1165
  const loc = this.peek().loc;
@@ -1135,15 +1175,7 @@ private parseArrayLiteral(): Literal {
1135
1175
  rhs = { kind: "literal", value: { kind: "str", value: this.consume(TT.STRING).value } };
1136
1176
  } else if (this.check(TT.IDENT)) {
1137
1177
  const rhsName = this.consume(TT.IDENT).value;
1138
- if (this.check(TT.DOT)) {
1139
- this.consume(TT.DOT);
1140
- rhs = { kind: "variable", name: rhsName + "." + this.consume(TT.IDENT).value };
1141
- } else if (this.check(TT.LBRACKET)) {
1142
- const rhsVar: Expression = { kind: "variable", name: rhsName };
1143
- rhs = this.parsePostfix(rhsVar);
1144
- } else {
1145
- rhs = { kind: "variable", name: rhsName };
1146
- }
1178
+ rhs = { kind: "variable", name: rhsName };
1147
1179
  } else {
1148
1180
  rhs = this.parseExpression(true);
1149
1181
  }
@@ -1178,9 +1210,6 @@ private parseArrayLiteral(): Literal {
1178
1210
  } else if (this.check(TT.DOT)) {
1179
1211
  this.consume(TT.DOT);
1180
1212
  rhs = { kind: "variable", name: rhsName + "." + this.consume(TT.IDENT).value };
1181
- } else if (this.check(TT.LBRACKET)) {
1182
- const rhsVar: Expression = { kind: "variable", name: rhsName };
1183
- rhs = this.parsePostfix(rhsVar);
1184
1213
  } else {
1185
1214
  rhs = { kind: "variable", name: rhsName };
1186
1215
  }
@@ -1235,9 +1264,6 @@ private parseArrayLiteral(): Literal {
1235
1264
  if (this.check(TT.DOT)) {
1236
1265
  this.consume(TT.DOT);
1237
1266
  rhs = { kind: "variable", name: rhsName + "." + this.consume(TT.IDENT).value };
1238
- } else if (this.check(TT.LBRACKET)) {
1239
- const rhsVar: Expression = { kind: "variable", name: rhsName };
1240
- rhs = this.parsePostfix(rhsVar);
1241
1267
  } else {
1242
1268
  rhs = { kind: "variable", name: rhsName };
1243
1269
  }
@@ -1268,9 +1294,6 @@ private parseArrayLiteral(): Literal {
1268
1294
  if (this.check(TT.DOT)) {
1269
1295
  this.consume(TT.DOT);
1270
1296
  rhs = { kind: "variable", name: rhsName + "." + this.consume(TT.IDENT).value };
1271
- } else if (this.check(TT.LBRACKET)) {
1272
- const rhsVar: Expression = { kind: "variable", name: rhsName };
1273
- rhs = this.parsePostfix(rhsVar);
1274
1297
  } else {
1275
1298
  rhs = { kind: "variable", name: rhsName };
1276
1299
  }
@@ -1300,9 +1323,6 @@ private parseArrayLiteral(): Literal {
1300
1323
  if (this.check(TT.DOT)) {
1301
1324
  this.consume(TT.DOT);
1302
1325
  rhs = { kind: "variable", name: rhsName + "." + this.consume(TT.IDENT).value };
1303
- } else if (this.check(TT.LBRACKET)) {
1304
- const rhsVar: Expression = { kind: "variable", name: rhsName };
1305
- rhs = this.parsePostfix(rhsVar);
1306
1326
  } else {
1307
1327
  rhs = { kind: "variable", name: rhsName };
1308
1328
  }
@@ -4,7 +4,6 @@ import { litToString } from "../../utils.ts";
4
4
 
5
5
  export function compileCustomElement(cel: CustomElDecl, opts: { sharedRuntime: boolean }, hash: string, ctx: CompileCtx): string {
6
6
  const varDecls = cel.varDecls;
7
- const varNames = varDecls.map(v => v.name);
8
7
 
9
8
  const varLines = varDecls.map(v => {
10
9
  if (v.value) {
@@ -24,46 +23,34 @@ export function compileCustomElement(cel: CustomElDecl, opts: { sharedRuntime: b
24
23
  logicBlocks: [],
25
24
  mixedBlocks: [],
26
25
  customEls: new Map(),
26
+ scopePrefix: 'host._',
27
+ scopeVar: 'host',
27
28
  };
28
29
 
29
- const bodyHTML = cel.body.map(c => renderChild(c, childCtx, new Map(), 0)).join("\n");
30
-
31
- function replaceVarsOutsideStrings(text: string, varNames: string[], replacement: (name: string) => string): string {
32
- const varPattern = varNames.join('|');
33
- const regex = new RegExp(`("[^"]*"|'[^']*'|\`[^\`]*\`)|\\b(${varPattern})\\b`, 'g');
34
- const parts: string[] = [];
35
- let lastIndex = 0;
36
- let match;
37
-
38
- while ((match = regex.exec(text)) !== null) {
39
- parts.push(text.substring(lastIndex, match.index));
40
- if (match[1]) {
41
- parts.push(match[1]);
42
- } else if (match[2]) {
43
- parts.push(replacement(match[2]));
44
- }
45
- lastIndex = regex.lastIndex;
46
- }
47
- parts.push(text.substring(lastIndex));
48
- return parts.join('');
30
+ const customVarMap = new Map<string, string>();
31
+ for (const v of varDecls) {
32
+ customVarMap.set(v.name, `__VAR__${v.name}`);
49
33
  }
50
34
 
51
- let rewrittenHTML = bodyHTML;
52
- rewrittenHTML = rewrittenHTML.replace(/onclick="([^"]+)"/g, (match, content) => {
53
- const replaced = replaceVarsOutsideStrings(content, varNames, (name) => `host._${name}`);
54
- return `data-sinth-click="${replaced}"`;
55
- });
56
- rewrittenHTML = replaceVarsOutsideStrings(rewrittenHTML, varNames, (name) => `host._${name}`);
57
- rewrittenHTML = rewrittenHTML.replace(/sinthRender\(\)/g, 'host._render()');
58
-
59
- const escapedHTML = rewrittenHTML.replace(/\\/g, '\\\\').replace(/`/g, '\\`').replace(/\$/g, '\\$');
35
+ const bodyHTML = cel.body.map(c => renderChild(c, childCtx, customVarMap, 0)).join("\n");
36
+
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');
60
43
 
61
44
  const needsExpr = bodyHTML.includes("sinth-expr");
62
45
  const needsIf = bodyHTML.includes("data-sinth-if");
63
46
 
64
47
  const exprArrayJS = childCtx.exprRegistry.length > 0
65
48
  ? `let __X = [${childCtx.exprRegistry.map(js => {
66
- return `function(_ctx){ return ${replaceVarsOutsideStrings(js, varNames, (name) => `_ctx.host._${name}`)}; }`;
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}; }`;
67
54
  }).join(",")}];\n`
68
55
  : "";
69
56
 
@@ -78,36 +65,44 @@ export function compileCustomElement(cel: CustomElDecl, opts: { sharedRuntime: b
78
65
  } catch(e) {}
79
66
  };
80
67
 
81
- ${needsIf ? `
82
- function sinthIfBlock(t) {
83
- let ifId = t.dataset.sinthIfId;
84
- let condFn = __X[t.dataset.sinthIfExpr];
85
- let cond = condFn ? condFn() : false;
86
- if (cond) {
87
- let anchor = t.parentNode.querySelector('[data-sinth-if-anchor="' + ifId + '"]');
88
- if (!anchor) {
89
- anchor = document.createElement('span');
90
- anchor.style.display = 'none';
91
- anchor.dataset.sinthIfAnchor = ifId;
92
- t.parentNode.insertBefore(anchor, t);
93
- }
94
- let frag = document.createRange().createContextualFragment(t.innerHTML);
95
- frag.querySelectorAll('.sinth-expr').forEach(sinthExpr);
96
- t.parentNode.insertBefore(frag, t);
97
- } else {
98
- let anchor = t.parentNode.querySelector('[data-sinth-if-anchor="' + ifId + '"]');
99
- if (anchor) {
100
- let c = anchor.nextSibling;
101
- while (c && c !== t) { let n = c.nextSibling; c.remove(); c = n; }
102
- anchor.remove();
103
- }
104
- }
105
- }
106
- ` : ""}
107
-
108
68
  function render(host) {
109
69
  ${needsExpr ? `host.shadowRoot.querySelectorAll('.sinth-expr').forEach(function(el) { sinthExpr(el, host); });` : ""}
110
- ${needsIf ? `host.shadowRoot.querySelectorAll('template[data-sinth-if-expr]').forEach(sinthIfBlock);` : ""}
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
+ });
111
106
  }
112
107
 
113
108
  class ${cel.sinthName} extends HTMLElement {
@@ -117,12 +112,20 @@ export function compileCustomElement(cel: CustomElDecl, opts: { sharedRuntime: b
117
112
  ${varLines}
118
113
  }
119
114
  connectedCallback() {
120
- var self = this;
121
- this._render = function() { render(self); };
115
+ var host = this;
116
+ this._render = function() { render(host); };
122
117
  this.shadowRoot.innerHTML = \`${escapedHTML}\`;
123
- this.shadowRoot.querySelectorAll('[data-sinth-click]').forEach(function(el) {
124
- var fn = new Function('host', el.getAttribute('data-sinth-click'));
125
- el.addEventListener('click', function() { fn(self); });
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
+ }
126
129
  });
127
130
  render(this);
128
131
  }
@@ -9,12 +9,13 @@ export function compileFunctionDef(fn: FunctionDef, ctx: CompileCtx): string {
9
9
  }
10
10
 
11
11
  const bodyStatements: string[] = [];
12
+
12
13
  for (const child of fn.body) {
13
14
  switch (child.kind) {
14
15
  case "text":
15
16
  break;
16
17
  case "expr":
17
- bodyStatements.push(`return ${compileExprToJS(child.expression)};`);
18
+ bodyStatements.push(`${compileExprToJS(child.expression)};`);
18
19
  break;
19
20
  case "assign_stmt":
20
21
  bodyStatements.push(`${compileExprToJS(child.expression)};`);
@@ -22,12 +23,25 @@ export function compileFunctionDef(fn: FunctionDef, ctx: CompileCtx): string {
22
23
  case "if":
23
24
  bodyStatements.push(compileIfToJS(child as IfBlock));
24
25
  break;
25
- case "for":
26
+ case "for": {
27
+ const fl = child as any;
28
+ const itemVar = fl.itemVar;
29
+ const arrayVar = fl.arrayVar;
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)};`;
34
+ return "";
35
+ }).filter(Boolean).join("\n");
36
+ const bodyLines = bodyJS.split("\n");
37
+ const indentedBody = bodyLines.map((line: string) => ` ${line}`).join("\n");
38
+ bodyStatements.push(`for (let ${itemVar} of ${arrayVar}) {\n${indentedBody}\n }`);
26
39
  break;
40
+ }
27
41
  case "return":
28
42
  bodyStatements.push(`return ${child.expression ? compileExprToJS(child.expression) : ""};`);
29
43
  break;
30
44
  }
31
45
  }
32
46
  return `function ${fn.name}(${paramsJS}) {\n${bodyStatements.map(s => ` ${s}`).join("\n")}\n}`;
33
- }
47
+ }
@@ -95,16 +95,25 @@ function sinthDelay(el) {
95
95
  }
96
96
  }
97
97
  function sinthDelayExpr(el, _ctx) {
98
+ if (el.dataset.sinthDelayDone) return;
99
+ el.dataset.sinthDelayDone = '1';
98
100
  _ctx = _ctx || {};
99
101
  try {
100
102
  let fn = __X[el.dataset.sinthDelayExprId];
101
103
  let ms = fn ? parseInt(fn(_ctx)) || 0 : 0;
104
+ let hideEl = el.dataset.sinthDelayHide !== 'false';
102
105
  let show = function() {
103
- el.style.display = '';
106
+ if (hideEl) el.style.display = '';
104
107
  el.querySelectorAll('.sinth-expr').forEach(sinthExpr);
105
108
  };
106
- if (ms > 0) setTimeout(show, ms);
107
- else show();
109
+ if (hideEl) {
110
+ el.style.display = 'none';
111
+ if (ms > 0) setTimeout(show, ms);
112
+ else show();
113
+ } else {
114
+ if (ms > 0) setTimeout(show, ms);
115
+ else show();
116
+ }
108
117
  } catch(e) {}
109
118
  }
110
119
  `;
@@ -239,13 +248,14 @@ function hashString(str) {
239
248
  return String(hash);
240
249
  }
241
250
  function sinthForBlock(t) {
242
- let source = window[t.dataset.sinthFor];
251
+ t.querySelectorAll('template[data-sinth-if-expr]').forEach(function(innerT) {
252
+ innerT.dataset.sinthForHandled = '1';
253
+ });
254
+ let source = _sinthForData[t.dataset.sinthFor];
243
255
  if (source === undefined) source = [];
244
256
  let newHash = '';
245
257
  try { newHash = hashString(JSON.stringify(source)); } catch(e) { newHash = ''; }
246
- if (t.dataset.sinthForHash && t.dataset.sinthForHash === newHash) {
247
- return;
248
- }
258
+ if (t.dataset.sinthForHash && t.dataset.sinthForHash === newHash) return;
249
259
  t.dataset.sinthForHash = newHash;
250
260
  let isObj = (typeof source === 'object' && source !== null && !Array.isArray(source));
251
261
  let entries;
@@ -255,7 +265,14 @@ function sinthForBlock(t) {
255
265
  if (!Array.isArray(source)) source = [];
256
266
  entries = source.map(function(item, index) { return [index, item]; });
257
267
  }
258
- let anchor = t.parentNode ? t.parentNode.querySelector('[data-sinth-for-anchor="' + t.dataset.sinthFor + '"]') : null;
268
+ let anchorId = t.dataset.sinthForExpr || t.dataset.sinthFor;
269
+ let anchor = null;
270
+ if (t.parentNode) {
271
+ let all = t.parentNode.querySelectorAll('[data-sinth-for-anchor]');
272
+ for (let i = 0; i < all.length; i++) {
273
+ if (all[i].dataset.sinthForAnchor === anchorId) { anchor = all[i]; break; }
274
+ }
275
+ }
259
276
  if (anchor) {
260
277
  let cur2 = anchor.nextSibling;
261
278
  while (cur2 && cur2 !== t) { let nx2 = cur2.nextSibling; cur2.remove(); cur2 = nx2; }
@@ -263,63 +280,49 @@ function sinthForBlock(t) {
263
280
  }
264
281
  let fa = document.createElement('span');
265
282
  fa.style.display = 'none';
266
- fa.dataset.sinthForAnchor = t.dataset.sinthFor;
283
+ fa.dataset.sinthForAnchor = anchorId;
267
284
  t.parentNode && t.parentNode.insertBefore(fa, t);
268
285
  let _loopIdx = 0;
286
+ let tplContent = t.innerHTML;
269
287
  entries.forEach(function(entry) {
270
- let _k = entry[0];
271
- let _v = entry[1];
272
- let _item = (t.dataset && t.dataset.sinthItem) ? t.dataset.sinthItem : '__item__';
273
- let _key = t.dataset && t.dataset.sinthKey ? t.dataset.sinthKey : null;
274
- let _idx = t.dataset && t.dataset.sinthIndex ? t.dataset.sinthIndex : null;
288
+ let _k = entry[0], _v = entry[1];
289
+ let _item = t.dataset.sinthItem || '__item__';
290
+ let _key = t.dataset.sinthKey || null;
291
+ let _idx = t.dataset.sinthIndex || null;
275
292
  _loopIdx++;
276
- if (t.dataset.sinthIfReplace) {
277
- let _rp = document.getElementById(t.dataset.sinthIfReplace);
278
- if (_rp) _rp.parentNode.removeChild(_rp);
279
- }
280
293
  let loopCtx = {};
281
294
  if (_item) loopCtx[_item] = _v;
282
295
  if (_key) loopCtx[_key] = _k;
283
296
  if (_idx) loopCtx[_idx] = _loopIdx - 1;
284
- let frag = document.createRange().createContextualFragment(t.innerHTML);
297
+ let frag = document.createRange().createContextualFragment(tplContent);
285
298
  frag.querySelectorAll('.sinth-expr').forEach(function(el) {
286
- try {
287
- let exprFn = __X[el.dataset.exprId];
288
- if (exprFn) el.textContent = exprFn(loopCtx);
289
- } catch(e) {}
299
+ try { let fn = __X[el.dataset.exprId]; if (fn) el.textContent = fn(loopCtx); } catch(e) {}
290
300
  el.classList.remove('sinth-expr');
291
301
  });
302
+ frag.querySelectorAll('[data-sinth-delay-expr-id]').forEach(function(el) {
303
+ sinthDelayExpr(el, loopCtx);
304
+ });
305
+ frag.querySelectorAll('[onclick*="_ctx."]').forEach(function(el) {
306
+ var onclick = el.getAttribute('onclick');
307
+ for (var key in loopCtx) {
308
+ onclick = onclick.split('_ctx.' + key).join(JSON.stringify(loopCtx[key]));
309
+ }
310
+ el.setAttribute('onclick', onclick);
311
+ });
292
312
  frag.querySelectorAll('template[data-sinth-if-expr]').forEach(function(ifT) {
293
313
  let condFn = __X[ifT.dataset.sinthIfExpr];
294
- let cond = false;
295
- try { if (condFn) cond = condFn(loopCtx); } catch(e) {}
314
+ let cond = condFn ? condFn(loopCtx) : false;
296
315
  if (cond) {
297
- let ifContent = document.createRange().createContextualFragment(ifT.innerHTML);
298
- ifContent.querySelectorAll('.sinth-expr').forEach(function(el2) {
299
- try {
300
- let exprFn2 = __X[el2.dataset.exprId];
301
- if (exprFn2) el2.textContent = exprFn2(loopCtx);
302
- } catch(e) {}
316
+ let ifFrag = document.createRange().createContextualFragment(ifT.innerHTML);
317
+ ifFrag.querySelectorAll('.sinth-expr').forEach(function(el2) {
318
+ try { let fn2 = __X[el2.dataset.exprId]; if (fn2) el2.textContent = fn2(loopCtx); } catch(e) {}
319
+ el2.classList.remove('sinth-expr');
303
320
  });
304
- ifT.parentNode.insertBefore(ifContent, ifT);
321
+ ifT.replaceWith(ifFrag);
305
322
  } else {
306
- let elseT = ifT.nextElementSibling;
307
- if (elseT && elseT.hasAttribute('data-sinth-else')) {
308
- let elseContent = document.createRange().createContextualFragment(elseT.innerHTML);
309
- elseContent.querySelectorAll('.sinth-expr').forEach(function(el2) {
310
- try {
311
- let exprFn2 = __X[el2.dataset.exprId];
312
- if (exprFn2) el2.textContent = exprFn2(loopCtx);
313
- } catch(e) {}
314
- });
315
- ifT.parentNode.insertBefore(elseContent, ifT);
316
- }
323
+ ifT.remove();
317
324
  }
318
325
  });
319
- if (${needsDelay}) {
320
- frag.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
321
- frag.querySelectorAll('[data-sinth-delay-expr-id]').forEach(function(el) { sinthDelayExpr(el, loopCtx); });
322
- }
323
326
  t.parentNode && t.parentNode.insertBefore(frag, t);
324
327
  });
325
328
  }
@@ -44,15 +44,15 @@ export function buildRenderBody(opts: {
44
44
  }
45
45
  }
46
46
 
47
- if (needsIf) {
48
- renderBody += ` document.querySelectorAll('template[data-sinth-if-expr]').forEach(sinthIfBlock);\n`;
49
- }
50
47
  renderBody += ` document.querySelectorAll('[data-sinth-remove]').forEach(function(el) {
51
48
  let target = document.getElementById(el.dataset.sinthRemove);
52
49
  if (target) target.remove();
53
50
  });\n`;
54
51
  if (needsFor) {
55
- renderBody += ` document.querySelectorAll('template[data-sinth-for]').forEach(sinthForBlock);\n`;
52
+ renderBody += ` document.querySelectorAll('template[data-sinth-for], template[data-sinth-for-expr]').forEach(sinthForBlock);\n`;
53
+ }
54
+ if (needsIf) {
55
+ renderBody += ` document.querySelectorAll('template[data-sinth-if-expr]').forEach(function(t) { var p = t.parentElement; while(p && p.tagName !== 'TEMPLATE') p = p.parentElement; if (!p || (!p.hasAttribute('data-sinth-for') && !p.hasAttribute('data-sinth-for-expr'))) sinthIfBlock(t); });\n`;
56
56
  }
57
57
  renderBody += ` document.querySelectorAll('[data-sinth-value]').forEach(function(el) {
58
58
  try { if (document.activeElement !== el) { let v=el.dataset.sinthValue; el.value = __X[v] ? __X[v]({}) : ''; } } catch(e) {}
@@ -84,7 +84,8 @@ export function buildRenderBody(opts: {
84
84
  el._sinthLastContent = newContent;
85
85
  delete el.dataset.sinthDelayDone;
86
86
  }
87
- });\n`;
87
+ });
88
+ document.querySelectorAll('[data-sinth-delay-expr-id]').forEach(function(el) { sinthDelayExpr(el, {}); });\n`;
88
89
  }
89
90
  if (needsExpr) {
90
91
  renderBody += ` document.querySelectorAll('.sinth-expr').forEach(function(el) {
@@ -123,6 +124,7 @@ export function buildRenderBody(opts: {
123
124
  if (needsDelay) {
124
125
  renderBody += ` setTimeout(function() {
125
126
  document.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
127
+ document.querySelectorAll('[data-sinth-delay-expr-id]').forEach(function(el) { sinthDelayExpr(el, {}); });
126
128
  }, 0);\n`;
127
129
  }
128
130
  renderBody += ` window.scrollTo(_sx, _sy);\n`;
package/src/core/types.ts CHANGED
@@ -103,7 +103,6 @@ export interface FunctionDef {
103
103
  body: Child[];
104
104
  loc: Loc;
105
105
  }
106
-
107
106
  export interface SinthFile {
108
107
  filePath: string;
109
108
  isPage: boolean;
@@ -149,6 +148,10 @@ export interface CompileCtx {
149
148
  loopVars?: Set<string>;
150
149
  diffingEnabled?: boolean;
151
150
  declaredVars?: Set<string>;
151
+ // custom elements
152
+ scopePrefix?: string;
153
+ scopeVar?: string;
154
+ ceActionHandlers?: string[];
152
155
  }
153
156
 
154
157
  export class SinthError extends Error {