@yannosay/sinth 0.13.1 → 0.13.3
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 +30 -1
- package/package.json +1 -1
- package/src/core/builtins.ts +117 -0
- package/src/core/compiler.ts +64 -927
- package/src/core/expr.ts +6 -2
- package/src/core/head-builder.ts +86 -0
- package/src/core/parser.ts +8 -10
- package/src/core/runtime/functions.ts +33 -0
- package/src/core/runtime/helpers.ts +296 -0
- package/src/core/runtime/render.ts +82 -0
- package/src/core/style-processor.ts +299 -0
- package/src/resolver.ts +1 -1
- package/src/utils.ts +40 -1
package/src/core/compiler.ts
CHANGED
|
@@ -2,440 +2,23 @@ import * as path from "path";
|
|
|
2
2
|
import * as fs from "fs";
|
|
3
3
|
import { Loc, Literal, Expression, Child, Attr, CompUse, IfBlock, ForLoop, RemoveStmt, ReturnStmt, StyleBlock, CompDef, ParamDecl, VarDeclaration, SinthFile, CompileCtx, MixedBlockEntry, SinthError, SinthWarning, TT, AssignStmt, MetaEntry } from "./types.ts";
|
|
4
4
|
import { Parser } from "./parser.ts";
|
|
5
|
-
import { fnv1a, camelToKebab, esc, escAttr, litToString, tagNameToPascal } from "../utils.ts";
|
|
5
|
+
import { fnv1a, camelToKebab, esc, escAttr, litToString, tagNameToPascal, interpolateAttr, renderText } from "../utils.ts";
|
|
6
6
|
import { compileExprToJS, compileIfToJS, bodyToJS } from "./expr.ts";
|
|
7
7
|
import { FunctionDef } from "./types.ts";
|
|
8
8
|
import { parseFile, resolveImports, ResolverConfig, ResolvedImports } from "../resolver.ts";
|
|
9
|
+
import { compileFunctionDef } from "./runtime/functions.ts";
|
|
10
|
+
import { generateHelpers } from "./runtime/helpers.ts";
|
|
11
|
+
import { buildRenderBody } from "./runtime/render.ts";
|
|
12
|
+
import { BUILTIN_MAP, VOID_TAGS, BuiltinInfo } from "./builtins.ts";
|
|
13
|
+
import { processStyleBlock } from "./style-processor.ts";
|
|
14
|
+
import { buildHeadData, renderHead, HeadData } from "./head-builder.ts";
|
|
9
15
|
|
|
10
16
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
export interface BuiltinInfo { tag: string; defaultClass?: string; voidEl?: boolean }
|
|
14
|
-
|
|
15
|
-
export const BUILTIN_MAP: Record<string, BuiltinInfo> = {
|
|
16
|
-
// structural
|
|
17
|
-
Main: { tag: "main" },
|
|
18
|
-
Header: { tag: "header" },
|
|
19
|
-
Footer: { tag: "footer" },
|
|
20
|
-
Nav: { tag: "nav" },
|
|
21
|
-
Section: { tag: "section" },
|
|
22
|
-
Article: { tag: "article" },
|
|
23
|
-
Aside: { tag: "aside" },
|
|
24
|
-
Div: { tag: "div" },
|
|
25
|
-
Span: { tag: "span" },
|
|
26
|
-
Hero: { tag: "section", defaultClass: "hero" },
|
|
27
|
-
Container: { tag: "div", defaultClass: "container" },
|
|
28
|
-
Grid: { tag: "div", defaultClass: "grid" },
|
|
29
|
-
Flex: { tag: "div", defaultClass: "flex" },
|
|
30
|
-
Stack: { tag: "div", defaultClass: "stack" },
|
|
31
|
-
Row: { tag: "div", defaultClass: "row" },
|
|
32
|
-
Column: { tag: "div", defaultClass: "col" },
|
|
33
|
-
CardGrid: { tag: "div", defaultClass: "card-grid" },
|
|
34
|
-
// typography
|
|
35
|
-
Heading: { tag: "h1" },
|
|
36
|
-
SubHeading: { tag: "p", defaultClass: "subheading" },
|
|
37
|
-
Paragraph: { tag: "p" },
|
|
38
|
-
Lead: { tag: "p", defaultClass: "lead" },
|
|
39
|
-
Small: { tag: "small" },
|
|
40
|
-
Strong: { tag: "strong" },
|
|
41
|
-
Em: { tag: "em" },
|
|
42
|
-
Code: { tag: "code" },
|
|
43
|
-
Pre: { tag: "pre" },
|
|
44
|
-
Blockquote: { tag: "blockquote" },
|
|
45
|
-
Mark: { tag: "mark" },
|
|
46
|
-
Label: { tag: "label" },
|
|
47
|
-
Abbr: { tag: "abbr" },
|
|
48
|
-
Del: { tag: "del" },
|
|
49
|
-
Ins: { tag: "ins" },
|
|
50
|
-
Sub: { tag: "sub" },
|
|
51
|
-
Sup: { tag: "sup" },
|
|
52
|
-
Data: { tag: "data" },
|
|
53
|
-
Time: { tag: "time" },
|
|
54
|
-
Bdi: { tag: "bdi" },
|
|
55
|
-
Bdo: { tag: "bdo" },
|
|
56
|
-
Cite: { tag: "cite" },
|
|
57
|
-
Dfn: { tag: "dfn" },
|
|
58
|
-
Kbd: { tag: "kbd" },
|
|
59
|
-
Samp: { tag: "samp" },
|
|
60
|
-
Var: { tag: "var" },
|
|
61
|
-
Address: { tag: "address" },
|
|
62
|
-
Ruby: { tag: "ruby" },
|
|
63
|
-
Rt: { tag: "rt" },
|
|
64
|
-
Rp: { tag: "rp" },
|
|
65
|
-
// interactive
|
|
66
|
-
Button: { tag: "button" },
|
|
67
|
-
Link: { tag: "a" },
|
|
68
|
-
NavLink: { tag: "a" },
|
|
69
|
-
Select: { tag: "select" },
|
|
70
|
-
Form: { tag: "form" },
|
|
71
|
-
Fieldset: { tag: "fieldset" },
|
|
72
|
-
Legend: { tag: "legend" },
|
|
73
|
-
Details: { tag: "details" },
|
|
74
|
-
Summary: { tag: "summary" },
|
|
75
|
-
Dialog: { tag: "dialog" },
|
|
76
|
-
Textarea: { tag: "textarea" },
|
|
77
|
-
Datalist: { tag: "datalist" },
|
|
78
|
-
Optgroup: { tag: "optgroup" },
|
|
79
|
-
Option: { tag: "option" },
|
|
80
|
-
Progress: { tag: "progress" },
|
|
81
|
-
Meter: { tag: "meter" },
|
|
82
|
-
Output: { tag: "output" },
|
|
83
|
-
Map: { tag: "map" },
|
|
84
|
-
// media
|
|
85
|
-
Picture: { tag: "picture" },
|
|
86
|
-
Video: { tag: "video" },
|
|
87
|
-
Audio: { tag: "audio" },
|
|
88
|
-
Figure: { tag: "figure" },
|
|
89
|
-
Figcaption: { tag: "figcaption" },
|
|
90
|
-
Canvas: { tag: "canvas" },
|
|
91
|
-
Svg: { tag: "svg" },
|
|
92
|
-
IFrame: { tag: "iframe" },
|
|
93
|
-
Object: { tag: "object" },
|
|
94
|
-
// void elements
|
|
95
|
-
Img: { tag: "img", voidEl: true },
|
|
96
|
-
Logo: { tag: "img", voidEl: true },
|
|
97
|
-
Input: { tag: "input", voidEl: true },
|
|
98
|
-
Checkbox: { tag: "input", voidEl: true },
|
|
99
|
-
Hr: { tag: "hr", voidEl: true },
|
|
100
|
-
Br: { tag: "br", voidEl: true },
|
|
101
|
-
Wbr: { tag: "wbr", voidEl: true },
|
|
102
|
-
Source: { tag: "source", voidEl: true },
|
|
103
|
-
Embed: { tag: "embed", voidEl: true },
|
|
104
|
-
Col: { tag: "col", voidEl: true },
|
|
105
|
-
Area: { tag: "area", voidEl: true },
|
|
106
|
-
// lists
|
|
107
|
-
Ul: { tag: "ul" }, Ol: { tag: "ol" }, Li: { tag: "li" },
|
|
108
|
-
Dl: { tag: "dl" }, Dt: { tag: "dt" }, Dd: { tag: "dd" },
|
|
109
|
-
// tables
|
|
110
|
-
Table: { tag: "table" },
|
|
111
|
-
Caption: { tag: "caption" },
|
|
112
|
-
Thead: { tag: "thead" },
|
|
113
|
-
Tbody: { tag: "tbody" },
|
|
114
|
-
Tfoot: { tag: "tfoot" },
|
|
115
|
-
Tr: { tag: "tr" },
|
|
116
|
-
Th: { tag: "th" },
|
|
117
|
-
Td: { tag: "td" },
|
|
118
|
-
Colgroup: { tag: "colgroup" },
|
|
119
|
-
// utility
|
|
120
|
-
Template: { tag: "template" },
|
|
121
|
-
Slot: { tag: "slot" },
|
|
122
|
-
NoScript: { tag: "noscript" },
|
|
123
|
-
RawHTML: { tag: "__RAW__" },
|
|
124
|
-
};
|
|
125
|
-
|
|
126
|
-
export const VOID_TAGS = new Set([
|
|
127
|
-
"area","base","br","col","embed","hr","img","input",
|
|
128
|
-
"link","meta","param","source","track","wbr",
|
|
129
|
-
]);
|
|
130
|
-
|
|
131
17
|
const EVENT_RE = /^on[A-Z]/;
|
|
132
18
|
function eventAttrName(name: string): string | null {
|
|
133
19
|
return EVENT_RE.test(name) ? name.toLowerCase() : null;
|
|
134
20
|
}
|
|
135
21
|
|
|
136
|
-
// preprocessor
|
|
137
|
-
|
|
138
|
-
/**
|
|
139
|
-
* for who's reading this: This maps Sinth Style pseudo-class shorthand keywords to real CSS pseudo-classes.
|
|
140
|
-
* these are used inside component style blocks, for example: onHover { color: "blue" }
|
|
141
|
-
*/
|
|
142
|
-
export const SINTH_PSEUDO_CLASS: Record<string, string> = {
|
|
143
|
-
onHover: ":hover",
|
|
144
|
-
onFocus: ":focus",
|
|
145
|
-
onActive: ":active",
|
|
146
|
-
onVisited: ":visited",
|
|
147
|
-
onChecked: ":checked",
|
|
148
|
-
onDisabled: ":disabled",
|
|
149
|
-
onEnabled: ":enabled",
|
|
150
|
-
onRequired: ":required",
|
|
151
|
-
onOptional: ":optional",
|
|
152
|
-
onValid: ":valid",
|
|
153
|
-
onInvalid: ":invalid",
|
|
154
|
-
onPlaceholderShown:":placeholder-shown",
|
|
155
|
-
onFocusWithin: ":focus-within",
|
|
156
|
-
onFocusVisible: ":focus-visible",
|
|
157
|
-
onFirst: ":first-child",
|
|
158
|
-
onLast: ":last-child",
|
|
159
|
-
onFirstOfType: ":first-of-type",
|
|
160
|
-
onLastOfType: ":last-of-type",
|
|
161
|
-
onEmpty: ":empty",
|
|
162
|
-
onTarget: ":target",
|
|
163
|
-
onLink: ":link",
|
|
164
|
-
};
|
|
165
|
-
|
|
166
|
-
export const SINTH_PSEUDO_ELEMENT: Record<string, string> = {
|
|
167
|
-
before: "::before",
|
|
168
|
-
after: "::after",
|
|
169
|
-
placeholder: "::placeholder",
|
|
170
|
-
selection: "::selection",
|
|
171
|
-
firstLine: "::first-line",
|
|
172
|
-
firstLetter: "::first-letter",
|
|
173
|
-
marker: "::marker",
|
|
174
|
-
backdrop: "::backdrop",
|
|
175
|
-
};
|
|
176
|
-
|
|
177
|
-
export function sinthCompToSelector(name: string): string {
|
|
178
|
-
const info = BUILTIN_MAP[name];
|
|
179
|
-
if (!info) return name.toLowerCase();
|
|
180
|
-
if (info.defaultClass) {
|
|
181
|
-
const classes = info.defaultClass.split(" ").map(c => `.${c}`).join("");
|
|
182
|
-
return `${info.tag}${classes}`;
|
|
183
|
-
}
|
|
184
|
-
return info.tag;
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
/**
|
|
188
|
-
* supported conversions:
|
|
189
|
-
* - component names as selectors: `Paragraph { ... }` → `p { ... }`
|
|
190
|
-
* - pseudo-class shorthands: `onHover { ... }` → `&:hover { ... }`
|
|
191
|
-
* - pseudo-element shorthands: `before { ... }` → `&::before { ... }`
|
|
192
|
-
* - media queries: `media(maxWidth: "600px") { ... }` → `@media (max-width: 600px) { ... }`
|
|
193
|
-
* - CSS custom properties: `var --primary: "#3b82f6"` → `--primary: #3b82f6;`
|
|
194
|
-
*/
|
|
195
|
-
export function preprocessSinthStyle(raw: string): string {
|
|
196
|
-
const lines = raw.split("\n");
|
|
197
|
-
const result: string[] = [];
|
|
198
|
-
|
|
199
|
-
for (const line of lines) {
|
|
200
|
-
const trimmed = line.trim();
|
|
201
|
-
const indent = line.match(/^(\s*)/)?.[1] ?? "";
|
|
202
|
-
|
|
203
|
-
if (!trimmed) { result.push(line); continue; }
|
|
204
|
-
|
|
205
|
-
if (trimmed.startsWith("--") && !trimmed.startsWith("--[")) { continue; }
|
|
206
|
-
// Standard comments pass through
|
|
207
|
-
if (trimmed.startsWith("//") || trimmed.startsWith("/*") || trimmed.startsWith("*")) {
|
|
208
|
-
result.push(line); continue;
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
const mediaMatch = trimmed.match(/^media\s*\(([^)]+)\)\s*(\{?\s*)$/);
|
|
212
|
-
if (mediaMatch) {
|
|
213
|
-
const params = parseSinthMediaParams(mediaMatch[1]);
|
|
214
|
-
result.push(`${indent}@media (${params}) {`);
|
|
215
|
-
continue;
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
const blockMatch = trimmed.match(/^([a-zA-Z][a-zA-Z0-9]*)(\s*\{\s*)$/);
|
|
219
|
-
if (blockMatch) {
|
|
220
|
-
const keyword = blockMatch[1];
|
|
221
|
-
|
|
222
|
-
const pseudoCls = SINTH_PSEUDO_CLASS[keyword];
|
|
223
|
-
if (pseudoCls) {
|
|
224
|
-
result.push(`${indent}&${pseudoCls} {`);
|
|
225
|
-
continue;
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
const pseudoEl = SINTH_PSEUDO_ELEMENT[keyword];
|
|
229
|
-
if (pseudoEl) {
|
|
230
|
-
result.push(`${indent}&${pseudoEl} {`);
|
|
231
|
-
continue;
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
if (/^[A-Z]/.test(keyword) && BUILTIN_MAP[keyword]) {
|
|
235
|
-
result.push(`${indent}${sinthCompToSelector(keyword)} {`);
|
|
236
|
-
continue;
|
|
237
|
-
}
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
const varPropMatch = trimmed.match(/^var\s+(--[a-zA-Z][a-zA-Z0-9-]*)\s*:\s*["']?([^"';]+)["']?\s*;?\s*$/);
|
|
241
|
-
if (varPropMatch) {
|
|
242
|
-
result.push(`${indent}${varPropMatch[1]}: ${varPropMatch[2].trim()};`);
|
|
243
|
-
continue;
|
|
244
|
-
}
|
|
245
|
-
|
|
246
|
-
result.push(line);
|
|
247
|
-
}
|
|
248
|
-
|
|
249
|
-
return result.join("\n");
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
export function parseSinthMediaParams(params: string): string {
|
|
253
|
-
const parts = params.split(",").map(p => {
|
|
254
|
-
const m = p.trim().match(/^([a-zA-Z]+)\s*:\s*["']?([^"',]+)["']?\s*$/);
|
|
255
|
-
if (!m) return p.trim();
|
|
256
|
-
return `${camelToKebab(m[1])}: ${m[2].trim()}`;
|
|
257
|
-
});
|
|
258
|
-
return parts.join(") and (");
|
|
259
|
-
}
|
|
260
|
-
|
|
261
|
-
// style processor
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
export function convertCSSProps(css: string): string {
|
|
265
|
-
return css.split("\n").map(line => {
|
|
266
|
-
const trimmed = line.trim();
|
|
267
|
-
if (!trimmed) return line;
|
|
268
|
-
if (trimmed === "}" || trimmed.startsWith("}")) return line;
|
|
269
|
-
if (trimmed.startsWith("//") || trimmed.startsWith("/*") || trimmed.startsWith("*")) return line;
|
|
270
|
-
if (trimmed.startsWith("@")) return line;
|
|
271
|
-
if (trimmed.includes("{")) return line;
|
|
272
|
-
|
|
273
|
-
const m = line.match(/^(\s*)([a-zA-Z][a-zA-Z0-9-]*)(\s*:\s*)(.+?)(\s*;?\s*)$/);
|
|
274
|
-
if (!m) return line;
|
|
275
|
-
|
|
276
|
-
const [, indent, rawProp, , rawVal] = m;
|
|
277
|
-
|
|
278
|
-
const hasCamelCase = /[a-z][A-Z]/.test(rawProp) || /^[A-Z]/.test(rawProp);
|
|
279
|
-
const hasQuotedVal = /^["']/.test(rawVal.trim());
|
|
280
|
-
if (!hasCamelCase && !hasQuotedVal) return line;
|
|
281
|
-
|
|
282
|
-
let val = rawVal.trim();
|
|
283
|
-
if (val.endsWith(";")) val = val.slice(0, -1).trimEnd();
|
|
284
|
-
if ((val.startsWith('"') && val.endsWith('"')) ||
|
|
285
|
-
(val.startsWith("'") && val.endsWith("'"))) {
|
|
286
|
-
val = val.slice(1, -1);
|
|
287
|
-
}
|
|
288
|
-
|
|
289
|
-
return `${indent}${camelToKebab(rawProp)}: ${val};`;
|
|
290
|
-
}).join("\n");
|
|
291
|
-
}
|
|
292
|
-
|
|
293
|
-
export function processStyleBlock(
|
|
294
|
-
block: StyleBlock,
|
|
295
|
-
hash: string,
|
|
296
|
-
params: Map<string, string> = new Map(),
|
|
297
|
-
): string {
|
|
298
|
-
let raw = block.raw;
|
|
299
|
-
|
|
300
|
-
// 1. interpolate {param} placeholders
|
|
301
|
-
if (params.size > 0) raw = interpolateAttr(raw, params);
|
|
302
|
-
|
|
303
|
-
// 2. sinth style preprocessing
|
|
304
|
-
raw = preprocessSinthStyle(raw);
|
|
305
|
-
|
|
306
|
-
// 3. warn if & in plain CSS
|
|
307
|
-
if (block.lang === "css" && raw.includes("&")) {
|
|
308
|
-
SinthWarning.emit(
|
|
309
|
-
`'&' (CSS nesting) found in style block. Nested selectors require a modern browser or lang="scss".`,
|
|
310
|
-
block.loc,
|
|
311
|
-
);
|
|
312
|
-
}
|
|
313
|
-
|
|
314
|
-
// 4. camelCase → kebab-case
|
|
315
|
-
let css = convertCSSProps(raw);
|
|
316
|
-
|
|
317
|
-
// 5. SCSS compilation
|
|
318
|
-
if (block.lang === "scss") {
|
|
319
|
-
try {
|
|
320
|
-
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
321
|
-
const sass: { compileString: (src: string) => { css: string } } = require("sass");
|
|
322
|
-
css = sass.compileString(css).css;
|
|
323
|
-
} catch (e: unknown) {
|
|
324
|
-
const err = e as { code?: string; message?: string };
|
|
325
|
-
if (err.code === "MODULE_NOT_FOUND" || err.message?.includes("Cannot find module")) {
|
|
326
|
-
throw new SinthError("SCSS requires the 'sass' package. Install with: npm install sass");
|
|
327
|
-
}
|
|
328
|
-
throw new SinthError(`SCSS compilation failed: ${err.message ?? String(e)}`);
|
|
329
|
-
}
|
|
330
|
-
}
|
|
331
|
-
|
|
332
|
-
// 6. if target component given, wrap content in its CSS selector
|
|
333
|
-
if (block.target) {
|
|
334
|
-
const selector = sinthCompToSelector(block.target);
|
|
335
|
-
css = `${selector} {\n${css}\n}`;
|
|
336
|
-
}
|
|
337
|
-
|
|
338
|
-
// 7. scope (except it's global)
|
|
339
|
-
if (!block.global) css = scopeCSS(css, hash);
|
|
340
|
-
|
|
341
|
-
return css;
|
|
342
|
-
}
|
|
343
|
-
|
|
344
|
-
export function scopeCSS(css: string, hash: string): string {
|
|
345
|
-
return processRules(css, `[data-s="${hash}"]`);
|
|
346
|
-
}
|
|
347
|
-
|
|
348
|
-
export function processRules(css: string, attr: string): string {
|
|
349
|
-
let out = "", i = 0;
|
|
350
|
-
|
|
351
|
-
while (i < css.length) {
|
|
352
|
-
if (/\s/.test(css[i])) { out += css[i++]; continue; }
|
|
353
|
-
|
|
354
|
-
if (css[i] === "/" && css[i + 1] === "*") {
|
|
355
|
-
const end = css.indexOf("*/", i + 2);
|
|
356
|
-
if (end === -1) { out += css.substring(i); break; }
|
|
357
|
-
out += css.substring(i, end + 2);
|
|
358
|
-
i = end + 2;
|
|
359
|
-
continue;
|
|
360
|
-
}
|
|
361
|
-
|
|
362
|
-
const braceIdx = findCSSBrace(css, i);
|
|
363
|
-
if (braceIdx === -1) { out += css.substring(i); break; }
|
|
364
|
-
|
|
365
|
-
const selector = css.substring(i, braceIdx).trim();
|
|
366
|
-
const { content, end } = extractCSSBlock(css, braceIdx);
|
|
367
|
-
|
|
368
|
-
if (/^@(-webkit-|-moz-)?keyframes/.test(selector)) {
|
|
369
|
-
out += `${selector} {${content}}\n`;
|
|
370
|
-
} else if (/^@(media|supports|layer|container)/.test(selector)) {
|
|
371
|
-
out += `${selector} {\n${processRules(content, attr)}\n}\n`;
|
|
372
|
-
} else if (selector.startsWith("@")) {
|
|
373
|
-
out += `${selector} {${content}}\n`;
|
|
374
|
-
} else if (selector.length > 0) {
|
|
375
|
-
out += `${scopeSelectors(selector, attr)} {${content}}\n`;
|
|
376
|
-
}
|
|
377
|
-
|
|
378
|
-
i = end;
|
|
379
|
-
}
|
|
380
|
-
return out;
|
|
381
|
-
}
|
|
382
|
-
|
|
383
|
-
export function scopeSelectors(selList: string, attr: string): string {
|
|
384
|
-
return selList
|
|
385
|
-
.split(",")
|
|
386
|
-
.map(s => {
|
|
387
|
-
s = s.trim();
|
|
388
|
-
if (!s) return "";
|
|
389
|
-
if (/^(html|body|:root)(\s|$|{|,)/.test(s)) return s;
|
|
390
|
-
const m = s.match(/^(.*?)((?::{1,2}[a-zA-Z-]+(?:\([^)]*\))?)+)$/);
|
|
391
|
-
if (m && m[1].trim()) {
|
|
392
|
-
return `${attr} ${m[1].trimEnd()}${m[2]}, ${m[1].trimEnd()}${attr}${m[2]}`;
|
|
393
|
-
}
|
|
394
|
-
return `${attr} ${s}, ${s}${attr}`;
|
|
395
|
-
})
|
|
396
|
-
.filter(Boolean)
|
|
397
|
-
.join(",\n");
|
|
398
|
-
}
|
|
399
|
-
|
|
400
|
-
export function findCSSBrace(css: string, from: number): number {
|
|
401
|
-
let i = from;
|
|
402
|
-
while (i < css.length) {
|
|
403
|
-
if (css[i] === '"' || css[i] === "'") {
|
|
404
|
-
const q = css[i++];
|
|
405
|
-
while (i < css.length && css[i] !== q) { if (css[i] === "\\") i++; i++; }
|
|
406
|
-
i++;
|
|
407
|
-
} else if (css[i] === "{") {
|
|
408
|
-
return i;
|
|
409
|
-
} else { i++; }
|
|
410
|
-
}
|
|
411
|
-
return -1;
|
|
412
|
-
}
|
|
413
|
-
|
|
414
|
-
export function extractCSSBlock(css: string, openBrace: number): { content: string; end: number } {
|
|
415
|
-
let i = openBrace + 1, depth = 1;
|
|
416
|
-
while (i < css.length && depth > 0) {
|
|
417
|
-
if (css[i] === '"' || css[i] === "'") {
|
|
418
|
-
const q = css[i++];
|
|
419
|
-
while (i < css.length && css[i] !== q) { if (css[i] === "\\") i++; i++; }
|
|
420
|
-
i++;
|
|
421
|
-
} else if (css[i] === "/" && css[i + 1] === "*") {
|
|
422
|
-
i += 2;
|
|
423
|
-
while (i < css.length - 1 && !(css[i] === "*" && css[i + 1] === "/")) i++;
|
|
424
|
-
i += 2;
|
|
425
|
-
} else if (css[i] === "{") { depth++; i++; }
|
|
426
|
-
else if (css[i] === "}") { depth--; if (depth > 0) i++; else break; }
|
|
427
|
-
else { i++; }
|
|
428
|
-
}
|
|
429
|
-
return { content: css.substring(openBrace + 1, i), end: i + 1 };
|
|
430
|
-
}
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
// the HTML generator
|
|
438
|
-
|
|
439
22
|
/**
|
|
440
23
|
* CSS property names that are allowed as inline style shorthand attributes on
|
|
441
24
|
* any Sinth component: Paragraph(color: "red", fontSize: "1.2rem") { "Hi" }
|
|
@@ -552,7 +135,7 @@ if (name === "delay") {
|
|
|
552
135
|
const exprJson = raw.substring("__EXPR__".length);
|
|
553
136
|
try {
|
|
554
137
|
const expr: Expression = JSON.parse(exprJson);
|
|
555
|
-
const jsExpr = compileExprToJS(expr);
|
|
138
|
+
const jsExpr = compileExprToJS(expr, ctx?.loopVars);
|
|
556
139
|
const ev = eventAttrName(name);
|
|
557
140
|
if (ev) return `${ev}="(function(){ ${jsExpr.replace(/"/g, """)}; sinthRender(); })()"`;
|
|
558
141
|
return `${name}="${escAttr(jsExpr)}"`;
|
|
@@ -569,46 +152,37 @@ if (name === "delay") {
|
|
|
569
152
|
return `${name}="${escAttr(raw)}"`;
|
|
570
153
|
}
|
|
571
154
|
|
|
572
|
-
export function renderText(text: string, params: Map<string, string>): string {
|
|
573
|
-
const rawSlots = new Map<string, string>();
|
|
574
|
-
let counter = 0;
|
|
575
155
|
|
|
576
|
-
let s = text.replace(/\\\$/g, "\x00DOLLAR\x00");
|
|
577
156
|
|
|
578
|
-
s = s.replace(/\$([a-zA-Z_][a-zA-Z0-9_]*)/g, (_, n) => {
|
|
579
|
-
const val = params.get(n);
|
|
580
|
-
if (val === undefined) return `$${n}`;
|
|
581
|
-
if (n === "slot") {
|
|
582
|
-
const ph = `\x00RAW${counter++}\x00`;
|
|
583
|
-
rawSlots.set(ph, val);
|
|
584
|
-
return ph;
|
|
585
|
-
}
|
|
586
|
-
return val;
|
|
587
|
-
});
|
|
588
157
|
|
|
589
|
-
s = esc(s);
|
|
590
158
|
|
|
591
|
-
for (const [ph, val] of rawSlots) s = s.replace(ph, val);
|
|
592
|
-
s = s.replace(/\x00DOLLAR\x00/g, "$");
|
|
593
159
|
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
160
|
+
function substituteParamsInExpr(expr: Expression, params: Map<string, string>): Expression {
|
|
161
|
+
if (expr.kind === "variable" && expr.name && params.has(expr.name)) {
|
|
162
|
+
const val = params.get(expr.name)!;
|
|
163
|
+
if (val.startsWith("__LIT__")) {
|
|
164
|
+
return { kind: "literal", value: { kind: "str", value: val.slice(7) } };
|
|
165
|
+
}
|
|
166
|
+
if (val.startsWith("__EXPR__")) {
|
|
167
|
+
try {
|
|
168
|
+
return JSON.parse(val.substring(8));
|
|
169
|
+
} catch { return expr; }
|
|
170
|
+
}
|
|
171
|
+
return { kind: "literal", value: { kind: "str", value: val } };
|
|
600
172
|
}
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
173
|
+
if (expr.kind === "binary") {
|
|
174
|
+
return {
|
|
175
|
+
...expr,
|
|
176
|
+
left: expr.left ? substituteParamsInExpr(expr.left, params) : undefined,
|
|
177
|
+
right: expr.right ? substituteParamsInExpr(expr.right, params) : undefined,
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
if (expr.kind === "unary" && expr.operand) {
|
|
181
|
+
return { ...expr, operand: substituteParamsInExpr(expr.operand, params) };
|
|
182
|
+
}
|
|
183
|
+
return expr;
|
|
609
184
|
}
|
|
610
185
|
|
|
611
|
-
|
|
612
186
|
export function renderChild(
|
|
613
187
|
child: Child,
|
|
614
188
|
ctx: CompileCtx,
|
|
@@ -622,15 +196,28 @@ export function renderChild(
|
|
|
622
196
|
return renderText(child.value, params);
|
|
623
197
|
|
|
624
198
|
case "expr": {
|
|
625
|
-
if (child.expression
|
|
626
|
-
|
|
199
|
+
if (!child.expression) return "";
|
|
200
|
+
|
|
201
|
+
if (child.expression.kind === "variable" && child.expression.name && params.has(child.expression.name)) {
|
|
202
|
+
const val = params.get(child.expression.name)!;
|
|
627
203
|
if (val.startsWith("__LIT__")) {
|
|
628
204
|
return esc(val.slice(7));
|
|
629
205
|
}
|
|
206
|
+
if (val.startsWith("__RAW__")) {
|
|
207
|
+
return val.slice(7);
|
|
208
|
+
}
|
|
630
209
|
if (val.startsWith("__VAR__")) {
|
|
631
210
|
const exprId = registerExpr(ctx, { kind: "variable", name: val.slice(7) });
|
|
632
211
|
return `<span class="sinth-expr" data-expr-id="${exprId}"></span>`;
|
|
633
212
|
}
|
|
213
|
+
if (val.startsWith("__EXPR__")) {
|
|
214
|
+
try {
|
|
215
|
+
const expr: Expression = JSON.parse(val.substring(8));
|
|
216
|
+
const exprId = registerExpr(ctx, expr);
|
|
217
|
+
return `<span class="sinth-expr" data-expr-id="${exprId}"></span>`;
|
|
218
|
+
} catch { return esc(val); }
|
|
219
|
+
}
|
|
220
|
+
return esc(val);
|
|
634
221
|
}
|
|
635
222
|
if (child.expression.kind === "call" && child.expression.callee?.kind === "variable") {
|
|
636
223
|
const fnName = child.expression.callee.name;
|
|
@@ -698,7 +285,11 @@ export function renderChild(
|
|
|
698
285
|
const exprId = registerExpr(ctx, child.expression);
|
|
699
286
|
return `<span class="sinth-expr" data-expr-id="${exprId}"></span>`;
|
|
700
287
|
}
|
|
701
|
-
|
|
288
|
+
let expr = child.expression;
|
|
289
|
+
if (params.size > 0) {
|
|
290
|
+
expr = substituteParamsInExpr(expr, params);
|
|
291
|
+
}
|
|
292
|
+
const exprId = registerExpr(ctx, expr);
|
|
702
293
|
return `<span class="sinth-expr" data-expr-id="${exprId}"></span>`;
|
|
703
294
|
}
|
|
704
295
|
|
|
@@ -1033,7 +624,7 @@ export function expandUserComp(
|
|
|
1033
624
|
params: Map<string, string>,
|
|
1034
625
|
depth: number,
|
|
1035
626
|
): string {
|
|
1036
|
-
if (use.name === def.name && depth >
|
|
627
|
+
if (use.name === def.name && depth > 4) {
|
|
1037
628
|
throw new SinthError(`Recursive component '${def.name}' is not allowed.`, use.loc);
|
|
1038
629
|
}
|
|
1039
630
|
|
|
@@ -1048,7 +639,11 @@ export function expandUserComp(
|
|
|
1048
639
|
local.set(attr.name, "true");
|
|
1049
640
|
} else if (attr.value.kind !== "null") {
|
|
1050
641
|
const raw = litToString(attr.value);
|
|
1051
|
-
|
|
642
|
+
if (raw.startsWith("__EXPR__")) {
|
|
643
|
+
local.set(attr.name, raw);
|
|
644
|
+
} else {
|
|
645
|
+
local.set(attr.name, attr.value.kind === "str" ? interpolateAttr(raw, params) : raw);
|
|
646
|
+
}
|
|
1052
647
|
}
|
|
1053
648
|
}
|
|
1054
649
|
|
|
@@ -1062,7 +657,7 @@ export function expandUserComp(
|
|
|
1062
657
|
}
|
|
1063
658
|
|
|
1064
659
|
const slotHTML = use.children.map(c => renderChild(c, ctx, params, depth)).join("");
|
|
1065
|
-
local.set("slot", slotHTML);
|
|
660
|
+
local.set("slot", "__RAW__" + slotHTML);
|
|
1066
661
|
|
|
1067
662
|
for (const block of def.styles) {
|
|
1068
663
|
ctx.extraCSS.push(processStyleBlock(block, ctx.scopeHash, local));
|
|
@@ -1071,7 +666,7 @@ export function expandUserComp(
|
|
|
1071
666
|
return def.body.map(c => renderChild(c, ctx, local, depth)).join("");
|
|
1072
667
|
}
|
|
1073
668
|
|
|
1074
|
-
|
|
669
|
+
|
|
1075
670
|
|
|
1076
671
|
export function collectScripts(
|
|
1077
672
|
file: SinthFile,
|
|
@@ -1111,122 +706,10 @@ export function extractFunctionNames(js: string): string[] {
|
|
|
1111
706
|
}
|
|
1112
707
|
|
|
1113
708
|
|
|
1114
|
-
// head gen
|
|
1115
|
-
|
|
1116
|
-
export interface HeadData {
|
|
1117
|
-
title?: string; fav?: string;
|
|
1118
|
-
lang: string; charset: string; viewport: string;
|
|
1119
|
-
metaTags: { name: string; content: string }[];
|
|
1120
|
-
metaProps: { property: string; content: string }[];
|
|
1121
|
-
}
|
|
1122
|
-
|
|
1123
|
-
export function buildHeadData(meta: MetaEntry[]): HeadData {
|
|
1124
|
-
let title: string | undefined, fav: string | undefined;
|
|
1125
|
-
let lang = "en", charset = "UTF-8", viewport = "width=device-width, initial-scale=1.0";
|
|
1126
|
-
const metaTags: { name: string; content: string }[] = [];
|
|
1127
|
-
const metaProps: { property: string; content: string }[] = [];
|
|
1128
|
-
|
|
1129
|
-
for (const m of meta) {
|
|
1130
|
-
const val = litToString(m.value);
|
|
1131
|
-
switch (m.key) {
|
|
1132
|
-
case "title": title = val; break;
|
|
1133
|
-
case "fav": fav = val; break;
|
|
1134
|
-
case "lang": lang = val; break;
|
|
1135
|
-
case "charset": charset = val; break;
|
|
1136
|
-
case "viewport": viewport = val; break;
|
|
1137
|
-
case "descr": metaTags.push({ name: "description", content: val }); break;
|
|
1138
|
-
case "author": metaTags.push({ name: "author", content: val }); break;
|
|
1139
|
-
case "keywords": metaTags.push({ name: "keywords", content: val }); break;
|
|
1140
|
-
case "robots": metaTags.push({ name: "robots", content: val }); break;
|
|
1141
|
-
default:
|
|
1142
|
-
if (m.key.startsWith("og") || m.key.startsWith("twitter")) {
|
|
1143
|
-
const prop = m.key
|
|
1144
|
-
.replace(/^og([A-Z])/, (_: string, c: string) => `og:${c.toLowerCase()}`)
|
|
1145
|
-
.replace(/^twitter([A-Z])/, (_: string, c: string) => `twitter:${c.toLowerCase()}`);
|
|
1146
|
-
metaProps.push({ property: prop, content: val });
|
|
1147
|
-
} else {
|
|
1148
|
-
metaTags.push({ name: camelToKebab(m.key), content: val });
|
|
1149
|
-
}
|
|
1150
|
-
}
|
|
1151
|
-
}
|
|
1152
|
-
|
|
1153
|
-
return { title, fav, lang, charset, viewport, metaTags, metaProps };
|
|
1154
|
-
}
|
|
1155
|
-
|
|
1156
|
-
export function faviconType(p: string): string {
|
|
1157
|
-
switch (path.extname(p).toLowerCase()) {
|
|
1158
|
-
case ".ico": return "image/x-icon";
|
|
1159
|
-
case ".png": return "image/png";
|
|
1160
|
-
case ".svg": return "image/svg+xml";
|
|
1161
|
-
case ".gif": return "image/gif";
|
|
1162
|
-
case ".webp": return "image/webp";
|
|
1163
|
-
case ".jpg":
|
|
1164
|
-
case ".jpeg": return "image/jpeg";
|
|
1165
|
-
default:
|
|
1166
|
-
SinthWarning.emit(`Unknown favicon extension '${path.extname(p)}', defaulting to image/x-icon`);
|
|
1167
|
-
return "image/x-icon";
|
|
1168
|
-
}
|
|
1169
|
-
}
|
|
1170
|
-
|
|
1171
|
-
export function renderHead(
|
|
1172
|
-
hd: HeadData,
|
|
1173
|
-
cssLinks: string[],
|
|
1174
|
-
jsLinks: { src: string; attrs: Record<string, string> }[],
|
|
1175
|
-
scopedCSS: string,
|
|
1176
|
-
companionJS: string | undefined,
|
|
1177
|
-
): string {
|
|
1178
|
-
const lines: string[] = [];
|
|
1179
|
-
lines.push(` <meta charset="${escAttr(hd.charset)}">`);
|
|
1180
|
-
lines.push(` <meta name="viewport" content="${escAttr(hd.viewport)}">`);
|
|
1181
|
-
if (hd.title) lines.push(` <title>${esc(hd.title)}</title>`);
|
|
1182
|
-
if (hd.fav) lines.push(` <link rel="icon" href="${escAttr(hd.fav)}" type="${faviconType(hd.fav)}">`);
|
|
1183
|
-
for (const m of hd.metaTags) lines.push(` <meta name="${escAttr(m.name)}" content="${escAttr(m.content)}">`);
|
|
1184
|
-
for (const m of hd.metaProps) lines.push(` <meta property="${escAttr(m.property)}" content="${escAttr(m.content)}">`);
|
|
1185
|
-
for (const css of cssLinks) lines.push(` <link rel="stylesheet" href="${escAttr(css)}">`);
|
|
1186
|
-
if (scopedCSS.trim()) lines.push(` <style>\n${scopedCSS}\n </style>`);
|
|
1187
|
-
for (const js of jsLinks) {
|
|
1188
|
-
const extra = Object.entries(js.attrs)
|
|
1189
|
-
.map(([k, v]) => v === "true" ? k : `${k}="${escAttr(v)}"`)
|
|
1190
|
-
.join(" ");
|
|
1191
|
-
lines.push(` <script src="${escAttr(js.src)}"${extra ? " " + extra : ""}></script>`);
|
|
1192
|
-
}
|
|
1193
|
-
if (companionJS) lines.push(` <script src="${escAttr(companionJS)}"></script>`);
|
|
1194
|
-
return `<head>\n${lines.join("\n")}\n</head>`;
|
|
1195
|
-
}
|
|
1196
709
|
|
|
1197
710
|
|
|
1198
711
|
// sinth runtime
|
|
1199
712
|
|
|
1200
|
-
function compileFunctionDef(fn: FunctionDef, ctx: CompileCtx): string {
|
|
1201
|
-
const paramsJS = fn.params.map(p => p.name).join(", ");
|
|
1202
|
-
|
|
1203
|
-
if (fn.returnType === "ui") {
|
|
1204
|
-
return "";
|
|
1205
|
-
}
|
|
1206
|
-
|
|
1207
|
-
const bodyStatements: string[] = [];
|
|
1208
|
-
for (const child of fn.body) {
|
|
1209
|
-
switch (child.kind) {
|
|
1210
|
-
case "text":
|
|
1211
|
-
break;
|
|
1212
|
-
case "expr":
|
|
1213
|
-
bodyStatements.push(`return ${compileExprToJS(child.expression)};`);
|
|
1214
|
-
break;
|
|
1215
|
-
case "assign_stmt":
|
|
1216
|
-
bodyStatements.push(`${compileExprToJS(child.expression)};`);
|
|
1217
|
-
break;
|
|
1218
|
-
case "if":
|
|
1219
|
-
bodyStatements.push(compileIfToJS(child as IfBlock));
|
|
1220
|
-
break;
|
|
1221
|
-
case "for":
|
|
1222
|
-
break;
|
|
1223
|
-
case "return":
|
|
1224
|
-
bodyStatements.push(`return ${child.expression ? compileExprToJS(child.expression) : ""};`);
|
|
1225
|
-
break;
|
|
1226
|
-
}
|
|
1227
|
-
}
|
|
1228
|
-
return `function ${fn.name}(${paramsJS}) {\n${bodyStatements.map(s => ` ${s}`).join("\n")}\n}`;
|
|
1229
|
-
}
|
|
1230
713
|
|
|
1231
714
|
export function buildRuntime(opts: {
|
|
1232
715
|
varDecls: VarDeclaration[];
|
|
@@ -1278,364 +761,18 @@ export function buildRuntime(opts: {
|
|
|
1278
761
|
return varLines ? `// Sinth compiled runtime\n${varLines}` : "";
|
|
1279
762
|
}
|
|
1280
763
|
|
|
1281
|
-
let helpers = "";
|
|
1282
764
|
|
|
1283
|
-
|
|
1284
|
-
helpers += `
|
|
1285
|
-
function sinthExpr(el) {
|
|
1286
|
-
try {
|
|
1287
|
-
var exprFn = __X[el.dataset.exprId];
|
|
1288
|
-
if (exprFn) el.textContent = exprFn({});
|
|
1289
|
-
} catch(e) {}
|
|
1290
|
-
}
|
|
1291
|
-
`;
|
|
1292
|
-
}
|
|
1293
|
-
|
|
1294
|
-
if (needsIf || needsMixed) {
|
|
1295
|
-
helpers += `
|
|
1296
|
-
function sinthReplaceInsert(t, anchor, ifId, replaceId) {
|
|
1297
|
-
if (anchor) {
|
|
1298
|
-
var cur = anchor.nextSibling;
|
|
1299
|
-
while (cur && cur !== t) { var nx = cur.nextSibling; cur.remove(); cur = nx; }
|
|
1300
|
-
} else {
|
|
1301
|
-
anchor = document.createElement('span');
|
|
1302
|
-
anchor.style.display = 'none';
|
|
1303
|
-
anchor.dataset.sinthIfAnchor = ifId;
|
|
1304
|
-
t.parentNode.insertBefore(anchor, t);
|
|
1305
|
-
}
|
|
1306
|
-
var _rp = null, _rpParent = null, _rpNext = null;
|
|
1307
|
-
if (replaceId) {
|
|
1308
|
-
_rp = document.getElementById(replaceId);
|
|
1309
|
-
if (_rp) {
|
|
1310
|
-
_rpParent = _rp.parentNode;
|
|
1311
|
-
_rpNext = _rp.nextSibling;
|
|
1312
|
-
_rp.parentNode.removeChild(_rp);
|
|
1313
|
-
anchor._sinthReplaced = _rp;
|
|
1314
|
-
anchor._sinthReplacedParent = _rpParent;
|
|
1315
|
-
anchor._sinthReplacedNext = _rpNext;
|
|
1316
|
-
}
|
|
1317
|
-
}
|
|
1318
|
-
var frag = document.createRange().createContextualFragment(t.innerHTML);
|
|
1319
|
-
frag.querySelectorAll('.sinth-expr').forEach(sinthExpr);
|
|
1320
|
-
if (${needsDelay}) {
|
|
1321
|
-
frag.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
|
|
1322
|
-
frag.querySelectorAll('[data-sinth-delay-expr-id]').forEach(function(el) { sinthDelayExpr(el, {}); });
|
|
1323
|
-
}
|
|
1324
|
-
var fragFirst = frag.firstChild;
|
|
1325
|
-
var fragLast = frag.lastChild;
|
|
1326
|
-
if (_rpParent && _rpNext) {
|
|
1327
|
-
_rpParent.insertBefore(frag, _rpNext);
|
|
1328
|
-
} else if (_rpParent) {
|
|
1329
|
-
_rpParent.appendChild(frag);
|
|
1330
|
-
} else {
|
|
1331
|
-
t.parentNode.insertBefore(frag, t);
|
|
1332
|
-
}
|
|
1333
|
-
if (replaceId && anchor) {
|
|
1334
|
-
anchor._sinthInsertedFirst = fragFirst;
|
|
1335
|
-
anchor._sinthInsertedLast = fragLast;
|
|
1336
|
-
}
|
|
1337
|
-
return anchor;
|
|
1338
|
-
}
|
|
1339
|
-
`;
|
|
1340
|
-
}
|
|
1341
|
-
|
|
1342
|
-
if (needsDelay) {
|
|
1343
|
-
helpers += `
|
|
1344
|
-
function sinthDelay(el) {
|
|
1345
|
-
if (el.dataset.sinthDelayDone) { return; }
|
|
1346
|
-
el.dataset.sinthDelayDone = '1';
|
|
1347
|
-
var ms = parseInt(el.dataset.sinthDelay) || 0;
|
|
1348
|
-
if (el.dataset.sinthDelayHide !== 'false') {
|
|
1349
|
-
el.style.display = 'none';
|
|
1350
|
-
}
|
|
1351
|
-
var show = function() {
|
|
1352
|
-
el.style.display = '';
|
|
1353
|
-
el.querySelectorAll('.sinth-expr').forEach(sinthExpr);
|
|
1354
|
-
};
|
|
1355
|
-
if (ms > 0) setTimeout(show, ms);
|
|
1356
|
-
else show();
|
|
1357
|
-
}
|
|
1358
|
-
function sinthDelayExpr(el, _ctx) {
|
|
1359
|
-
_ctx = _ctx || {};
|
|
1360
|
-
try {
|
|
1361
|
-
var fn = __X[el.dataset.sinthDelayExprId];
|
|
1362
|
-
var ms = fn ? parseInt(fn(_ctx)) || 0 : 0;
|
|
1363
|
-
var show = function() {
|
|
1364
|
-
el.style.display = '';
|
|
1365
|
-
el.querySelectorAll('.sinth-expr').forEach(sinthExpr);
|
|
1366
|
-
};
|
|
1367
|
-
if (ms > 0) setTimeout(show, ms);
|
|
1368
|
-
else show();
|
|
1369
|
-
} catch(e) {}
|
|
1370
|
-
}
|
|
1371
|
-
`;
|
|
1372
|
-
}
|
|
765
|
+
const helpers = generateHelpers({ needsExpr, needsIf, needsFor, needsDelay, needsMixed });
|
|
1373
766
|
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
var ifId = t.dataset.sinthIfId;
|
|
1378
|
-
var anchor = t.parentNode.querySelector('[data-sinth-if-anchor="' + ifId + '"]');
|
|
1379
|
-
var condFn = __X[t.dataset.sinthIfExpr];
|
|
1380
|
-
var cond = condFn ? condFn() : false;
|
|
1381
|
-
if (cond) {
|
|
1382
|
-
var _hasContent = anchor || t.parentNode.querySelector('[data-sinth-if-anchor="__else__' + ifId + '"]');
|
|
1383
|
-
if (t.dataset.sinthIfDelayHide === 'false' && t.dataset.sinthIfDelay && _hasContent) {
|
|
1384
|
-
var dms = parseInt(t.dataset.sinthIfDelay) || 0;
|
|
1385
|
-
setTimeout(function() {
|
|
1386
|
-
sinthReplaceInsert(t, anchor, ifId, t.dataset.sinthIfReplace);
|
|
1387
|
-
}, dms);
|
|
1388
|
-
} else {
|
|
1389
|
-
anchor = sinthReplaceInsert(t, anchor, ifId, t.dataset.sinthIfReplace);
|
|
1390
|
-
}
|
|
1391
|
-
} else {
|
|
1392
|
-
var runElse = function() {
|
|
1393
|
-
if (anchor) {
|
|
1394
|
-
if (anchor._sinthReplaced) {
|
|
1395
|
-
var insFirst = anchor._sinthInsertedFirst;
|
|
1396
|
-
var insLast = anchor._sinthInsertedLast;
|
|
1397
|
-
var rpParent = anchor._sinthReplacedParent;
|
|
1398
|
-
var rpNext = anchor._sinthReplacedNext;
|
|
1399
|
-
if (insFirst && insLast) {
|
|
1400
|
-
var cur = insFirst;
|
|
1401
|
-
while (cur && cur !== insLast) {
|
|
1402
|
-
var next = cur.nextSibling;
|
|
1403
|
-
cur.remove();
|
|
1404
|
-
cur = next;
|
|
1405
|
-
}
|
|
1406
|
-
if (insLast) insLast.remove();
|
|
1407
|
-
}
|
|
1408
|
-
if (rpParent && rpNext) {
|
|
1409
|
-
rpParent.insertBefore(anchor._sinthReplaced, rpNext);
|
|
1410
|
-
} else if (rpParent) {
|
|
1411
|
-
rpParent.appendChild(anchor._sinthReplaced);
|
|
1412
|
-
}
|
|
1413
|
-
if (anchor._sinthReplaced && anchor._sinthReplaced.dataset.sinthDelay) {
|
|
1414
|
-
delete anchor._sinthReplaced.dataset.sinthDelayDone;
|
|
1415
|
-
sinthDelay(anchor._sinthReplaced);
|
|
1416
|
-
}
|
|
1417
|
-
} else {
|
|
1418
|
-
var cur2 = anchor.nextSibling;
|
|
1419
|
-
while (cur2 && cur2 !== t) { var nx2 = cur2.nextSibling; cur2.remove(); cur2 = nx2; }
|
|
1420
|
-
}
|
|
1421
|
-
anchor.remove();
|
|
1422
|
-
}
|
|
1423
|
-
var elseT = t.nextElementSibling;
|
|
1424
|
-
if (elseT && elseT.hasAttribute('data-sinth-else')) {
|
|
1425
|
-
var elseIfId = elseT.dataset.sinthIfId;
|
|
1426
|
-
var ea = t.parentNode.querySelector('[data-sinth-if-anchor="__else__' + elseIfId + '"]');
|
|
1427
|
-
if (ea) {
|
|
1428
|
-
var cur3 = ea.nextSibling;
|
|
1429
|
-
while (cur3 && cur3 !== t) { var nx3 = cur3.nextSibling; cur3.remove(); cur3 = nx3; }
|
|
1430
|
-
} else {
|
|
1431
|
-
ea = document.createElement('span');
|
|
1432
|
-
ea.style.display = 'none';
|
|
1433
|
-
ea.dataset.sinthIfAnchor = '__else__' + elseIfId;
|
|
1434
|
-
t.parentNode.insertBefore(ea, t);
|
|
1435
|
-
}
|
|
1436
|
-
var ef = document.createRange().createContextualFragment(elseT.innerHTML);
|
|
1437
|
-
ef.querySelectorAll('.sinth-expr').forEach(sinthExpr);
|
|
1438
|
-
if (${needsDelay}) {
|
|
1439
|
-
ef.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
|
|
1440
|
-
ef.querySelectorAll('[data-sinth-delay-expr-id]').forEach(function(el) { sinthDelayExpr(el, {}); });
|
|
1441
|
-
}
|
|
1442
|
-
t.parentNode.insertBefore(ef, t);
|
|
1443
|
-
ef.querySelectorAll('[data-sinth-delay]').forEach(function(el) {
|
|
1444
|
-
delete el.dataset.sinthDelayDone;
|
|
1445
|
-
sinthDelay(el);
|
|
1446
|
-
});
|
|
1447
|
-
} else {
|
|
1448
|
-
var ea2 = t.parentNode.querySelector('[data-sinth-if-anchor="__else__' + ifId + '"]');
|
|
1449
|
-
if (ea2) {
|
|
1450
|
-
var ec = ea2.nextSibling;
|
|
1451
|
-
while (ec && ec !== t) { var en = ec.nextSibling; ec.remove(); ec = en; }
|
|
1452
|
-
ea2.remove();
|
|
1453
|
-
}
|
|
1454
|
-
}
|
|
1455
|
-
};
|
|
1456
|
-
var elseT = t.nextElementSibling;
|
|
1457
|
-
if (elseT && elseT.hasAttribute('data-sinth-else') && elseT.dataset.sinthIfDelayHide === 'false' && elseT.dataset.sinthIfDelay && anchor) {
|
|
1458
|
-
var edms = parseInt(elseT.dataset.sinthIfDelay) || 0;
|
|
1459
|
-
setTimeout(runElse, edms);
|
|
1460
|
-
} else {
|
|
1461
|
-
runElse();
|
|
1462
|
-
}
|
|
1463
|
-
}
|
|
1464
|
-
}
|
|
1465
|
-
`;
|
|
1466
|
-
}
|
|
1467
|
-
|
|
1468
|
-
if (needsFor) {
|
|
1469
|
-
helpers += `
|
|
1470
|
-
function hashString(str) {
|
|
1471
|
-
var hash = 0, i, chr;
|
|
1472
|
-
for (i = 0; i < str.length; i++) {
|
|
1473
|
-
chr = str.charCodeAt(i);
|
|
1474
|
-
hash = ((hash << 5) - hash) + chr;
|
|
1475
|
-
hash |= 0;
|
|
1476
|
-
}
|
|
1477
|
-
return String(hash);
|
|
1478
|
-
}
|
|
1479
|
-
function sinthForBlock(t) {
|
|
1480
|
-
var source = window[t.dataset.sinthFor];
|
|
1481
|
-
if (source === undefined) source = [];
|
|
1482
|
-
var newHash = '';
|
|
1483
|
-
try { newHash = hashString(JSON.stringify(source)); } catch(e) { newHash = ''; }
|
|
1484
|
-
if (t.dataset.sinthForHash && t.dataset.sinthForHash === newHash) {
|
|
1485
|
-
return;
|
|
1486
|
-
}
|
|
1487
|
-
t.dataset.sinthForHash = newHash;
|
|
1488
|
-
var isObj = (typeof source === 'object' && source !== null && !Array.isArray(source));
|
|
1489
|
-
var entries;
|
|
1490
|
-
if (isObj) {
|
|
1491
|
-
entries = Object.entries(source);
|
|
1492
|
-
} else {
|
|
1493
|
-
if (!Array.isArray(source)) source = [];
|
|
1494
|
-
entries = source.map(function(item, index) { return [index, item]; });
|
|
1495
|
-
}
|
|
1496
|
-
var anchor = t.parentNode ? t.parentNode.querySelector('[data-sinth-for-anchor="' + t.dataset.sinthFor + '"]') : null;
|
|
1497
|
-
if (anchor) {
|
|
1498
|
-
var cur2 = anchor.nextSibling;
|
|
1499
|
-
while (cur2 && cur2 !== t) { var nx2 = cur2.nextSibling; cur2.remove(); cur2 = nx2; }
|
|
1500
|
-
anchor.remove();
|
|
1501
|
-
}
|
|
1502
|
-
var fa = document.createElement('span');
|
|
1503
|
-
fa.style.display = 'none';
|
|
1504
|
-
fa.dataset.sinthForAnchor = t.dataset.sinthFor;
|
|
1505
|
-
t.parentNode && t.parentNode.insertBefore(fa, t);
|
|
1506
|
-
var _loopIdx = 0;
|
|
1507
|
-
entries.forEach(function(entry) {
|
|
1508
|
-
var _k = entry[0];
|
|
1509
|
-
var _v = entry[1];
|
|
1510
|
-
var _item = (t.dataset && t.dataset.sinthItem) ? t.dataset.sinthItem : '__item__';
|
|
1511
|
-
var _key = t.dataset && t.dataset.sinthKey ? t.dataset.sinthKey : null;
|
|
1512
|
-
var _idx = t.dataset && t.dataset.sinthIndex ? t.dataset.sinthIndex : null;
|
|
1513
|
-
_loopIdx++;
|
|
1514
|
-
if (t.dataset.sinthIfReplace) {
|
|
1515
|
-
var _rp = document.getElementById(t.dataset.sinthIfReplace);
|
|
1516
|
-
if (_rp) _rp.parentNode.removeChild(_rp);
|
|
1517
|
-
}
|
|
1518
|
-
var loopCtx = {};
|
|
1519
|
-
if (_item) loopCtx[_item] = _v;
|
|
1520
|
-
if (_key) loopCtx[_key] = _k;
|
|
1521
|
-
if (_idx) loopCtx[_idx] = _loopIdx - 1;
|
|
1522
|
-
var frag = document.createRange().createContextualFragment(t.innerHTML);
|
|
1523
|
-
frag.querySelectorAll('.sinth-expr').forEach(function(el) {
|
|
1524
|
-
try {
|
|
1525
|
-
var exprFn = __X[el.dataset.exprId];
|
|
1526
|
-
if (exprFn) el.textContent = exprFn(loopCtx);
|
|
1527
|
-
} catch(e) {}
|
|
1528
|
-
el.classList.remove('sinth-expr');
|
|
1529
|
-
});
|
|
1530
|
-
frag.querySelectorAll('template[data-sinth-if-expr]').forEach(function(ifT) {
|
|
1531
|
-
var condFn = __X[ifT.dataset.sinthIfExpr];
|
|
1532
|
-
var cond = false;
|
|
1533
|
-
try { if (condFn) cond = condFn(loopCtx); } catch(e) {}
|
|
1534
|
-
if (cond) {
|
|
1535
|
-
var ifContent = document.createRange().createContextualFragment(ifT.innerHTML);
|
|
1536
|
-
ifContent.querySelectorAll('.sinth-expr').forEach(function(el2) {
|
|
1537
|
-
try {
|
|
1538
|
-
var exprFn2 = __X[el2.dataset.exprId];
|
|
1539
|
-
if (exprFn2) el2.textContent = exprFn2(loopCtx);
|
|
1540
|
-
} catch(e) {}
|
|
1541
|
-
});
|
|
1542
|
-
ifT.parentNode.insertBefore(ifContent, ifT);
|
|
1543
|
-
} else {
|
|
1544
|
-
var elseT = ifT.nextElementSibling;
|
|
1545
|
-
if (elseT && elseT.hasAttribute('data-sinth-else')) {
|
|
1546
|
-
var elseContent = document.createRange().createContextualFragment(elseT.innerHTML);
|
|
1547
|
-
elseContent.querySelectorAll('.sinth-expr').forEach(function(el2) {
|
|
1548
|
-
try {
|
|
1549
|
-
var exprFn2 = __X[el2.dataset.exprId];
|
|
1550
|
-
if (exprFn2) el2.textContent = exprFn2(loopCtx);
|
|
1551
|
-
} catch(e) {}
|
|
1552
|
-
});
|
|
1553
|
-
ifT.parentNode.insertBefore(elseContent, ifT);
|
|
1554
|
-
}
|
|
1555
|
-
}
|
|
1556
|
-
});
|
|
1557
|
-
if (${needsDelay}) {
|
|
1558
|
-
frag.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
|
|
1559
|
-
frag.querySelectorAll('[data-sinth-delay-expr-id]').forEach(function(el) { sinthDelayExpr(el, loopCtx); });
|
|
1560
|
-
}
|
|
1561
|
-
t.parentNode && t.parentNode.insertBefore(frag, t);
|
|
767
|
+
const renderBody = buildRenderBody({
|
|
768
|
+
bodyHTML, logicBlocks, mixedBlocks,
|
|
769
|
+
needsLogic, needsMixed, needsIf, needsFor, needsExpr, needsDelay
|
|
1562
770
|
});
|
|
1563
|
-
}
|
|
1564
|
-
`;
|
|
1565
|
-
}
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
771
|
|
|
1569
772
|
const exprArrayJS = exprRegistry.length > 0
|
|
1570
773
|
? `var __X = [${exprRegistry.map((js) => `function(_ctx){ return ${js}; }`).join(",")}];\n`
|
|
1571
774
|
: "";
|
|
1572
775
|
|
|
1573
|
-
let renderBody = "";
|
|
1574
|
-
renderBody += ` var _sx = window.scrollX, _sy = window.scrollY;\n`;
|
|
1575
|
-
|
|
1576
|
-
if (needsLogic) {
|
|
1577
|
-
renderBody += logicBlocks.map(b => b.replace(/^/gm, " ")).join("\n") + "\n";
|
|
1578
|
-
}
|
|
1579
|
-
|
|
1580
|
-
if (needsMixed) {
|
|
1581
|
-
for (const mb of mixedBlocks) {
|
|
1582
|
-
const ifJS = mb.ifJS ? mb.ifJS.trim() : "";
|
|
1583
|
-
const elseJS = mb.elseJS ? mb.elseJS.trim() : "";
|
|
1584
|
-
renderBody += ` (function() {
|
|
1585
|
-
var __el = document.getElementById(${JSON.stringify(mb.replaceId || mb.id)});
|
|
1586
|
-
if (__el) {
|
|
1587
|
-
var __condFn = __X[${mb.conditionJS}];
|
|
1588
|
-
if (__condFn ? __condFn() : false) {
|
|
1589
|
-
${ifJS}
|
|
1590
|
-
__el.innerHTML = ${JSON.stringify(mb.ifHTML)};
|
|
1591
|
-
} else {
|
|
1592
|
-
${elseJS}
|
|
1593
|
-
__el.innerHTML = ${JSON.stringify(mb.elseHTML)};
|
|
1594
|
-
}
|
|
1595
|
-
__el.querySelectorAll('.sinth-expr').forEach(sinthExpr);
|
|
1596
|
-
__el.querySelectorAll('template[data-sinth-if-expr]').forEach(sinthIfBlock);
|
|
1597
|
-
${needsDelay ? `__el.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
|
|
1598
|
-
__el.querySelectorAll('[data-sinth-delay-expr-id]').forEach(function(el) { sinthDelayExpr(el, {}); });` : ""}
|
|
1599
|
-
}
|
|
1600
|
-
})();\n`;
|
|
1601
|
-
}
|
|
1602
|
-
}
|
|
1603
|
-
|
|
1604
|
-
renderBody += ` document.querySelectorAll('[data-sinth-remove]').forEach(function(el) {
|
|
1605
|
-
var target = document.getElementById(el.dataset.sinthRemove);
|
|
1606
|
-
if (target) target.remove();
|
|
1607
|
-
});\n`;
|
|
1608
|
-
|
|
1609
|
-
if (needsIf) {
|
|
1610
|
-
renderBody += ` document.querySelectorAll('template[data-sinth-if-expr]').forEach(sinthIfBlock);\n`;
|
|
1611
|
-
}
|
|
1612
|
-
if (needsFor) {
|
|
1613
|
-
renderBody += ` document.querySelectorAll('template[data-sinth-for]').forEach(sinthForBlock);\n`;
|
|
1614
|
-
}
|
|
1615
|
-
renderBody += ` document.querySelectorAll('[data-sinth-value]').forEach(function(el) {
|
|
1616
|
-
try { el.value = window[el.dataset.sinthValue] || ''; } catch(e) {}
|
|
1617
|
-
});\n`;
|
|
1618
|
-
renderBody += ` document.querySelectorAll('[data-sinth-checked]').forEach(function(el) {
|
|
1619
|
-
try { el.checked = !!window[el.dataset.sinthChecked]; } catch(e) {}
|
|
1620
|
-
});\n`;
|
|
1621
|
-
if (bodyHTML.includes("data-sinth-checked-expr")) {
|
|
1622
|
-
renderBody += ` document.querySelectorAll('[data-sinth-checked-expr]').forEach(function(el) {
|
|
1623
|
-
try {
|
|
1624
|
-
var exprFn = __X[el.dataset.sinthCheckedExpr];
|
|
1625
|
-
if (exprFn) el.checked = !!exprFn({});
|
|
1626
|
-
} catch(e) {}
|
|
1627
|
-
});\n`;
|
|
1628
|
-
}
|
|
1629
|
-
if (needsExpr) {
|
|
1630
|
-
renderBody += ` document.querySelectorAll('.sinth-expr').forEach(sinthExpr);\n`;
|
|
1631
|
-
}
|
|
1632
|
-
if (needsDelay) {
|
|
1633
|
-
renderBody += ` setTimeout(function() {
|
|
1634
|
-
document.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
|
|
1635
|
-
}, 0);\n`;
|
|
1636
|
-
}
|
|
1637
|
-
renderBody += ` window.scrollTo(_sx, _sy);\n`;
|
|
1638
|
-
|
|
1639
776
|
const renderFunc = needsRender ? `function sinthRender() {\n${renderBody}}\nsinthRender();` : "";
|
|
1640
777
|
|
|
1641
778
|
const pageCode = `// Sinth page runtime
|
|
@@ -1676,7 +813,7 @@ export function compileFile(filePath: string, opts: CompileOptions): { html: str
|
|
|
1676
813
|
const hash = fnv1a(absPath);
|
|
1677
814
|
|
|
1678
815
|
const allVarDecls: VarDeclaration[] = file.varDecls;
|
|
1679
|
-
const functionDefs: FunctionDef[] = file.functions;
|
|
816
|
+
const functionDefs: FunctionDef[] = file.functions;
|
|
1680
817
|
|
|
1681
818
|
const ctx: CompileCtx = {
|
|
1682
819
|
allDefs, functionDefs, customEls, cssLinks, jsLinks,
|