@yannosay/sinth 1.1.0 → 1.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -2
- package/package.json +1 -1
- package/src/cli.ts +1 -1
- package/src/core/compiler.ts +20 -1
- package/src/core/parser.ts +51 -9
- package/src/core/runtime/custom-element.ts +115 -0
- package/src/core/types.ts +2 -2
package/README.md
CHANGED
|
@@ -33,6 +33,22 @@ Main {
|
|
|
33
33
|
}
|
|
34
34
|
```
|
|
35
35
|
|
|
36
|
+
#### Declare your own HTML tags
|
|
37
|
+
|
|
38
|
+
```ts
|
|
39
|
+
custom MyCounter(export: <awesome-counter />) {
|
|
40
|
+
var int count = 0
|
|
41
|
+
Button(onClick: count += 1) { count }
|
|
42
|
+
}
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
then use it in an non-sinth HTML project
|
|
46
|
+
|
|
47
|
+
```html
|
|
48
|
+
<awesome-counter />
|
|
49
|
+
<script src="awesome-counter.js"></script>
|
|
50
|
+
```
|
|
51
|
+
|
|
36
52
|
#### Logic and UI live together.
|
|
37
53
|
```ts
|
|
38
54
|
if user.isAdmin {
|
|
@@ -151,8 +167,6 @@ Main {
|
|
|
151
167
|
```
|
|
152
168
|
Count updates every click because count changed. The alert fires only on page load — zero dependencies means it's cached forever. Just a meta flag.
|
|
153
169
|
|
|
154
|
-
|
|
155
|
-
|
|
156
170
|
#### Animations that make sense.
|
|
157
171
|
```ts
|
|
158
172
|
for item, index in items {
|
package/package.json
CHANGED
package/src/cli.ts
CHANGED
|
@@ -167,7 +167,7 @@ async function main(): Promise<void> {
|
|
|
167
167
|
\x1b[1mSinth Compiler v${version}\x1b[0m
|
|
168
168
|
|
|
169
169
|
\x1b[1mCommands:\x1b[0m
|
|
170
|
-
sinth build [files] [--out ./dist] [--prod]
|
|
170
|
+
sinth build [files] [--out ./dist] [--prod] [--shared-runtime] Compile .sinth pages
|
|
171
171
|
sinth dev [files] [--port 3000] Live-reload dev server
|
|
172
172
|
sinth check Lint without emitting
|
|
173
173
|
sinth init [name] Scaffold a new project
|
package/src/core/compiler.ts
CHANGED
|
@@ -12,7 +12,7 @@ import { buildRenderBody } from "./runtime/render.ts";
|
|
|
12
12
|
import { BUILTIN_MAP, VOID_TAGS, BuiltinInfo } from "./builtins.ts";
|
|
13
13
|
import { processStyleBlock } from "./style-processor.ts";
|
|
14
14
|
import { buildHeadData, renderHead, HeadData } from "./head-builder.ts";
|
|
15
|
-
|
|
15
|
+
import { compileCustomElement } from "./runtime/custom-element.ts";
|
|
16
16
|
|
|
17
17
|
const EVENT_RE = /^on[A-Z]/;
|
|
18
18
|
function eventAttrName(name: string): string | null {
|
|
@@ -1460,10 +1460,29 @@ const sharedRuntimeTag = (() => {
|
|
|
1460
1460
|
"</html>",
|
|
1461
1461
|
].filter(Boolean).join("\n");
|
|
1462
1462
|
|
|
1463
|
+
for (const cel of file.customEls) {
|
|
1464
|
+
if (cel.exportTag) {
|
|
1465
|
+
try {
|
|
1466
|
+
const compJs = compileCustomElement(cel, opts, hash, ctx);
|
|
1467
|
+
const relPath = path.relative(opts.projectRoot, path.dirname(absPath));
|
|
1468
|
+
const outPath = path.join(opts.outDir, relPath, cel.exportTag + ".js");
|
|
1469
|
+
if (!opts.checkOnly) {
|
|
1470
|
+
fs.mkdirSync(path.dirname(outPath), { recursive: true });
|
|
1471
|
+
fs.writeFileSync(outPath, compJs);
|
|
1472
|
+
process.stdout.write(` \x1b[32m✓\x1b[0m ${cel.exportTag}.js (custom element)\n`);
|
|
1473
|
+
}
|
|
1474
|
+
} catch (e: unknown) {
|
|
1475
|
+
SinthWarning.emit(`Failed to compile custom element '${cel.exportTag}': ${(e as Error).message}`, cel.loc);
|
|
1476
|
+
}
|
|
1477
|
+
}
|
|
1478
|
+
}
|
|
1479
|
+
|
|
1463
1480
|
const finalHTML = opts.minify ? minifyHTML(html) : html;
|
|
1464
1481
|
return sharedJS ? { html: finalHTML, shared: sharedJS } : { html: finalHTML };
|
|
1465
1482
|
}
|
|
1466
1483
|
|
|
1484
|
+
|
|
1485
|
+
|
|
1467
1486
|
export function minifyHTML(html: string): string {
|
|
1468
1487
|
return html.replace(/>\s+</g, "><").replace(/\n\s*\n/g, "\n").trim();
|
|
1469
1488
|
}
|
package/src/core/parser.ts
CHANGED
|
@@ -308,15 +308,11 @@ private parseArrayLiteral(): Literal {
|
|
|
308
308
|
}
|
|
309
309
|
|
|
310
310
|
// var or assignment
|
|
311
|
-
if ((tok.type as any) === TT.KW_REMOVE) {
|
|
312
|
-
const name = this.consume(TT.KW_REMOVE).value;
|
|
313
|
-
return { kind: "variable", name };
|
|
314
|
-
}
|
|
315
311
|
if (tok.type === TT.IDENT) {
|
|
316
312
|
const name = this.consume(TT.IDENT).value;
|
|
317
313
|
let varExpr: Expression;
|
|
318
314
|
|
|
319
|
-
// dot notation -> user.age
|
|
315
|
+
// dot notation -> e.g. user.age
|
|
320
316
|
if (this.check(TT.DOT)) {
|
|
321
317
|
this.consume(TT.DOT);
|
|
322
318
|
const propName = this.consume(TT.IDENT).value;
|
|
@@ -525,10 +521,56 @@ private parseArrayLiteral(): Literal {
|
|
|
525
521
|
const loc = this.peek().loc;
|
|
526
522
|
if (this.check(TT.KW_CUSTOM_EL)) this.consume(TT.KW_CUSTOM_EL);
|
|
527
523
|
else if (this.check(TT.KW_CUSTOM)) this.consume(TT.KW_CUSTOM);
|
|
528
|
-
const
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
524
|
+
const sinthName = this.consume(TT.IDENT).value;
|
|
525
|
+
let exportTag: string | undefined;
|
|
526
|
+
if (this.check(TT.LPAREN)) {
|
|
527
|
+
this.consume(TT.LPAREN);
|
|
528
|
+
while (!this.check(TT.RPAREN)) {
|
|
529
|
+
const attrName = this.consume(TT.IDENT).value;
|
|
530
|
+
if (attrName === "export") {
|
|
531
|
+
this.consume(TT.COLON);
|
|
532
|
+
if (!this.check(TT.OP_LT)) throw new SinthError("Expected '<tag/>' after 'export:'", this.peek().loc);
|
|
533
|
+
this.consume(TT.OP_LT);
|
|
534
|
+
exportTag = this.consume(TT.IDENT).value;
|
|
535
|
+
if (!this.check(TT.OP_SLASH)) throw new SinthError("Expected '/>' in tag literal", this.peek().loc);
|
|
536
|
+
this.consume(TT.OP_SLASH);
|
|
537
|
+
this.consume(TT.OP_GT);
|
|
538
|
+
}
|
|
539
|
+
if (!this.check(TT.RPAREN)) this.consume(TT.COMMA);
|
|
540
|
+
}
|
|
541
|
+
this.consume(TT.RPAREN);
|
|
542
|
+
}
|
|
543
|
+
if (this.check(TT.RAW_BLOCK)) {
|
|
544
|
+
const rawTok = this.consume(TT.RAW_BLOCK);
|
|
545
|
+
const tokens = new Lexer(rawTok.value, rawTok.loc.file).tokenize();
|
|
546
|
+
const sub = new Parser(tokens, rawTok.loc.file);
|
|
547
|
+
sub._varDecls = this._varDecls;
|
|
548
|
+
const parsed = sub.parseBodyContents();
|
|
549
|
+
return { sinthName, tagName: sinthName.toLowerCase(), exportTag, params: [], body: parsed.body, styles: parsed.styles, scripts: parsed.scripts, varDecls: this._varDecls, loc };
|
|
550
|
+
}
|
|
551
|
+
if (!this.check(TT.LBRACE)) throw new SinthError("Expected '{' after custom element declaration", this.peek().loc);
|
|
552
|
+
this.consume(TT.LBRACE);
|
|
553
|
+
const body: Child[] = [];
|
|
554
|
+
const styles: StyleBlock[] = [];
|
|
555
|
+
const scripts: ScriptBlock[] = [];
|
|
556
|
+
const varDecls: VarDeclaration[] = [];
|
|
557
|
+
while (!this.check(TT.RBRACE) && !this.check(TT.EOF)) {
|
|
558
|
+
if (this.check(TT.KW_STYLE)) { styles.push(this.parseStyleBlock()); }
|
|
559
|
+
else if (this.check(TT.KW_SCRIPT)) { scripts.push(this.parseScriptBlock()); }
|
|
560
|
+
else if (this.check(TT.IDENT) && this.peek().value === "var") {
|
|
561
|
+
const vd = this.parseVarDeclaration();
|
|
562
|
+
if (vd) varDecls.push(vd);
|
|
563
|
+
}
|
|
564
|
+
else if (this.check(TT.KW_IF)) { body.push(this.parseIfBlock()); }
|
|
565
|
+
else if (this.check(TT.KW_FOR)) { body.push(this.parseForLoop()); }
|
|
566
|
+
else if (this.check(TT.IDENT)) { body.push(this.parseCompUse()); }
|
|
567
|
+
else if (this.check(TT.STRING)) {
|
|
568
|
+
body.push({ kind: "text", value: this.consume(TT.STRING).value, loc: this.peek().loc });
|
|
569
|
+
}
|
|
570
|
+
else throw new SinthError(`Unexpected token in custom element body`, this.peek().loc);
|
|
571
|
+
}
|
|
572
|
+
this.consume(TT.RBRACE);
|
|
573
|
+
return { sinthName, tagName: sinthName.toLowerCase(), exportTag, params: [], body, styles, scripts, varDecls, loc };
|
|
532
574
|
}
|
|
533
575
|
|
|
534
576
|
private parseReturnStmt(): ReturnStmt {
|
|
@@ -0,0 +1,115 @@
|
|
|
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
|
+
const varNames = varDecls.map(v => v.name);
|
|
8
|
+
|
|
9
|
+
const varLines = varDecls.map(v => {
|
|
10
|
+
if (v.value) {
|
|
11
|
+
const val = litToString(v.value);
|
|
12
|
+
if (v.varType === "int") return `this._${v.name} = ${parseFloat(val) || 0};`;
|
|
13
|
+
if (v.varType === "bool") return `this._${v.name} = ${val === "true" ? "true" : "false"};`;
|
|
14
|
+
return `this._${v.name} = ${JSON.stringify(val)};`;
|
|
15
|
+
}
|
|
16
|
+
const defaults: Record<string, string> = { str: '""', int: "0", bool: "false", "str[]": "[]" };
|
|
17
|
+
return `this._${v.name} = ${defaults[v.varType ?? "str"] ?? "undefined"};`;
|
|
18
|
+
}).join("\n ");
|
|
19
|
+
|
|
20
|
+
const childCtx: CompileCtx = {
|
|
21
|
+
...ctx,
|
|
22
|
+
exprRegistry: [],
|
|
23
|
+
exprMap: new Map(),
|
|
24
|
+
logicBlocks: [],
|
|
25
|
+
mixedBlocks: [],
|
|
26
|
+
customEls: new Map(),
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
const bodyHTML = cel.body.map(c => renderChild(c, childCtx, new Map(), 0)).join("\n");
|
|
30
|
+
|
|
31
|
+
let rewrittenHTML = bodyHTML;
|
|
32
|
+
for (const name of varNames) {
|
|
33
|
+
rewrittenHTML = rewrittenHTML.replace(new RegExp(`\\b${name}\\b`, 'g'), `host._${name}`);
|
|
34
|
+
}
|
|
35
|
+
rewrittenHTML = rewrittenHTML.replace(/sinthRender\(\)/g, 'host._render()');
|
|
36
|
+
rewrittenHTML = rewrittenHTML.replace(/onclick="([^"]+)"/g, 'data-sinth-click="$1"');
|
|
37
|
+
|
|
38
|
+
const escapedHTML = rewrittenHTML.replace(/\\/g, '\\\\').replace(/`/g, '\\`').replace(/\$/g, '\\$');
|
|
39
|
+
|
|
40
|
+
const needsExpr = bodyHTML.includes("sinth-expr");
|
|
41
|
+
const needsIf = bodyHTML.includes("data-sinth-if");
|
|
42
|
+
|
|
43
|
+
const exprArrayJS = childCtx.exprRegistry.length > 0
|
|
44
|
+
? `let __X = [${childCtx.exprRegistry.map(js => {
|
|
45
|
+
let fixed = js;
|
|
46
|
+
for (const name of varNames) {
|
|
47
|
+
fixed = fixed.replace(new RegExp(`\\b${name}\\b`, 'g'), `_ctx.host._${name}`);
|
|
48
|
+
}
|
|
49
|
+
return `function(_ctx){ return ${fixed}; }`;
|
|
50
|
+
}).join(",")}];\n`
|
|
51
|
+
: "";
|
|
52
|
+
|
|
53
|
+
return `// Sinth Custom Element: ${cel.exportTag}
|
|
54
|
+
(function() {
|
|
55
|
+
${exprArrayJS}
|
|
56
|
+
|
|
57
|
+
var sinthExpr = function(el, host) {
|
|
58
|
+
try {
|
|
59
|
+
let exprFn = __X[el.dataset.exprId];
|
|
60
|
+
if (exprFn) el.textContent = exprFn({host: host});
|
|
61
|
+
} catch(e) {}
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
${needsIf ? `
|
|
65
|
+
function sinthIfBlock(t) {
|
|
66
|
+
let ifId = t.dataset.sinthIfId;
|
|
67
|
+
let condFn = __X[t.dataset.sinthIfExpr];
|
|
68
|
+
let cond = condFn ? condFn() : false;
|
|
69
|
+
if (cond) {
|
|
70
|
+
let anchor = t.parentNode.querySelector('[data-sinth-if-anchor="' + ifId + '"]');
|
|
71
|
+
if (!anchor) {
|
|
72
|
+
anchor = document.createElement('span');
|
|
73
|
+
anchor.style.display = 'none';
|
|
74
|
+
anchor.dataset.sinthIfAnchor = ifId;
|
|
75
|
+
t.parentNode.insertBefore(anchor, t);
|
|
76
|
+
}
|
|
77
|
+
let frag = document.createRange().createContextualFragment(t.innerHTML);
|
|
78
|
+
frag.querySelectorAll('.sinth-expr').forEach(sinthExpr);
|
|
79
|
+
t.parentNode.insertBefore(frag, t);
|
|
80
|
+
} else {
|
|
81
|
+
let anchor = t.parentNode.querySelector('[data-sinth-if-anchor="' + ifId + '"]');
|
|
82
|
+
if (anchor) {
|
|
83
|
+
let c = anchor.nextSibling;
|
|
84
|
+
while (c && c !== t) { let n = c.nextSibling; c.remove(); c = n; }
|
|
85
|
+
anchor.remove();
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
` : ""}
|
|
90
|
+
|
|
91
|
+
function render(host) {
|
|
92
|
+
${needsExpr ? `host.shadowRoot.querySelectorAll('.sinth-expr').forEach(function(el) { sinthExpr(el, host); });` : ""}
|
|
93
|
+
${needsIf ? `host.shadowRoot.querySelectorAll('template[data-sinth-if-expr]').forEach(sinthIfBlock);` : ""}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
class ${cel.sinthName} extends HTMLElement {
|
|
97
|
+
constructor() {
|
|
98
|
+
super();
|
|
99
|
+
this.attachShadow({ mode: 'open' });
|
|
100
|
+
${varLines}
|
|
101
|
+
}
|
|
102
|
+
connectedCallback() {
|
|
103
|
+
var self = this;
|
|
104
|
+
this._render = function() { render(self); };
|
|
105
|
+
this.shadowRoot.innerHTML = \`${escapedHTML}\`;
|
|
106
|
+
this.shadowRoot.querySelectorAll('[data-sinth-click]').forEach(function(el) {
|
|
107
|
+
var fn = new Function('host', el.getAttribute('data-sinth-click'));
|
|
108
|
+
el.addEventListener('click', function() { fn(self); });
|
|
109
|
+
});
|
|
110
|
+
render(this);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
customElements.define('${cel.exportTag}', ${cel.sinthName});
|
|
114
|
+
})();`;
|
|
115
|
+
}
|
package/src/core/types.ts
CHANGED
|
@@ -83,8 +83,8 @@ export interface StyleBlock {
|
|
|
83
83
|
|
|
84
84
|
export interface ScriptBlock { raw: string; attrs: Record<string, string>; loc: Loc }
|
|
85
85
|
export interface CompDef { name: string; params: ParamDecl[]; body: Child[]; styles: StyleBlock[]; scripts: ScriptBlock[]; loc: Loc }
|
|
86
|
-
export interface CustomElDecl { sinthName: string; tagName: string; params: ParamDecl[]; loc: Loc
|
|
87
|
-
export interface CustomElInfo { tagName: string; params: ParamDecl[] }
|
|
86
|
+
export interface CustomElDecl { sinthName: string; tagName: string; exportTag?: string; params: ParamDecl[]; body: Child[]; styles: StyleBlock[]; scripts: ScriptBlock[]; varDecls: VarDeclaration[]; loc: Loc
|
|
87
|
+
}export interface CustomElInfo { tagName: string; params: ParamDecl[] }
|
|
88
88
|
|
|
89
89
|
export type VarType = "int" | "str" | "bool" | "str[]" | "obj" | "ui";
|
|
90
90
|
export interface VarDeclaration { kind: "var"; name: string; varType: VarType; value: Literal | null; loc: Loc }
|