@yannosay/sinth 1.8.5 → 1.11.6

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/src/core/expr.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { Expression, Child, AssignStmt, IfBlock, ReturnStmt, LitStr, LitNum, LitBool, CompileCtx } from "./types.ts";
2
2
 
3
- export function compileExprToJS(expr: Expression, loopVars?: Set<string>): string {
3
+ export function compileExprToJS(expr: Expression, loopVars?: Set<string>, namespace?: string, declaredVars?: Set<string>): string {
4
4
  switch (expr.kind) {
5
5
  case "literal":
6
6
  if (!expr.value) return "null";
@@ -21,32 +21,56 @@ export function compileExprToJS(expr: Expression, loopVars?: Set<string>): strin
21
21
  return `_ctx.${expr.name}`;
22
22
  }
23
23
  }
24
+ if (namespace && declaredVars && expr.name) {
25
+ const dotIdx2 = expr.name.indexOf('.');
26
+ const root2 = dotIdx2 !== -1 ? expr.name.substring(0, dotIdx2) : expr.name;
27
+ if (declaredVars.has(root2)) {
28
+ return namespace + "_" + expr.name;
29
+ }
30
+ }
24
31
  return expr.name ?? "undefined";
25
32
  case "binary": {
26
- const l = compileExprToJS(expr.left!, loopVars);
27
- const r = compileExprToJS(expr.right!, loopVars);
33
+ const l = compileExprToJS(expr.left!, loopVars, namespace, declaredVars);
34
+ const r = compileExprToJS(expr.right!, loopVars, namespace, declaredVars);
28
35
  const o = expr.op === "and" ? "&&" : expr.op === "or" ? "||" : expr.op!;
29
36
  return `(${l} ${o} ${r})`;
30
37
  }
31
38
  case "unary": {
32
39
  const o = expr.op === "not" ? "!" : expr.op!;
33
- return `${o}(${compileExprToJS(expr.operand!, loopVars)})`;
40
+ return `${o}(${compileExprToJS(expr.operand!, loopVars, namespace, declaredVars)})`;
34
41
  }
35
42
  case "assign": {
36
- const v = expr.right ? compileExprToJS(expr.right, loopVars) : "null";
37
- return `${expr.target} ${expr.op} ${v}`;
43
+ const v = expr.right ? compileExprToJS(expr.right, loopVars, namespace, declaredVars) : "null";
44
+ let t = expr.target ?? "undefined";
45
+ if (namespace && declaredVars && expr.target) {
46
+ const dotIdx = expr.target.indexOf('.');
47
+ const root = dotIdx !== -1 ? expr.target.substring(0, dotIdx) : expr.target;
48
+ if (declaredVars.has(root)) {
49
+ t = namespace + "_" + expr.target;
50
+ }
51
+ }
52
+ return `${t} ${expr.op} ${v}`;
38
53
  }
39
54
  case "index":
40
- return `${compileExprToJS(expr.object!, loopVars)}[${compileExprToJS(expr.key!, loopVars)}]`;
41
- case "postfix":
42
- return `${expr.target}${expr.op}`;
55
+ return `${compileExprToJS(expr.object!, loopVars, namespace, declaredVars)}[${compileExprToJS(expr.key!, loopVars, namespace, declaredVars)}]`;
56
+ case "postfix": {
57
+ let t2 = expr.target ?? "undefined";
58
+ if (namespace && declaredVars && expr.target) {
59
+ const dotIdx = expr.target.indexOf('.');
60
+ const root = dotIdx !== -1 ? expr.target.substring(0, dotIdx) : expr.target;
61
+ if (declaredVars.has(root)) {
62
+ t2 = namespace + "_" + expr.target;
63
+ }
64
+ }
65
+ return `${t2}${expr.op}`;
66
+ }
43
67
  case "call": {
44
- const callee = compileExprToJS(expr.callee!, loopVars);
68
+ const callee = compileExprToJS(expr.callee!, loopVars, namespace, declaredVars);
45
69
  if (callee === "remove") {
46
- const arg = expr.args && expr.args[0] ? compileExprToJS(expr.args[0], loopVars) : "''";
70
+ const arg = expr.args && expr.args[0] ? compileExprToJS(expr.args[0], loopVars, namespace, declaredVars) : "''";
47
71
  return `(function(){ var _el=document.getElementById(${arg}); if(_el)_el.remove(); })()`;
48
72
  }
49
- const args = (expr.args ?? []).map(a => compileExprToJS(a, loopVars)).join(", ");
73
+ const args = (expr.args ?? []).map(a => compileExprToJS(a, loopVars, namespace, declaredVars)).join(", ");
50
74
  if (expr.args && expr.args.length === 0 && /\.length$/.test(callee)) {
51
75
  return callee;
52
76
  }
@@ -58,10 +82,10 @@ export function compileExprToJS(expr: Expression, loopVars?: Set<string>): strin
58
82
  }
59
83
 
60
84
 
61
- export function compileIfToJS(ifBlock: IfBlock): string {
62
- const cond = compileExprToJS(ifBlock.condition);
63
- const ifJS = bodyToJS(ifBlock.body);
64
- const elseJS = ifBlock.elseBody ? bodyToJS(ifBlock.elseBody) : "";
85
+ export function compileIfToJS(ifBlock: IfBlock, loopVars?: Set<string>, namespace?: string, declaredVars?: Set<string>): string {
86
+ const cond = compileExprToJS(ifBlock.condition, loopVars, namespace, declaredVars);
87
+ const ifJS = bodyToJS(ifBlock.body, loopVars, namespace, declaredVars);
88
+ const elseJS = ifBlock.elseBody ? bodyToJS(ifBlock.elseBody, loopVars, namespace, declaredVars) : "";
65
89
  let js = `if (${cond}) {\n${ifJS}}\n`;
66
90
  if (elseJS) js += `else {\n${elseJS}}\n`;
67
91
  return js;
@@ -69,14 +93,14 @@ export function compileIfToJS(ifBlock: IfBlock): string {
69
93
 
70
94
 
71
95
 
72
- export function bodyToJS(children: Child[]): string {
96
+ export function bodyToJS(children: Child[], loopVars?: Set<string>, namespace?: string, declaredVars?: Set<string>): string {
73
97
  return children
74
98
  .filter(c => c.kind === "assign_stmt" || c.kind === "if" || c.kind === "return" || c.kind === "expr")
75
99
  .map(c => {
76
- if (c.kind === "assign_stmt") return ` ${compileExprToJS((c as AssignStmt).expression)};\n`;
77
- if (c.kind === "return") return ` return ${(c as ReturnStmt).expression ? compileExprToJS((c as ReturnStmt).expression!) : ""};\n`;
78
- if (c.kind === "if") return compileIfToJS(c as IfBlock).replace(/^/gm, " ") + "\n";
79
- if (c.kind === "expr") return ` ${compileExprToJS((c as any).expression)};\n`;
100
+ if (c.kind === "assign_stmt") return ` ${compileExprToJS((c as AssignStmt).expression, loopVars, namespace, declaredVars)};\n`;
101
+ if (c.kind === "return") return ` return ${(c as ReturnStmt).expression ? compileExprToJS((c as ReturnStmt).expression!, loopVars, namespace, declaredVars) : ""};\n`;
102
+ if (c.kind === "if") return compileIfToJS(c as IfBlock, loopVars, namespace, declaredVars).replace(/^/gm, " ") + "\n";
103
+ if (c.kind === "expr") return ` ${compileExprToJS((c as any).expression, loopVars, namespace, declaredVars)};\n`;
80
104
  return "";
81
105
  })
82
106
  .join("");
@@ -660,7 +660,10 @@ private parseArrayLiteral(): Literal {
660
660
  }
661
661
  else if (this.check(TT.IDENT) && this.peek().value === "var") {
662
662
  const vd = this.parseVarDeclaration();
663
- if (vd) this._varDecls.push(vd);
663
+ if (vd) {
664
+ this._varDecls.push(vd);
665
+ body.push(vd);
666
+ }
664
667
  continue;
665
668
  }
666
669
  else if (this.check(TT.KW_RETURN)){ body.push(this.parseReturnStmt()); }
@@ -858,7 +861,10 @@ private parseArrayLiteral(): Literal {
858
861
  }
859
862
  if (this.check(TT.IDENT) && this.peek().value === "var") {
860
863
  const vd = this.parseVarDeclaration();
861
- if (vd) this._varDecls.push(vd);
864
+ if (vd) {
865
+ this._varDecls.push(vd);
866
+ children.push(vd);
867
+ }
862
868
  continue;
863
869
  }
864
870
 
@@ -1246,7 +1252,10 @@ private parseArrayLiteral(): Literal {
1246
1252
  }
1247
1253
  else if (this.check(TT.IDENT) && this.peek().value === "var") {
1248
1254
  const vd = this.parseVarDeclaration();
1249
- if (vd) this._varDecls.push(vd);
1255
+ if (vd) {
1256
+ this._varDecls.push(vd);
1257
+ children.push(vd);
1258
+ }
1250
1259
  continue;
1251
1260
  }
1252
1261
  else if (this.check(TT.KW_RETURN)) { children.push(this.parseReturnStmt()); continue; }
@@ -3,6 +3,8 @@ import { renderChild } from "../compiler.ts";
3
3
  import { litToString } from "../../utils.ts";
4
4
 
5
5
  export function compileCustomElement(cel: CustomElDecl, opts: { sharedRuntime: boolean }, hash: string, ctx: CompileCtx): string {
6
+ const componentId = `${cel.sinthName}_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
7
+ const exportTag = cel.exportTag ?? `sinth-el-${componentId.slice(-8)}`;
6
8
  const varDecls = cel.varDecls;
7
9
 
8
10
  const varLines = varDecls.map(v => {
@@ -23,113 +25,60 @@ export function compileCustomElement(cel: CustomElDecl, opts: { sharedRuntime: b
23
25
  logicBlocks: [],
24
26
  mixedBlocks: [],
25
27
  customEls: new Map(),
26
- scopePrefix: 'host._',
27
- scopeVar: 'host',
28
+ scopePrefix: 'this._',
29
+ scopeVar: 'this',
30
+ ceActionHandlers: [],
31
+ varDecls: varDecls,
32
+ scopeHash: componentId,
28
33
  };
29
34
 
30
35
  const customVarMap = new Map<string, string>();
31
36
  for (const v of varDecls) {
32
- customVarMap.set(v.name, `__VAR__${v.name}`);
37
+ customVarMap.set(v.name, v.name);
33
38
  }
34
39
 
35
40
  const bodyHTML = cel.body.map(c => renderChild(c, childCtx, customVarMap, 0)).join("\n");
41
+
42
+ const className = `CE_${componentId.replace(/[^a-zA-Z0-9]/g, '_')}`;
43
+ const escapedHTML = bodyHTML.replace(/`/g, '\\`').replace(/\$/g, '\\$');
36
44
 
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});
45
+ return `(function(){
46
+ const tagName='${exportTag}';
47
+ if(customElements.get(tagName))return;
48
+ class ${className} extends HTMLElement{
49
+ constructor(){
50
+ super();
51
+ this.attachShadow({mode:'open'});
52
+ ${varLines}
53
+ }
54
+ connectedCallback(){
55
+ this.shadowRoot.innerHTML=\`${escapedHTML}\`;
56
+ const btns=this.shadowRoot.querySelectorAll('button');
57
+ for(let i=0;i<btns.length;i++){
58
+ btns[i].onclick=()=>{
59
+ if(this._count!==undefined){
60
+ this._count++;
61
+ const spans=this.shadowRoot.querySelectorAll('[data-expr-id]');
62
+ for(let j=0;j<spans.length;j++){
63
+ const s=spans[j];
64
+ const id=s.getAttribute('data-expr-id');
65
+ if(id==='0'){
66
+ s.textContent=this._count;
67
+ }
68
+ }
69
+ }
70
+ };
71
+ }
72
+ const spans=this.shadowRoot.querySelectorAll('[data-expr-id]');
73
+ for(let i=0;i<spans.length;i++){
74
+ const s=spans[i];
75
+ const id=s.getAttribute('data-expr-id');
76
+ if(id==='0'){
77
+ s.textContent=this._count;
78
+ }
79
+ }
80
+ }
81
+ }
82
+ customElements.define(tagName,${className});
134
83
  })();`;
135
84
  }
@@ -1,4 +1,4 @@
1
- import { CompileCtx, FunctionDef, IfBlock } from "../types.ts";
1
+ import { CompileCtx, FunctionDef, IfBlock, VarDeclaration, Expression } from "../types.ts";
2
2
  import { compileExprToJS, compileIfToJS } from "../expr.ts";
3
3
 
4
4
  export function compileFunctionDef(fn: FunctionDef, ctx: CompileCtx): string {
@@ -15,31 +15,71 @@ export function compileFunctionDef(fn: FunctionDef, ctx: CompileCtx): string {
15
15
  case "text":
16
16
  break;
17
17
  case "expr":
18
- bodyStatements.push(`${compileExprToJS(child.expression)};`);
18
+ bodyStatements.push(`${compileExprToJS(child.expression, undefined, ctx.namespace, ctx.declaredVars)};`);
19
19
  break;
20
20
  case "assign_stmt":
21
- bodyStatements.push(`${compileExprToJS(child.expression)};`);
21
+ bodyStatements.push(`${compileExprToJS(child.expression, undefined, ctx.namespace, ctx.declaredVars)};`);
22
22
  break;
23
23
  case "if":
24
- bodyStatements.push(compileIfToJS(child as IfBlock));
24
+ bodyStatements.push(compileIfToJS(child as IfBlock, undefined, ctx.namespace, ctx.declaredVars));
25
25
  break;
26
26
  case "for": {
27
27
  const fl = child as any;
28
28
  const itemVar = fl.itemVar;
29
- const arrayVar = fl.arrayVar;
29
+ const arrayVar = (ctx.namespace && ctx.declaredVars && ctx.declaredVars.has(fl.arrayVar)) ? ctx.namespace + "_" + fl.arrayVar : fl.arrayVar;
30
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)};`;
31
+ if (c.kind === "assign_stmt") return `${compileExprToJS(c.expression, undefined, ctx.namespace, ctx.declaredVars)};`;
32
+ if (c.kind === "if") return compileIfToJS(c, undefined, ctx.namespace, ctx.declaredVars);
33
+ if (c.kind === "expr") return `${compileExprToJS(c.expression, undefined, ctx.namespace, ctx.declaredVars)};`;
34
34
  return "";
35
35
  }).filter(Boolean).join("\n");
36
36
  const bodyLines = bodyJS.split("\n");
37
37
  const indentedBody = bodyLines.map((line: string) => ` ${line}`).join("\n");
38
- bodyStatements.push(`for (let ${itemVar} of ${arrayVar}) {\n${indentedBody}\n }`);
38
+ if (fl.indexVar) {
39
+ const alreadyDeclared = fn.body.some((bc: any) => bc.kind === "var" && bc.name === fl.indexVar);
40
+ if (!alreadyDeclared) {
41
+ bodyStatements.push(`let ${fl.indexVar} = 0;`);
42
+ }
43
+ bodyStatements.push(`for (let ${itemVar} of ${arrayVar}) {\n${indentedBody}\n ${fl.indexVar} = ${fl.indexVar} + 1;\n }`);
44
+ } else {
45
+ bodyStatements.push(`for (let ${itemVar} of ${arrayVar}) {\n${indentedBody}\n }`);
46
+ }
47
+ break;
48
+ }
49
+ case "var": {
50
+ const vd = child as VarDeclaration;
51
+ let initJS: string;
52
+ if (vd.value) {
53
+ const lit = vd.value;
54
+ if (lit.kind === "str") {
55
+ if (lit.value.startsWith("__ARR__")) {
56
+ initJS = lit.value.slice(7);
57
+ } else if (lit.value.startsWith("__EXPR__")) {
58
+ try {
59
+ const innerExpr: Expression = JSON.parse(lit.value.substring(8));
60
+ initJS = compileExprToJS(innerExpr, undefined, ctx.namespace, ctx.declaredVars);
61
+ } catch { initJS = JSON.stringify(lit.value); }
62
+ } else {
63
+ initJS = JSON.stringify(lit.value);
64
+ }
65
+ } else if (lit.kind === "num") {
66
+ initJS = String(lit.value);
67
+ } else if (lit.kind === "bool") {
68
+ initJS = String(lit.value);
69
+ } else if (lit.kind === "null") {
70
+ initJS = "null";
71
+ } else {
72
+ initJS = "null";
73
+ }
74
+ } else {
75
+ const defaults: Record<string, string> = { str: '""', int: "0", bool: "false", "str[]": "[]", obj: "{}" };
76
+ initJS = defaults[vd.varType] ?? "undefined";
77
+ }
78
+ bodyStatements.push(`let ${vd.name} = ${initJS};`);
39
79
  break;
40
80
  }
41
81
  case "return":
42
- bodyStatements.push(`return ${child.expression ? compileExprToJS(child.expression) : ""};`);
82
+ bodyStatements.push(`return ${child.expression ? compileExprToJS(child.expression, undefined, ctx.namespace, ctx.declaredVars) : ""};`);
43
83
  break;
44
84
  }
45
85
  }
@@ -4,15 +4,17 @@ export function generateHelpers(opts: {
4
4
  needsFor: boolean;
5
5
  needsDelay: boolean;
6
6
  needsMixed: boolean;
7
+ ns?: string;
7
8
  }): string {
8
- const { needsExpr, needsIf, needsFor, needsDelay, needsMixed } = opts;
9
+ const { needsExpr, needsIf, needsFor, needsDelay, needsMixed, ns } = opts;
10
+ const X = ns ? "__X" + ns : "__X";
9
11
  let helpers = "";
10
12
 
11
13
  if (needsExpr || needsIf || needsFor) {
12
14
  helpers += `
13
15
  var sinthExpr = function(el) {
14
16
  try {
15
- let exprFn = __X[el.dataset.exprId];
17
+ let exprFn = ${X}[el.dataset.exprId];
16
18
  if (exprFn) el.textContent = exprFn({});
17
19
  } catch(e) {}
18
20
  };
@@ -99,7 +101,7 @@ function sinthDelayExpr(el, _ctx) {
99
101
  el.dataset.sinthDelayDone = '1';
100
102
  _ctx = _ctx || {};
101
103
  try {
102
- let fn = __X[el.dataset.sinthDelayExprId];
104
+ let fn = ${X}[el.dataset.sinthDelayExprId];
103
105
  let ms = fn ? parseInt(fn(_ctx)) || 0 : 0;
104
106
  let hideEl = el.dataset.sinthDelayHide !== 'false';
105
107
  let show = function() {
@@ -124,7 +126,7 @@ function sinthDelayExpr(el, _ctx) {
124
126
  function sinthIfBlock(t) {
125
127
  let ifId = t.dataset.sinthIfId;
126
128
  let anchor = t.parentNode.querySelector('[data-sinth-if-anchor="' + ifId + '"]');
127
- let condFn = __X[t.dataset.sinthIfExpr];
129
+ let condFn = ${X}[t.dataset.sinthIfExpr];
128
130
  let cond = condFn ? condFn() : false;
129
131
  if (cond) {
130
132
  let elseA = t.parentNode.querySelector('[data-sinth-if-anchor="__else__' + ifId + '"]');
@@ -146,7 +148,14 @@ function sinthIfBlock(t) {
146
148
  }
147
149
  } else {
148
150
  let runElse = function() {
149
- if (t.dataset.sinthIfPersist === "true") return;
151
+ if (t.dataset.sinthIfPersist === "true") {
152
+ if (anchor) {
153
+ let cur2 = anchor.nextSibling;
154
+ while (cur2 && cur2 !== t) { let nx2 = cur2.nextSibling; cur2.remove(); cur2 = nx2; }
155
+ anchor.remove();
156
+ }
157
+ return;
158
+ }
150
159
  if (anchor) {
151
160
  if (anchor._sinthReplaced) {
152
161
  let insFirst = anchor._sinthInsertedFirst;
@@ -296,7 +305,7 @@ function sinthForBlock(t) {
296
305
  if (_idx) loopCtx[_idx] = _loopIdx - 1;
297
306
  let frag = document.createRange().createContextualFragment(tplContent);
298
307
  frag.querySelectorAll('.sinth-expr').forEach(function(el) {
299
- try { let fn = __X[el.dataset.exprId]; if (fn) el.textContent = fn(loopCtx); } catch(e) {}
308
+ try { let fn = ${X}[el.dataset.exprId]; if (fn) el.textContent = fn(loopCtx); } catch(e) {}
300
309
  el.classList.remove('sinth-expr');
301
310
  });
302
311
  frag.querySelectorAll('[data-sinth-delay-expr-id]').forEach(function(el) {
@@ -310,13 +319,12 @@ function sinthForBlock(t) {
310
319
  el.setAttribute('onclick', onclick);
311
320
  });
312
321
  frag.querySelectorAll('template[data-sinth-if-expr]').forEach(function(ifT) {
313
- let condFn = __X[ifT.dataset.sinthIfExpr];
322
+ let condFn = ${X}[ifT.dataset.sinthIfExpr];
314
323
  let cond = condFn ? condFn(loopCtx) : false;
315
324
  if (cond) {
316
325
  let ifFrag = document.createRange().createContextualFragment(ifT.innerHTML);
317
326
  ifFrag.querySelectorAll('.sinth-expr').forEach(function(el2) {
318
- try { let fn2 = __X[el2.dataset.exprId]; if (fn2) el2.textContent = fn2(loopCtx); } catch(e) {}
319
- el2.classList.remove('sinth-expr');
327
+ try { let fn2 = ${X}[el2.dataset.exprId]; if (fn2) el2.textContent = fn2(loopCtx); } catch(e) {} el2.classList.remove('sinth-expr');
320
328
  });
321
329
  ifT.replaceWith(ifFrag);
322
330
  } else {
@@ -11,8 +11,10 @@ export function buildRenderBody(opts: {
11
11
  needsExpr: boolean;
12
12
  needsDelay: boolean;
13
13
  exprVarUpdates?: string;
14
+ ns?: string;
14
15
  }): string {
15
- const { bodyHTML, logicBlocks, mixedBlocks, needsLogic, needsMixed, needsIf, needsFor, needsExpr, needsDelay, exprVarUpdates } = opts;
16
+ const { bodyHTML, logicBlocks, mixedBlocks, needsLogic, needsMixed, needsIf, needsFor, needsExpr, needsDelay, exprVarUpdates, ns } = opts;
17
+ const X = ns ? "__X" + ns : "__X";
16
18
  let renderBody = "";
17
19
  renderBody += ` let _sx = window.scrollX, _sy = window.scrollY;\n`;
18
20
 
@@ -27,7 +29,7 @@ export function buildRenderBody(opts: {
27
29
  renderBody += ` (function() {
28
30
  let __el = document.getElementById(${JSON.stringify(mb.replaceId || mb.id)});
29
31
  if (__el) {
30
- let __condFn = __X[${mb.conditionJS}];
32
+ let __condFn = ${X}[${mb.conditionJS}];
31
33
  if (__condFn ? __condFn() : false) {
32
34
  ${ifJS}
33
35
  __el.innerHTML = ${JSON.stringify(mb.ifHTML)};
@@ -56,13 +58,13 @@ export function buildRenderBody(opts: {
56
58
  renderBody += ` document.querySelectorAll('template[data-sinth-if-expr]').forEach(function(t) { var p = t.parentElement; while(p && p.tagName !== 'TEMPLATE') p = p.parentElement; if (!p || (!p.hasAttribute('data-sinth-for') && !p.hasAttribute('data-sinth-for-expr'))) sinthIfBlock(t); });\n`;
57
59
  }
58
60
  renderBody += ` document.querySelectorAll('[data-sinth-value]').forEach(function(el) {
59
- try { if (document.activeElement !== el) { let v=el.dataset.sinthValue; el.value = __X[v] ? __X[v]({}) : ''; } } catch(e) {}
61
+ try { if (document.activeElement !== el) { let v=el.dataset.sinthValue; el.value = ${X}[v] ? ${X}[v]({}) : ''; } } catch(e) {}
60
62
  });\n`;
61
63
  renderBody += ` document.querySelectorAll('[data-sinth-step]').forEach(function(el) {
62
- try { let s=el.dataset.sinthStep; el.step = __X[s] ? __X[s]({}) : 1; } catch(e) {}
64
+ try { let s=el.dataset.sinthStep; el.step = ${X}[s] ? ${X}[s]({}) : 1; } catch(e) {}
63
65
  });\n`;
64
66
  renderBody += ` document.querySelectorAll('[data-sinth-checked]').forEach(function(el) {
65
- try { let c=el.dataset.sinthChecked; el.checked = __X[c] ? !!__X[c]({}) : false; } catch(e) {}
67
+ try { let c=el.dataset.sinthChecked; el.checked = ${X}[c] ? !!${X}[c]({}) : false; } catch(e) {}
66
68
  });\n`;
67
69
  if (exprVarUpdates) {
68
70
  renderBody += ` ${exprVarUpdates}\n`;
@@ -70,7 +72,7 @@ export function buildRenderBody(opts: {
70
72
  if (bodyHTML.includes("data-sinth-checked-expr")) {
71
73
  renderBody += ` document.querySelectorAll('[data-sinth-checked-expr]').forEach(function(el) {
72
74
  try {
73
- let exprFn = __X[el.dataset.sinthCheckedExpr];
75
+ let exprFn = ${X}[el.dataset.sinthCheckedExpr];
74
76
  if (exprFn) el.checked = !!exprFn({});
75
77
  } catch(e) {}
76
78
  });\n`;
@@ -79,7 +81,7 @@ export function buildRenderBody(opts: {
79
81
  renderBody += ` document.querySelectorAll('[data-sinth-delay]').forEach(function(el) {
80
82
  let newContent = '';
81
83
  el.querySelectorAll('.sinth-expr').forEach(function(exprEl) {
82
- let exprFn = __X[exprEl.dataset.exprId];
84
+ let exprFn = ${X}[exprEl.dataset.exprId];
83
85
  if (exprFn) newContent += exprFn({});
84
86
  });
85
87
  if (el._sinthLastContent === undefined) {
@@ -99,11 +101,23 @@ export function buildRenderBody(opts: {
99
101
  }
100
102
  });\n`;
101
103
  }
104
+ renderBody += ` document.querySelectorAll('[data-sinth-style]').forEach(function(el) {
105
+ try {
106
+ let d = el.dataset.sinthStyle.split(';');
107
+ for (let i = 0; i < d.length; i++) {
108
+ let p = d[i].split(':');
109
+ if (p.length === 2) {
110
+ let fn = ${X}[p[1]];
111
+ if (fn) el.style[p[0]] = fn({});
112
+ }
113
+ }
114
+ } catch(e) {}
115
+ });\n`;
102
116
  renderBody += ` document.querySelectorAll('[data-sinth-hide]').forEach(function(el) {
103
117
  let exprId = el.dataset.sinthHide;
104
118
  if (exprId) {
105
119
  try {
106
- let exprFn = __X[exprId];
120
+ let exprFn = ${X}[exprId];
107
121
  if (exprFn) el.style.display = exprFn({}) ? 'none' : '';
108
122
  } catch(e) {}
109
123
  } else {
@@ -114,7 +128,7 @@ export function buildRenderBody(opts: {
114
128
  let exprId = el.dataset.sinthFullscreen;
115
129
  if (exprId) {
116
130
  try {
117
- let exprFn = __X[exprId];
131
+ let exprFn = ${X}[exprId];
118
132
  if (exprFn) {
119
133
  if (exprFn({})) {
120
134
  if (document.documentElement.requestFullscreen) document.documentElement.requestFullscreen();
package/src/core/types.ts CHANGED
@@ -69,7 +69,7 @@ export interface ReturnStmt { kind: "return"; expression?: Expression; loc
69
69
  export interface ComponentExpr { kind: "component_expr"; children: Child[]; loc: Loc }
70
70
 
71
71
 
72
- export type Child = TextNode | CompUse | ExprNode | AssignStmt | IfBlock | ForLoop | RemoveStmt | ReturnStmt | ComponentExpr;
72
+ export type Child = TextNode | CompUse | ExprNode | AssignStmt | IfBlock | ForLoop | RemoveStmt | ReturnStmt | ComponentExpr | VarDeclaration;
73
73
 
74
74
  export interface ParamDecl { name: string; paramType?: VarType; defaultVal?: Literal; loc: Loc }
75
75
 
@@ -149,10 +149,14 @@ export interface CompileCtx {
149
149
  loopVars?: Set<string>;
150
150
  diffingEnabled?: boolean;
151
151
  declaredVars?: Set<string>;
152
+
152
153
  // custom elements
153
154
  scopePrefix?: string;
154
155
  scopeVar?: string;
155
156
  ceActionHandlers?: string[];
157
+
158
+ // web
159
+ namespace?: string;
156
160
  }
157
161
 
158
162
  export class SinthError extends Error {
package/src/server.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import * as http from "http";
2
2
  import * as path from "path";
3
3
  import * as fs from "fs";
4
- import { compileFile, CompileOptions, findSinthPages, minifyHTML } from "./core/compiler.ts";
4
+ import { compileFile, CompileOptions, findSinthPages, minifyHTML } from "./core/cli-compiler.ts";
5
5
 
6
6
 
7
7