@yannosay/sinth 1.11.6 → 1.12.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/sinth.js +1 -4
- package/dist/browser/compile.js +62 -0
- package/dist/cli.js +469 -0
- package/dist/core/builtins.js +117 -0
- package/dist/core/cli-compiler.js +553 -0
- package/dist/core/compiler.js +1344 -0
- package/dist/core/expr.js +122 -0
- package/dist/core/head-builder.js +130 -0
- package/dist/core/lexer.js +414 -0
- package/dist/core/parser.js +1672 -0
- package/dist/core/runtime/custom-element.js +81 -0
- package/dist/core/runtime/functions.js +99 -0
- package/{src/core/runtime/helpers.ts → dist/core/runtime/helpers.js} +24 -34
- package/{src/core/runtime/render.ts → dist/core/runtime/render.js} +48 -63
- package/dist/core/style-processor.js +318 -0
- package/dist/core/types.js +93 -0
- package/dist/resolver.js +175 -0
- package/dist/server.js +168 -0
- package/dist/update-check.js +101 -0
- package/dist/utils.js +73 -0
- package/package.json +12 -8
- package/src/browser/compile.ts +0 -72
- package/src/cli.ts +0 -339
- package/src/core/builtins.ts +0 -117
- package/src/core/cli-compiler.ts +0 -514
- package/src/core/compiler.ts +0 -1351
- package/src/core/expr.ts +0 -113
- package/src/core/head-builder.ts +0 -86
- package/src/core/lexer.ts +0 -276
- package/src/core/parser.ts +0 -1533
- package/src/core/runtime/custom-element.ts +0 -84
- package/src/core/runtime/functions.ts +0 -87
- package/src/core/style-processor.ts +0 -299
- package/src/core/types.ts +0 -197
- package/src/resolver.ts +0 -150
- package/src/server.ts +0 -129
- package/src/utils.ts +0 -77
- package/tsconfig.json +0 -27
package/src/core/compiler.ts
DELETED
|
@@ -1,1351 +0,0 @@
|
|
|
1
|
-
import { Loc, Literal, Expression, Child, Attr, CompUse, IfBlock, ForLoop, RemoveStmt, ReturnStmt, StyleBlock, CompDef, ParamDecl, VarDeclaration, SinthFile, CompileCtx, MixedBlockEntry, SinthError, SinthWarning, TT, AssignStmt, MetaEntry } from "./types.ts";
|
|
2
|
-
import { Parser } from "./parser.ts";
|
|
3
|
-
import { fnv1a, camelToKebab, esc, escAttr, litToString, tagNameToPascal, interpolateAttr, renderText } from "../utils.ts";
|
|
4
|
-
import { compileExprToJS, compileIfToJS, bodyToJS } from "./expr.ts";
|
|
5
|
-
import { FunctionDef } from "./types.ts";
|
|
6
|
-
import { parseFile, resolveImports, ResolverConfig, ResolvedImports } from "../resolver.ts";
|
|
7
|
-
import { compileFunctionDef } from "./runtime/functions.ts";
|
|
8
|
-
import { generateHelpers } from "./runtime/helpers.ts";
|
|
9
|
-
import { buildRenderBody } from "./runtime/render.ts";
|
|
10
|
-
import { BUILTIN_MAP, VOID_TAGS, BuiltinInfo } from "./builtins.ts";
|
|
11
|
-
import { processStyleBlock } from "./style-processor.ts";
|
|
12
|
-
import { buildHeadData, renderHead, HeadData } from "./head-builder.ts";
|
|
13
|
-
import { compileCustomElement } from "./runtime/custom-element.ts";
|
|
14
|
-
|
|
15
|
-
const EVENT_RE = /^on[A-Z]/;
|
|
16
|
-
export function eventAttrName(name: string): string | null {
|
|
17
|
-
return EVENT_RE.test(name) ? name.toLowerCase() : null;
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
/**
|
|
21
|
-
* CSS property names that are allowed as inline style shorthand attributes on
|
|
22
|
-
* any Sinth component: Paragraph(color: "red", fontSize: "1.2rem") { "Hi" }
|
|
23
|
-
*/
|
|
24
|
-
export const INLINE_STYLE_PROPS = new Set([
|
|
25
|
-
"color","backgroundColor","backgroundImage","backgroundSize","backgroundPosition",
|
|
26
|
-
"fontSize","fontWeight","fontFamily","fontStyle","fontVariant","lineHeight","letterSpacing","textAlign",
|
|
27
|
-
"textDecoration","textTransform","whiteSpace","wordBreak","wordWrap","textOverflow",
|
|
28
|
-
"margin","marginTop","marginBottom","marginLeft","marginRight",
|
|
29
|
-
"padding","paddingTop","paddingBottom","paddingLeft","paddingRight",
|
|
30
|
-
"width","height","minWidth","maxWidth","minHeight","maxHeight",
|
|
31
|
-
"display","flexDirection","flexWrap","flex","flexGrow","flexShrink","flexBasis",
|
|
32
|
-
"justifyContent","alignItems","alignContent","alignSelf","gap","rowGap","columnGap",
|
|
33
|
-
"gridTemplateColumns","gridTemplateRows","gridColumn","gridRow","gridArea",
|
|
34
|
-
"position","top","right","bottom","left","zIndex",
|
|
35
|
-
"border","borderTop","borderBottom","borderLeft","borderRight",
|
|
36
|
-
"borderWidth","borderStyle","borderColor","borderRadius",
|
|
37
|
-
"outline","outlineWidth","outlineStyle","outlineColor","outlineOffset",
|
|
38
|
-
"boxShadow","textShadow","opacity","visibility",
|
|
39
|
-
"overflow","overflowX","overflowY","objectFit","objectPosition",
|
|
40
|
-
"cursor","userSelect","pointerEvents","resize",
|
|
41
|
-
"transform","transition","animation","animationDuration","animationDelay",
|
|
42
|
-
"listStyle","listStyleType","listStylePosition",
|
|
43
|
-
"verticalAlign","float","clear",
|
|
44
|
-
"content","quotes",
|
|
45
|
-
]);
|
|
46
|
-
|
|
47
|
-
function inlineFunctionBody(fnDef: FunctionDef, args: Expression[], ctx: CompileCtx): string | null {
|
|
48
|
-
const paramMap = new Map<string, string>();
|
|
49
|
-
for (let i = 0; i < fnDef.params.length && i < args.length; i++) {
|
|
50
|
-
paramMap.set(fnDef.params[i].name, compileExprToJS(args[i], ctx.loopVars, ctx.namespace));
|
|
51
|
-
}
|
|
52
|
-
const subExpr = (expr: Expression): Expression => {
|
|
53
|
-
if (expr.kind === "variable" && expr.name && paramMap.has(expr.name)) {
|
|
54
|
-
return { kind: "variable", name: paramMap.get(expr.name)! };
|
|
55
|
-
}
|
|
56
|
-
if (expr.kind === "binary") {
|
|
57
|
-
return { ...expr, left: expr.left ? subExpr(expr.left) : undefined, right: expr.right ? subExpr(expr.right) : undefined };
|
|
58
|
-
}
|
|
59
|
-
if (expr.kind === "unary") {
|
|
60
|
-
return { ...expr, operand: expr.operand ? subExpr(expr.operand) : undefined };
|
|
61
|
-
}
|
|
62
|
-
if (expr.kind === "assign") {
|
|
63
|
-
if (expr.target && paramMap.has(expr.target)) {
|
|
64
|
-
return { ...expr, target: paramMap.get(expr.target)!, right: expr.right ? subExpr(expr.right) : undefined };
|
|
65
|
-
}
|
|
66
|
-
return { ...expr, right: expr.right ? subExpr(expr.right) : undefined };
|
|
67
|
-
}
|
|
68
|
-
if (expr.kind === "postfix" && expr.target && paramMap.has(expr.target)) {
|
|
69
|
-
return { ...expr, target: paramMap.get(expr.target)!, op: expr.op };
|
|
70
|
-
}
|
|
71
|
-
if (expr.kind === "index") {
|
|
72
|
-
return { ...expr, object: expr.object ? subExpr(expr.object) : undefined, key: expr.key ? subExpr(expr.key) : undefined };
|
|
73
|
-
}
|
|
74
|
-
if (expr.kind === "call") {
|
|
75
|
-
return { ...expr, callee: expr.callee ? subExpr(expr.callee) : undefined, args: expr.args?.map(a => subExpr(a)) };
|
|
76
|
-
}
|
|
77
|
-
return expr;
|
|
78
|
-
};
|
|
79
|
-
const subChild = (child: Child): Child => {
|
|
80
|
-
switch (child.kind) {
|
|
81
|
-
case "assign_stmt":
|
|
82
|
-
return { ...child, expression: subExpr(child.expression) as Expression };
|
|
83
|
-
case "if": {
|
|
84
|
-
const ib = child as IfBlock;
|
|
85
|
-
return {
|
|
86
|
-
...ib,
|
|
87
|
-
condition: subExpr(ib.condition),
|
|
88
|
-
body: ib.body.map(subChild),
|
|
89
|
-
elseBody: ib.elseBody?.map(subChild),
|
|
90
|
-
};
|
|
91
|
-
}
|
|
92
|
-
case "return":
|
|
93
|
-
return { ...child, expression: child.expression ? subExpr(child.expression) : undefined };
|
|
94
|
-
default:
|
|
95
|
-
return child;
|
|
96
|
-
}
|
|
97
|
-
};
|
|
98
|
-
const statements: string[] = [];
|
|
99
|
-
|
|
100
|
-
for (const c of fnDef.body) {
|
|
101
|
-
const substituted = subChild(c);
|
|
102
|
-
if (substituted.kind === "assign_stmt") {
|
|
103
|
-
statements.push(compileExprToJS(substituted.expression, ctx.loopVars, ctx.namespace, ctx.declaredVars) + ";");
|
|
104
|
-
} else if (substituted.kind === "expr") {
|
|
105
|
-
statements.push(compileExprToJS((substituted as any).expression, ctx.loopVars, ctx.namespace, ctx.declaredVars) + ";");
|
|
106
|
-
} else if (substituted.kind === "if") {
|
|
107
|
-
statements.push(compileIfToJS(substituted as IfBlock, ctx.loopVars, ctx.namespace, ctx.declaredVars));
|
|
108
|
-
} else if (substituted.kind === "return") {
|
|
109
|
-
} else if (substituted.kind === "for") {
|
|
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
|
-
}
|
|
119
|
-
const bodyStmts = fl.body.map((bc: any) => {
|
|
120
|
-
const s = subChild(bc);
|
|
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) + ";";
|
|
124
|
-
return "";
|
|
125
|
-
}).filter(Boolean).join(" ");
|
|
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};`);
|
|
169
|
-
}
|
|
170
|
-
}
|
|
171
|
-
if (statements.length === 0) return null;
|
|
172
|
-
return statements.join(" ");
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
export function resolveBuiltinTag(
|
|
176
|
-
name: string,
|
|
177
|
-
attrs: Attr[],
|
|
178
|
-
): { tag: string; defaultClass?: string; voidEl: boolean } {
|
|
179
|
-
if (name === "Heading") {
|
|
180
|
-
const la = attrs.find(a => a.name === "level");
|
|
181
|
-
const lv = la?.value?.kind === "num" ? Math.min(6, Math.max(1, la.value.value)) : 1;
|
|
182
|
-
if (!la) SinthWarning.emit(`Heading used without 'level' attribute, defaulting to h1`);
|
|
183
|
-
return { tag: `h${lv}`, voidEl: false };
|
|
184
|
-
}
|
|
185
|
-
const info = BUILTIN_MAP[name];
|
|
186
|
-
if (info) return { tag: info.tag, defaultClass: info.defaultClass, voidEl: info.voidEl ?? false };
|
|
187
|
-
SinthWarning.emit(`Unknown component '${name}', treating as <${name.toLowerCase()}>`);
|
|
188
|
-
return { tag: name.toLowerCase(), voidEl: false };
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
export function registerExpr(ctx: CompileCtx, expr: Expression): number {
|
|
192
|
-
let jsExpr = compileExprToJS(expr, ctx.loopVars, ctx.namespace, ctx.declaredVars);
|
|
193
|
-
if (ctx.scopePrefix && ctx.scopeVar && expr.kind === "variable" && expr.name && ctx.varDecls?.some(v => v.name === expr.name)) {
|
|
194
|
-
jsExpr = `_ctx.${ctx.scopePrefix}${expr.name}`;
|
|
195
|
-
}
|
|
196
|
-
const existing = ctx.exprMap.get(jsExpr);
|
|
197
|
-
if (existing !== undefined) return existing;
|
|
198
|
-
const id = ctx.exprRegistry.length;
|
|
199
|
-
ctx.exprRegistry.push(jsExpr);
|
|
200
|
-
ctx.exprMap.set(jsExpr, id);
|
|
201
|
-
return id;
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
function emitCEAction(ctx: CompileCtx, eventName: string, handlerBody: string): string {
|
|
205
|
-
if (!ctx.ceActionHandlers) ctx.ceActionHandlers = [];
|
|
206
|
-
const idx = ctx.ceActionHandlers.length;
|
|
207
|
-
ctx.ceActionHandlers.push(`function(e, host) { ${handlerBody} }`);
|
|
208
|
-
return `data-sinth-ce-${eventName}="${idx}"`;
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
export function renderAttr(attr: Attr, paramMap: Map<string, string>, ctx: CompileCtx): string {
|
|
213
|
-
const { name, value } = attr;
|
|
214
|
-
const renderFn = ctx.namespace ? "sinthRender_" + ctx.namespace : "sinthRender";
|
|
215
|
-
if (value === null) return name;
|
|
216
|
-
if (value.kind === "null") return "";
|
|
217
|
-
if (value.kind === "bool") return value.value ? name : "";
|
|
218
|
-
|
|
219
|
-
if (name === "model" && value?.kind === "str") {
|
|
220
|
-
let vName = interpolateAttr(value.value, paramMap);
|
|
221
|
-
if (ctx.scopePrefix && ctx.scopeVar && ctx.varDecls?.some(v => v.name === vName)) {
|
|
222
|
-
vName = `${ctx.scopePrefix}${vName}`;
|
|
223
|
-
}
|
|
224
|
-
if (ctx.namespace) vName = ctx.namespace + "_" + vName;
|
|
225
|
-
const varDecl = ctx?.varDecls?.find(v => v.name === vName);
|
|
226
|
-
const rhs = (varDecl && varDecl.varType === "int")
|
|
227
|
-
? `Number(e.target.value) || 0`
|
|
228
|
-
: `e.target.value`;
|
|
229
|
-
const renderCall = ctx.scopeVar ? `${ctx.scopeVar}._render()` : renderFn + "()";
|
|
230
|
-
const handlerBody = `${vName} = ${rhs}; ${renderCall}`;
|
|
231
|
-
if (ctx.scopePrefix) {
|
|
232
|
-
const oninputAttr = emitCEAction(ctx, 'input', handlerBody);
|
|
233
|
-
return `${oninputAttr} value="${escAttr(vName)}"`;
|
|
234
|
-
}
|
|
235
|
-
return `oninput="(function(e){ ${handlerBody} })(event)" value="${escAttr(vName)}"`;
|
|
236
|
-
}
|
|
237
|
-
|
|
238
|
-
if (name === "step" && value?.kind === "str") {
|
|
239
|
-
const raw = value.value;
|
|
240
|
-
if (raw.startsWith("__EXPR__")) {
|
|
241
|
-
try {
|
|
242
|
-
const expr: Expression = JSON.parse(raw.substring(8));
|
|
243
|
-
if (expr.kind === "variable" && expr.name) {
|
|
244
|
-
const stepExprId = registerExpr(ctx, expr);
|
|
245
|
-
return `data-sinth-step="${stepExprId}"`;
|
|
246
|
-
}
|
|
247
|
-
} catch {}
|
|
248
|
-
}
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
if (name === "delay") {
|
|
254
|
-
if (value.kind === "num") {
|
|
255
|
-
return `data-sinth-delay="${value.value}"`;
|
|
256
|
-
}
|
|
257
|
-
const v = litToString(value);
|
|
258
|
-
if (/^\d+$/.test(v)) return `data-sinth-delay="${escAttr(v)}"`;
|
|
259
|
-
if (v.startsWith("__EXPR__")) {
|
|
260
|
-
try {
|
|
261
|
-
const expr: Expression = JSON.parse(v.substring(8));
|
|
262
|
-
const id = registerExpr(ctx, expr);
|
|
263
|
-
return `data-sinth-delay-expr-id="${id}"`;
|
|
264
|
-
} catch {}
|
|
265
|
-
}
|
|
266
|
-
const id = registerExpr(ctx, { kind: "variable", name: v });
|
|
267
|
-
return `data-sinth-delay-expr-id="${id}"`;
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
if (name === "hide") {
|
|
271
|
-
if (value === null) return `data-sinth-hide=""`;
|
|
272
|
-
if (value && (value as any).kind === "bool") {
|
|
273
|
-
return (value as any).value ? `data-sinth-hide=""` : "";
|
|
274
|
-
}
|
|
275
|
-
if (value?.kind === "str") {
|
|
276
|
-
const v = value.value;
|
|
277
|
-
if (v === "true") return `data-sinth-hide=""`;
|
|
278
|
-
if (v === "false") return "";
|
|
279
|
-
if (v.startsWith("__EXPR__")) {
|
|
280
|
-
try {
|
|
281
|
-
const expr: Expression = JSON.parse(v.substring(8));
|
|
282
|
-
const id = registerExpr(ctx, expr);
|
|
283
|
-
return `data-sinth-hide="${id}"`;
|
|
284
|
-
} catch { return ""; }
|
|
285
|
-
}
|
|
286
|
-
}
|
|
287
|
-
return "";
|
|
288
|
-
}
|
|
289
|
-
|
|
290
|
-
if (name === "fullscreen") {
|
|
291
|
-
if (value?.kind === "str") {
|
|
292
|
-
const v = value.value;
|
|
293
|
-
if (v.startsWith("__EXPR__")) {
|
|
294
|
-
try {
|
|
295
|
-
const expr: Expression = JSON.parse(v.substring(8));
|
|
296
|
-
const id = registerExpr(ctx, expr);
|
|
297
|
-
return `data-sinth-fullscreen="${id}"`;
|
|
298
|
-
} catch { return ""; }
|
|
299
|
-
}
|
|
300
|
-
}
|
|
301
|
-
return "";
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
if (name === "fullscreenSync") {
|
|
305
|
-
if (value?.kind === "str") {
|
|
306
|
-
const raw = value.value;
|
|
307
|
-
if (raw.startsWith("__EXPR__")) {
|
|
308
|
-
try {
|
|
309
|
-
const expr: Expression = JSON.parse(raw.substring(8));
|
|
310
|
-
if (expr.kind === "variable" && expr.name) {
|
|
311
|
-
return `data-sinth-fullscreen-sync="${escAttr(expr.name)}"`;
|
|
312
|
-
}
|
|
313
|
-
} catch {}
|
|
314
|
-
}
|
|
315
|
-
return `data-sinth-fullscreen-sync="${escAttr(raw)}"`;
|
|
316
|
-
}
|
|
317
|
-
return "";
|
|
318
|
-
}
|
|
319
|
-
|
|
320
|
-
if (name === "checked") {
|
|
321
|
-
return (value as any)?.kind === "bool" && (value as any).value ? "checked" : "";
|
|
322
|
-
}
|
|
323
|
-
|
|
324
|
-
if (value.kind === "num") return `${name}="${value.value}"`;
|
|
325
|
-
|
|
326
|
-
let raw = value.value;
|
|
327
|
-
|
|
328
|
-
if (raw.startsWith("__ACTION_JS__")) {
|
|
329
|
-
const js = raw.substring("__ACTION_JS__".length);
|
|
330
|
-
const ev = eventAttrName(name);
|
|
331
|
-
if (ev) return `${ev}="(function(){ ${js.replace(/"/g, """)}; ${renderFn}(); })()"`;
|
|
332
|
-
return `${name}="${escAttr(js)}"`;
|
|
333
|
-
}
|
|
334
|
-
if (raw.startsWith("__MULTI_EXPR__")) {
|
|
335
|
-
const exprJson = raw.substring("__MULTI_EXPR__".length);
|
|
336
|
-
try {
|
|
337
|
-
const exprs: Expression[] = JSON.parse(exprJson);
|
|
338
|
-
const jsExprs = exprs.map(e => compileExprToJS(e, undefined, ctx.namespace)).join("; ");
|
|
339
|
-
const ev = eventAttrName(name);
|
|
340
|
-
let bumps = "";
|
|
341
|
-
if (ctx.diffingEnabled) {
|
|
342
|
-
const targets: string[] = [];
|
|
343
|
-
for (const e of exprs) {
|
|
344
|
-
if (e.kind === "assign" && e.target) targets.push(e.target);
|
|
345
|
-
}
|
|
346
|
-
if (targets.length) bumps = ";" + targets.map(t => `window._bump&&window._bump('${t.replace(/'/g, "\\'")}')`).join(";");
|
|
347
|
-
}
|
|
348
|
-
if (ev) return `${ev}="(function(){ ${jsExprs.replace(/"/g, """)}${bumps}; ${renderFn}(); })()"`;
|
|
349
|
-
return `${name}="${escAttr(jsExprs)}"`;
|
|
350
|
-
} catch { }
|
|
351
|
-
}
|
|
352
|
-
if (raw.startsWith("__EXPR__")) {
|
|
353
|
-
const exprJson = raw.substring("__EXPR__".length);
|
|
354
|
-
try {
|
|
355
|
-
const expr: Expression = JSON.parse(exprJson);
|
|
356
|
-
const ev = eventAttrName(name);
|
|
357
|
-
if (ev && expr.kind === "call" && expr.callee?.kind === "variable") {
|
|
358
|
-
const fnName = expr.callee.name;
|
|
359
|
-
const fnDef = fnName ? ctx.functionDefs.find(f => f.name === fnName) : undefined;
|
|
360
|
-
if (fnDef) {
|
|
361
|
-
const inlinedJS = inlineFunctionBody(fnDef, expr.args ?? [], ctx);
|
|
362
|
-
if (inlinedJS) {
|
|
363
|
-
return `${ev}="(function(){ ${inlinedJS.replace(/"/g, """)}; ${renderFn}(); })()"`;
|
|
364
|
-
}
|
|
365
|
-
}
|
|
366
|
-
}
|
|
367
|
-
let jsExpr = compileExprToJS(expr, ctx?.loopVars, ctx.namespace);
|
|
368
|
-
if (ctx.scopePrefix && ctx.scopeVar) {
|
|
369
|
-
if (expr.kind === "variable" && expr.name && ctx.varDecls?.some(v => v.name === expr.name)) {
|
|
370
|
-
jsExpr = `${ctx.scopePrefix}${expr.name}`;
|
|
371
|
-
} else if (expr.kind === "assign" && expr.target && ctx.varDecls?.some(v => v.name === expr.target)) {
|
|
372
|
-
jsExpr = jsExpr.replace(new RegExp(`^${expr.target}\\b`), `${ctx.scopePrefix}${expr.target}`);
|
|
373
|
-
}
|
|
374
|
-
}
|
|
375
|
-
if (ev && expr.kind === "variable" && expr.name && ctx.functionDefs.some(f => f.name === expr.name)) {
|
|
376
|
-
jsExpr = jsExpr + "()";
|
|
377
|
-
}
|
|
378
|
-
const renderCall = ctx.scopeVar ? `${ctx.scopeVar}._render()` : renderFn + "()";
|
|
379
|
-
let bump = "";
|
|
380
|
-
if (ctx.diffingEnabled && expr.kind === "assign" && expr.target) {
|
|
381
|
-
bump = `;window._bump&&window._bump('${expr.target.replace(/'/g, "\\'")}')`;
|
|
382
|
-
}
|
|
383
|
-
if (ev) {
|
|
384
|
-
const handlerBody = `${jsExpr}${bump}; ${renderCall}`;
|
|
385
|
-
if (ctx.scopePrefix) {
|
|
386
|
-
return emitCEAction(ctx, ev, handlerBody);
|
|
387
|
-
}
|
|
388
|
-
return `${ev}="(function(){ ${handlerBody.replace(/"/g, """)} })()"`;
|
|
389
|
-
}
|
|
390
|
-
return `${name}="${escAttr(jsExpr)}"`;
|
|
391
|
-
} catch { }
|
|
392
|
-
}
|
|
393
|
-
|
|
394
|
-
raw = interpolateAttr(raw, paramMap);
|
|
395
|
-
|
|
396
|
-
const ev = eventAttrName(name);
|
|
397
|
-
if (ev) {
|
|
398
|
-
const call = raw.includes("(") ? raw : raw + "()";
|
|
399
|
-
return `${ev}="${escAttr(call)};${renderFn}()"`;
|
|
400
|
-
}
|
|
401
|
-
return `${name}="${escAttr(raw)}"`;
|
|
402
|
-
}
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
function substituteParamsInExpr(expr: Expression, params: Map<string, string>): Expression {
|
|
410
|
-
if (expr.kind === "variable" && expr.name && params.has(expr.name)) {
|
|
411
|
-
const val = params.get(expr.name)!;
|
|
412
|
-
if (val.startsWith("__LIT__")) {
|
|
413
|
-
return { kind: "literal", value: { kind: "str", value: val.slice(7) } };
|
|
414
|
-
}
|
|
415
|
-
if (val.startsWith("__EXPR__")) {
|
|
416
|
-
try {
|
|
417
|
-
return JSON.parse(val.substring(8));
|
|
418
|
-
} catch { return expr; }
|
|
419
|
-
}
|
|
420
|
-
return { kind: "literal", value: { kind: "str", value: val } };
|
|
421
|
-
}
|
|
422
|
-
if (expr.kind === "binary") {
|
|
423
|
-
return {
|
|
424
|
-
...expr,
|
|
425
|
-
left: expr.left ? substituteParamsInExpr(expr.left, params) : undefined,
|
|
426
|
-
right: expr.right ? substituteParamsInExpr(expr.right, params) : undefined,
|
|
427
|
-
};
|
|
428
|
-
}
|
|
429
|
-
if (expr.kind === "unary" && expr.operand) {
|
|
430
|
-
return { ...expr, operand: substituteParamsInExpr(expr.operand, params) };
|
|
431
|
-
}
|
|
432
|
-
return expr;
|
|
433
|
-
}
|
|
434
|
-
|
|
435
|
-
function exprDeps(expr: Expression, declaredVars: Set<string>): string {
|
|
436
|
-
const deps = new Set<string>();
|
|
437
|
-
function walk(e: Expression | undefined): void {
|
|
438
|
-
if (!e) return;
|
|
439
|
-
if (e.kind === "variable" && e.name && declaredVars.has(e.name)) deps.add(e.name);
|
|
440
|
-
if (e.kind === "binary") { walk(e.left); walk(e.right); }
|
|
441
|
-
if (e.kind === "unary") walk(e.operand);
|
|
442
|
-
if (e.kind === "call") { e.args?.forEach(walk); }
|
|
443
|
-
if (e.kind === "index") { walk(e.object); walk(e.key); }
|
|
444
|
-
if (e.kind === "assign") { if (e.target && declaredVars.has(e.target)) deps.add(e.target); walk(e.right); }
|
|
445
|
-
}
|
|
446
|
-
walk(expr);
|
|
447
|
-
return [...deps].join(",");
|
|
448
|
-
}
|
|
449
|
-
|
|
450
|
-
export function renderChild(
|
|
451
|
-
child: Child,
|
|
452
|
-
ctx: CompileCtx,
|
|
453
|
-
params: Map<string, string>,
|
|
454
|
-
depth: number,
|
|
455
|
-
): string {
|
|
456
|
-
if (depth > 64) throw new SinthError("Maximum component nesting depth (64) exceeded.");
|
|
457
|
-
|
|
458
|
-
switch (child.kind) {
|
|
459
|
-
case "text":
|
|
460
|
-
return renderText(child.value, params);
|
|
461
|
-
|
|
462
|
-
case "expr": {
|
|
463
|
-
if (!child.expression) return "";
|
|
464
|
-
|
|
465
|
-
if (child.expression.kind === "variable" && child.expression.name && params.has(child.expression.name)) {
|
|
466
|
-
const val = params.get(child.expression.name)!;
|
|
467
|
-
if (val.startsWith("__LIT__")) {
|
|
468
|
-
return esc(val.slice(7));
|
|
469
|
-
}
|
|
470
|
-
if (val.startsWith("__RAW__")) {
|
|
471
|
-
return val.slice(7);
|
|
472
|
-
}
|
|
473
|
-
if (val.startsWith("__VAR__")) {
|
|
474
|
-
const exprId = registerExpr(ctx, { kind: "variable", name: val.slice(7) });
|
|
475
|
-
return `<span class="sinth-expr" data-expr-id="${exprId}"${ctx.diffingEnabled ? ` data-sinth-deps="${exprDeps(child.expression, ctx.declaredVars ?? new Set())}"` : ""}></span>`;
|
|
476
|
-
}
|
|
477
|
-
if (val.startsWith("__EXPR__")) {
|
|
478
|
-
try {
|
|
479
|
-
const expr: Expression = JSON.parse(val.substring(8));
|
|
480
|
-
const exprId = registerExpr(ctx, expr);
|
|
481
|
-
return `<span class="sinth-expr" data-expr-id="${exprId}"${ctx.diffingEnabled ? ` data-sinth-deps="${exprDeps(child.expression, ctx.declaredVars ?? new Set())}"` : ""}></span>`;
|
|
482
|
-
} catch { return esc(val); }
|
|
483
|
-
}
|
|
484
|
-
return esc(val);
|
|
485
|
-
}
|
|
486
|
-
if (child.expression.kind === "call" && child.expression.callee?.kind === "variable") {
|
|
487
|
-
const fnName = child.expression.callee.name;
|
|
488
|
-
const isMemo = child.expression.memo === true;
|
|
489
|
-
if (isMemo) {
|
|
490
|
-
if (fnName && fnName.includes(".")) {
|
|
491
|
-
SinthWarning.emit(`'$' on '${fnName}()' has no effect — dotted calls cannot be memoized.`);
|
|
492
|
-
ctx.logicBlocks.push(compileExprToJS(child.expression, undefined, ctx.namespace) + ";");
|
|
493
|
-
return "";
|
|
494
|
-
}
|
|
495
|
-
const js = compileExprToJS(child.expression);
|
|
496
|
-
ctx.logicBlocks.push(`if(!_memo_${fnName}_done){_memo_${fnName}=${js};_memo_${fnName}_done=true;}`);
|
|
497
|
-
const exprId = registerExpr(ctx, { kind: "variable", name: `_memo_${fnName}` });
|
|
498
|
-
return `<span class="sinth-expr" data-expr-id="${exprId}"></span>`;
|
|
499
|
-
}
|
|
500
|
-
if (fnName && fnName.includes(".")) {
|
|
501
|
-
ctx.logicBlocks.push(compileExprToJS(child.expression, undefined, ctx.namespace) + ";");
|
|
502
|
-
return "";
|
|
503
|
-
}
|
|
504
|
-
if (fnName === "remove" && child.expression.args && child.expression.args.length === 1) {
|
|
505
|
-
const arg = child.expression.args[0];
|
|
506
|
-
if (arg.kind === "literal" && arg.value?.kind === "str") {
|
|
507
|
-
return `<span data-sinth-remove="${esc(arg.value.value)}"></span>`;
|
|
508
|
-
}
|
|
509
|
-
}
|
|
510
|
-
const fnDef = fnName ? ctx.functionDefs.find(f => f.name === fnName) : undefined;
|
|
511
|
-
if (fnDef && fnDef.returnType === "ui") {
|
|
512
|
-
const callArgs = child.expression.args ?? [];
|
|
513
|
-
const localParams = new Map<string, string>();
|
|
514
|
-
for (let i = 0; i < fnDef.params.length && i < callArgs.length; i++) {
|
|
515
|
-
const arg = callArgs[i];
|
|
516
|
-
if (arg.kind === "literal" && arg.value?.kind === "str") {
|
|
517
|
-
localParams.set(fnDef.params[i].name, "__LIT__" + arg.value.value);
|
|
518
|
-
} else if (arg.kind === "variable" && arg.name) {
|
|
519
|
-
localParams.set(fnDef.params[i].name, "__VAR__" + arg.name);
|
|
520
|
-
} else {
|
|
521
|
-
const exprId = registerExpr(ctx, arg);
|
|
522
|
-
localParams.set(fnDef.params[i].name, "__EXPRID__" + exprId);
|
|
523
|
-
}
|
|
524
|
-
}
|
|
525
|
-
const substituteExpr = (expr: Expression, pm: Map<string, string>): Expression => {
|
|
526
|
-
if (expr.kind === "variable" && pm.has(expr.name!)) {
|
|
527
|
-
const pv = pm.get(expr.name!)!;
|
|
528
|
-
if (pv.startsWith("__LIT__")) return { kind: "literal", value: { kind: "str", value: pv.slice(7) } };
|
|
529
|
-
if (pv.startsWith("__EXPRID__")) {
|
|
530
|
-
const id = parseInt(pv.slice(10), 10);
|
|
531
|
-
return { kind: "expr_ref", exprId: id };
|
|
532
|
-
}
|
|
533
|
-
return { kind: "variable", name: pv.slice(7) };
|
|
534
|
-
}
|
|
535
|
-
if (expr.kind === "binary") return { ...expr, left: substituteExpr(expr.left!, pm), right: substituteExpr(expr.right!, pm) };
|
|
536
|
-
if (expr.kind === "unary") return { ...expr, operand: substituteExpr(expr.operand!, pm) };
|
|
537
|
-
if (expr.kind === "call") return { ...expr, callee: substituteExpr(expr.callee!, pm), args: expr.args?.map(a => substituteExpr(a, pm)) };
|
|
538
|
-
if (expr.kind === "index") return { ...expr, object: substituteExpr(expr.object!, pm), key: substituteExpr(expr.key!, pm) };
|
|
539
|
-
if (expr.kind === "assign") {
|
|
540
|
-
const target = expr.target;
|
|
541
|
-
if (target && pm.has(target)) {
|
|
542
|
-
const pv = pm.get(target)!;
|
|
543
|
-
if (pv.startsWith("__VAR__")) {
|
|
544
|
-
return { ...expr, target: pv.slice(7), right: expr.right ? substituteExpr(expr.right, pm) : undefined };
|
|
545
|
-
}
|
|
546
|
-
}
|
|
547
|
-
return { ...expr, right: expr.right ? substituteExpr(expr.right, pm) : undefined };
|
|
548
|
-
}
|
|
549
|
-
return expr;
|
|
550
|
-
};
|
|
551
|
-
const substituteChild = (c: Child, pm: Map<string, string>): Child => {
|
|
552
|
-
if (c.kind === "expr") return { ...c, expression: substituteExpr(c.expression, pm) };
|
|
553
|
-
if (c.kind === "assign_stmt") return { ...c, expression: substituteExpr(c.expression, pm) as Expression };
|
|
554
|
-
if (c.kind === "return" && (c as ReturnStmt).expression) return { ...c, expression: substituteExpr((c as ReturnStmt).expression!, pm) } as Child;
|
|
555
|
-
if (c.kind === "if") {
|
|
556
|
-
const ib = c as IfBlock;
|
|
557
|
-
return { ...ib, condition: substituteExpr(ib.condition, pm), body: ib.body.map(bc => substituteChild(bc, pm)), elseBody: ib.elseBody?.map(bc => substituteChild(bc, pm)) };
|
|
558
|
-
}
|
|
559
|
-
if (c.kind === "for") {
|
|
560
|
-
const fl = c as ForLoop;
|
|
561
|
-
return { ...fl, body: fl.body.map(bc => substituteChild(bc, pm)) };
|
|
562
|
-
}
|
|
563
|
-
if (c.kind === "use") {
|
|
564
|
-
const u = c as CompUse;
|
|
565
|
-
const sa: Attr[] = u.attrs.map(a => {
|
|
566
|
-
if (a.value?.kind === "str") {
|
|
567
|
-
let raw = a.value.value;
|
|
568
|
-
if (raw.startsWith("__EXPR__")) {
|
|
569
|
-
try {
|
|
570
|
-
const expr: Expression = JSON.parse(raw.substring(8));
|
|
571
|
-
const substituted = substituteExpr(expr, pm);
|
|
572
|
-
return { ...a, value: { kind: "str" as const, value: "__EXPR__" + JSON.stringify(substituted) } };
|
|
573
|
-
} catch {}
|
|
574
|
-
}
|
|
575
|
-
if (raw.startsWith("__ACTION_JS__")) {
|
|
576
|
-
return { ...a, value: { kind: "str" as const, value: raw } };
|
|
577
|
-
}
|
|
578
|
-
if (raw.startsWith("__MULTI_EXPR__")) {
|
|
579
|
-
try {
|
|
580
|
-
const exprs: Expression[] = JSON.parse(raw.substring("__MULTI_EXPR__".length));
|
|
581
|
-
const substituted = exprs.map(e => substituteExpr(e, pm));
|
|
582
|
-
return { ...a, value: { kind: "str" as const, value: "__MULTI_EXPR__" + JSON.stringify(substituted) } };
|
|
583
|
-
} catch {}
|
|
584
|
-
}
|
|
585
|
-
for (const [pn, pv] of pm) {
|
|
586
|
-
if (pv.startsWith("__LIT__")) raw = raw.replace(new RegExp(`\\b${pn}\\b`, 'g'), pv.slice(7));
|
|
587
|
-
if (pv.startsWith("__VAR__")) raw = raw.replace(new RegExp(`\\b${pn}\\b`, 'g'), pv.slice(7));
|
|
588
|
-
}
|
|
589
|
-
return { ...a, value: { kind: "str" as const, value: raw } };
|
|
590
|
-
}
|
|
591
|
-
return a;
|
|
592
|
-
});
|
|
593
|
-
return { ...u, attrs: sa, children: u.children.map(cc => substituteChild(cc, pm)) };
|
|
594
|
-
}
|
|
595
|
-
return c;
|
|
596
|
-
};
|
|
597
|
-
return fnDef.body.map(c => renderChild(substituteChild(c, localParams), ctx, localParams, depth + 1)).join("");
|
|
598
|
-
}
|
|
599
|
-
}
|
|
600
|
-
if (child.expression.kind === "expr_ref" && child.expression.exprId !== undefined) {
|
|
601
|
-
return `<span class="sinth-expr" data-expr-id="${child.expression.exprId}"></span>`;
|
|
602
|
-
}
|
|
603
|
-
if (child.expression.kind === "literal" && child.expression.value) {
|
|
604
|
-
return esc(litToString(child.expression.value));
|
|
605
|
-
}
|
|
606
|
-
if (child.expression.kind === "variable" && child.expression.name && !ctx.loopVars?.has(child.expression.name)) {
|
|
607
|
-
const exprId = registerExpr(ctx, child.expression);
|
|
608
|
-
return `<span class="sinth-expr" data-expr-id="${exprId}"${ctx.diffingEnabled ? ` data-sinth-deps="${exprDeps(child.expression, ctx.declaredVars ?? new Set())}"` : ""}></span>`;
|
|
609
|
-
}
|
|
610
|
-
let expr = child.expression;
|
|
611
|
-
if (params.size > 0) {
|
|
612
|
-
expr = substituteParamsInExpr(expr, params);
|
|
613
|
-
}
|
|
614
|
-
const exprId = registerExpr(ctx, expr);
|
|
615
|
-
return `<span class="sinth-expr" data-expr-id="${exprId}"${ctx.diffingEnabled ? ` data-sinth-deps="${exprDeps(child.expression, ctx.declaredVars ?? new Set())}"` : ""}></span>`;
|
|
616
|
-
}
|
|
617
|
-
|
|
618
|
-
case "assign_stmt": {
|
|
619
|
-
ctx.logicBlocks.push(compileExprToJS(child.expression, undefined, ctx.namespace) + ";");
|
|
620
|
-
return "";
|
|
621
|
-
}
|
|
622
|
-
|
|
623
|
-
case "remove": {
|
|
624
|
-
return `<span data-sinth-remove="${esc((child as RemoveStmt).target)}"></span>`;
|
|
625
|
-
}
|
|
626
|
-
|
|
627
|
-
case "return":
|
|
628
|
-
return "";
|
|
629
|
-
|
|
630
|
-
case "var":
|
|
631
|
-
return "";
|
|
632
|
-
|
|
633
|
-
case "if":
|
|
634
|
-
return renderIfBlock(child, ctx, params, depth);
|
|
635
|
-
|
|
636
|
-
case "for": {
|
|
637
|
-
const loopVars = new Set<string>();
|
|
638
|
-
loopVars.add(child.itemVar);
|
|
639
|
-
if (child.keyVar) loopVars.add(child.keyVar);
|
|
640
|
-
if (child.indexVar) loopVars.add(child.indexVar);
|
|
641
|
-
const prev = ctx.loopVars;
|
|
642
|
-
ctx.loopVars = loopVars;
|
|
643
|
-
const bodyHTML = child.body.map(c => renderChild(c, ctx, params, depth + 1)).join("");
|
|
644
|
-
ctx.loopVars = prev;
|
|
645
|
-
const keyAttr = child.keyVar ? ` data-sinth-key="${escAttr(child.keyVar)}"` : "";
|
|
646
|
-
const idxAttr = child.indexVar ? ` data-sinth-index="${escAttr(child.indexVar)}"` : "";
|
|
647
|
-
return (
|
|
648
|
-
`<template data-sinth-for="${escAttr(child.arrayVar)}" data-sinth-item="${escAttr(child.itemVar)}"${keyAttr}${idxAttr}>${bodyHTML}</template>`
|
|
649
|
-
);
|
|
650
|
-
}
|
|
651
|
-
|
|
652
|
-
case "use":
|
|
653
|
-
return renderCompUse(child, ctx, params, depth);
|
|
654
|
-
|
|
655
|
-
case "component_expr":
|
|
656
|
-
return child.children.map(c => renderChild(c, ctx, params, depth + 1)).join("");
|
|
657
|
-
}
|
|
658
|
-
}
|
|
659
|
-
|
|
660
|
-
export function renderIfBlock(
|
|
661
|
-
ifBlock: IfBlock,
|
|
662
|
-
ctx: CompileCtx,
|
|
663
|
-
params: Map<string, string>,
|
|
664
|
-
depth: number,
|
|
665
|
-
): string {
|
|
666
|
-
if (depth > 64) throw new SinthError("Maximum if-block nesting depth (64) exceeded.", ifBlock.loc);
|
|
667
|
-
|
|
668
|
-
const condJS = compileExprToJS(ifBlock.condition, undefined, ctx.namespace, ctx.declaredVars);
|
|
669
|
-
const allChildren = [...ifBlock.body, ...(ifBlock.elseBody ?? [])];
|
|
670
|
-
const hasAssign = allChildren.some(c => c.kind === "assign_stmt");
|
|
671
|
-
const hasComp = allChildren.some(c => c.kind === "use");
|
|
672
|
-
|
|
673
|
-
if (!hasAssign && !hasComp) {
|
|
674
|
-
const tplId = ctx.ifIdCounter++;
|
|
675
|
-
const condId = registerExpr(ctx, ifBlock.condition);
|
|
676
|
-
const bodyHTML = ifBlock.body.map(c => renderChild(c, ctx, params, depth + 1)).join("");
|
|
677
|
-
const elseHTML = (ifBlock.elseBody ?? []).map(c => renderChild(c, ctx, params, depth + 1)).join("");
|
|
678
|
-
const persistAttr = ifBlock.persist ? ` data-sinth-if-persist="true"` : "";
|
|
679
|
-
return (
|
|
680
|
-
`<template data-sinth-if-id="${tplId}" data-sinth-if-expr="${condId}"${persistAttr}>${bodyHTML}</template>` +
|
|
681
|
-
(elseHTML ? `<template data-sinth-else data-sinth-if-id="${tplId}">${elseHTML}</template>` : "")
|
|
682
|
-
);
|
|
683
|
-
}
|
|
684
|
-
|
|
685
|
-
// pure logic
|
|
686
|
-
if (hasAssign && !hasComp) {
|
|
687
|
-
ctx.logicBlocks.push(compileIfToJS(ifBlock));
|
|
688
|
-
return "";
|
|
689
|
-
}
|
|
690
|
-
|
|
691
|
-
// pure DOM (components need replace/persist/delay handling)
|
|
692
|
-
if (!hasAssign && hasComp) {
|
|
693
|
-
const tplId = ctx.ifIdCounter++;
|
|
694
|
-
const condId = registerExpr(ctx, ifBlock.condition);
|
|
695
|
-
const bodyHTML = ifBlock.body.map(c => renderChild(c, ctx, params, depth + 1)).join("");
|
|
696
|
-
const elseHTML = (ifBlock.elseBody ?? []).map(c => renderChild(c, ctx, params, depth + 1)).join("");
|
|
697
|
-
let replaceAttr = "";
|
|
698
|
-
let persistAttr = (ifBlock.persist || hasComp) ? ` data-sinth-if-persist="true"` : "";
|
|
699
|
-
const firstComp = ifBlock.body.find(c => c.kind === "use") as CompUse | undefined;
|
|
700
|
-
if (firstComp) {
|
|
701
|
-
const idAttr = firstComp.attrs.find(a => a.name === "id");
|
|
702
|
-
const replAttr = firstComp.attrs.find(a => a.name === "replace");
|
|
703
|
-
const wantsReplace = replAttr && (replAttr.value === null || (replAttr.value?.kind === "bool" && replAttr.value.value));
|
|
704
|
-
if (idAttr && idAttr.value?.kind === "str" && wantsReplace) {
|
|
705
|
-
replaceAttr = ` data-sinth-if-replace="${escAttr(idAttr.value.value)}"`;
|
|
706
|
-
}
|
|
707
|
-
}
|
|
708
|
-
let delayAttr = "";
|
|
709
|
-
let delayHideAttr = "";
|
|
710
|
-
if (firstComp) {
|
|
711
|
-
const delayA = firstComp.attrs.find(a => a.name === "delay");
|
|
712
|
-
const hideA = firstComp.attrs.find(a => a.name === "hide");
|
|
713
|
-
if (delayA && hideA && hideA.value && (hideA.value as any).kind === "bool" && !(hideA.value as any).value) {
|
|
714
|
-
if (delayA.value?.kind === "num") {
|
|
715
|
-
delayAttr = ` data-sinth-if-delay="${delayA.value.value}"`;
|
|
716
|
-
} else if (delayA.value?.kind === "str") {
|
|
717
|
-
const v = litToString(delayA.value);
|
|
718
|
-
if (/^\d+$/.test(v)) delayAttr = ` data-sinth-if-delay="${v}"`;
|
|
719
|
-
}
|
|
720
|
-
delayHideAttr = ` data-sinth-if-delay-hide="false"`;
|
|
721
|
-
}
|
|
722
|
-
}
|
|
723
|
-
let elseDelayAttr = "";
|
|
724
|
-
let elseDelayHideAttr = "";
|
|
725
|
-
const elseFirstComp = (ifBlock.elseBody ?? []).find(c => c.kind === "use") as CompUse | undefined;
|
|
726
|
-
if (elseFirstComp) {
|
|
727
|
-
const delayA = elseFirstComp.attrs.find(a => a.name === "delay");
|
|
728
|
-
const hideA = elseFirstComp.attrs.find(a => a.name === "hide");
|
|
729
|
-
if (delayA && hideA && hideA.value && (hideA.value as any).kind === "bool" && !(hideA.value as any).value) {
|
|
730
|
-
if (delayA.value?.kind === "num") {
|
|
731
|
-
elseDelayAttr = ` data-sinth-if-delay="${delayA.value.value}"`;
|
|
732
|
-
} else if (delayA.value?.kind === "str") {
|
|
733
|
-
const v = litToString(delayA.value);
|
|
734
|
-
if (/^\d+$/.test(v)) elseDelayAttr = ` data-sinth-if-delay="${v}"`;
|
|
735
|
-
}
|
|
736
|
-
elseDelayHideAttr = ` data-sinth-if-delay-hide="false"`;
|
|
737
|
-
}
|
|
738
|
-
}
|
|
739
|
-
return (
|
|
740
|
-
`<template data-sinth-if-id="${tplId}" data-sinth-if-expr="${condId}"${replaceAttr}${delayAttr}${delayHideAttr}${persistAttr}>${bodyHTML}</template>` +
|
|
741
|
-
(elseHTML ? `<template data-sinth-else data-sinth-if-id="${tplId}"${elseDelayAttr}${elseDelayHideAttr}>${elseHTML}</template>` : "")
|
|
742
|
-
);
|
|
743
|
-
}
|
|
744
|
-
|
|
745
|
-
// mixed
|
|
746
|
-
const id = `__sm${ctx.mixedCounter++}__`;
|
|
747
|
-
|
|
748
|
-
const ifAssignJS = ifBlock.body
|
|
749
|
-
.filter(c => c.kind === "assign_stmt")
|
|
750
|
-
.map(c => {
|
|
751
|
-
const e = (c as AssignStmt).expression;
|
|
752
|
-
const js = compileExprToJS(e, undefined, ctx.namespace);
|
|
753
|
-
let bump = "";
|
|
754
|
-
if (ctx.diffingEnabled && e.kind === "assign" && e.target) {
|
|
755
|
-
bump = `;window._bump&&window._bump('${e.target.replace(/'/g, "\\'")}')`;
|
|
756
|
-
}
|
|
757
|
-
return ` ${js};${bump}`;
|
|
758
|
-
})
|
|
759
|
-
.join("\n");
|
|
760
|
-
|
|
761
|
-
const ifHTML = ifBlock.body
|
|
762
|
-
.filter(c => c.kind !== "assign_stmt")
|
|
763
|
-
.map(c => renderChild(c, ctx, params, depth + 1))
|
|
764
|
-
.join("");
|
|
765
|
-
|
|
766
|
-
const elseAssignJS = (ifBlock.elseBody ?? [])
|
|
767
|
-
.filter(c => c.kind === "assign_stmt")
|
|
768
|
-
.map(c => {
|
|
769
|
-
const e = (c as AssignStmt).expression;
|
|
770
|
-
const js = compileExprToJS(e, undefined, ctx.namespace);
|
|
771
|
-
let bump = "";
|
|
772
|
-
if (ctx.diffingEnabled && e.kind === "assign" && e.target) {
|
|
773
|
-
bump = `;window._bump&&window._bump('${e.target.replace(/'/g, "\\'")}')`;
|
|
774
|
-
}
|
|
775
|
-
return ` ${js};${bump}`;
|
|
776
|
-
})
|
|
777
|
-
.join("\n");
|
|
778
|
-
|
|
779
|
-
const elseHTML = (ifBlock.elseBody ?? [])
|
|
780
|
-
.filter(c => c.kind !== "assign_stmt")
|
|
781
|
-
.map(c => renderChild(c, ctx, params, depth + 1))
|
|
782
|
-
.join("");
|
|
783
|
-
|
|
784
|
-
let replaceId: string | undefined;
|
|
785
|
-
const ifFirstComp = ifBlock.body.find(c => c.kind === "use") as CompUse | undefined;
|
|
786
|
-
const elseFirstComp = (ifBlock.elseBody ?? []).find(c => c.kind === "use") as CompUse | undefined;
|
|
787
|
-
if (ifFirstComp) {
|
|
788
|
-
const ifId = ifFirstComp.attrs.find(a => a.name === "id")?.value;
|
|
789
|
-
const ifReplace = ifFirstComp.attrs.find(a => a.name === "replace");
|
|
790
|
-
const ifReplaceVal = ifReplace?.value;
|
|
791
|
-
const ifWantsReplace = ifReplace && (ifReplaceVal === null || (ifReplaceVal?.kind === "bool" && ifReplaceVal.value));
|
|
792
|
-
|
|
793
|
-
if (ifId && ifId.kind === "str" && ifWantsReplace) {
|
|
794
|
-
if (elseFirstComp) {
|
|
795
|
-
const elseId = elseFirstComp.attrs.find(a => a.name === "id")?.value;
|
|
796
|
-
const elseReplace = elseFirstComp.attrs.find(a => a.name === "replace");
|
|
797
|
-
const elseReplaceVal = elseReplace?.value;
|
|
798
|
-
const elseWantsReplace = elseReplace && (elseReplaceVal === null || (elseReplaceVal?.kind === "bool" && elseReplaceVal.value));
|
|
799
|
-
|
|
800
|
-
if (elseId && elseId.kind === "str" && elseId.value === ifId.value && elseWantsReplace) {
|
|
801
|
-
replaceId = ifId.value;
|
|
802
|
-
}
|
|
803
|
-
}
|
|
804
|
-
}
|
|
805
|
-
}
|
|
806
|
-
|
|
807
|
-
const condId = registerExpr(ctx, ifBlock.condition);
|
|
808
|
-
|
|
809
|
-
const hasFullscreen = ifHTML.includes("data-sinth-fullscreen") || elseHTML.includes("data-sinth-fullscreen");
|
|
810
|
-
|
|
811
|
-
ctx.mixedBlocks.push({ id, conditionJS: String(condId), ifJS: ifAssignJS, ifHTML, elseJS: elseAssignJS, elseHTML, replaceId });
|
|
812
|
-
|
|
813
|
-
if (hasFullscreen) {
|
|
814
|
-
return `<span id="${replaceId || id}" data-sinth-mixed data-sinth-mixed-fullscreen="${condId}"></span>`;
|
|
815
|
-
}
|
|
816
|
-
return `<span id="${replaceId || id}" data-sinth-mixed></span>`;
|
|
817
|
-
}
|
|
818
|
-
|
|
819
|
-
export function renderCompUse(
|
|
820
|
-
use: CompUse,
|
|
821
|
-
ctx: CompileCtx,
|
|
822
|
-
params: Map<string, string>,
|
|
823
|
-
depth: number,
|
|
824
|
-
): string {
|
|
825
|
-
const renderFn = ctx.namespace ? "sinthRender_" + ctx.namespace : "sinthRender";
|
|
826
|
-
if (use.name === "__IF_ROOT__") {
|
|
827
|
-
return use.children.map(c => renderChild(c, ctx, params, depth)).join("");
|
|
828
|
-
}
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
if (use.name === "RawHTML") {
|
|
832
|
-
const ca = use.attrs.find(a => a.name === "content");
|
|
833
|
-
if (!ca || !ca.value) return "";
|
|
834
|
-
return interpolateAttr(litToString(ca.value), params);
|
|
835
|
-
}
|
|
836
|
-
|
|
837
|
-
// user-defined component
|
|
838
|
-
const userDef = ctx.allDefs.get(use.name);
|
|
839
|
-
if (userDef) return expandUserComp(use, userDef, ctx, params, depth + 1);
|
|
840
|
-
|
|
841
|
-
// custom element
|
|
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
|
-
// }
|
|
853
|
-
|
|
854
|
-
// built-in component
|
|
855
|
-
const { tag, defaultClass, voidEl } = resolveBuiltinTag(use.name, use.attrs);
|
|
856
|
-
const isVoid = voidEl || VOID_TAGS.has(tag);
|
|
857
|
-
|
|
858
|
-
let attrParts: string[] = [`data-s="${ctx.scopeHash}"`];
|
|
859
|
-
let userClass: string | undefined;
|
|
860
|
-
const inlineStyleParts: string[] = [];
|
|
861
|
-
|
|
862
|
-
for (const attr of use.attrs) {
|
|
863
|
-
if (attr.name === "level" && use.name === "Heading") continue;
|
|
864
|
-
|
|
865
|
-
if (INLINE_STYLE_PROPS.has(attr.name) && attr.value) {
|
|
866
|
-
if (attr.value.kind === "str" && attr.value.value.startsWith("__EXPR__")) {
|
|
867
|
-
try {
|
|
868
|
-
const expr: Expression = JSON.parse(attr.value.value.substring(8));
|
|
869
|
-
const exprId = registerExpr(ctx, expr);
|
|
870
|
-
inlineStyleParts.push(`${camelToKebab(attr.name)}:__EXPR__${exprId}`);
|
|
871
|
-
} catch {
|
|
872
|
-
inlineStyleParts.push(`${camelToKebab(attr.name)}: ${interpolateAttr(attr.value.value, params)}`);
|
|
873
|
-
}
|
|
874
|
-
} else {
|
|
875
|
-
const val = attr.value.kind === "str"
|
|
876
|
-
? interpolateAttr(attr.value.value, params)
|
|
877
|
-
: litToString(attr.value);
|
|
878
|
-
inlineStyleParts.push(`${camelToKebab(attr.name)}: ${val}`);
|
|
879
|
-
}
|
|
880
|
-
continue;
|
|
881
|
-
}
|
|
882
|
-
|
|
883
|
-
if (attr.name === "class") {
|
|
884
|
-
if (attr.value?.kind === "str") userClass = interpolateAttr(attr.value.value, params);
|
|
885
|
-
continue;
|
|
886
|
-
}
|
|
887
|
-
if (use.name === "Checkbox" && (attr.name === "checked" || attr.name === "onChange" || attr.name === "label")) continue;
|
|
888
|
-
if (attr.name === "hide") {
|
|
889
|
-
const rendered = renderAttr(attr, params, ctx);
|
|
890
|
-
if (rendered) attrParts.push(rendered);
|
|
891
|
-
continue;
|
|
892
|
-
}
|
|
893
|
-
const rendered = renderAttr(attr, params, ctx);
|
|
894
|
-
if (rendered) attrParts.push(rendered);
|
|
895
|
-
}
|
|
896
|
-
|
|
897
|
-
const classes = [defaultClass, userClass].filter(Boolean).join(" ");
|
|
898
|
-
if (classes) attrParts.push(`class="${escAttr(classes)}"`);
|
|
899
|
-
if (inlineStyleParts.length > 0) {
|
|
900
|
-
const staticParts: string[] = [];
|
|
901
|
-
const exprParts: string[] = [];
|
|
902
|
-
for (const p of inlineStyleParts) {
|
|
903
|
-
if (p.includes(':__EXPR__')) {
|
|
904
|
-
exprParts.push(p.replace('__EXPR__', ''));
|
|
905
|
-
} else {
|
|
906
|
-
staticParts.push(p);
|
|
907
|
-
}
|
|
908
|
-
}
|
|
909
|
-
if (staticParts.length > 0) attrParts.push(`style="${escAttr(staticParts.join("; "))}"`);
|
|
910
|
-
if (exprParts.length > 0) attrParts.push(`data-sinth-style="${escAttr(exprParts.join(";"))}"`);
|
|
911
|
-
}
|
|
912
|
-
if (tag === "button" && !use.attrs.some(a => a.name === "type")) attrParts.push(`type="button"`);
|
|
913
|
-
|
|
914
|
-
const delayAttrVal = use.attrs.find(a => a.name === "delay");
|
|
915
|
-
if (delayAttrVal) {
|
|
916
|
-
const delayMs = delayAttrVal.value?.kind === "num" ? delayAttrVal.value.value : 1000;
|
|
917
|
-
const eventNames = ["onClick", "onChange", "onInput", "onSubmit"];
|
|
918
|
-
let hasEvent = false;
|
|
919
|
-
for (const en of eventNames) {
|
|
920
|
-
const evName = en.toLowerCase();
|
|
921
|
-
const idx = attrParts.findIndex(p => p.startsWith(evName + "="));
|
|
922
|
-
if (idx >= 0) {
|
|
923
|
-
hasEvent = true;
|
|
924
|
-
const current = attrParts[idx];
|
|
925
|
-
const match = current.match(/\(function\(\)\{\s*(.+?);\s*sinthRender\(\)/);
|
|
926
|
-
if (match) {
|
|
927
|
-
const action = match[1];
|
|
928
|
-
const qid = `__sq${ctx.ifIdCounter++}`;
|
|
929
|
-
const hideAttr = use.attrs.find(a => a.name === "hide");
|
|
930
|
-
const hideVal = hideAttr
|
|
931
|
-
? (hideAttr.value === null
|
|
932
|
-
? true
|
|
933
|
-
: (hideAttr.value.kind === "bool"
|
|
934
|
-
? hideAttr.value.value
|
|
935
|
-
: (hideAttr.value.kind === "str" && hideAttr.value.value !== "false")))
|
|
936
|
-
: true;
|
|
937
|
-
ctx.actionButtons.push({ qid, delayMs, hide: hideVal });
|
|
938
|
-
const delayIdx = attrParts.findIndex(p => p.startsWith("data-sinth-delay"));
|
|
939
|
-
if (delayIdx >= 0) attrParts.splice(delayIdx, 1);
|
|
940
|
-
const hideIdx = attrParts.findIndex(p => p.startsWith("data-sinth-delay-hide"));
|
|
941
|
-
if (hideIdx >= 0) attrParts.splice(hideIdx, 1);
|
|
942
|
-
const doneIdx = attrParts.findIndex(p => p.startsWith("data-sinth-delay-done"));
|
|
943
|
-
if (doneIdx >= 0) attrParts.splice(doneIdx, 1);
|
|
944
|
-
attrParts.push(`data-sinth-queue-id="${qid}"`);
|
|
945
|
-
if (hideVal) {
|
|
946
|
-
attrParts.push(`style="display:none"`);
|
|
947
|
-
}
|
|
948
|
-
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}; ${renderFn}(); }); 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); } })()`)}"`;
|
|
949
|
-
}
|
|
950
|
-
}
|
|
951
|
-
}
|
|
952
|
-
if (!hasEvent) {
|
|
953
|
-
if (use.attrs.some(a => a.name === "hide")) {
|
|
954
|
-
const hideAttr = use.attrs.find(a => a.name === "hide")!;
|
|
955
|
-
const hideVal = hideAttr.value;
|
|
956
|
-
const isHidden = (hideVal === null) ||
|
|
957
|
-
(hideVal?.kind === "bool" && hideVal.value) ||
|
|
958
|
-
(hideVal?.kind === "str" && hideVal.value !== "false");
|
|
959
|
-
attrParts.push(`data-sinth-delay-hide="${isHidden ? "true" : "false"}"`);
|
|
960
|
-
if (!isHidden) {
|
|
961
|
-
attrParts.push(`data-sinth-delay-done="1"`);
|
|
962
|
-
}
|
|
963
|
-
} else {
|
|
964
|
-
attrParts.push(`data-sinth-delay-hide="true"`);
|
|
965
|
-
}
|
|
966
|
-
}
|
|
967
|
-
}
|
|
968
|
-
if (use.name === "Input") {
|
|
969
|
-
const bindAttr = use.attrs.find(a => a.name === "bind");
|
|
970
|
-
const modelAttr = use.attrs.find(a => a.name === "model");
|
|
971
|
-
const bindOrModel = bindAttr || modelAttr;
|
|
972
|
-
if (bindOrModel?.value?.kind === "str") {
|
|
973
|
-
let vName = bindOrModel.value.value;
|
|
974
|
-
if (vName.startsWith("__EXPR__")) {
|
|
975
|
-
try {
|
|
976
|
-
const expr: Expression = JSON.parse(vName.substring(8));
|
|
977
|
-
if (expr.kind === "variable" && expr.name) vName = expr.name;
|
|
978
|
-
} catch {}
|
|
979
|
-
}
|
|
980
|
-
const varDecl = ctx.varDecls?.find(v => v.name === vName);
|
|
981
|
-
if (!use.attrs.some(a => a.name === "type")) {
|
|
982
|
-
if (varDecl && varDecl.varType === "int") {
|
|
983
|
-
attrParts.push(`type="number"`);
|
|
984
|
-
} else {
|
|
985
|
-
attrParts.push(`type="text"`);
|
|
986
|
-
}
|
|
987
|
-
}
|
|
988
|
-
if (varDecl && varDecl.varType === "int" && !use.attrs.some(a => a.name === "step")) {
|
|
989
|
-
attrParts.push(`step="1"`);
|
|
990
|
-
}
|
|
991
|
-
const rhs = (varDecl && varDecl.varType === "int")
|
|
992
|
-
? `Number(e.target.value) || 0`
|
|
993
|
-
: `e.target.value`;
|
|
994
|
-
const initialVal = varDecl?.value ? litToString(varDecl.value).replace(/"/g, '"') : "";
|
|
995
|
-
let resolvedName = vName;
|
|
996
|
-
if (ctx.scopePrefix && ctx.scopeVar && ctx.varDecls?.some(v => v.name === vName)) {
|
|
997
|
-
resolvedName = `${ctx.scopePrefix}${vName}`;
|
|
998
|
-
}
|
|
999
|
-
if (ctx.namespace) resolvedName = ctx.namespace + "_" + resolvedName;
|
|
1000
|
-
const renderCall = ctx.scopeVar ? `${ctx.scopeVar}._render()` : renderFn + "()";
|
|
1001
|
-
const handlerBody = `${resolvedName} = ${rhs}; ${renderCall}`;
|
|
1002
|
-
if (ctx.scopePrefix) {
|
|
1003
|
-
attrParts.push(emitCEAction(ctx, 'input', handlerBody));
|
|
1004
|
-
} else {
|
|
1005
|
-
attrParts.push(`oninput="(function(e){ ${handlerBody} })(event)"`);
|
|
1006
|
-
}
|
|
1007
|
-
attrParts.push(`value="${escAttr(initialVal)}"`);
|
|
1008
|
-
const valueExprId = registerExpr(ctx, { kind: "variable", name: vName });
|
|
1009
|
-
attrParts.push(`data-sinth-value="${valueExprId}"`);
|
|
1010
|
-
}
|
|
1011
|
-
}
|
|
1012
|
-
if (use.name === "Checkbox") {
|
|
1013
|
-
if (!use.attrs.some(a => a.name === "type")) attrParts.push(`type="checkbox"`);
|
|
1014
|
-
|
|
1015
|
-
const checkedAttr = use.attrs.find(a => a.name === "checked");
|
|
1016
|
-
const onChangeAttr = use.attrs.find(a => a.name === "onChange");
|
|
1017
|
-
|
|
1018
|
-
// Resolve bound variable name (same pattern as Input's bind/model)
|
|
1019
|
-
let boundVarName: string | null = null;
|
|
1020
|
-
if (checkedAttr && checkedAttr.value?.kind === "str") {
|
|
1021
|
-
let raw = checkedAttr.value.value;
|
|
1022
|
-
if (raw.startsWith("__EXPR__")) {
|
|
1023
|
-
try {
|
|
1024
|
-
const expr: Expression = JSON.parse(raw.substring(8));
|
|
1025
|
-
if (expr.kind === "variable" && expr.name) {
|
|
1026
|
-
boundVarName = expr.name;
|
|
1027
|
-
}
|
|
1028
|
-
} catch {}
|
|
1029
|
-
} else if (raw.match(/^[a-zA-Z_][a-zA-Z0-9_]*$/)) {
|
|
1030
|
-
boundVarName = raw;
|
|
1031
|
-
}
|
|
1032
|
-
}
|
|
1033
|
-
|
|
1034
|
-
let resolvedName = boundVarName;
|
|
1035
|
-
if (resolvedName && ctx.scopePrefix && ctx.scopeVar && ctx.varDecls?.some(v => v.name === resolvedName)) {
|
|
1036
|
-
resolvedName = `${ctx.scopePrefix}${resolvedName}`;
|
|
1037
|
-
}
|
|
1038
|
-
if (resolvedName && ctx.namespace) resolvedName = ctx.namespace + "_" + resolvedName;
|
|
1039
|
-
|
|
1040
|
-
if (checkedAttr && checkedAttr.value) {
|
|
1041
|
-
if (checkedAttr.value.kind === "bool") {
|
|
1042
|
-
if (checkedAttr.value.value) attrParts.push(`checked`);
|
|
1043
|
-
} else if (checkedAttr.value.kind === "str" && boundVarName) {
|
|
1044
|
-
const checkedExprId = registerExpr(ctx, { kind: "variable", name: boundVarName });
|
|
1045
|
-
attrParts.push(`data-sinth-checked="${checkedExprId}"`);
|
|
1046
|
-
}
|
|
1047
|
-
}
|
|
1048
|
-
|
|
1049
|
-
if (onChangeAttr && onChangeAttr.value?.kind === "str") {
|
|
1050
|
-
let raw = onChangeAttr.value.value;
|
|
1051
|
-
if (raw.startsWith("__EXPR__")) {
|
|
1052
|
-
try {
|
|
1053
|
-
const expr: Expression = JSON.parse(raw.substring(8));
|
|
1054
|
-
const jsExpr = compileExprToJS(expr, undefined, ctx.namespace);
|
|
1055
|
-
attrParts.push(`onchange="(function(){ ${jsExpr}; ${renderFn}(); })(event)"`);
|
|
1056
|
-
} catch {}
|
|
1057
|
-
} else {
|
|
1058
|
-
attrParts.push(`onchange="${escAttr(raw)};${renderFn}()"`);
|
|
1059
|
-
}
|
|
1060
|
-
} else if (!onChangeAttr && resolvedName) {
|
|
1061
|
-
attrParts.push(`onchange="(function(e){ ${resolvedName} = e.target.checked; ${renderFn}(); })(event)"`);
|
|
1062
|
-
}
|
|
1063
|
-
|
|
1064
|
-
const labelAttr = use.attrs.find(a => a.name === "label");
|
|
1065
|
-
const labelText = labelAttr?.value?.kind === "str" ? esc(interpolateAttr(labelAttr.value.value, params)) : "";
|
|
1066
|
-
|
|
1067
|
-
if (labelText) {
|
|
1068
|
-
const checkAttrStr = attrParts.length ? " " + attrParts.join(" ") : "";
|
|
1069
|
-
return `<label data-s="${ctx.scopeHash}"><input${checkAttrStr}> ${labelText}</label>`;
|
|
1070
|
-
}
|
|
1071
|
-
}
|
|
1072
|
-
|
|
1073
|
-
attrParts = attrParts.filter(p => !p.startsWith("bind="));
|
|
1074
|
-
const attrStr = attrParts.length ? " " + attrParts.join(" ") : "";
|
|
1075
|
-
|
|
1076
|
-
if (isVoid) {
|
|
1077
|
-
if (use.children.length > 0) SinthWarning.emit(`<${tag}> is void and cannot have children.`, use.loc);
|
|
1078
|
-
return `<${tag}${attrStr}>`;
|
|
1079
|
-
}
|
|
1080
|
-
|
|
1081
|
-
const inner = use.children.map(c => renderChild(c, ctx, params, depth + 1)).join("");
|
|
1082
|
-
return `<${tag}${attrStr}>${inner}</${tag}>`;
|
|
1083
|
-
}
|
|
1084
|
-
|
|
1085
|
-
export function expandUserComp(
|
|
1086
|
-
use: CompUse,
|
|
1087
|
-
def: CompDef,
|
|
1088
|
-
ctx: CompileCtx,
|
|
1089
|
-
params: Map<string, string>,
|
|
1090
|
-
depth: number,
|
|
1091
|
-
): string {
|
|
1092
|
-
if (use.name === def.name && depth > 4) {
|
|
1093
|
-
throw new SinthError(`Recursive component '${def.name}' is not allowed.`, use.loc);
|
|
1094
|
-
}
|
|
1095
|
-
|
|
1096
|
-
const local = new Map<string, string>();
|
|
1097
|
-
|
|
1098
|
-
for (const p of def.params) {
|
|
1099
|
-
if (p.defaultVal !== undefined) local.set(p.name, litToString(p.defaultVal));
|
|
1100
|
-
}
|
|
1101
|
-
|
|
1102
|
-
for (const attr of use.attrs) {
|
|
1103
|
-
if (attr.value === null) {
|
|
1104
|
-
local.set(attr.name, "true");
|
|
1105
|
-
} else if (attr.value.kind !== "null") {
|
|
1106
|
-
const raw = litToString(attr.value);
|
|
1107
|
-
if (raw.startsWith("__EXPR__")) {
|
|
1108
|
-
local.set(attr.name, raw);
|
|
1109
|
-
} else {
|
|
1110
|
-
local.set(attr.name, attr.value.kind === "str" ? interpolateAttr(raw, params) : raw);
|
|
1111
|
-
}
|
|
1112
|
-
}
|
|
1113
|
-
}
|
|
1114
|
-
|
|
1115
|
-
for (const p of def.params) {
|
|
1116
|
-
if (!local.has(p.name)) {
|
|
1117
|
-
throw new SinthError(
|
|
1118
|
-
`Component '${def.name}' requires parameter '${p.name}' but it was not provided.`,
|
|
1119
|
-
use.loc,
|
|
1120
|
-
);
|
|
1121
|
-
}
|
|
1122
|
-
}
|
|
1123
|
-
|
|
1124
|
-
const slotHTML = use.children.map(c => renderChild(c, ctx, params, depth)).join("");
|
|
1125
|
-
local.set("slot", "__RAW__" + slotHTML);
|
|
1126
|
-
|
|
1127
|
-
for (const block of def.styles) {
|
|
1128
|
-
ctx.extraCSS.push(processStyleBlock(block, ctx.scopeHash, local));
|
|
1129
|
-
}
|
|
1130
|
-
|
|
1131
|
-
return def.body.map(c => renderChild(c, ctx, local, depth)).join("");
|
|
1132
|
-
}
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
export function collectScripts(
|
|
1137
|
-
file: SinthFile,
|
|
1138
|
-
allDefs: Map<string, CompDef>,
|
|
1139
|
-
): { componentScripts: string[]; pageScripts: { raw: string; attrs: Record<string, string> }[] } {
|
|
1140
|
-
const componentScripts: string[] = [];
|
|
1141
|
-
const pageScripts: { raw: string; attrs: Record<string, string> }[] = [];
|
|
1142
|
-
const seenFunctions = new Set<string>();
|
|
1143
|
-
|
|
1144
|
-
for (const [, def] of allDefs) {
|
|
1145
|
-
for (const block of def.scripts) {
|
|
1146
|
-
for (const fn of extractFunctionNames(block.raw)) {
|
|
1147
|
-
if (seenFunctions.has(fn)) throw new SinthError(`Function '${fn}' defined in multiple component scripts.`);
|
|
1148
|
-
seenFunctions.add(fn);
|
|
1149
|
-
}
|
|
1150
|
-
componentScripts.push(`(function(){\n${block.raw}\n})();`);
|
|
1151
|
-
}
|
|
1152
|
-
}
|
|
1153
|
-
|
|
1154
|
-
for (const block of file.scripts) {
|
|
1155
|
-
for (const fn of extractFunctionNames(block.raw)) {
|
|
1156
|
-
if (seenFunctions.has(fn)) throw new SinthError(`Function '${fn}' conflicts with a component script.`);
|
|
1157
|
-
seenFunctions.add(fn);
|
|
1158
|
-
}
|
|
1159
|
-
pageScripts.push({ raw: block.raw, attrs: block.attrs });
|
|
1160
|
-
}
|
|
1161
|
-
|
|
1162
|
-
return { componentScripts, pageScripts };
|
|
1163
|
-
}
|
|
1164
|
-
|
|
1165
|
-
export function extractFunctionNames(js: string): string[] {
|
|
1166
|
-
const names: string[] = [];
|
|
1167
|
-
const re = /^\s*(?:async\s+)?function\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/gm;
|
|
1168
|
-
let m: RegExpExecArray | null;
|
|
1169
|
-
while ((m = re.exec(js)) !== null) names.push(m[1]);
|
|
1170
|
-
return names;
|
|
1171
|
-
}
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
// sinth runtime
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
export function buildRuntime(opts: {
|
|
1180
|
-
varDecls: VarDeclaration[];
|
|
1181
|
-
bodyHTML: string;
|
|
1182
|
-
logicBlocks: string[];
|
|
1183
|
-
mixedBlocks: MixedBlockEntry[];
|
|
1184
|
-
assignedVars: Set<string>;
|
|
1185
|
-
exprRegistry: string[];
|
|
1186
|
-
sharedRuntime: boolean;
|
|
1187
|
-
functionsJS: string;
|
|
1188
|
-
namespace?: string;
|
|
1189
|
-
}): string | { page: string; shared: string } {
|
|
1190
|
-
|
|
1191
|
-
const { varDecls, bodyHTML, logicBlocks, mixedBlocks, assignedVars, exprRegistry, functionsJS } = opts;
|
|
1192
|
-
const ns = opts.namespace ? "_" + opts.namespace : "";
|
|
1193
|
-
const renderFn = "sinthRender" + ns;
|
|
1194
|
-
const needsMixed = mixedBlocks.length > 0;
|
|
1195
|
-
const needsExpr = bodyHTML.includes("sinth-expr") || needsMixed;
|
|
1196
|
-
const needsIf = bodyHTML.includes("data-sinth-if") || needsMixed;
|
|
1197
|
-
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"));
|
|
1198
|
-
const needsLogic = logicBlocks.length > 0;
|
|
1199
|
-
const needsFullscreen = bodyHTML.includes("data-sinth-fullscreen");
|
|
1200
|
-
const needsFullscreenSync = bodyHTML.includes("data-sinth-fullscreen-sync");
|
|
1201
|
-
const needsRender = needsExpr || needsIf || needsFor || needsMixed || needsLogic || bodyHTML.includes("data-sinth-hide") || needsFullscreen || needsFullscreenSync || needsDelay;
|
|
1202
|
-
|
|
1203
|
-
const varLines = varDecls.map(v => {
|
|
1204
|
-
const vn = ns ? ns.slice(1) + "_" + v.name : v.name;
|
|
1205
|
-
if (!v.value) {
|
|
1206
|
-
if (!assignedVars.has(v.name)) {
|
|
1207
|
-
const defaults: Record<string, string> = { str: '""', int: "0", bool: "false", "str[]": "[]" };
|
|
1208
|
-
SinthWarning.emit(
|
|
1209
|
-
`Variable '${v.name}' is declared but never assigned. Defaulting to ${defaults[v.varType] ?? "undefined"}.`,
|
|
1210
|
-
v.loc,
|
|
1211
|
-
);
|
|
1212
|
-
}
|
|
1213
|
-
const defaults: Record<string, string> = { str: '""', int: "0", bool: "false", "str[]": "[]" };
|
|
1214
|
-
return `var ${vn} = ${defaults[v.varType] ?? "undefined"};`;
|
|
1215
|
-
}
|
|
1216
|
-
const val = litToString(v.value);
|
|
1217
|
-
if (val.startsWith("__VAR__")) return `var ${vn} = ${val.slice(7)};`;
|
|
1218
|
-
if (val.startsWith("__ARR__")) return `var ${vn} = ${val.slice(7)};`;
|
|
1219
|
-
if (val.startsWith("__EXPR__")) {
|
|
1220
|
-
try {
|
|
1221
|
-
const expr: Expression = JSON.parse(val.substring(8));
|
|
1222
|
-
const js = compileExprToJS(expr);
|
|
1223
|
-
const id = exprRegistry.length;
|
|
1224
|
-
exprRegistry.push(js);
|
|
1225
|
-
return `var ${vn} = __X${ns}[${id}]({});`;
|
|
1226
|
-
} catch { return `var ${vn} = ${val};`; }
|
|
1227
|
-
}
|
|
1228
|
-
if (v.varType === "obj") return `var ${vn} = ${val};`;
|
|
1229
|
-
if (v.varType === "str") return `var ${vn} = ${JSON.stringify(val)};`;
|
|
1230
|
-
if (v.varType === "str[]" && typeof val === 'string' && val.startsWith("__ARR__")) {
|
|
1231
|
-
try {
|
|
1232
|
-
const arr = JSON.parse(val.slice(7));
|
|
1233
|
-
return `var ${vn} = ${JSON.stringify(arr)};`;
|
|
1234
|
-
} catch { return `var ${vn} = ${val.slice(7)};`; }
|
|
1235
|
-
}
|
|
1236
|
-
return `var ${vn} = ${val};`;
|
|
1237
|
-
}).join("\n");
|
|
1238
|
-
|
|
1239
|
-
const memoVars = new Set<string>();
|
|
1240
|
-
for (const lb of logicBlocks) {
|
|
1241
|
-
let matches = lb.match(/_memo_(\w+)/g);
|
|
1242
|
-
if (matches) matches.forEach(m => memoVars.add(m));
|
|
1243
|
-
matches = lb.match(/_memo_(\w+)_done/g);
|
|
1244
|
-
if (matches) matches.forEach(m => memoVars.add(m));
|
|
1245
|
-
}
|
|
1246
|
-
for (const e of exprRegistry) {
|
|
1247
|
-
let matches = e.match(/_memo_(\w+)/g);
|
|
1248
|
-
if (matches) matches.forEach(m => memoVars.add(m));
|
|
1249
|
-
}
|
|
1250
|
-
const memoVarDecls = [...memoVars].map(m => `var ${m};`).join("\n");
|
|
1251
|
-
|
|
1252
|
-
if (!needsRender) {
|
|
1253
|
-
const out = [varLines, memoVarDecls].filter(Boolean).join("\n");
|
|
1254
|
-
return out ? `// Sinth compiled runtime\n${out}` : "";
|
|
1255
|
-
}
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
const helpers = generateHelpers({ needsExpr, needsIf, needsFor, needsDelay, needsMixed, ns });
|
|
1259
|
-
|
|
1260
|
-
const exprVarUpdates = varDecls
|
|
1261
|
-
.filter(v => v.value && litToString(v.value).startsWith("__EXPR__"))
|
|
1262
|
-
.map(v => {
|
|
1263
|
-
try {
|
|
1264
|
-
const expr: Expression = JSON.parse(litToString(v.value!).substring(8));
|
|
1265
|
-
const js = compileExprToJS(expr);
|
|
1266
|
-
const idx = exprRegistry.indexOf(js);
|
|
1267
|
-
const vn2 = ns ? ns.slice(1) + "_" + v.name : v.name;
|
|
1268
|
-
return `${vn2} = __X${ns}[${idx}]({});`;
|
|
1269
|
-
} catch { return ""; }
|
|
1270
|
-
})
|
|
1271
|
-
.filter(Boolean)
|
|
1272
|
-
.join("\n ");
|
|
1273
|
-
|
|
1274
|
-
const renderBody = buildRenderBody({
|
|
1275
|
-
bodyHTML, logicBlocks, mixedBlocks,
|
|
1276
|
-
needsLogic, needsMixed, needsIf, needsFor, needsExpr, needsDelay,
|
|
1277
|
-
exprVarUpdates: exprVarUpdates || undefined,
|
|
1278
|
-
ns
|
|
1279
|
-
});
|
|
1280
|
-
|
|
1281
|
-
let forDataJS = "";
|
|
1282
|
-
let forSyncBlock = "";
|
|
1283
|
-
if (needsFor) {
|
|
1284
|
-
const forArrays = new Set<string>();
|
|
1285
|
-
const forRegex = /data-sinth-for="([^"]+)"/g;
|
|
1286
|
-
let m;
|
|
1287
|
-
while ((m = forRegex.exec(bodyHTML)) !== null) {
|
|
1288
|
-
forArrays.add(m[1]);
|
|
1289
|
-
}
|
|
1290
|
-
if (forArrays.size > 0) {
|
|
1291
|
-
forDataJS = `var _sinthForData = {};\n`;
|
|
1292
|
-
forSyncBlock = [...forArrays].map(v => {
|
|
1293
|
-
const bare = v.replace(/"/g, '"');
|
|
1294
|
-
const namespaced = opts.namespace ? opts.namespace + "_" + bare : bare;
|
|
1295
|
-
return `_sinthForData['${bare}'] = ${namespaced};`;
|
|
1296
|
-
}).join("\n ") + "\n ";
|
|
1297
|
-
}
|
|
1298
|
-
}
|
|
1299
|
-
|
|
1300
|
-
const exprArrayJS = exprRegistry.length > 0
|
|
1301
|
-
? `let __X${ns} = [${exprRegistry.map((js) => `function(_ctx){ return ${js}; }`).join(",")}];\n`
|
|
1302
|
-
: "";
|
|
1303
|
-
|
|
1304
|
-
let renderFunc = '';
|
|
1305
|
-
if (needsRender) {
|
|
1306
|
-
renderFunc = `function ${renderFn}() {\n ${forSyncBlock}${renderBody.replace(/^/gm, " ")}\n}\n${renderFn}();`;
|
|
1307
|
-
}
|
|
1308
|
-
|
|
1309
|
-
if (needsFullscreenSync) {
|
|
1310
|
-
renderFunc += `
|
|
1311
|
-
(function() {
|
|
1312
|
-
let syncedEls = document.querySelectorAll('[data-sinth-fullscreen-sync]');
|
|
1313
|
-
if (syncedEls.length > 0) {
|
|
1314
|
-
let vars = [];
|
|
1315
|
-
syncedEls.forEach(function(el) { vars.push(el.dataset.sinthFullscreenSync); });
|
|
1316
|
-
document.addEventListener('fullscreenchange', function() {
|
|
1317
|
-
let state = !!document.fullscreenElement;
|
|
1318
|
-
vars.forEach(function(varName) {
|
|
1319
|
-
switch(varName) {
|
|
1320
|
-
${[...new Set(varDecls.filter(v => v.name).map(v => {
|
|
1321
|
-
const vn3 = ns ? ns.slice(1) + "_" + v.name : v.name;
|
|
1322
|
-
return `case '${v.name}': ${vn3} = state; break;`;
|
|
1323
|
-
}))].join('\n ')}
|
|
1324
|
-
}
|
|
1325
|
-
});
|
|
1326
|
-
${renderFn}();
|
|
1327
|
-
});
|
|
1328
|
-
}
|
|
1329
|
-
})();`;
|
|
1330
|
-
}
|
|
1331
|
-
|
|
1332
|
-
const pageCode = `// Sinth Page Runtime
|
|
1333
|
-
${forDataJS}
|
|
1334
|
-
${exprArrayJS}
|
|
1335
|
-
${memoVarDecls}
|
|
1336
|
-
${varLines}
|
|
1337
|
-
${renderFunc}`;
|
|
1338
|
-
if (opts.sharedRuntime && helpers.trim()) {
|
|
1339
|
-
const sharedCode = `// Sinth shared runtime
|
|
1340
|
-
${helpers}`;
|
|
1341
|
-
return { page: pageCode, shared: sharedCode };
|
|
1342
|
-
}
|
|
1343
|
-
|
|
1344
|
-
return `// Sinth compiled runtime
|
|
1345
|
-
${forDataJS}
|
|
1346
|
-
${functionsJS ? functionsJS + "\n" : ""}${helpers}
|
|
1347
|
-
${exprArrayJS}
|
|
1348
|
-
${memoVarDecls}
|
|
1349
|
-
${varLines}
|
|
1350
|
-
${renderFunc}`;
|
|
1351
|
-
}
|