@yannosay/sinth 0.9.0 → 0.11.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 +29 -0
- package/package.json +1 -1
- package/src/core/compiler.ts +102 -25
- package/src/core/expr.ts +5 -0
- package/src/core/lexer.ts +6 -0
- package/src/core/parser.ts +96 -20
- package/src/core/types.ts +18 -3
- package/src/resolver.ts +2 -2
- package/src/core/runtime.ts +0 -398
package/README.md
CHANGED
|
@@ -27,6 +27,34 @@ Button(onClick: "deletePost()") { "Delete" }
|
|
|
27
27
|
|
|
28
28
|
No JSX ternaries. No v-if. No separate script tags. Mixed logic. Clean.
|
|
29
29
|
|
|
30
|
+
#### Functions - easy as you know it
|
|
31
|
+
```ts
|
|
32
|
+
page
|
|
33
|
+
|
|
34
|
+
title = "Full Test"
|
|
35
|
+
|
|
36
|
+
var str userName = "Sinths User"
|
|
37
|
+
|
|
38
|
+
function greet(str name) -> str {
|
|
39
|
+
"Hello, " + name
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function renderHeading(str label) -> ui {
|
|
43
|
+
Heading(level: 2) {
|
|
44
|
+
(label)
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
Div {
|
|
49
|
+
(greet(userName)) + " — welcome back!"
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
(renderHeading(userName))
|
|
53
|
+
(renderHeading("This renders!"))
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
|
|
30
58
|
#### Animations that make sense.
|
|
31
59
|
```ts
|
|
32
60
|
for item, index in items {
|
|
@@ -137,6 +165,7 @@ Sinth's reactive runtime does not use eval(). Every expression is pre-compiled i
|
|
|
137
165
|
- GitHub: [Official Sinth Repo](https://github.com/yannosay/sinth)
|
|
138
166
|
- Website: [Sinth](https://sinth.yannosay.com) (not active at this moment)
|
|
139
167
|
- Discord: [Join here!](https://discord.gg/SUvcrafTQm)
|
|
168
|
+
- VS Code Extension: [Download here](https://marketplace.visualstudio.com/items?itemName=YannosayProductions.sinth-vscode)
|
|
140
169
|
|
|
141
170
|
|
|
142
171
|
|
package/package.json
CHANGED
package/src/core/compiler.ts
CHANGED
|
@@ -4,6 +4,7 @@ import { Loc, Literal, Expression, Child, Attr, CompUse, IfBlock, ForLoop, Remov
|
|
|
4
4
|
import { Parser } from "./parser.ts";
|
|
5
5
|
import { fnv1a, camelToKebab, esc, escAttr, litToString, tagNameToPascal } from "../utils.ts";
|
|
6
6
|
import { compileExprToJS, compileIfToJS, bodyToJS } from "./expr.ts";
|
|
7
|
+
import { FunctionDef } from "./types.ts";
|
|
7
8
|
import { parseFile, resolveImports, ResolverConfig, ResolvedImports } from "../resolver.ts";
|
|
8
9
|
|
|
9
10
|
|
|
@@ -612,6 +613,41 @@ export function renderChild(
|
|
|
612
613
|
return renderText(child.value, params);
|
|
613
614
|
|
|
614
615
|
case "expr": {
|
|
616
|
+
if (child.expression.kind === "variable" && params.has(child.expression.name!)) {
|
|
617
|
+
const val = params.get(child.expression.name!)!;
|
|
618
|
+
if (val.startsWith("__LIT__")) {
|
|
619
|
+
return esc(val.slice(7));
|
|
620
|
+
}
|
|
621
|
+
if (val.startsWith("__VAR__")) {
|
|
622
|
+
const exprId = registerExpr(ctx, { kind: "variable", name: val.slice(7) });
|
|
623
|
+
return `<span class="sinth-expr" data-expr-id="${exprId}"></span>`;
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
if (child.expression.kind === "call" && child.expression.callee?.kind === "variable") {
|
|
627
|
+
const fnName = child.expression.callee.name;
|
|
628
|
+
const fnDef = fnName ? ctx.functionDefs.find(f => f.name === fnName) : undefined;
|
|
629
|
+
if (fnDef && fnDef.returnType === "ui") {
|
|
630
|
+
const callArgs = child.expression.args ?? [];
|
|
631
|
+
const localParams = new Map<string, string>();
|
|
632
|
+
for (let i = 0; i < fnDef.params.length && i < callArgs.length; i++) {
|
|
633
|
+
const arg = callArgs[i];
|
|
634
|
+
if (arg.kind === "literal" && arg.value?.kind === "str") {
|
|
635
|
+
localParams.set(fnDef.params[i].name, "__LIT__" + arg.value.value);
|
|
636
|
+
} else if (arg.kind === "variable" && arg.name) {
|
|
637
|
+
localParams.set(fnDef.params[i].name, "__VAR__" + arg.name);
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
return fnDef.body.map(c => {
|
|
641
|
+
if (c.kind === "expr" && c.expression.kind === "variable" && localParams.has(c.expression.name!)) {
|
|
642
|
+
return localParams.get(c.expression.name!)!;
|
|
643
|
+
}
|
|
644
|
+
if (c.kind === "use") {
|
|
645
|
+
return renderCompUse(c, ctx, localParams, depth + 1);
|
|
646
|
+
}
|
|
647
|
+
return renderChild(c, ctx, localParams, depth + 1);
|
|
648
|
+
}).join("");
|
|
649
|
+
}
|
|
650
|
+
}
|
|
615
651
|
if (child.expression.kind === "literal" && child.expression.value) {
|
|
616
652
|
return esc(litToString(child.expression.value));
|
|
617
653
|
}
|
|
@@ -655,6 +691,9 @@ export function renderChild(
|
|
|
655
691
|
|
|
656
692
|
case "use":
|
|
657
693
|
return renderCompUse(child, ctx, params, depth);
|
|
694
|
+
|
|
695
|
+
case "component_expr":
|
|
696
|
+
return child.children.map(c => renderChild(c, ctx, params, depth + 1)).join("");
|
|
658
697
|
}
|
|
659
698
|
}
|
|
660
699
|
|
|
@@ -1031,6 +1070,35 @@ export function renderHead(
|
|
|
1031
1070
|
|
|
1032
1071
|
// sinth runtime
|
|
1033
1072
|
|
|
1073
|
+
function compileFunctionDef(fn: FunctionDef, ctx: CompileCtx): string {
|
|
1074
|
+
const paramsJS = fn.params.map(p => p.name).join(", ");
|
|
1075
|
+
|
|
1076
|
+
if (fn.returnType === "ui") {
|
|
1077
|
+
const childHTMLs = fn.body.map(c => renderChild(c, ctx, new Map(), 0));
|
|
1078
|
+
return `function ${fn.name}(${paramsJS}) {\n return [${childHTMLs.map(h => JSON.stringify(h)).join(", ")}];\n}`;
|
|
1079
|
+
}
|
|
1080
|
+
|
|
1081
|
+
const bodyStatements: string[] = [];
|
|
1082
|
+
for (const child of fn.body) {
|
|
1083
|
+
switch (child.kind) {
|
|
1084
|
+
case "text":
|
|
1085
|
+
break;
|
|
1086
|
+
case "expr":
|
|
1087
|
+
bodyStatements.push(`return ${compileExprToJS(child.expression)};`);
|
|
1088
|
+
break;
|
|
1089
|
+
case "assign_stmt":
|
|
1090
|
+
bodyStatements.push(`${compileExprToJS(child.expression)};`);
|
|
1091
|
+
break;
|
|
1092
|
+
case "if":
|
|
1093
|
+
bodyStatements.push(compileIfToJS(child as IfBlock));
|
|
1094
|
+
break;
|
|
1095
|
+
case "for":
|
|
1096
|
+
break;
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
return `function ${fn.name}(${paramsJS}) {\n${bodyStatements.map(s => ` ${s}`).join("\n")}\n}`;
|
|
1100
|
+
}
|
|
1101
|
+
|
|
1034
1102
|
export function buildRuntime(opts: {
|
|
1035
1103
|
varDecls: VarDeclaration[];
|
|
1036
1104
|
bodyHTML: string;
|
|
@@ -1039,8 +1107,9 @@ export function buildRuntime(opts: {
|
|
|
1039
1107
|
assignedVars: Set<string>;
|
|
1040
1108
|
exprRegistry: string[];
|
|
1041
1109
|
sharedRuntime: boolean;
|
|
1110
|
+
functionsJS: string;
|
|
1042
1111
|
}): string | { page: string; shared: string } {
|
|
1043
|
-
const { varDecls, bodyHTML, logicBlocks, mixedBlocks, assignedVars, exprRegistry } = opts;
|
|
1112
|
+
const { varDecls, bodyHTML, logicBlocks, mixedBlocks, assignedVars, exprRegistry, functionsJS } = opts;
|
|
1044
1113
|
|
|
1045
1114
|
const needsExpr = bodyHTML.includes("sinth-expr");
|
|
1046
1115
|
const needsIf = bodyHTML.includes("data-sinth-if");
|
|
@@ -1335,27 +1404,7 @@ function sinthForBlock(t) {
|
|
|
1335
1404
|
`;
|
|
1336
1405
|
}
|
|
1337
1406
|
|
|
1338
|
-
|
|
1339
|
-
helpers += `
|
|
1340
|
-
function sinthMixedBlock(el, condId, ifJS, ifHTML, elseJS, elseHTML) {
|
|
1341
|
-
var condFn = __X[condId];
|
|
1342
|
-
var cond = condFn ? condFn() : false;
|
|
1343
|
-
if (cond) {
|
|
1344
|
-
if (ifJS) eval(ifJS);
|
|
1345
|
-
el.innerHTML = ifHTML;
|
|
1346
|
-
} else {
|
|
1347
|
-
if (elseJS) eval(elseJS);
|
|
1348
|
-
el.innerHTML = elseHTML;
|
|
1349
|
-
}
|
|
1350
|
-
el.querySelectorAll('.sinth-expr').forEach(sinthExpr);
|
|
1351
|
-
el.querySelectorAll('template[data-sinth-if-expr]').forEach(sinthIfBlock);
|
|
1352
|
-
if (${needsDelay}) {
|
|
1353
|
-
el.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
|
|
1354
|
-
el.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
|
|
1355
|
-
}
|
|
1356
|
-
}
|
|
1357
|
-
`;
|
|
1358
|
-
}
|
|
1407
|
+
|
|
1359
1408
|
|
|
1360
1409
|
const exprArrayJS = exprRegistry.length > 0
|
|
1361
1410
|
? `var __X = [${exprRegistry.map((js) => `function(_ctx){ return ${js}; }`).join(",")}];\n`
|
|
@@ -1370,9 +1419,24 @@ function sinthMixedBlock(el, condId, ifJS, ifHTML, elseJS, elseHTML) {
|
|
|
1370
1419
|
|
|
1371
1420
|
if (needsMixed) {
|
|
1372
1421
|
for (const mb of mixedBlocks) {
|
|
1422
|
+
const ifJS = mb.ifJS ? mb.ifJS.trim() : "";
|
|
1423
|
+
const elseJS = mb.elseJS ? mb.elseJS.trim() : "";
|
|
1373
1424
|
renderBody += ` (function() {
|
|
1374
1425
|
var __el = document.getElementById(${JSON.stringify(mb.replaceId || mb.id)});
|
|
1375
|
-
if (__el)
|
|
1426
|
+
if (__el) {
|
|
1427
|
+
var __condFn = __X[${mb.conditionJS}];
|
|
1428
|
+
if (__condFn ? __condFn() : false) {
|
|
1429
|
+
${ifJS}
|
|
1430
|
+
__el.innerHTML = ${JSON.stringify(mb.ifHTML)};
|
|
1431
|
+
} else {
|
|
1432
|
+
${elseJS}
|
|
1433
|
+
__el.innerHTML = ${JSON.stringify(mb.elseHTML)};
|
|
1434
|
+
}
|
|
1435
|
+
__el.querySelectorAll('.sinth-expr').forEach(sinthExpr);
|
|
1436
|
+
__el.querySelectorAll('template[data-sinth-if-expr]').forEach(sinthIfBlock);
|
|
1437
|
+
${needsDelay ? `__el.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
|
|
1438
|
+
__el.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);` : ""}
|
|
1439
|
+
}
|
|
1376
1440
|
})();\n`;
|
|
1377
1441
|
}
|
|
1378
1442
|
}
|
|
@@ -1420,7 +1484,7 @@ ${helpers}`;
|
|
|
1420
1484
|
|
|
1421
1485
|
return `// Sinth compiled runtime
|
|
1422
1486
|
${varLines}
|
|
1423
|
-
${helpers}
|
|
1487
|
+
${functionsJS ? functionsJS + "\n" : ""}${helpers}
|
|
1424
1488
|
${exprArrayJS}
|
|
1425
1489
|
${renderFunc}`;
|
|
1426
1490
|
}
|
|
@@ -1445,9 +1509,10 @@ export function compileFile(filePath: string, opts: CompileOptions): { html: str
|
|
|
1445
1509
|
const hash = fnv1a(absPath);
|
|
1446
1510
|
|
|
1447
1511
|
const allVarDecls: VarDeclaration[] = file.varDecls;
|
|
1512
|
+
const functionDefs: FunctionDef[] = file.functions; // ← new
|
|
1448
1513
|
|
|
1449
1514
|
const ctx: CompileCtx = {
|
|
1450
|
-
allDefs, customEls, cssLinks, jsLinks,
|
|
1515
|
+
allDefs, functionDefs, customEls, cssLinks, jsLinks,
|
|
1451
1516
|
scopeHash: hash,
|
|
1452
1517
|
pageFile: absPath,
|
|
1453
1518
|
extraCSS: [],
|
|
@@ -1480,6 +1545,17 @@ export function compileFile(filePath: string, opts: CompileOptions): { html: str
|
|
|
1480
1545
|
}
|
|
1481
1546
|
for (const v of file.varDecls) { if (v.value) assignedVars.add(v.name); }
|
|
1482
1547
|
|
|
1548
|
+
// warn about reserved browser globals
|
|
1549
|
+
const RESERVED_GLOBALS = new Set(["name", "location", "history", "status", "closed", "length", "top", "self", "parent", "frames", "origin"]);
|
|
1550
|
+
for (const v of file.varDecls) {
|
|
1551
|
+
if (RESERVED_GLOBALS.has(v.name)) {
|
|
1552
|
+
SinthWarning.emit(`Variable '${v.name}' shadows a reserved browser global. This may cause unexpected behavior. Consider renaming.`, v.loc);
|
|
1553
|
+
}
|
|
1554
|
+
}
|
|
1555
|
+
|
|
1556
|
+
// compile function definitions to JS
|
|
1557
|
+
const compiledFunctions = functionDefs.map(f => compileFunctionDef(f, ctx)).join("\n");
|
|
1558
|
+
|
|
1483
1559
|
// companion JS file (needs same name as .sinth, adds support for JS libraries)
|
|
1484
1560
|
const companionJS = (() => {
|
|
1485
1561
|
const base = absPath.replace(/\.sinth$/, ".js");
|
|
@@ -1506,6 +1582,7 @@ export function compileFile(filePath: string, opts: CompileOptions): { html: str
|
|
|
1506
1582
|
assignedVars,
|
|
1507
1583
|
exprRegistry: ctx.exprRegistry,
|
|
1508
1584
|
sharedRuntime: opts.sharedRuntime,
|
|
1585
|
+
functionsJS: compiledFunctions, // ← pass compiled functions
|
|
1509
1586
|
});
|
|
1510
1587
|
const runtimeJS = typeof runtimeResult === 'string' ? runtimeResult : runtimeResult.page;
|
|
1511
1588
|
const sharedJS = typeof runtimeResult === 'string' ? null : runtimeResult.shared;
|
package/src/core/expr.ts
CHANGED
|
@@ -31,6 +31,11 @@ export function compileExprToJS(expr: Expression, loopVars?: Set<string>): strin
|
|
|
31
31
|
return `${compileExprToJS(expr.object!, loopVars)}[${compileExprToJS(expr.key!, loopVars)}]`;
|
|
32
32
|
case "postfix":
|
|
33
33
|
return `${expr.target}${expr.op}`;
|
|
34
|
+
case "call": {
|
|
35
|
+
const callee = compileExprToJS(expr.callee!, loopVars);
|
|
36
|
+
const args = (expr.args ?? []).map(a => compileExprToJS(a, loopVars)).join(", ");
|
|
37
|
+
return `${callee}(${args})`;
|
|
38
|
+
}
|
|
34
39
|
default:
|
|
35
40
|
return "";
|
|
36
41
|
}
|
package/src/core/lexer.ts
CHANGED
|
@@ -21,6 +21,7 @@ const KEYWORDS: Record<string, TT> = {
|
|
|
21
21
|
"for": TT.KW_FOR,
|
|
22
22
|
"in": TT.KW_IN,
|
|
23
23
|
"remove": TT.KW_REMOVE,
|
|
24
|
+
"function": TT.KW_FUNCTION,
|
|
24
25
|
};
|
|
25
26
|
|
|
26
27
|
export class Lexer {
|
|
@@ -62,6 +63,11 @@ export class Lexer {
|
|
|
62
63
|
if (ch === ";") { tokens.push(this.single(TT.OP_SEMI, loc)); continue; }
|
|
63
64
|
if (ch === "<") { tokens.push(this.single(TT.OP_LT, loc)); continue; }
|
|
64
65
|
if (ch === ">") { tokens.push(this.single(TT.OP_GT, loc)); continue; }
|
|
66
|
+
if (ch === "-" && this.src[this.pos + 1] === ">") {
|
|
67
|
+
this.adv(); this.adv();
|
|
68
|
+
tokens.push({ type: TT.OP_ARROW, value: "->", loc });
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
65
71
|
if (ch === "-" && !this.isDigit(this.src[this.pos + 1] ?? "")) {
|
|
66
72
|
tokens.push(this.single(TT.OP_MINUS, loc)); continue;
|
|
67
73
|
}
|
package/src/core/parser.ts
CHANGED
|
@@ -1,27 +1,24 @@
|
|
|
1
|
-
import { TT, Token, Loc, Literal, Expression, Attr, Child, CompUse, IfBlock, ForLoop, RemoveStmt, ParamDecl, StyleBlock, ScriptBlock, CompDef, CustomElDecl, VarDeclaration, ImportNode, MetaEntry, SinthFile, SinthError, SinthWarning, AssignOp, VarType } from "./types.ts";
|
|
1
|
+
import { TT, Token, Loc, Literal, Expression, Attr, Child, CompUse, IfBlock, ForLoop, RemoveStmt, ParamDecl, StyleBlock, ScriptBlock, CompDef, CustomElDecl, VarDeclaration, ImportNode, MetaEntry, FunctionDef, SinthFile, SinthError, SinthWarning, AssignOp, VarType, BinaryOp } from "./types.ts";
|
|
2
2
|
import { Lexer } from "./lexer.ts";
|
|
3
3
|
import { compileExprToJS, compileIfToJS } from "./expr.ts";
|
|
4
|
+
import { tagNameToPascal } from "../utils.ts";
|
|
4
5
|
|
|
5
6
|
|
|
6
7
|
|
|
7
|
-
|
|
8
|
-
// parser
|
|
9
|
-
|
|
10
8
|
export class Parser {
|
|
11
9
|
private pos = 0;
|
|
12
10
|
private loopVar: string | null = null;
|
|
13
|
-
/** Accumulated var declarations for type-checking in bodies. */
|
|
14
11
|
private _varDecls: VarDeclaration[] = [];
|
|
15
12
|
|
|
16
13
|
constructor(private tokens: Token[], private file: string) {}
|
|
17
14
|
|
|
18
15
|
|
|
19
|
-
// top-level file parse
|
|
20
16
|
parse(): SinthFile {
|
|
21
17
|
let isPage = false;
|
|
22
18
|
const imports: ImportNode[] = [];
|
|
23
19
|
const meta: MetaEntry[] = [];
|
|
24
20
|
const defs: CompDef[] = [];
|
|
21
|
+
const functions: FunctionDef[] = [];
|
|
25
22
|
const uses: CompUse[] = [];
|
|
26
23
|
const styles: StyleBlock[] = [];
|
|
27
24
|
const scripts: ScriptBlock[] = [];
|
|
@@ -48,6 +45,7 @@ export class Parser {
|
|
|
48
45
|
|
|
49
46
|
while (!this.check(TT.EOF)) {
|
|
50
47
|
if (this.check(TT.KW_COMPONENT)) { defs.push(this.parseCompDef()); }
|
|
48
|
+
else if (this.check(TT.KW_FUNCTION)) { functions.push(this.parseFunctionDef()); } // ← new
|
|
51
49
|
else if (this.check(TT.KW_STYLE)) { styles.push(this.parseStyleBlock()); }
|
|
52
50
|
else if (this.check(TT.KW_SCRIPT)) { scripts.push(this.parseScriptBlock()); }
|
|
53
51
|
else if (this.check(TT.KW_CUSTOM_EL) || this.check(TT.KW_CUSTOM)) { customEls.push(this.parseCustomEl()); }
|
|
@@ -63,6 +61,15 @@ export class Parser {
|
|
|
63
61
|
const forNode = this.parseForLoop();
|
|
64
62
|
uses.push({ kind: "use", name: "__IF_ROOT__", attrs: [], children: [forNode], loc: forNode.loc });
|
|
65
63
|
}
|
|
64
|
+
else if (this.check(TT.LPAREN)) {
|
|
65
|
+
const loc = this.peek().loc;
|
|
66
|
+
this.consume(TT.LPAREN);
|
|
67
|
+
const expr = this.parseExpression();
|
|
68
|
+
if (!expr) throw new SinthError("Expected expression after '('", loc);
|
|
69
|
+
if (!this.check(TT.RPAREN)) throw new SinthError("Expected ')'", loc);
|
|
70
|
+
this.consume(TT.RPAREN);
|
|
71
|
+
uses.push({ kind: "use", name: "__IF_ROOT__", attrs: [], children: [{ kind: "expr", expression: expr, loc }], loc });
|
|
72
|
+
}
|
|
66
73
|
else if (this.check(TT.IDENT)) {
|
|
67
74
|
const savedPos = this.pos;
|
|
68
75
|
const identName = this.peek().value;
|
|
@@ -107,7 +114,7 @@ uses.push(this.parseCompUse());
|
|
|
107
114
|
);
|
|
108
115
|
}
|
|
109
116
|
|
|
110
|
-
return { filePath: this.file, isPage, imports, meta, defs, uses, styles, scripts, customEls, varDecls };
|
|
117
|
+
return { filePath: this.file, isPage, imports, meta, defs, functions, uses, styles, scripts, customEls, varDecls };
|
|
111
118
|
}
|
|
112
119
|
|
|
113
120
|
private flattenIfToUses(ifNode: IfBlock, scripts: ScriptBlock[]): CompUse[] {
|
|
@@ -173,8 +180,8 @@ uses.push(this.parseCompUse());
|
|
|
173
180
|
this.consume(TT.LBRACKET); this.consume(TT.RBRACKET);
|
|
174
181
|
typeStr = "str[]";
|
|
175
182
|
}
|
|
176
|
-
if (!["int", "str", "bool", "str[]", "obj"].includes(typeStr)) {
|
|
177
|
-
throw new SinthError(`Unknown type '${typeStr}'. Expected: int, str, bool, str[], obj`, typeTok.loc);
|
|
183
|
+
if (!["int", "str", "bool", "str[]", "obj", "ui"].includes(typeStr)) {
|
|
184
|
+
throw new SinthError(`Unknown type '${typeStr}'. Expected: int, str, bool, str[], obj, component`, typeTok.loc);
|
|
178
185
|
}
|
|
179
186
|
|
|
180
187
|
const nameTok = this.consume(TT.IDENT);
|
|
@@ -260,7 +267,7 @@ private parseArrayLiteral(): Literal {
|
|
|
260
267
|
const operand = this.parseExpression();
|
|
261
268
|
if (!operand) throw new SinthError("Expected expression after 'not'", tok.loc);
|
|
262
269
|
const unaryExpr: Expression = { kind: "unary", op: "not", operand };
|
|
263
|
-
return this.parseBinaryRHS(this.parsePostfix(unaryExpr));
|
|
270
|
+
return this.parseBinaryRHS(this.parseCallExpr(this.parsePostfix(unaryExpr)));
|
|
264
271
|
}
|
|
265
272
|
|
|
266
273
|
if (this.check(TT.LPAREN)) {
|
|
@@ -269,7 +276,7 @@ private parseArrayLiteral(): Literal {
|
|
|
269
276
|
if (!inner) throw new SinthError("Expected expression after '('", this.peek().loc);
|
|
270
277
|
if (!this.check(TT.RPAREN)) throw new SinthError("Expected closing ')'", this.peek().loc);
|
|
271
278
|
this.consume(TT.RPAREN);
|
|
272
|
-
return this.parseBinaryRHS(this.parsePostfix(inner));
|
|
279
|
+
return this.parseBinaryRHS(this.parseCallExpr(this.parsePostfix(inner)));
|
|
273
280
|
}
|
|
274
281
|
|
|
275
282
|
// literal
|
|
@@ -277,7 +284,7 @@ private parseArrayLiteral(): Literal {
|
|
|
277
284
|
this.check(TT.BOOL_FALSE) || this.check(TT.NULL_LIT)) {
|
|
278
285
|
const lit = this.parseLiteral();
|
|
279
286
|
const base: Expression = { kind: "literal", value: lit };
|
|
280
|
-
return this.parseBinaryRHS(this.parsePostfix(base));
|
|
287
|
+
return this.parseBinaryRHS(this.parseCallExpr(this.parsePostfix(base)));
|
|
281
288
|
}
|
|
282
289
|
|
|
283
290
|
// var or assignment
|
|
@@ -298,9 +305,9 @@ private parseArrayLiteral(): Literal {
|
|
|
298
305
|
// apply bracket postfixes (e.g. data[key], data["x"])
|
|
299
306
|
const indexedExpr = this.parsePostfix(varExpr);
|
|
300
307
|
|
|
301
|
-
// if indexing was applied, we don't allow assignment, just binary RHS
|
|
308
|
+
// if indexing was applied, we don't allow assignment, just binary RHS (after possible call)
|
|
302
309
|
if (indexedExpr !== varExpr) {
|
|
303
|
-
return this.parseBinaryRHS(indexedExpr);
|
|
310
|
+
return this.parseBinaryRHS(this.parseCallExpr(indexedExpr));
|
|
304
311
|
}
|
|
305
312
|
|
|
306
313
|
// no indexing – check for assignment operators
|
|
@@ -324,7 +331,7 @@ private parseArrayLiteral(): Literal {
|
|
|
324
331
|
return { kind: "assign", target: varExpr.name!, op: "=", right: rhs };
|
|
325
332
|
}
|
|
326
333
|
|
|
327
|
-
return this.parseBinaryRHS(varExpr);
|
|
334
|
+
return this.parseBinaryRHS(this.parseCallExpr(varExpr));
|
|
328
335
|
}
|
|
329
336
|
|
|
330
337
|
return null;
|
|
@@ -366,9 +373,47 @@ private parseArrayLiteral(): Literal {
|
|
|
366
373
|
return expr;
|
|
367
374
|
}
|
|
368
375
|
|
|
376
|
+
private parseCallExpr(expr: Expression): Expression {
|
|
377
|
+
while (this.check(TT.LPAREN)) {
|
|
378
|
+
this.consume(TT.LPAREN);
|
|
379
|
+
const args: Expression[] = [];
|
|
380
|
+
if (!this.check(TT.RPAREN)) {
|
|
381
|
+
args.push(this.parseExpression()!);
|
|
382
|
+
while (this.check(TT.COMMA)) {
|
|
383
|
+
this.consume(TT.COMMA);
|
|
384
|
+
args.push(this.parseExpression()!);
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
if (!this.check(TT.RPAREN)) throw new SinthError("Expected ')' after arguments", this.peek().loc);
|
|
388
|
+
this.consume(TT.RPAREN);
|
|
389
|
+
expr = { kind: "call", callee: expr, args };
|
|
390
|
+
}
|
|
391
|
+
return expr;
|
|
392
|
+
}
|
|
393
|
+
|
|
369
394
|
|
|
370
395
|
// component definitions
|
|
371
396
|
|
|
397
|
+
private parseFunctionDef(): FunctionDef {
|
|
398
|
+
const loc = this.consume(TT.KW_FUNCTION).loc;
|
|
399
|
+
const name = this.consume(TT.IDENT).value;
|
|
400
|
+
const params = this.parseParamDecls();
|
|
401
|
+
let returnType: VarType | undefined;
|
|
402
|
+
if (this.check(TT.OP_ARROW)) {
|
|
403
|
+
this.consume(TT.OP_ARROW);
|
|
404
|
+
const typeTok = this.consume(TT.IDENT);
|
|
405
|
+
if (!["int","str","bool","str[]","obj","ui"].includes(typeTok.value)) {
|
|
406
|
+
throw new SinthError(`Unknown return type '${typeTok.value}'. Expected: int, str, bool, str[], obj, ui`, typeTok.loc);
|
|
407
|
+
}
|
|
408
|
+
returnType = typeTok.value as VarType;
|
|
409
|
+
}
|
|
410
|
+
if (!this.check(TT.LBRACE)) throw new SinthError("Expected '{' after function signature", this.peek().loc);
|
|
411
|
+
this.consume(TT.LBRACE);
|
|
412
|
+
const body = this.parseChildList();
|
|
413
|
+
this.consume(TT.RBRACE);
|
|
414
|
+
return { name, params, returnType, body, loc };
|
|
415
|
+
}
|
|
416
|
+
|
|
372
417
|
private parseCompDef(): CompDef {
|
|
373
418
|
const loc = this.consume(TT.KW_COMPONENT).loc;
|
|
374
419
|
const name = this.consume(TT.IDENT).value;
|
|
@@ -394,8 +439,15 @@ private parseArrayLiteral(): Literal {
|
|
|
394
439
|
this.consume(TT.LPAREN);
|
|
395
440
|
while (!this.check(TT.RPAREN)) {
|
|
396
441
|
const ploc = this.peek().loc;
|
|
397
|
-
|
|
398
|
-
|
|
442
|
+
let pname: string;
|
|
443
|
+
if (this.check(TT.IDENT) && ["int","str","bool","str[]","obj"].includes(this.peek().value) &&
|
|
444
|
+
this.tokens[this.pos + 1]?.type === TT.IDENT) {
|
|
445
|
+
this.consume(TT.IDENT); // consume type
|
|
446
|
+
pname = this.consume(TT.IDENT).value;
|
|
447
|
+
} else {
|
|
448
|
+
const nameTok = this.check(TT.IDENT) ? this.consume(TT.IDENT) : this.consume(this.peek().type);
|
|
449
|
+
pname = nameTok.value;
|
|
450
|
+
}
|
|
399
451
|
let defaultVal: Literal | undefined;
|
|
400
452
|
if (this.check(TT.EQUALS)) { this.consume(TT.EQUALS); defaultVal = this.parseLiteral(); }
|
|
401
453
|
params.push({ name: pname, defaultVal, loc: ploc });
|
|
@@ -761,10 +813,34 @@ private parseArrayLiteral(): Literal {
|
|
|
761
813
|
while (!this.check(TT.EOF) && !this.check(TT.RBRACE)) {
|
|
762
814
|
if (this.check(TT.LPAREN)) {
|
|
763
815
|
const loc = this.peek().loc;
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
816
|
+
this.consume(TT.LPAREN);
|
|
817
|
+
let expr = this.parseExpression();
|
|
818
|
+
if (!expr) throw new SinthError("Expected expression after '('", this.peek().loc);
|
|
819
|
+
if (!this.check(TT.RPAREN)) throw new SinthError("Expected ')'", this.peek().loc);
|
|
820
|
+
this.consume(TT.RPAREN);
|
|
821
|
+
while (this.check(TT.OP_PLUS)) {
|
|
822
|
+
this.consume(TT.OP_PLUS);
|
|
823
|
+
let rhs: Expression | null = null;
|
|
824
|
+
if (this.check(TT.STRING)) {
|
|
825
|
+
rhs = { kind: "literal", value: { kind: "str", value: this.consume(TT.STRING).value } };
|
|
826
|
+
} else if (this.check(TT.IDENT)) {
|
|
827
|
+
const rhsName = this.consume(TT.IDENT).value;
|
|
828
|
+
if (this.check(TT.DOT)) {
|
|
829
|
+
this.consume(TT.DOT);
|
|
830
|
+
rhs = { kind: "variable", name: rhsName + "." + this.consume(TT.IDENT).value };
|
|
831
|
+
} else if (this.check(TT.LBRACKET)) {
|
|
832
|
+
const rhsVar: Expression = { kind: "variable", name: rhsName };
|
|
833
|
+
rhs = this.parsePostfix(rhsVar);
|
|
834
|
+
} else {
|
|
835
|
+
rhs = { kind: "variable", name: rhsName };
|
|
836
|
+
}
|
|
837
|
+
} else {
|
|
838
|
+
rhs = this.parseExpression();
|
|
839
|
+
}
|
|
840
|
+
if (!rhs) throw new SinthError("Expected expression after +", this.peek().loc);
|
|
841
|
+
expr = { kind: "binary", left: expr, op: "+", right: rhs };
|
|
767
842
|
}
|
|
843
|
+
children.push({ kind: "expr", expression: expr, loc });
|
|
768
844
|
continue;
|
|
769
845
|
}
|
|
770
846
|
if (this.check(TT.STRING)) {
|
package/src/core/types.ts
CHANGED
|
@@ -19,8 +19,10 @@ export enum TT {
|
|
|
19
19
|
KW_GLOBAL, KW_PAGE, KW_LANG,
|
|
20
20
|
KW_CUSTOM_EL, KW_CUSTOM,
|
|
21
21
|
KW_IF, KW_ELSE, KW_FOR, KW_IN, KW_REMOVE,
|
|
22
|
+
KW_FUNCTION,
|
|
22
23
|
OP_PLUS, OP_MINUS, OP_STAR, OP_SLASH, OP_SEMI,
|
|
23
24
|
OP_LT, OP_GT, OP_NEQ, OP_EQEQ, OP_LTEQ, OP_GTEQ,
|
|
25
|
+
OP_ARROW,
|
|
24
26
|
EOF,
|
|
25
27
|
}
|
|
26
28
|
|
|
@@ -38,7 +40,7 @@ export type AssignOp = "=" | "+=" | "-=";
|
|
|
38
40
|
export type PostfixOp = "++" | "--";
|
|
39
41
|
|
|
40
42
|
export interface Expression {
|
|
41
|
-
kind: "literal" | "variable" | "unary" | "binary" | "assign" | "postfix" | "index";
|
|
43
|
+
kind: "literal" | "variable" | "unary" | "binary" | "assign" | "postfix" | "index" | "call";
|
|
42
44
|
value?: Literal;
|
|
43
45
|
name?: string;
|
|
44
46
|
op?: UnaryOp | BinaryOp | AssignOp | PostfixOp;
|
|
@@ -48,6 +50,8 @@ export interface Expression {
|
|
|
48
50
|
target?: string;
|
|
49
51
|
object?: Expression;
|
|
50
52
|
key?: Expression;
|
|
53
|
+
callee?: Expression;
|
|
54
|
+
args?: Expression[];
|
|
51
55
|
}
|
|
52
56
|
|
|
53
57
|
export interface Attr { name: string; value: Literal | null; loc: Loc }
|
|
@@ -58,9 +62,10 @@ export interface AssignStmt { kind: "assign_stmt"; expression: Expression;
|
|
|
58
62
|
export interface IfBlock { kind: "if"; condition: Expression; body: Child[]; elseBody?: Child[]; loc: Loc }
|
|
59
63
|
export interface ForLoop { kind: "for"; keyVar?: string; itemVar: string; indexVar?: string; arrayVar: string; body: Child[]; loc: Loc }
|
|
60
64
|
export interface RemoveStmt { kind: "remove"; target: string; loc: Loc }
|
|
65
|
+
export interface ComponentExpr { kind: "component_expr"; children: Child[]; loc: Loc }
|
|
61
66
|
|
|
62
67
|
|
|
63
|
-
export type Child = TextNode | CompUse | ExprNode | AssignStmt | IfBlock | ForLoop | RemoveStmt;
|
|
68
|
+
export type Child = TextNode | CompUse | ExprNode | AssignStmt | IfBlock | ForLoop | RemoveStmt | ComponentExpr;
|
|
64
69
|
|
|
65
70
|
export interface ParamDecl { name: string; defaultVal?: Literal; loc: Loc }
|
|
66
71
|
|
|
@@ -78,7 +83,7 @@ export interface CompDef { name: string; params: ParamDecl[]; body: Child[]
|
|
|
78
83
|
export interface CustomElDecl { sinthName: string; tagName: string; params: ParamDecl[]; loc: Loc }
|
|
79
84
|
export interface CustomElInfo { tagName: string; params: ParamDecl[] }
|
|
80
85
|
|
|
81
|
-
export type VarType = "int" | "str" | "bool" | "str[]" | "obj";
|
|
86
|
+
export type VarType = "int" | "str" | "bool" | "str[]" | "obj" | "ui";
|
|
82
87
|
export interface VarDeclaration { kind: "var"; name: string; varType: VarType; value: Literal | null; loc: Loc }
|
|
83
88
|
|
|
84
89
|
export type ImportNode =
|
|
@@ -88,12 +93,21 @@ export type ImportNode =
|
|
|
88
93
|
|
|
89
94
|
export interface MetaEntry { key: string; value: Literal; loc: Loc }
|
|
90
95
|
|
|
96
|
+
export interface FunctionDef {
|
|
97
|
+
name: string;
|
|
98
|
+
params: ParamDecl[];
|
|
99
|
+
returnType?: VarType;
|
|
100
|
+
body: Child[];
|
|
101
|
+
loc: Loc;
|
|
102
|
+
}
|
|
103
|
+
|
|
91
104
|
export interface SinthFile {
|
|
92
105
|
filePath: string;
|
|
93
106
|
isPage: boolean;
|
|
94
107
|
imports: ImportNode[];
|
|
95
108
|
meta: MetaEntry[];
|
|
96
109
|
defs: CompDef[];
|
|
110
|
+
functions: FunctionDef[];
|
|
97
111
|
uses: CompUse[];
|
|
98
112
|
styles: StyleBlock[];
|
|
99
113
|
scripts: ScriptBlock[];
|
|
@@ -113,6 +127,7 @@ export interface MixedBlockEntry {
|
|
|
113
127
|
|
|
114
128
|
export interface CompileCtx {
|
|
115
129
|
allDefs: Map<string, CompDef>;
|
|
130
|
+
functionDefs: FunctionDef[];
|
|
116
131
|
customEls: Map<string, CustomElInfo>;
|
|
117
132
|
cssLinks: string[];
|
|
118
133
|
jsLinks: { src: string; attrs: Record<string, string> }[];
|
package/src/resolver.ts
CHANGED
|
@@ -7,9 +7,9 @@ import { BUILTIN_MAP } from "./core/compiler.ts";
|
|
|
7
7
|
|
|
8
8
|
|
|
9
9
|
|
|
10
|
-
interface ResolverConfig { projectRoot: string; libraryPaths: string[] }
|
|
10
|
+
export interface ResolverConfig { projectRoot: string; libraryPaths: string[] }
|
|
11
11
|
|
|
12
|
-
interface ResolvedImports {
|
|
12
|
+
export interface ResolvedImports {
|
|
13
13
|
allDefs: Map<string, CompDef>;
|
|
14
14
|
customEls: Map<string, CustomElInfo>;
|
|
15
15
|
cssLinks: string[];
|
package/src/core/runtime.ts
DELETED
|
@@ -1,398 +0,0 @@
|
|
|
1
|
-
import { VarDeclaration, MixedBlockEntry, SinthWarning } from "./types.ts";
|
|
2
|
-
import { litToString } from "../utils.ts";
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
export function buildRuntime(opts: {
|
|
7
|
-
varDecls: VarDeclaration[];
|
|
8
|
-
bodyHTML: string;
|
|
9
|
-
logicBlocks: string[];
|
|
10
|
-
mixedBlocks: MixedBlockEntry[];
|
|
11
|
-
assignedVars: Set<string>;
|
|
12
|
-
exprRegistry: string[];
|
|
13
|
-
sharedRuntime: boolean;
|
|
14
|
-
}): string | { page: string; shared: string } {
|
|
15
|
-
const { varDecls, bodyHTML, logicBlocks, mixedBlocks, assignedVars, exprRegistry } = opts;
|
|
16
|
-
|
|
17
|
-
const needsExpr = bodyHTML.includes("sinth-expr");
|
|
18
|
-
const needsIf = bodyHTML.includes("data-sinth-if");
|
|
19
|
-
const needsFor = bodyHTML.includes("data-sinth-for");
|
|
20
|
-
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"));
|
|
21
|
-
const needsMixed = mixedBlocks.length > 0;
|
|
22
|
-
const needsLogic = logicBlocks.length > 0;
|
|
23
|
-
const needsRender = needsExpr || needsIf || needsFor || needsMixed || needsLogic;
|
|
24
|
-
|
|
25
|
-
const varLines = varDecls.map(v => {
|
|
26
|
-
if (!v.value) {
|
|
27
|
-
if (!assignedVars.has(v.name)) {
|
|
28
|
-
const defaults: Record<string, string> = { str: '""', int: "0", bool: "false", "str[]": "[]" };
|
|
29
|
-
SinthWarning.emit(
|
|
30
|
-
`Variable '${v.name}' is declared but never assigned. Defaulting to ${defaults[v.varType] ?? "undefined"}.`,
|
|
31
|
-
v.loc,
|
|
32
|
-
);
|
|
33
|
-
}
|
|
34
|
-
const defaults: Record<string, string> = { str: '""', int: "0", bool: "false", "str[]": "[]" };
|
|
35
|
-
return `var ${v.name} = ${defaults[v.varType] ?? "undefined"};`;
|
|
36
|
-
}
|
|
37
|
-
const val = litToString(v.value);
|
|
38
|
-
if (val.startsWith("__VAR__")) return `var ${v.name} = ${val.slice(7)};`;
|
|
39
|
-
if (val.startsWith("__ARR__")) return `var ${v.name} = ${val.slice(7)};`;
|
|
40
|
-
if (v.varType === "obj") return `var ${v.name} = ${val};`;
|
|
41
|
-
if (v.varType === "str") return `var ${v.name} = ${JSON.stringify(val)};`;
|
|
42
|
-
if (v.varType === "str[]" && typeof val === 'string' && val.startsWith("__ARR__")) {
|
|
43
|
-
try {
|
|
44
|
-
const arr = JSON.parse(val.slice(7));
|
|
45
|
-
return `var ${v.name} = ${JSON.stringify(arr)};`;
|
|
46
|
-
} catch { return `var ${v.name} = ${val.slice(7)};`; }
|
|
47
|
-
}
|
|
48
|
-
return `var ${v.name} = ${val};`;
|
|
49
|
-
}).join("\n");
|
|
50
|
-
|
|
51
|
-
if (!needsRender && !needsDelay) {
|
|
52
|
-
return varLines ? `// Sinth compiled runtime\n${varLines}` : "";
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
let helpers = "";
|
|
56
|
-
|
|
57
|
-
if (needsExpr || needsIf || needsFor) {
|
|
58
|
-
helpers += `
|
|
59
|
-
function sinthExpr(el) {
|
|
60
|
-
try {
|
|
61
|
-
var exprFn = __X[el.dataset.exprId];
|
|
62
|
-
if (exprFn) el.textContent = exprFn({});
|
|
63
|
-
} catch(e) {}
|
|
64
|
-
}
|
|
65
|
-
`;
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
if (needsIf || needsMixed) {
|
|
69
|
-
helpers += `
|
|
70
|
-
function sinthReplaceInsert(t, anchor, ifId, replaceId) {
|
|
71
|
-
if (anchor) {
|
|
72
|
-
var cur = anchor.nextSibling;
|
|
73
|
-
while (cur && cur !== t) { var nx = cur.nextSibling; cur.remove(); cur = nx; }
|
|
74
|
-
} else {
|
|
75
|
-
anchor = document.createElement('span');
|
|
76
|
-
anchor.style.display = 'none';
|
|
77
|
-
anchor.dataset.sinthIfAnchor = ifId;
|
|
78
|
-
t.parentNode.insertBefore(anchor, t);
|
|
79
|
-
}
|
|
80
|
-
var _rp = null, _rpParent = null, _rpNext = null;
|
|
81
|
-
if (replaceId) {
|
|
82
|
-
_rp = document.getElementById(replaceId);
|
|
83
|
-
if (_rp) {
|
|
84
|
-
_rpParent = _rp.parentNode;
|
|
85
|
-
_rpNext = _rp.nextSibling;
|
|
86
|
-
_rp.parentNode.removeChild(_rp);
|
|
87
|
-
anchor._sinthReplaced = _rp;
|
|
88
|
-
anchor._sinthReplacedParent = _rpParent;
|
|
89
|
-
anchor._sinthReplacedNext = _rpNext;
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
var frag = document.createRange().createContextualFragment(t.innerHTML);
|
|
93
|
-
frag.querySelectorAll('.sinth-expr').forEach(sinthExpr);
|
|
94
|
-
if (${needsDelay}) {
|
|
95
|
-
frag.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
|
|
96
|
-
frag.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
|
|
97
|
-
}
|
|
98
|
-
var fragFirst = frag.firstChild;
|
|
99
|
-
var fragLast = frag.lastChild;
|
|
100
|
-
if (_rpParent && _rpNext) {
|
|
101
|
-
_rpParent.insertBefore(frag, _rpNext);
|
|
102
|
-
} else if (_rpParent) {
|
|
103
|
-
_rpParent.appendChild(frag);
|
|
104
|
-
} else {
|
|
105
|
-
t.parentNode.insertBefore(frag, t);
|
|
106
|
-
}
|
|
107
|
-
if (replaceId && anchor) {
|
|
108
|
-
anchor._sinthInsertedFirst = fragFirst;
|
|
109
|
-
anchor._sinthInsertedLast = fragLast;
|
|
110
|
-
}
|
|
111
|
-
return anchor;
|
|
112
|
-
}
|
|
113
|
-
`;
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
if (needsDelay) {
|
|
117
|
-
helpers += `
|
|
118
|
-
function sinthDelay(el) {
|
|
119
|
-
if (el.dataset.sinthDelayDone) { el.style.display = ''; return; }
|
|
120
|
-
el.dataset.sinthDelayDone = '1';
|
|
121
|
-
var ms = parseInt(el.dataset.sinthDelay) || 0;
|
|
122
|
-
el.style.display = 'none';
|
|
123
|
-
if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
|
|
124
|
-
else el.style.display = '';
|
|
125
|
-
}
|
|
126
|
-
function sinthDelayExpr(el) {
|
|
127
|
-
try {
|
|
128
|
-
var fn = __X[el.dataset.sinthDelayExprId];
|
|
129
|
-
var ms = fn ? parseInt(fn()) || 0 : 0;
|
|
130
|
-
el.style.display = '';
|
|
131
|
-
if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
|
|
132
|
-
} catch(e) {}
|
|
133
|
-
}
|
|
134
|
-
`;
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
if (needsIf) {
|
|
138
|
-
helpers += `
|
|
139
|
-
function sinthIfBlock(t) {
|
|
140
|
-
var ifId = t.dataset.sinthIfId;
|
|
141
|
-
var anchor = t.parentNode.querySelector('[data-sinth-if-anchor="' + ifId + '"]');
|
|
142
|
-
var condFn = __X[t.dataset.sinthIfExpr];
|
|
143
|
-
var cond = condFn ? condFn() : false;
|
|
144
|
-
if (cond) {
|
|
145
|
-
anchor = sinthReplaceInsert(t, anchor, ifId, t.dataset.sinthIfReplace);
|
|
146
|
-
} else {
|
|
147
|
-
if (anchor) {
|
|
148
|
-
if (anchor._sinthReplaced) {
|
|
149
|
-
var insFirst = anchor._sinthInsertedFirst;
|
|
150
|
-
var insLast = anchor._sinthInsertedLast;
|
|
151
|
-
var rpParent = anchor._sinthReplacedParent;
|
|
152
|
-
var rpNext = anchor._sinthReplacedNext;
|
|
153
|
-
if (insFirst && insLast) {
|
|
154
|
-
var cur = insFirst;
|
|
155
|
-
while (cur && cur !== insLast) {
|
|
156
|
-
var next = cur.nextSibling;
|
|
157
|
-
cur.remove();
|
|
158
|
-
cur = next;
|
|
159
|
-
}
|
|
160
|
-
if (insLast) insLast.remove();
|
|
161
|
-
}
|
|
162
|
-
if (rpParent && rpNext) {
|
|
163
|
-
rpParent.insertBefore(anchor._sinthReplaced, rpNext);
|
|
164
|
-
} else if (rpParent) {
|
|
165
|
-
rpParent.appendChild(anchor._sinthReplaced);
|
|
166
|
-
}
|
|
167
|
-
} else {
|
|
168
|
-
var cur2 = anchor.nextSibling;
|
|
169
|
-
while (cur2 && cur2 !== t) { var nx2 = cur2.nextSibling; cur2.remove(); cur2 = nx2; }
|
|
170
|
-
}
|
|
171
|
-
anchor.remove();
|
|
172
|
-
}
|
|
173
|
-
var elseT = t.nextElementSibling;
|
|
174
|
-
if (elseT && elseT.hasAttribute('data-sinth-else')) {
|
|
175
|
-
var elseIfId = elseT.dataset.sinthIfId;
|
|
176
|
-
var ea = t.parentNode.querySelector('[data-sinth-if-anchor="__else__' + elseIfId + '"]');
|
|
177
|
-
if (ea) {
|
|
178
|
-
var cur3 = ea.nextSibling;
|
|
179
|
-
while (cur3 && cur3 !== t) { var nx3 = cur3.nextSibling; cur3.remove(); cur3 = nx3; }
|
|
180
|
-
} else {
|
|
181
|
-
ea = document.createElement('span');
|
|
182
|
-
ea.style.display = 'none';
|
|
183
|
-
ea.dataset.sinthIfAnchor = '__else__' + elseIfId;
|
|
184
|
-
t.parentNode.insertBefore(ea, t);
|
|
185
|
-
}
|
|
186
|
-
var ef = document.createRange().createContextualFragment(elseT.innerHTML);
|
|
187
|
-
ef.querySelectorAll('.sinth-expr').forEach(sinthExpr);
|
|
188
|
-
if (${needsDelay}) {
|
|
189
|
-
ef.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
|
|
190
|
-
ef.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
|
|
191
|
-
}
|
|
192
|
-
t.parentNode.insertBefore(ef, t);
|
|
193
|
-
} else {
|
|
194
|
-
var ea2 = t.parentNode.querySelector('[data-sinth-if-anchor="__else__' + ifId + '"]');
|
|
195
|
-
if (ea2) {
|
|
196
|
-
var ec = ea2.nextSibling;
|
|
197
|
-
while (ec && ec !== t) { var en = ec.nextSibling; ec.remove(); ec = en; }
|
|
198
|
-
ea2.remove();
|
|
199
|
-
}
|
|
200
|
-
}
|
|
201
|
-
}
|
|
202
|
-
}
|
|
203
|
-
`;
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
if (needsFor) {
|
|
207
|
-
helpers += `
|
|
208
|
-
function hashString(str) {
|
|
209
|
-
var hash = 0, i, chr;
|
|
210
|
-
for (i = 0; i < str.length; i++) {
|
|
211
|
-
chr = str.charCodeAt(i);
|
|
212
|
-
hash = ((hash << 5) - hash) + chr;
|
|
213
|
-
hash |= 0;
|
|
214
|
-
}
|
|
215
|
-
return String(hash);
|
|
216
|
-
}
|
|
217
|
-
function sinthForBlock(t) {
|
|
218
|
-
var source = window[t.dataset.sinthFor];
|
|
219
|
-
if (source === undefined) source = [];
|
|
220
|
-
var newHash = '';
|
|
221
|
-
try { newHash = hashString(JSON.stringify(source)); } catch(e) { newHash = ''; }
|
|
222
|
-
if (t.dataset.sinthForHash && t.dataset.sinthForHash === newHash) {
|
|
223
|
-
return;
|
|
224
|
-
}
|
|
225
|
-
t.dataset.sinthForHash = newHash;
|
|
226
|
-
var isObj = (typeof source === 'object' && source !== null && !Array.isArray(source));
|
|
227
|
-
var entries;
|
|
228
|
-
if (isObj) {
|
|
229
|
-
entries = Object.entries(source);
|
|
230
|
-
} else {
|
|
231
|
-
if (!Array.isArray(source)) source = [];
|
|
232
|
-
entries = source.map(function(item, index) { return [index, item]; });
|
|
233
|
-
}
|
|
234
|
-
var anchor = t.parentNode ? t.parentNode.querySelector('[data-sinth-for-anchor="' + t.dataset.sinthFor + '"]') : null;
|
|
235
|
-
if (anchor) {
|
|
236
|
-
var cur2 = anchor.nextSibling;
|
|
237
|
-
while (cur2 && cur2 !== t) { var nx2 = cur2.nextSibling; cur2.remove(); cur2 = nx2; }
|
|
238
|
-
anchor.remove();
|
|
239
|
-
}
|
|
240
|
-
var fa = document.createElement('span');
|
|
241
|
-
fa.style.display = 'none';
|
|
242
|
-
fa.dataset.sinthForAnchor = t.dataset.sinthFor;
|
|
243
|
-
t.parentNode && t.parentNode.insertBefore(fa, t);
|
|
244
|
-
var _loopIdx = 0;
|
|
245
|
-
entries.forEach(function(entry) {
|
|
246
|
-
var _k = entry[0];
|
|
247
|
-
var _v = entry[1];
|
|
248
|
-
var _item = (t.dataset && t.dataset.sinthItem) ? t.dataset.sinthItem : '__item__';
|
|
249
|
-
var _key = t.dataset && t.dataset.sinthKey ? t.dataset.sinthKey : null;
|
|
250
|
-
var _idx = t.dataset && t.dataset.sinthIndex ? t.dataset.sinthIndex : null;
|
|
251
|
-
_loopIdx++;
|
|
252
|
-
if (t.dataset.sinthIfReplace) {
|
|
253
|
-
var _rp = document.getElementById(t.dataset.sinthIfReplace);
|
|
254
|
-
if (_rp) _rp.parentNode.removeChild(_rp);
|
|
255
|
-
}
|
|
256
|
-
var frag = document.createRange().createContextualFragment(t.innerHTML);
|
|
257
|
-
frag.querySelectorAll('.sinth-expr').forEach(function(el) {
|
|
258
|
-
try {
|
|
259
|
-
var exprFn = __X[el.dataset.exprId];
|
|
260
|
-
if (!exprFn) return;
|
|
261
|
-
var _ctx = {};
|
|
262
|
-
if (_item) _ctx[_item] = _v;
|
|
263
|
-
if (_key) _ctx[_key] = _k;
|
|
264
|
-
if (_idx) _ctx[_idx] = _loopIdx - 1;
|
|
265
|
-
el.textContent = exprFn(_ctx);
|
|
266
|
-
el.classList.remove('sinth-expr');
|
|
267
|
-
} catch(e) {}
|
|
268
|
-
});
|
|
269
|
-
frag.querySelectorAll('template[data-sinth-if-expr]').forEach(function(ifT) {
|
|
270
|
-
var condFn = __X[ifT.dataset.sinthIfExpr];
|
|
271
|
-
var _ctx = {};
|
|
272
|
-
if (_item) _ctx[_item] = _v;
|
|
273
|
-
if (_key) _ctx[_key] = _k;
|
|
274
|
-
if (_idx) _ctx[_idx] = _loopIdx - 1;
|
|
275
|
-
var cond = false;
|
|
276
|
-
try { if (condFn) cond = condFn(_ctx); } catch(e) {}
|
|
277
|
-
if (cond) {
|
|
278
|
-
var ifContent = document.createRange().createContextualFragment(ifT.innerHTML);
|
|
279
|
-
ifContent.querySelectorAll('.sinth-expr').forEach(function(el2) {
|
|
280
|
-
try {
|
|
281
|
-
var exprFn2 = __X[el2.dataset.exprId];
|
|
282
|
-
if (exprFn2) el2.textContent = exprFn2(_ctx);
|
|
283
|
-
} catch(e) {}
|
|
284
|
-
});
|
|
285
|
-
ifT.parentNode.insertBefore(ifContent, ifT);
|
|
286
|
-
} else {
|
|
287
|
-
var elseT = ifT.nextElementSibling;
|
|
288
|
-
if (elseT && elseT.hasAttribute('data-sinth-else')) {
|
|
289
|
-
var elseContent = document.createRange().createContextualFragment(elseT.innerHTML);
|
|
290
|
-
elseContent.querySelectorAll('.sinth-expr').forEach(function(el2) {
|
|
291
|
-
try {
|
|
292
|
-
var exprFn2 = __X[el2.dataset.exprId];
|
|
293
|
-
if (exprFn2) el2.textContent = exprFn2(_ctx);
|
|
294
|
-
} catch(e) {}
|
|
295
|
-
});
|
|
296
|
-
ifT.parentNode.insertBefore(elseContent, ifT);
|
|
297
|
-
}
|
|
298
|
-
}
|
|
299
|
-
});
|
|
300
|
-
if (${needsDelay}) {
|
|
301
|
-
frag.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
|
|
302
|
-
frag.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
|
|
303
|
-
}
|
|
304
|
-
t.parentNode && t.parentNode.insertBefore(frag, t);
|
|
305
|
-
});
|
|
306
|
-
}
|
|
307
|
-
`;
|
|
308
|
-
}
|
|
309
|
-
|
|
310
|
-
if (needsMixed) {
|
|
311
|
-
helpers += `
|
|
312
|
-
function sinthMixedBlock(el, condId, ifJS, ifHTML, elseJS, elseHTML) {
|
|
313
|
-
var condFn = __X[condId];
|
|
314
|
-
var cond = condFn ? condFn() : false;
|
|
315
|
-
if (cond) {
|
|
316
|
-
if (ifJS) eval(ifJS);
|
|
317
|
-
el.innerHTML = ifHTML;
|
|
318
|
-
} else {
|
|
319
|
-
if (elseJS) eval(elseJS);
|
|
320
|
-
el.innerHTML = elseHTML;
|
|
321
|
-
}
|
|
322
|
-
el.querySelectorAll('.sinth-expr').forEach(sinthExpr);
|
|
323
|
-
el.querySelectorAll('template[data-sinth-if-expr]').forEach(sinthIfBlock);
|
|
324
|
-
if (${needsDelay}) {
|
|
325
|
-
el.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
|
|
326
|
-
el.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
|
|
327
|
-
}
|
|
328
|
-
}
|
|
329
|
-
`;
|
|
330
|
-
}
|
|
331
|
-
|
|
332
|
-
const exprArrayJS = exprRegistry.length > 0
|
|
333
|
-
? `var __X = [${exprRegistry.map((js) => `function(_ctx){ return ${js}; }`).join(",")}];\n`
|
|
334
|
-
: "";
|
|
335
|
-
|
|
336
|
-
let renderBody = "";
|
|
337
|
-
renderBody += ` var _sx = window.scrollX, _sy = window.scrollY;\n`;
|
|
338
|
-
|
|
339
|
-
if (needsLogic) {
|
|
340
|
-
renderBody += logicBlocks.map(b => b.replace(/^/gm, " ")).join("\n") + "\n";
|
|
341
|
-
}
|
|
342
|
-
|
|
343
|
-
if (needsMixed) {
|
|
344
|
-
for (const mb of mixedBlocks) {
|
|
345
|
-
renderBody += ` (function() {
|
|
346
|
-
var __el = document.getElementById(${JSON.stringify(mb.replaceId || mb.id)});
|
|
347
|
-
if (__el) sinthMixedBlock(__el, ${mb.conditionJS}, ${JSON.stringify(mb.ifJS)}, ${JSON.stringify(mb.ifHTML)}, ${JSON.stringify(mb.elseJS)}, ${JSON.stringify(mb.elseHTML)});
|
|
348
|
-
})();\n`;
|
|
349
|
-
}
|
|
350
|
-
}
|
|
351
|
-
|
|
352
|
-
renderBody += ` document.querySelectorAll('[data-sinth-remove]').forEach(function(el) {
|
|
353
|
-
var target = document.getElementById(el.dataset.sinthRemove);
|
|
354
|
-
if (target) target.remove();
|
|
355
|
-
});\n`;
|
|
356
|
-
|
|
357
|
-
if (needsIf) {
|
|
358
|
-
renderBody += ` document.querySelectorAll('template[data-sinth-if-expr]').forEach(sinthIfBlock);\n`;
|
|
359
|
-
}
|
|
360
|
-
if (needsFor) {
|
|
361
|
-
renderBody += ` document.querySelectorAll('template[data-sinth-for]').forEach(sinthForBlock);\n`;
|
|
362
|
-
}
|
|
363
|
-
renderBody += ` document.querySelectorAll('[data-sinth-value]').forEach(function(el) {
|
|
364
|
-
try { el.value = window[el.dataset.sinthValue] || ''; } catch(e) {}
|
|
365
|
-
});\n`;
|
|
366
|
-
renderBody += ` document.querySelectorAll('[data-sinth-checked]').forEach(function(el) {
|
|
367
|
-
try { el.checked = !!window[el.dataset.sinthChecked]; } catch(e) {}
|
|
368
|
-
});\n`;
|
|
369
|
-
if (needsExpr) {
|
|
370
|
-
renderBody += ` document.querySelectorAll('.sinth-expr').forEach(sinthExpr);\n`;
|
|
371
|
-
}
|
|
372
|
-
if (needsDelay) {
|
|
373
|
-
renderBody += ` setTimeout(function() {
|
|
374
|
-
document.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
|
|
375
|
-
document.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
|
|
376
|
-
}, 0);\n`;
|
|
377
|
-
}
|
|
378
|
-
renderBody += ` window.scrollTo(_sx, _sy);\n`;
|
|
379
|
-
|
|
380
|
-
const renderFunc = needsRender ? `function sinthRender() {\n${renderBody}}\nsinthRender();` : "";
|
|
381
|
-
|
|
382
|
-
const pageCode = `// Sinth page runtime
|
|
383
|
-
${varLines}
|
|
384
|
-
${exprArrayJS}
|
|
385
|
-
${renderFunc}`;
|
|
386
|
-
|
|
387
|
-
if (opts.sharedRuntime && helpers.trim()) {
|
|
388
|
-
const sharedCode = `// Sinth shared runtime
|
|
389
|
-
${helpers}`;
|
|
390
|
-
return { page: pageCode, shared: sharedCode };
|
|
391
|
-
}
|
|
392
|
-
|
|
393
|
-
return `// Sinth compiled runtime
|
|
394
|
-
${varLines}
|
|
395
|
-
${helpers}
|
|
396
|
-
${exprArrayJS}
|
|
397
|
-
${renderFunc}`;
|
|
398
|
-
}
|