@yannosay/sinth 1.0.0 → 1.2.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 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="femboy-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 {
@@ -262,6 +276,63 @@ Main {
262
276
  }
263
277
  ```
264
278
 
279
+ ## Use in real life
280
+ ```ts
281
+ page
282
+
283
+ title = "Kick Users Admin Panel"
284
+
285
+ var str userName = "test username"
286
+ var int count = 0
287
+
288
+ style lang= "scss"{
289
+ @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap');
290
+
291
+ * {
292
+ font-family: 'Inter', sans-serif;
293
+ }
294
+ }
295
+
296
+ Main {
297
+ Div(display: "flex", flexDirection: "column", gap: "16px", alignItems: "center", padding: "40px", fontFamily: "Inter") {
298
+ Heading(level: 1, fontSize: "28px", color: "#000000", fontWeight: "700") {
299
+ "Kick Counter: " + count
300
+ }
301
+ Div(display: "flex", gap: "12px", alignItems: "center") {
302
+ Input(
303
+ bind: userName,
304
+ padding: "10px 14px",
305
+ fontSize: "16px",
306
+ borderRadius: "8px",
307
+ border: "2px solid #6366f1",
308
+ outline: "none",
309
+ width: "250px",
310
+ backgroundColor: "#1e1b4b",
311
+ color: "#e0e7ff",
312
+ fontWeight: "400"
313
+ )
314
+ Button(
315
+ onClick: alert("Kicked: " + userName); console.log("User kicked"); count += 1,
316
+ padding: "10px 20px",
317
+ fontSize: "16px",
318
+ fontWeight: "600",
319
+ borderRadius: "8px",
320
+ border: "none",
321
+ backgroundColor: "#6366f1",
322
+ color: "#ffffff",
323
+ cursor: "pointer",
324
+ minWidth: "180px",
325
+ textAlign: "left"
326
+ ) {
327
+ "Kick " + userName
328
+ }
329
+ }
330
+ Paragraph(fontSize: "14px", color: "#a5b4fc", fontWeight: "400") {
331
+ "Total kicks: " + count
332
+ }
333
+ }
334
+ }
335
+ ```
265
336
 
266
337
  # Install
267
338
  npm install -g @yannosay/sinth
@@ -368,4 +439,4 @@ Main {
368
439
 
369
440
  ## License
370
441
 
371
- AGPL-3.0
442
+ AGPL-3.0 (Just the compiler, the generated Output is 100% yours)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yannosay/sinth",
3
- "version": "1.0.0",
3
+ "version": "1.2.0",
4
4
  "description": "A declarative & reactive language that compiles to pure HTML, CSS, and JavaScript.",
5
5
  "author": "Yannosay Productions",
6
6
  "license": "AGPL-3.0",
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] Compile .sinth pages
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
@@ -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 {
@@ -159,7 +159,8 @@ if (name === "step" && value?.kind === "str") {
159
159
  try {
160
160
  const expr: Expression = JSON.parse(raw.substring(8));
161
161
  if (expr.kind === "variable" && expr.name) {
162
- return `data-sinth-step="${escAttr(expr.name)}"`;
162
+ const stepExprId = registerExpr(ctx, expr);
163
+ return `data-sinth-step="${stepExprId}"`;
163
164
  }
164
165
  } catch {}
165
166
  }
@@ -835,7 +836,8 @@ export function renderCompUse(
835
836
  const initialVal = varDecl?.value ? litToString(varDecl.value).replace(/"/g, '&quot;') : "";
836
837
  attrParts.push(`oninput="(function(e){ ${vName} = ${rhs}; sinthRender(); })(event)"`);
837
838
  attrParts.push(`value="${escAttr(initialVal)}"`);
838
- attrParts.push(`data-sinth-value="${escAttr(vName)}"`);
839
+ const valueExprId = registerExpr(ctx, { kind: "variable", name: vName });
840
+ attrParts.push(`data-sinth-value="${valueExprId}"`);
839
841
  }
840
842
  }
841
843
  if (use.name === "Checkbox") {
@@ -851,14 +853,16 @@ export function renderCompUse(
851
853
  try {
852
854
  const expr: Expression = JSON.parse(raw.substring(8));
853
855
  if (expr.kind === "variable" && expr.name) {
854
- attrParts.push(`data-sinth-checked="${escAttr(expr.name)}"`);
856
+ const checkedExprId = registerExpr(ctx, { kind: "variable", name: expr.name });
857
+ attrParts.push(`data-sinth-checked="${checkedExprId}"`);
855
858
  } else {
856
859
  const exprId = registerExpr(ctx, expr);
857
860
  attrParts.push(`data-sinth-checked-expr="${exprId}"`);
858
861
  }
859
862
  } catch {}
860
863
  } else {
861
- attrParts.push(`data-sinth-checked="${escAttr(raw)}"`);
864
+ const checkedExprId = registerExpr(ctx, { kind: "variable", name: raw });
865
+ attrParts.push(`data-sinth-checked="${checkedExprId}"`);
862
866
  }
863
867
  }
864
868
  }
@@ -1067,7 +1071,7 @@ export function buildRuntime(opts: {
1067
1071
  ? `let __X = [${exprRegistry.map((js) => `function(_ctx){ return ${js}; }`).join(",")}];\n`
1068
1072
  : "";
1069
1073
 
1070
- let renderFunc = needsRender ? `function sinthRender() {\n${renderBody}}\nsinthRender();` : "";
1074
+ let renderFunc = needsRender ? `var _sinthRenderPending = false;\nfunction sinthRender() {\n if (_sinthRenderPending) return;\n _sinthRenderPending = true;\n requestAnimationFrame(function() {\n _sinthRenderPending = false;\n${renderBody.replace(/^/gm, " ")}\n });\n}\nsinthRender();` : "";
1071
1075
 
1072
1076
  if (needsFullscreenSync) {
1073
1077
  renderFunc += `
