@yannosay/sinth 1.8.0 → 1.8.2

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.
@@ -1,135 +1,135 @@
1
- import { CustomElDecl, CompileCtx } from "../types.ts";
2
- import { renderChild } from "../compiler.ts";
3
- import { litToString } from "../../utils.ts";
4
-
5
- export function compileCustomElement(cel: CustomElDecl, opts: { sharedRuntime: boolean }, hash: string, ctx: CompileCtx): string {
6
- const varDecls = cel.varDecls;
7
-
8
- const varLines = varDecls.map(v => {
9
- if (v.value) {
10
- const val = litToString(v.value);
11
- if (v.varType === "int") return `this._${v.name} = ${parseFloat(val) || 0};`;
12
- if (v.varType === "bool") return `this._${v.name} = ${val === "true" ? "true" : "false"};`;
13
- return `this._${v.name} = ${JSON.stringify(val)};`;
14
- }
15
- const defaults: Record<string, string> = { str: '""', int: "0", bool: "false", "str[]": "[]" };
16
- return `this._${v.name} = ${defaults[v.varType ?? "str"] ?? "undefined"};`;
17
- }).join("\n ");
18
-
19
- const childCtx: CompileCtx = {
20
- ...ctx,
21
- exprRegistry: [],
22
- exprMap: new Map(),
23
- logicBlocks: [],
24
- mixedBlocks: [],
25
- customEls: new Map(),
26
- scopePrefix: 'host._',
27
- scopeVar: 'host',
28
- };
29
-
30
- const customVarMap = new Map<string, string>();
31
- for (const v of varDecls) {
32
- customVarMap.set(v.name, `__VAR__${v.name}`);
33
- }
34
-
35
- const bodyHTML = cel.body.map(c => renderChild(c, childCtx, customVarMap, 0)).join("\n");
36
-
37
- const escapedHTML = bodyHTML
38
- .replace(/sinthRender\(\)/g, 'host._render()')
39
- .replace(/\\/g, '\\\\')
40
- .replace(/`/g, '\\`')
41
- .replace(/\$/g, '\\$')
42
- .replace(/__VAR__(\w+)/g, 'host._$$1');
43
-
44
- const needsExpr = bodyHTML.includes("sinth-expr");
45
- const needsIf = bodyHTML.includes("data-sinth-if");
46
-
47
- const exprArrayJS = childCtx.exprRegistry.length > 0
48
- ? `let __X = [${childCtx.exprRegistry.map(js => {
49
- const replaced = varDecls.reduce((acc, v) => {
50
- const regex = new RegExp(`\\b${v.name}\\b(?![.\\(])`, 'g');
51
- return acc.replace(regex, `_ctx.host._${v.name}`);
52
- }, js);
53
- return `function(_ctx){ return ${replaced}; }`;
54
- }).join(",")}];\n`
55
- : "";
56
-
57
- return `// Sinth Custom Element: ${cel.exportTag}
58
- (function() {
59
- ${exprArrayJS}
60
-
61
- var sinthExpr = function(el, host) {
62
- try {
63
- let exprFn = __X[el.dataset.exprId];
64
- if (exprFn) el.textContent = exprFn({host: host});
65
- } catch(e) {}
66
- };
67
-
68
- function render(host) {
69
- ${needsExpr ? `host.shadowRoot.querySelectorAll('.sinth-expr').forEach(function(el) { sinthExpr(el, host); });` : ""}
70
- ${needsIf ? `
71
- var templates = host.shadowRoot.querySelectorAll('template[data-sinth-if-expr]');
72
- var seen = {};
73
- templates.forEach(function(t) {
74
- var ifId = t.dataset.sinthIfId;
75
- if (seen[ifId]) return;
76
- seen[ifId] = true;
77
- var condFn = __X[t.dataset.sinthIfExpr];
78
- var cond = condFn ? condFn({host: host}) : false;
79
- var elseT = host.shadowRoot.querySelector('template[data-sinth-else][data-sinth-if-id="' + ifId + '"]');
80
- var sourceT = cond ? t : elseT;
81
- var anchor = host.shadowRoot.querySelector('[data-sinth-if-anchor="' + ifId + '"]');
82
- if (sourceT) {
83
- if (!anchor) {
84
- anchor = document.createElement('span');
85
- anchor.style.display = 'none';
86
- anchor.dataset.sinthIfAnchor = ifId;
87
- t.parentNode.insertBefore(anchor, t);
88
- }
89
- var c = anchor.nextSibling;
90
- while (c && c !== t) { var n = c.nextSibling; c.remove(); c = n; }
91
- var frag = document.createRange().createContextualFragment(sourceT.innerHTML);
92
- frag.querySelectorAll('.sinth-expr').forEach(function(el) { sinthExpr(el, host); });
93
- t.parentNode.insertBefore(frag, t);
94
- } else {
95
- if (anchor) {
96
- var c = anchor.nextSibling;
97
- while (c && c !== t) { var n = c.nextSibling; c.remove(); c = n; }
98
- anchor.remove();
99
- }
100
- }
101
- });
102
- ` : ""}
103
- host.shadowRoot.querySelectorAll('[data-sinth-value]').forEach(function(el) {
104
- try { if (document.activeElement !== el) { let v = el.dataset.sinthValue; el.value = __X[v] ? __X[v]({host: host}) : ''; } } catch(e) {}
105
- });
106
- }
107
-
108
- class ${cel.sinthName} extends HTMLElement {
109
- constructor() {
110
- super();
111
- this.attachShadow({ mode: 'open' });
112
- ${varLines}
113
- }
114
- connectedCallback() {
115
- var host = this;
116
- this._render = function() { render(host); };
117
- this.shadowRoot.innerHTML = \`${escapedHTML}\`;
118
- var _ceHandlers = [${(childCtx.ceActionHandlers || []).join(',')}];
119
- this.shadowRoot.querySelectorAll('[data-sinth-ce-click],[data-sinth-ce-input],[data-sinth-ce-change],[data-sinth-ce-submit]').forEach(function(el) {
120
- var attrs = el.attributes;
121
- for (var i = 0; i < attrs.length; i++) {
122
- var name = attrs[i].name;
123
- if (name.indexOf('data-sinth-ce-') === 0) {
124
- var eventType = name.substring('data-sinth-ce-'.length);
125
- var idx = parseInt(attrs[i].value);
126
- el.addEventListener(eventType, function(e) { _ceHandlers[idx](e, host); });
127
- }
128
- }
129
- });
130
- render(this);
131
- }
132
- }
133
- customElements.define('${cel.exportTag}', ${cel.sinthName});
134
- })();`;
1
+ import { CustomElDecl, CompileCtx } from "../types.ts";
2
+ import { renderChild } from "../compiler.ts";
3
+ import { litToString } from "../../utils.ts";
4
+
5
+ export function compileCustomElement(cel: CustomElDecl, opts: { sharedRuntime: boolean }, hash: string, ctx: CompileCtx): string {
6
+ const varDecls = cel.varDecls;
7
+
8
+ const varLines = varDecls.map(v => {
9
+ if (v.value) {
10
+ const val = litToString(v.value);
11
+ if (v.varType === "int") return `this._${v.name} = ${parseFloat(val) || 0};`;
12
+ if (v.varType === "bool") return `this._${v.name} = ${val === "true" ? "true" : "false"};`;
13
+ return `this._${v.name} = ${JSON.stringify(val)};`;
14
+ }
15
+ const defaults: Record<string, string> = { str: '""', int: "0", bool: "false", "str[]": "[]" };
16
+ return `this._${v.name} = ${defaults[v.varType ?? "str"] ?? "undefined"};`;
17
+ }).join("\n ");
18
+
19
+ const childCtx: CompileCtx = {
20
+ ...ctx,
21
+ exprRegistry: [],
22
+ exprMap: new Map(),
23
+ logicBlocks: [],
24
+ mixedBlocks: [],
25
+ customEls: new Map(),
26
+ scopePrefix: 'host._',
27
+ scopeVar: 'host',
28
+ };
29
+
30
+ const customVarMap = new Map<string, string>();
31
+ for (const v of varDecls) {
32
+ customVarMap.set(v.name, `__VAR__${v.name}`);
33
+ }
34
+
35
+ const bodyHTML = cel.body.map(c => renderChild(c, childCtx, customVarMap, 0)).join("\n");
36
+
37
+ const escapedHTML = bodyHTML
38
+ .replace(/sinthRender\(\)/g, 'host._render()')
39
+ .replace(/\\/g, '\\\\')
40
+ .replace(/`/g, '\\`')
41
+ .replace(/\$/g, '\\$')
42
+ .replace(/__VAR__(\w+)/g, 'host._$$1');
43
+
44
+ const needsExpr = bodyHTML.includes("sinth-expr");
45
+ const needsIf = bodyHTML.includes("data-sinth-if");
46
+
47
+ const exprArrayJS = childCtx.exprRegistry.length > 0
48
+ ? `let __X = [${childCtx.exprRegistry.map(js => {
49
+ const replaced = varDecls.reduce((acc, v) => {
50
+ const regex = new RegExp(`\\b${v.name}\\b(?![.\\(])`, 'g');
51
+ return acc.replace(regex, `_ctx.host._${v.name}`);
52
+ }, js);
53
+ return `function(_ctx){ return ${replaced}; }`;
54
+ }).join(",")}];\n`
55
+ : "";
56
+
57
+ return `// Sinth Custom Element: ${cel.exportTag}
58
+ (function() {
59
+ ${exprArrayJS}
60
+
61
+ var sinthExpr = function(el, host) {
62
+ try {
63
+ let exprFn = __X[el.dataset.exprId];
64
+ if (exprFn) el.textContent = exprFn({host: host});
65
+ } catch(e) {}
66
+ };
67
+
68
+ function render(host) {
69
+ ${needsExpr ? `host.shadowRoot.querySelectorAll('.sinth-expr').forEach(function(el) { sinthExpr(el, host); });` : ""}
70
+ ${needsIf ? `
71
+ var templates = host.shadowRoot.querySelectorAll('template[data-sinth-if-expr]');
72
+ var seen = {};
73
+ templates.forEach(function(t) {
74
+ var ifId = t.dataset.sinthIfId;
75
+ if (seen[ifId]) return;
76
+ seen[ifId] = true;
77
+ var condFn = __X[t.dataset.sinthIfExpr];
78
+ var cond = condFn ? condFn({host: host}) : false;
79
+ var elseT = host.shadowRoot.querySelector('template[data-sinth-else][data-sinth-if-id="' + ifId + '"]');
80
+ var sourceT = cond ? t : elseT;
81
+ var anchor = host.shadowRoot.querySelector('[data-sinth-if-anchor="' + ifId + '"]');
82
+ if (sourceT) {
83
+ if (!anchor) {
84
+ anchor = document.createElement('span');
85
+ anchor.style.display = 'none';
86
+ anchor.dataset.sinthIfAnchor = ifId;
87
+ t.parentNode.insertBefore(anchor, t);
88
+ }
89
+ var c = anchor.nextSibling;
90
+ while (c && c !== t) { var n = c.nextSibling; c.remove(); c = n; }
91
+ var frag = document.createRange().createContextualFragment(sourceT.innerHTML);
92
+ frag.querySelectorAll('.sinth-expr').forEach(function(el) { sinthExpr(el, host); });
93
+ t.parentNode.insertBefore(frag, t);
94
+ } else {
95
+ if (anchor) {
96
+ var c = anchor.nextSibling;
97
+ while (c && c !== t) { var n = c.nextSibling; c.remove(); c = n; }
98
+ anchor.remove();
99
+ }
100
+ }
101
+ });
102
+ ` : ""}
103
+ host.shadowRoot.querySelectorAll('[data-sinth-value]').forEach(function(el) {
104
+ try { if (document.activeElement !== el) { let v = el.dataset.sinthValue; el.value = __X[v] ? __X[v]({host: host}) : ''; } } catch(e) {}
105
+ });
106
+ }
107
+
108
+ class ${cel.sinthName} extends HTMLElement {
109
+ constructor() {
110
+ super();
111
+ this.attachShadow({ mode: 'open' });
112
+ ${varLines}
113
+ }
114
+ connectedCallback() {
115
+ var host = this;
116
+ this._render = function() { render(host); };
117
+ this.shadowRoot.innerHTML = \`${escapedHTML}\`;
118
+ var _ceHandlers = [${(childCtx.ceActionHandlers || []).join(',')}];
119
+ this.shadowRoot.querySelectorAll('[data-sinth-ce-click],[data-sinth-ce-input],[data-sinth-ce-change],[data-sinth-ce-submit]').forEach(function(el) {
120
+ var attrs = el.attributes;
121
+ for (var i = 0; i < attrs.length; i++) {
122
+ var name = attrs[i].name;
123
+ if (name.indexOf('data-sinth-ce-') === 0) {
124
+ var eventType = name.substring('data-sinth-ce-'.length);
125
+ var idx = parseInt(attrs[i].value);
126
+ el.addEventListener(eventType, function(e) { _ceHandlers[idx](e, host); });
127
+ }
128
+ }
129
+ });
130
+ render(this);
131
+ }
132
+ }
133
+ customElements.define('${cel.exportTag}', ${cel.sinthName});
134
+ })();`;
135
135
  }
@@ -1,47 +1,47 @@
1
- import { CompileCtx, FunctionDef, IfBlock } from "../types.ts";
2
- import { compileExprToJS, compileIfToJS } from "../expr.ts";
3
-
4
- export function compileFunctionDef(fn: FunctionDef, ctx: CompileCtx): string {
5
- const paramsJS = fn.params.map(p => p.name).join(", ");
6
-
7
- if (fn.returnType === "ui") {
8
- return "";
9
- }
10
-
11
- const bodyStatements: string[] = [];
12
-
13
- for (const child of fn.body) {
14
- switch (child.kind) {
15
- case "text":
16
- break;
17
- case "expr":
18
- bodyStatements.push(`${compileExprToJS(child.expression)};`);
19
- break;
20
- case "assign_stmt":
21
- bodyStatements.push(`${compileExprToJS(child.expression)};`);
22
- break;
23
- case "if":
24
- bodyStatements.push(compileIfToJS(child as IfBlock));
25
- break;
26
- case "for": {
27
- const fl = child as any;
28
- const itemVar = fl.itemVar;
29
- const arrayVar = fl.arrayVar;
30
- const bodyJS = fl.body.map((c: any) => {
31
- if (c.kind === "assign_stmt") return `${compileExprToJS(c.expression)};`;
32
- if (c.kind === "if") return compileIfToJS(c);
33
- if (c.kind === "expr") return `${compileExprToJS(c.expression)};`;
34
- return "";
35
- }).filter(Boolean).join("\n");
36
- const bodyLines = bodyJS.split("\n");
37
- const indentedBody = bodyLines.map((line: string) => ` ${line}`).join("\n");
38
- bodyStatements.push(`for (let ${itemVar} of ${arrayVar}) {\n${indentedBody}\n }`);
39
- break;
40
- }
41
- case "return":
42
- bodyStatements.push(`return ${child.expression ? compileExprToJS(child.expression) : ""};`);
43
- break;
44
- }
45
- }
46
- return `function ${fn.name}(${paramsJS}) {\n${bodyStatements.map(s => ` ${s}`).join("\n")}\n}`;
1
+ import { CompileCtx, FunctionDef, IfBlock } from "../types.ts";
2
+ import { compileExprToJS, compileIfToJS } from "../expr.ts";
3
+
4
+ export function compileFunctionDef(fn: FunctionDef, ctx: CompileCtx): string {
5
+ const paramsJS = fn.params.map(p => p.name).join(", ");
6
+
7
+ if (fn.returnType === "ui") {
8
+ return "";
9
+ }
10
+
11
+ const bodyStatements: string[] = [];
12
+
13
+ for (const child of fn.body) {
14
+ switch (child.kind) {
15
+ case "text":
16
+ break;
17
+ case "expr":
18
+ bodyStatements.push(`${compileExprToJS(child.expression)};`);
19
+ break;
20
+ case "assign_stmt":
21
+ bodyStatements.push(`${compileExprToJS(child.expression)};`);
22
+ break;
23
+ case "if":
24
+ bodyStatements.push(compileIfToJS(child as IfBlock));
25
+ break;
26
+ case "for": {
27
+ const fl = child as any;
28
+ const itemVar = fl.itemVar;
29
+ const arrayVar = fl.arrayVar;
30
+ const bodyJS = fl.body.map((c: any) => {
31
+ if (c.kind === "assign_stmt") return `${compileExprToJS(c.expression)};`;
32
+ if (c.kind === "if") return compileIfToJS(c);
33
+ if (c.kind === "expr") return `${compileExprToJS(c.expression)};`;
34
+ return "";
35
+ }).filter(Boolean).join("\n");
36
+ const bodyLines = bodyJS.split("\n");
37
+ const indentedBody = bodyLines.map((line: string) => ` ${line}`).join("\n");
38
+ bodyStatements.push(`for (let ${itemVar} of ${arrayVar}) {\n${indentedBody}\n }`);
39
+ break;
40
+ }
41
+ case "return":
42
+ bodyStatements.push(`return ${child.expression ? compileExprToJS(child.expression) : ""};`);
43
+ break;
44
+ }
45
+ }
46
+ return `function ${fn.name}(${paramsJS}) {\n${bodyStatements.map(s => ` ${s}`).join("\n")}\n}`;
47
47
  }