@yannosay/sinth 0.10.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 +17 -4
- package/package.json +1 -1
- package/src/core/compiler.ts +72 -25
- package/src/core/parser.ts +36 -25
- package/src/core/types.ts +4 -2
- package/src/core/runtime.ts +0 -399
package/README.md
CHANGED
|
@@ -25,22 +25,35 @@ Button(onClick: "deletePost()") { "Delete" }
|
|
|
25
25
|
}
|
|
26
26
|
```
|
|
27
27
|
|
|
28
|
+
No JSX ternaries. No v-if. No separate script tags. Mixed logic. Clean.
|
|
29
|
+
|
|
28
30
|
#### Functions - easy as you know it
|
|
29
31
|
```ts
|
|
30
32
|
page
|
|
31
33
|
|
|
32
|
-
title = "
|
|
34
|
+
title = "Full Test"
|
|
33
35
|
|
|
34
|
-
|
|
36
|
+
var str userName = "Sinths User"
|
|
37
|
+
|
|
38
|
+
function greet(str name) -> str {
|
|
35
39
|
"Hello, " + name
|
|
36
40
|
}
|
|
37
41
|
|
|
42
|
+
function renderHeading(str label) -> ui {
|
|
43
|
+
Heading(level: 2) {
|
|
44
|
+
(label)
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
38
48
|
Div {
|
|
39
|
-
(greet(
|
|
49
|
+
(greet(userName)) + " — welcome back!"
|
|
40
50
|
}
|
|
51
|
+
|
|
52
|
+
(renderHeading(userName))
|
|
53
|
+
(renderHeading("This renders!"))
|
|
41
54
|
```
|
|
42
55
|
|
|
43
|
-
|
|
56
|
+
|
|
44
57
|
|
|
45
58
|
#### Animations that make sense.
|
|
46
59
|
```ts
|
package/package.json
CHANGED
package/src/core/compiler.ts
CHANGED
|
@@ -613,6 +613,41 @@ export function renderChild(
|
|
|
613
613
|
return renderText(child.value, params);
|
|
614
614
|
|
|
615
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
|
+
}
|
|
616
651
|
if (child.expression.kind === "literal" && child.expression.value) {
|
|
617
652
|
return esc(litToString(child.expression.value));
|
|
618
653
|
}
|
|
@@ -656,6 +691,9 @@ export function renderChild(
|
|
|
656
691
|
|
|
657
692
|
case "use":
|
|
658
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("");
|
|
659
697
|
}
|
|
660
698
|
}
|
|
661
699
|
|
|
@@ -1032,8 +1070,14 @@ export function renderHead(
|
|
|
1032
1070
|
|
|
1033
1071
|
// sinth runtime
|
|
1034
1072
|
|
|
1035
|
-
function compileFunctionDef(fn: FunctionDef): string {
|
|
1073
|
+
function compileFunctionDef(fn: FunctionDef, ctx: CompileCtx): string {
|
|
1036
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
|
+
|
|
1037
1081
|
const bodyStatements: string[] = [];
|
|
1038
1082
|
for (const child of fn.body) {
|
|
1039
1083
|
switch (child.kind) {
|
|
@@ -1360,27 +1404,7 @@ function sinthForBlock(t) {
|
|
|
1360
1404
|
`;
|
|
1361
1405
|
}
|
|
1362
1406
|
|
|
1363
|
-
|
|
1364
|
-
helpers += `
|
|
1365
|
-
function sinthMixedBlock(el, condId, ifJS, ifHTML, elseJS, elseHTML) {
|
|
1366
|
-
var condFn = __X[condId];
|
|
1367
|
-
var cond = condFn ? condFn() : false;
|
|
1368
|
-
if (cond) {
|
|
1369
|
-
if (ifJS) eval(ifJS);
|
|
1370
|
-
el.innerHTML = ifHTML;
|
|
1371
|
-
} else {
|
|
1372
|
-
if (elseJS) eval(elseJS);
|
|
1373
|
-
el.innerHTML = elseHTML;
|
|
1374
|
-
}
|
|
1375
|
-
el.querySelectorAll('.sinth-expr').forEach(sinthExpr);
|
|
1376
|
-
el.querySelectorAll('template[data-sinth-if-expr]').forEach(sinthIfBlock);
|
|
1377
|
-
if (${needsDelay}) {
|
|
1378
|
-
el.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
|
|
1379
|
-
el.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
|
|
1380
|
-
}
|
|
1381
|
-
}
|
|
1382
|
-
`;
|
|
1383
|
-
}
|
|
1407
|
+
|
|
1384
1408
|
|
|
1385
1409
|
const exprArrayJS = exprRegistry.length > 0
|
|
1386
1410
|
? `var __X = [${exprRegistry.map((js) => `function(_ctx){ return ${js}; }`).join(",")}];\n`
|
|
@@ -1395,9 +1419,24 @@ function sinthMixedBlock(el, condId, ifJS, ifHTML, elseJS, elseHTML) {
|
|
|
1395
1419
|
|
|
1396
1420
|
if (needsMixed) {
|
|
1397
1421
|
for (const mb of mixedBlocks) {
|
|
1422
|
+
const ifJS = mb.ifJS ? mb.ifJS.trim() : "";
|
|
1423
|
+
const elseJS = mb.elseJS ? mb.elseJS.trim() : "";
|
|
1398
1424
|
renderBody += ` (function() {
|
|
1399
1425
|
var __el = document.getElementById(${JSON.stringify(mb.replaceId || mb.id)});
|
|
1400
|
-
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
|
+
}
|
|
1401
1440
|
})();\n`;
|
|
1402
1441
|
}
|
|
1403
1442
|
}
|
|
@@ -1473,7 +1512,7 @@ export function compileFile(filePath: string, opts: CompileOptions): { html: str
|
|
|
1473
1512
|
const functionDefs: FunctionDef[] = file.functions; // ← new
|
|
1474
1513
|
|
|
1475
1514
|
const ctx: CompileCtx = {
|
|
1476
|
-
allDefs, customEls, cssLinks, jsLinks,
|
|
1515
|
+
allDefs, functionDefs, customEls, cssLinks, jsLinks,
|
|
1477
1516
|
scopeHash: hash,
|
|
1478
1517
|
pageFile: absPath,
|
|
1479
1518
|
extraCSS: [],
|
|
@@ -1506,8 +1545,16 @@ export function compileFile(filePath: string, opts: CompileOptions): { html: str
|
|
|
1506
1545
|
}
|
|
1507
1546
|
for (const v of file.varDecls) { if (v.value) assignedVars.add(v.name); }
|
|
1508
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
|
+
|
|
1509
1556
|
// compile function definitions to JS
|
|
1510
|
-
const compiledFunctions = functionDefs.map(f => compileFunctionDef(f)).join("\n");
|
|
1557
|
+
const compiledFunctions = functionDefs.map(f => compileFunctionDef(f, ctx)).join("\n");
|
|
1511
1558
|
|
|
1512
1559
|
// companion JS file (needs same name as .sinth, adds support for JS libraries)
|
|
1513
1560
|
const companionJS = (() => {
|
package/src/core/parser.ts
CHANGED
|
@@ -61,6 +61,15 @@ export class Parser {
|
|
|
61
61
|
const forNode = this.parseForLoop();
|
|
62
62
|
uses.push({ kind: "use", name: "__IF_ROOT__", attrs: [], children: [forNode], loc: forNode.loc });
|
|
63
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
|
+
}
|
|
64
73
|
else if (this.check(TT.IDENT)) {
|
|
65
74
|
const savedPos = this.pos;
|
|
66
75
|
const identName = this.peek().value;
|
|
@@ -171,8 +180,8 @@ uses.push(this.parseCompUse());
|
|
|
171
180
|
this.consume(TT.LBRACKET); this.consume(TT.RBRACKET);
|
|
172
181
|
typeStr = "str[]";
|
|
173
182
|
}
|
|
174
|
-
if (!["int", "str", "bool", "str[]", "obj"].includes(typeStr)) {
|
|
175
|
-
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);
|
|
176
185
|
}
|
|
177
186
|
|
|
178
187
|
const nameTok = this.consume(TT.IDENT);
|
|
@@ -393,8 +402,8 @@ private parseArrayLiteral(): Literal {
|
|
|
393
402
|
if (this.check(TT.OP_ARROW)) {
|
|
394
403
|
this.consume(TT.OP_ARROW);
|
|
395
404
|
const typeTok = this.consume(TT.IDENT);
|
|
396
|
-
if (!["int","str","bool","str[]","obj"].includes(typeTok.value)) {
|
|
397
|
-
throw new SinthError(`Unknown return type '${typeTok.value}'. Expected: int, str, bool, str[], obj`, typeTok.loc);
|
|
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);
|
|
398
407
|
}
|
|
399
408
|
returnType = typeTok.value as VarType;
|
|
400
409
|
}
|
|
@@ -804,32 +813,34 @@ private parseArrayLiteral(): Literal {
|
|
|
804
813
|
while (!this.check(TT.EOF) && !this.check(TT.RBRACE)) {
|
|
805
814
|
if (this.check(TT.LPAREN)) {
|
|
806
815
|
const loc = this.peek().loc;
|
|
816
|
+
this.consume(TT.LPAREN);
|
|
807
817
|
let expr = this.parseExpression();
|
|
808
|
-
if (expr)
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
}
|
|
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);
|
|
825
834
|
} else {
|
|
826
|
-
rhs =
|
|
835
|
+
rhs = { kind: "variable", name: rhsName };
|
|
827
836
|
}
|
|
828
|
-
|
|
829
|
-
|
|
837
|
+
} else {
|
|
838
|
+
rhs = this.parseExpression();
|
|
830
839
|
}
|
|
831
|
-
|
|
840
|
+
if (!rhs) throw new SinthError("Expected expression after +", this.peek().loc);
|
|
841
|
+
expr = { kind: "binary", left: expr, op: "+", right: rhs };
|
|
832
842
|
}
|
|
843
|
+
children.push({ kind: "expr", expression: expr, loc });
|
|
833
844
|
continue;
|
|
834
845
|
}
|
|
835
846
|
if (this.check(TT.STRING)) {
|
package/src/core/types.ts
CHANGED
|
@@ -62,9 +62,10 @@ export interface AssignStmt { kind: "assign_stmt"; expression: Expression;
|
|
|
62
62
|
export interface IfBlock { kind: "if"; condition: Expression; body: Child[]; elseBody?: Child[]; loc: Loc }
|
|
63
63
|
export interface ForLoop { kind: "for"; keyVar?: string; itemVar: string; indexVar?: string; arrayVar: string; body: Child[]; loc: Loc }
|
|
64
64
|
export interface RemoveStmt { kind: "remove"; target: string; loc: Loc }
|
|
65
|
+
export interface ComponentExpr { kind: "component_expr"; children: Child[]; loc: Loc }
|
|
65
66
|
|
|
66
67
|
|
|
67
|
-
export type Child = TextNode | CompUse | ExprNode | AssignStmt | IfBlock | ForLoop | RemoveStmt;
|
|
68
|
+
export type Child = TextNode | CompUse | ExprNode | AssignStmt | IfBlock | ForLoop | RemoveStmt | ComponentExpr;
|
|
68
69
|
|
|
69
70
|
export interface ParamDecl { name: string; defaultVal?: Literal; loc: Loc }
|
|
70
71
|
|
|
@@ -82,7 +83,7 @@ export interface CompDef { name: string; params: ParamDecl[]; body: Child[]
|
|
|
82
83
|
export interface CustomElDecl { sinthName: string; tagName: string; params: ParamDecl[]; loc: Loc }
|
|
83
84
|
export interface CustomElInfo { tagName: string; params: ParamDecl[] }
|
|
84
85
|
|
|
85
|
-
export type VarType = "int" | "str" | "bool" | "str[]" | "obj";
|
|
86
|
+
export type VarType = "int" | "str" | "bool" | "str[]" | "obj" | "ui";
|
|
86
87
|
export interface VarDeclaration { kind: "var"; name: string; varType: VarType; value: Literal | null; loc: Loc }
|
|
87
88
|
|
|
88
89
|
export type ImportNode =
|
|
@@ -126,6 +127,7 @@ export interface MixedBlockEntry {
|
|
|
126
127
|
|
|
127
128
|
export interface CompileCtx {
|
|
128
129
|
allDefs: Map<string, CompDef>;
|
|
130
|
+
functionDefs: FunctionDef[];
|
|
129
131
|
customEls: Map<string, CustomElInfo>;
|
|
130
132
|
cssLinks: string[];
|
|
131
133
|
jsLinks: { src: string; attrs: Record<string, string> }[];
|
package/src/core/runtime.ts
DELETED
|
@@ -1,399 +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
|
-
functionsJS: string; // ← new
|
|
15
|
-
}): string | { page: string; shared: string } {
|
|
16
|
-
const { varDecls, bodyHTML, logicBlocks, mixedBlocks, assignedVars, exprRegistry, functionsJS } = opts;
|
|
17
|
-
|
|
18
|
-
const needsExpr = bodyHTML.includes("sinth-expr");
|
|
19
|
-
const needsIf = bodyHTML.includes("data-sinth-if");
|
|
20
|
-
const needsFor = bodyHTML.includes("data-sinth-for");
|
|
21
|
-
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"));
|
|
22
|
-
const needsMixed = mixedBlocks.length > 0;
|
|
23
|
-
const needsLogic = logicBlocks.length > 0;
|
|
24
|
-
const needsRender = needsExpr || needsIf || needsFor || needsMixed || needsLogic;
|
|
25
|
-
|
|
26
|
-
const varLines = varDecls.map(v => {
|
|
27
|
-
if (!v.value) {
|
|
28
|
-
if (!assignedVars.has(v.name)) {
|
|
29
|
-
const defaults: Record<string, string> = { str: '""', int: "0", bool: "false", "str[]": "[]" };
|
|
30
|
-
SinthWarning.emit(
|
|
31
|
-
`Variable '${v.name}' is declared but never assigned. Defaulting to ${defaults[v.varType] ?? "undefined"}.`,
|
|
32
|
-
v.loc,
|
|
33
|
-
);
|
|
34
|
-
}
|
|
35
|
-
const defaults: Record<string, string> = { str: '""', int: "0", bool: "false", "str[]": "[]" };
|
|
36
|
-
return `var ${v.name} = ${defaults[v.varType] ?? "undefined"};`;
|
|
37
|
-
}
|
|
38
|
-
const val = litToString(v.value);
|
|
39
|
-
if (val.startsWith("__VAR__")) return `var ${v.name} = ${val.slice(7)};`;
|
|
40
|
-
if (val.startsWith("__ARR__")) return `var ${v.name} = ${val.slice(7)};`;
|
|
41
|
-
if (v.varType === "obj") return `var ${v.name} = ${val};`;
|
|
42
|
-
if (v.varType === "str") return `var ${v.name} = ${JSON.stringify(val)};`;
|
|
43
|
-
if (v.varType === "str[]" && typeof val === 'string' && val.startsWith("__ARR__")) {
|
|
44
|
-
try {
|
|
45
|
-
const arr = JSON.parse(val.slice(7));
|
|
46
|
-
return `var ${v.name} = ${JSON.stringify(arr)};`;
|
|
47
|
-
} catch { return `var ${v.name} = ${val.slice(7)};`; }
|
|
48
|
-
}
|
|
49
|
-
return `var ${v.name} = ${val};`;
|
|
50
|
-
}).join("\n");
|
|
51
|
-
|
|
52
|
-
if (!needsRender && !needsDelay) {
|
|
53
|
-
return varLines ? `// Sinth compiled runtime\n${varLines}` : "";
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
let helpers = "";
|
|
57
|
-
|
|
58
|
-
if (needsExpr || needsIf || needsFor) {
|
|
59
|
-
helpers += `
|
|
60
|
-
function sinthExpr(el) {
|
|
61
|
-
try {
|
|
62
|
-
var exprFn = __X[el.dataset.exprId];
|
|
63
|
-
if (exprFn) el.textContent = exprFn({});
|
|
64
|
-
} catch(e) {}
|
|
65
|
-
}
|
|
66
|
-
`;
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
if (needsIf || needsMixed) {
|
|
70
|
-
helpers += `
|
|
71
|
-
function sinthReplaceInsert(t, anchor, ifId, replaceId) {
|
|
72
|
-
if (anchor) {
|
|
73
|
-
var cur = anchor.nextSibling;
|
|
74
|
-
while (cur && cur !== t) { var nx = cur.nextSibling; cur.remove(); cur = nx; }
|
|
75
|
-
} else {
|
|
76
|
-
anchor = document.createElement('span');
|
|
77
|
-
anchor.style.display = 'none';
|
|
78
|
-
anchor.dataset.sinthIfAnchor = ifId;
|
|
79
|
-
t.parentNode.insertBefore(anchor, t);
|
|
80
|
-
}
|
|
81
|
-
var _rp = null, _rpParent = null, _rpNext = null;
|
|
82
|
-
if (replaceId) {
|
|
83
|
-
_rp = document.getElementById(replaceId);
|
|
84
|
-
if (_rp) {
|
|
85
|
-
_rpParent = _rp.parentNode;
|
|
86
|
-
_rpNext = _rp.nextSibling;
|
|
87
|
-
_rp.parentNode.removeChild(_rp);
|
|
88
|
-
anchor._sinthReplaced = _rp;
|
|
89
|
-
anchor._sinthReplacedParent = _rpParent;
|
|
90
|
-
anchor._sinthReplacedNext = _rpNext;
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
var frag = document.createRange().createContextualFragment(t.innerHTML);
|
|
94
|
-
frag.querySelectorAll('.sinth-expr').forEach(sinthExpr);
|
|
95
|
-
if (${needsDelay}) {
|
|
96
|
-
frag.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
|
|
97
|
-
frag.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
|
|
98
|
-
}
|
|
99
|
-
var fragFirst = frag.firstChild;
|
|
100
|
-
var fragLast = frag.lastChild;
|
|
101
|
-
if (_rpParent && _rpNext) {
|
|
102
|
-
_rpParent.insertBefore(frag, _rpNext);
|
|
103
|
-
} else if (_rpParent) {
|
|
104
|
-
_rpParent.appendChild(frag);
|
|
105
|
-
} else {
|
|
106
|
-
t.parentNode.insertBefore(frag, t);
|
|
107
|
-
}
|
|
108
|
-
if (replaceId && anchor) {
|
|
109
|
-
anchor._sinthInsertedFirst = fragFirst;
|
|
110
|
-
anchor._sinthInsertedLast = fragLast;
|
|
111
|
-
}
|
|
112
|
-
return anchor;
|
|
113
|
-
}
|
|
114
|
-
`;
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
if (needsDelay) {
|
|
118
|
-
helpers += `
|
|
119
|
-
function sinthDelay(el) {
|
|
120
|
-
if (el.dataset.sinthDelayDone) { el.style.display = ''; return; }
|
|
121
|
-
el.dataset.sinthDelayDone = '1';
|
|
122
|
-
var ms = parseInt(el.dataset.sinthDelay) || 0;
|
|
123
|
-
el.style.display = 'none';
|
|
124
|
-
if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
|
|
125
|
-
else el.style.display = '';
|
|
126
|
-
}
|
|
127
|
-
function sinthDelayExpr(el) {
|
|
128
|
-
try {
|
|
129
|
-
var fn = __X[el.dataset.sinthDelayExprId];
|
|
130
|
-
var ms = fn ? parseInt(fn()) || 0 : 0;
|
|
131
|
-
el.style.display = '';
|
|
132
|
-
if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
|
|
133
|
-
} catch(e) {}
|
|
134
|
-
}
|
|
135
|
-
`;
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
if (needsIf) {
|
|
139
|
-
helpers += `
|
|
140
|
-
function sinthIfBlock(t) {
|
|
141
|
-
var ifId = t.dataset.sinthIfId;
|
|
142
|
-
var anchor = t.parentNode.querySelector('[data-sinth-if-anchor="' + ifId + '"]');
|
|
143
|
-
var condFn = __X[t.dataset.sinthIfExpr];
|
|
144
|
-
var cond = condFn ? condFn() : false;
|
|
145
|
-
if (cond) {
|
|
146
|
-
anchor = sinthReplaceInsert(t, anchor, ifId, t.dataset.sinthIfReplace);
|
|
147
|
-
} else {
|
|
148
|
-
if (anchor) {
|
|
149
|
-
if (anchor._sinthReplaced) {
|
|
150
|
-
var insFirst = anchor._sinthInsertedFirst;
|
|
151
|
-
var insLast = anchor._sinthInsertedLast;
|
|
152
|
-
var rpParent = anchor._sinthReplacedParent;
|
|
153
|
-
var rpNext = anchor._sinthReplacedNext;
|
|
154
|
-
if (insFirst && insLast) {
|
|
155
|
-
var cur = insFirst;
|
|
156
|
-
while (cur && cur !== insLast) {
|
|
157
|
-
var next = cur.nextSibling;
|
|
158
|
-
cur.remove();
|
|
159
|
-
cur = next;
|
|
160
|
-
}
|
|
161
|
-
if (insLast) insLast.remove();
|
|
162
|
-
}
|
|
163
|
-
if (rpParent && rpNext) {
|
|
164
|
-
rpParent.insertBefore(anchor._sinthReplaced, rpNext);
|
|
165
|
-
} else if (rpParent) {
|
|
166
|
-
rpParent.appendChild(anchor._sinthReplaced);
|
|
167
|
-
}
|
|
168
|
-
} else {
|
|
169
|
-
var cur2 = anchor.nextSibling;
|
|
170
|
-
while (cur2 && cur2 !== t) { var nx2 = cur2.nextSibling; cur2.remove(); cur2 = nx2; }
|
|
171
|
-
}
|
|
172
|
-
anchor.remove();
|
|
173
|
-
}
|
|
174
|
-
var elseT = t.nextElementSibling;
|
|
175
|
-
if (elseT && elseT.hasAttribute('data-sinth-else')) {
|
|
176
|
-
var elseIfId = elseT.dataset.sinthIfId;
|
|
177
|
-
var ea = t.parentNode.querySelector('[data-sinth-if-anchor="__else__' + elseIfId + '"]');
|
|
178
|
-
if (ea) {
|
|
179
|
-
var cur3 = ea.nextSibling;
|
|
180
|
-
while (cur3 && cur3 !== t) { var nx3 = cur3.nextSibling; cur3.remove(); cur3 = nx3; }
|
|
181
|
-
} else {
|
|
182
|
-
ea = document.createElement('span');
|
|
183
|
-
ea.style.display = 'none';
|
|
184
|
-
ea.dataset.sinthIfAnchor = '__else__' + elseIfId;
|
|
185
|
-
t.parentNode.insertBefore(ea, t);
|
|
186
|
-
}
|
|
187
|
-
var ef = document.createRange().createContextualFragment(elseT.innerHTML);
|
|
188
|
-
ef.querySelectorAll('.sinth-expr').forEach(sinthExpr);
|
|
189
|
-
if (${needsDelay}) {
|
|
190
|
-
ef.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
|
|
191
|
-
ef.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
|
|
192
|
-
}
|
|
193
|
-
t.parentNode.insertBefore(ef, t);
|
|
194
|
-
} else {
|
|
195
|
-
var ea2 = t.parentNode.querySelector('[data-sinth-if-anchor="__else__' + ifId + '"]');
|
|
196
|
-
if (ea2) {
|
|
197
|
-
var ec = ea2.nextSibling;
|
|
198
|
-
while (ec && ec !== t) { var en = ec.nextSibling; ec.remove(); ec = en; }
|
|
199
|
-
ea2.remove();
|
|
200
|
-
}
|
|
201
|
-
}
|
|
202
|
-
}
|
|
203
|
-
}
|
|
204
|
-
`;
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
if (needsFor) {
|
|
208
|
-
helpers += `
|
|
209
|
-
function hashString(str) {
|
|
210
|
-
var hash = 0, i, chr;
|
|
211
|
-
for (i = 0; i < str.length; i++) {
|
|
212
|
-
chr = str.charCodeAt(i);
|
|
213
|
-
hash = ((hash << 5) - hash) + chr;
|
|
214
|
-
hash |= 0;
|
|
215
|
-
}
|
|
216
|
-
return String(hash);
|
|
217
|
-
}
|
|
218
|
-
function sinthForBlock(t) {
|
|
219
|
-
var source = window[t.dataset.sinthFor];
|
|
220
|
-
if (source === undefined) source = [];
|
|
221
|
-
var newHash = '';
|
|
222
|
-
try { newHash = hashString(JSON.stringify(source)); } catch(e) { newHash = ''; }
|
|
223
|
-
if (t.dataset.sinthForHash && t.dataset.sinthForHash === newHash) {
|
|
224
|
-
return;
|
|
225
|
-
}
|
|
226
|
-
t.dataset.sinthForHash = newHash;
|
|
227
|
-
var isObj = (typeof source === 'object' && source !== null && !Array.isArray(source));
|
|
228
|
-
var entries;
|
|
229
|
-
if (isObj) {
|
|
230
|
-
entries = Object.entries(source);
|
|
231
|
-
} else {
|
|
232
|
-
if (!Array.isArray(source)) source = [];
|
|
233
|
-
entries = source.map(function(item, index) { return [index, item]; });
|
|
234
|
-
}
|
|
235
|
-
var anchor = t.parentNode ? t.parentNode.querySelector('[data-sinth-for-anchor="' + t.dataset.sinthFor + '"]') : null;
|
|
236
|
-
if (anchor) {
|
|
237
|
-
var cur2 = anchor.nextSibling;
|
|
238
|
-
while (cur2 && cur2 !== t) { var nx2 = cur2.nextSibling; cur2.remove(); cur2 = nx2; }
|
|
239
|
-
anchor.remove();
|
|
240
|
-
}
|
|
241
|
-
var fa = document.createElement('span');
|
|
242
|
-
fa.style.display = 'none';
|
|
243
|
-
fa.dataset.sinthForAnchor = t.dataset.sinthFor;
|
|
244
|
-
t.parentNode && t.parentNode.insertBefore(fa, t);
|
|
245
|
-
var _loopIdx = 0;
|
|
246
|
-
entries.forEach(function(entry) {
|
|
247
|
-
var _k = entry[0];
|
|
248
|
-
var _v = entry[1];
|
|
249
|
-
var _item = (t.dataset && t.dataset.sinthItem) ? t.dataset.sinthItem : '__item__';
|
|
250
|
-
var _key = t.dataset && t.dataset.sinthKey ? t.dataset.sinthKey : null;
|
|
251
|
-
var _idx = t.dataset && t.dataset.sinthIndex ? t.dataset.sinthIndex : null;
|
|
252
|
-
_loopIdx++;
|
|
253
|
-
if (t.dataset.sinthIfReplace) {
|
|
254
|
-
var _rp = document.getElementById(t.dataset.sinthIfReplace);
|
|
255
|
-
if (_rp) _rp.parentNode.removeChild(_rp);
|
|
256
|
-
}
|
|
257
|
-
var frag = document.createRange().createContextualFragment(t.innerHTML);
|
|
258
|
-
frag.querySelectorAll('.sinth-expr').forEach(function(el) {
|
|
259
|
-
try {
|
|
260
|
-
var exprFn = __X[el.dataset.exprId];
|
|
261
|
-
if (!exprFn) return;
|
|
262
|
-
var _ctx = {};
|
|
263
|
-
if (_item) _ctx[_item] = _v;
|
|
264
|
-
if (_key) _ctx[_key] = _k;
|
|
265
|
-
if (_idx) _ctx[_idx] = _loopIdx - 1;
|
|
266
|
-
el.textContent = exprFn(_ctx);
|
|
267
|
-
el.classList.remove('sinth-expr');
|
|
268
|
-
} catch(e) {}
|
|
269
|
-
});
|
|
270
|
-
frag.querySelectorAll('template[data-sinth-if-expr]').forEach(function(ifT) {
|
|
271
|
-
var condFn = __X[ifT.dataset.sinthIfExpr];
|
|
272
|
-
var _ctx = {};
|
|
273
|
-
if (_item) _ctx[_item] = _v;
|
|
274
|
-
if (_key) _ctx[_key] = _k;
|
|
275
|
-
if (_idx) _ctx[_idx] = _loopIdx - 1;
|
|
276
|
-
var cond = false;
|
|
277
|
-
try { if (condFn) cond = condFn(_ctx); } catch(e) {}
|
|
278
|
-
if (cond) {
|
|
279
|
-
var ifContent = document.createRange().createContextualFragment(ifT.innerHTML);
|
|
280
|
-
ifContent.querySelectorAll('.sinth-expr').forEach(function(el2) {
|
|
281
|
-
try {
|
|
282
|
-
var exprFn2 = __X[el2.dataset.exprId];
|
|
283
|
-
if (exprFn2) el2.textContent = exprFn2(_ctx);
|
|
284
|
-
} catch(e) {}
|
|
285
|
-
});
|
|
286
|
-
ifT.parentNode.insertBefore(ifContent, ifT);
|
|
287
|
-
} else {
|
|
288
|
-
var elseT = ifT.nextElementSibling;
|
|
289
|
-
if (elseT && elseT.hasAttribute('data-sinth-else')) {
|
|
290
|
-
var elseContent = document.createRange().createContextualFragment(elseT.innerHTML);
|
|
291
|
-
elseContent.querySelectorAll('.sinth-expr').forEach(function(el2) {
|
|
292
|
-
try {
|
|
293
|
-
var exprFn2 = __X[el2.dataset.exprId];
|
|
294
|
-
if (exprFn2) el2.textContent = exprFn2(_ctx);
|
|
295
|
-
} catch(e) {}
|
|
296
|
-
});
|
|
297
|
-
ifT.parentNode.insertBefore(elseContent, ifT);
|
|
298
|
-
}
|
|
299
|
-
}
|
|
300
|
-
});
|
|
301
|
-
if (${needsDelay}) {
|
|
302
|
-
frag.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
|
|
303
|
-
frag.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
|
|
304
|
-
}
|
|
305
|
-
t.parentNode && t.parentNode.insertBefore(frag, t);
|
|
306
|
-
});
|
|
307
|
-
}
|
|
308
|
-
`;
|
|
309
|
-
}
|
|
310
|
-
|
|
311
|
-
if (needsMixed) {
|
|
312
|
-
helpers += `
|
|
313
|
-
function sinthMixedBlock(el, condId, ifJS, ifHTML, elseJS, elseHTML) {
|
|
314
|
-
var condFn = __X[condId];
|
|
315
|
-
var cond = condFn ? condFn() : false;
|
|
316
|
-
if (cond) {
|
|
317
|
-
if (ifJS) eval(ifJS);
|
|
318
|
-
el.innerHTML = ifHTML;
|
|
319
|
-
} else {
|
|
320
|
-
if (elseJS) eval(elseJS);
|
|
321
|
-
el.innerHTML = elseHTML;
|
|
322
|
-
}
|
|
323
|
-
el.querySelectorAll('.sinth-expr').forEach(sinthExpr);
|
|
324
|
-
el.querySelectorAll('template[data-sinth-if-expr]').forEach(sinthIfBlock);
|
|
325
|
-
if (${needsDelay}) {
|
|
326
|
-
el.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
|
|
327
|
-
el.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
|
|
328
|
-
}
|
|
329
|
-
}
|
|
330
|
-
`;
|
|
331
|
-
}
|
|
332
|
-
|
|
333
|
-
const exprArrayJS = exprRegistry.length > 0
|
|
334
|
-
? `var __X = [${exprRegistry.map((js) => `function(_ctx){ return ${js}; }`).join(",")}];\n`
|
|
335
|
-
: "";
|
|
336
|
-
|
|
337
|
-
let renderBody = "";
|
|
338
|
-
renderBody += ` var _sx = window.scrollX, _sy = window.scrollY;\n`;
|
|
339
|
-
|
|
340
|
-
if (needsLogic) {
|
|
341
|
-
renderBody += logicBlocks.map(b => b.replace(/^/gm, " ")).join("\n") + "\n";
|
|
342
|
-
}
|
|
343
|
-
|
|
344
|
-
if (needsMixed) {
|
|
345
|
-
for (const mb of mixedBlocks) {
|
|
346
|
-
renderBody += ` (function() {
|
|
347
|
-
var __el = document.getElementById(${JSON.stringify(mb.replaceId || mb.id)});
|
|
348
|
-
if (__el) sinthMixedBlock(__el, ${mb.conditionJS}, ${JSON.stringify(mb.ifJS)}, ${JSON.stringify(mb.ifHTML)}, ${JSON.stringify(mb.elseJS)}, ${JSON.stringify(mb.elseHTML)});
|
|
349
|
-
})();\n`;
|
|
350
|
-
}
|
|
351
|
-
}
|
|
352
|
-
|
|
353
|
-
renderBody += ` document.querySelectorAll('[data-sinth-remove]').forEach(function(el) {
|
|
354
|
-
var target = document.getElementById(el.dataset.sinthRemove);
|
|
355
|
-
if (target) target.remove();
|
|
356
|
-
});\n`;
|
|
357
|
-
|
|
358
|
-
if (needsIf) {
|
|
359
|
-
renderBody += ` document.querySelectorAll('template[data-sinth-if-expr]').forEach(sinthIfBlock);\n`;
|
|
360
|
-
}
|
|
361
|
-
if (needsFor) {
|
|
362
|
-
renderBody += ` document.querySelectorAll('template[data-sinth-for]').forEach(sinthForBlock);\n`;
|
|
363
|
-
}
|
|
364
|
-
renderBody += ` document.querySelectorAll('[data-sinth-value]').forEach(function(el) {
|
|
365
|
-
try { el.value = window[el.dataset.sinthValue] || ''; } catch(e) {}
|
|
366
|
-
});\n`;
|
|
367
|
-
renderBody += ` document.querySelectorAll('[data-sinth-checked]').forEach(function(el) {
|
|
368
|
-
try { el.checked = !!window[el.dataset.sinthChecked]; } catch(e) {}
|
|
369
|
-
});\n`;
|
|
370
|
-
if (needsExpr) {
|
|
371
|
-
renderBody += ` document.querySelectorAll('.sinth-expr').forEach(sinthExpr);\n`;
|
|
372
|
-
}
|
|
373
|
-
if (needsDelay) {
|
|
374
|
-
renderBody += ` setTimeout(function() {
|
|
375
|
-
document.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
|
|
376
|
-
document.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
|
|
377
|
-
}, 0);\n`;
|
|
378
|
-
}
|
|
379
|
-
renderBody += ` window.scrollTo(_sx, _sy);\n`;
|
|
380
|
-
|
|
381
|
-
const renderFunc = needsRender ? `function sinthRender() {\n${renderBody}}\nsinthRender();` : "";
|
|
382
|
-
|
|
383
|
-
const pageCode = `// Sinth page runtime
|
|
384
|
-
${varLines}
|
|
385
|
-
${functionsJS ? functionsJS + "\n" : ""}${exprArrayJS}
|
|
386
|
-
${renderFunc}`;
|
|
387
|
-
|
|
388
|
-
if (opts.sharedRuntime && helpers.trim()) {
|
|
389
|
-
const sharedCode = `// Sinth shared runtime
|
|
390
|
-
${helpers}`;
|
|
391
|
-
return { page: pageCode, shared: sharedCode };
|
|
392
|
-
}
|
|
393
|
-
|
|
394
|
-
return `// Sinth compiled runtime
|
|
395
|
-
${varLines}
|
|
396
|
-
${functionsJS ? functionsJS + "\n" : ""}${helpers}
|
|
397
|
-
${exprArrayJS}
|
|
398
|
-
${renderFunc}`;
|
|
399
|
-
}
|