@@ -1456,10 +1460,29 @@ const sharedRuntimeTag = (() => {
1456
1460
  "</html>",
1457
1461
  ].filter(Boolean).join("\n");
1458
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
+
1459
1480
  const finalHTML = opts.minify ? minifyHTML(html) : html;
1460
1481
  return sharedJS ? { html: finalHTML, shared: sharedJS } : { html: finalHTML };
1461
1482
  }
1462
1483
 
1484
+
1485
+
1463
1486
  export function minifyHTML(html: string): string {
1464
1487
  return html.replace(/>\s+</g, "><").replace(/\n\s*\n/g, "\n").trim();
1465
1488
  }
@@ -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 tagName = this.consume(TT.IDENT).value;
529
- const sinthName = tagNameToPascal(tagName);
530
- const params = this.parseParamDecls();
531
- return { sinthName, tagName, params, loc };
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
+ }
@@ -55,13 +55,13 @@ export function buildRenderBody(opts: {
55
55
  renderBody += ` document.querySelectorAll('template[data-sinth-for]').forEach(sinthForBlock);\n`;
56
56
  }
57
57
  renderBody += ` document.querySelectorAll('[data-sinth-value]').forEach(function(el) {
58
- try { if (document.activeElement !== el) { el.value = Function('"use strict"; return (' + el.dataset.sinthValue + ')')(); } } catch(e) {}
58
+ try { if (document.activeElement !== el) { let v=el.dataset.sinthValue; el.value = __X[v] ? __X[v]({}) : ''; } } catch(e) {}
59
59
  });\n`;
60
60
  renderBody += ` document.querySelectorAll('[data-sinth-step]').forEach(function(el) {
61
- try { el.step = Function('"use strict"; return (' + el.dataset.sinthStep + ')')() || 1; } catch(e) {}
61
+ try { let s=el.dataset.sinthStep; el.step = __X[s] ? __X[s]({}) : 1; } catch(e) {}
62
62
  });\n`;
63
63
  renderBody += ` document.querySelectorAll('[data-sinth-checked]').forEach(function(el) {
64
- try { el.checked = !!Function('"use strict"; return (' + el.dataset.sinthChecked + ')')(); } catch(e) {}
64
+ try { let c=el.dataset.sinthChecked; el.checked = __X[c] ? !!__X[c]({}) : false; } catch(e) {}
65
65
  });\n`;
66
66
  if (bodyHTML.includes("data-sinth-checked-expr")) {
67
67
  renderBody += ` document.querySelectorAll('[data-sinth-checked-expr]').forEach(function(el) {
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 }