clarusjs 0.15.0 → 0.17.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.
Files changed (75) hide show
  1. package/dist/check/generate.js +115 -13
  2. package/dist/cli/check.d.ts +9 -2
  3. package/dist/cli/check.js +91 -15
  4. package/dist/cli/explain.js +3 -0
  5. package/dist/cli/index.js +24 -3
  6. package/dist/cli/mapper.js +6 -1
  7. package/dist/cli/project.d.ts +7 -0
  8. package/dist/cli/project.js +1 -1
  9. package/dist/compiler/components.d.ts +29 -0
  10. package/dist/compiler/components.js +18 -0
  11. package/dist/compiler/element-attrs.d.ts +7 -0
  12. package/dist/compiler/element-attrs.js +32 -0
  13. package/dist/compiler/emit-client.js +39 -9
  14. package/dist/compiler/emit-server.js +1 -1
  15. package/dist/compiler/events.d.ts +9 -0
  16. package/dist/compiler/events.js +46 -0
  17. package/dist/compiler/html-expr.js +13 -8
  18. package/dist/compiler/index.d.ts +2 -2
  19. package/dist/compiler/index.js +126 -12
  20. package/dist/compiler/ir.d.ts +18 -0
  21. package/dist/compiler/ir.js +79 -10
  22. package/dist/compiler/lint.d.ts +31 -3
  23. package/dist/compiler/lint.js +177 -8
  24. package/dist/compiler/loops.d.ts +13 -0
  25. package/dist/compiler/loops.js +49 -0
  26. package/dist/compiler/parse.d.ts +40 -0
  27. package/dist/compiler/parse.js +164 -1
  28. package/dist/compiler/script.d.ts +2 -0
  29. package/dist/compiler/script.js +78 -1
  30. package/dist/forms/index.js +35 -15
  31. package/dist/forms/types.d.ts +7 -0
  32. package/dist/node/serve.d.ts +26 -0
  33. package/dist/node/serve.js +150 -0
  34. package/dist/runtime/attrs.d.ts +1 -1
  35. package/dist/runtime/attrs.js +8 -5
  36. package/dist/runtime/dom.d.ts +40 -4
  37. package/dist/runtime/dom.js +200 -49
  38. package/dist/runtime/hot.js +3 -2
  39. package/dist/runtime/index.d.ts +1 -1
  40. package/dist/runtime/index.js +1 -1
  41. package/dist/runtime/loader.js +39 -7
  42. package/dist/runtime/motion.d.ts +59 -0
  43. package/dist/runtime/motion.js +339 -0
  44. package/dist/runtime/navigate.d.ts +2 -0
  45. package/dist/runtime/navigate.js +7 -1
  46. package/dist/runtime/navigation.d.ts +44 -0
  47. package/dist/runtime/navigation.js +69 -3
  48. package/dist/runtime/signals.d.ts +2 -0
  49. package/dist/runtime/signals.js +31 -0
  50. package/dist/seo.d.ts +140 -0
  51. package/dist/seo.js +64 -0
  52. package/dist/server/handler.d.ts +1 -0
  53. package/dist/server/handler.js +1 -0
  54. package/dist/server/head.js +5 -0
  55. package/dist/vite/build.d.ts +9 -2
  56. package/dist/vite/build.js +20 -5
  57. package/dist/vite/cloudflare.d.ts +3 -0
  58. package/dist/vite/cloudflare.js +55 -0
  59. package/dist/vite/env.d.ts +19 -0
  60. package/dist/vite/env.js +34 -0
  61. package/dist/vite/headers.d.ts +27 -0
  62. package/dist/vite/headers.js +70 -0
  63. package/dist/vite/libraries.d.ts +32 -0
  64. package/dist/vite/libraries.js +77 -0
  65. package/dist/vite/manifest.d.ts +11 -1
  66. package/dist/vite/manifest.js +10 -1
  67. package/dist/vite/netlify.d.ts +5 -2
  68. package/dist/vite/netlify.js +4 -2
  69. package/dist/vite/node.d.ts +4 -0
  70. package/dist/vite/node.js +9 -2
  71. package/dist/vite/plugin.d.ts +30 -3
  72. package/dist/vite/plugin.js +97 -28
  73. package/dist/vite/vercel.d.ts +3 -0
  74. package/dist/vite/vercel.js +53 -0
  75. package/package.json +14 -1
@@ -25,6 +25,35 @@ export declare function componentIndex(files: string[], dirs: string[]): {
25
25
  names: ComponentNames;
26
26
  skipped: string[];
27
27
  };
28
+ /**
29
+ * A component library an app uses, resolved: its package `name`, the `prefix` of its tags, and its `.tscl` files
30
+ * (posix, relative to the folder its package.json's `clarusjs.components` names).
31
+ * @since 0.16.0
32
+ * @see https://clarusjs.com/guide/components#components-from-libraries
33
+ */
34
+ export type Library = {
35
+ name: string;
36
+ prefix: string;
37
+ files: string[];
38
+ };
39
+ /**
40
+ * Name each library component: its prefix, folders and file joined with hyphens (`ui` + `dialog.tscl` → `ui-dialog`),
41
+ * imported as `<package>/<file>`. Only kebab-case names with a hyphen; a name two libraries share is ambiguous.
42
+ * @example
43
+ * libraryNames([{ name: '@clarusjs/ui-primitives', prefix: 'ui', files: ['dialog.tscl'] }])
44
+ * // { 'ui-dialog': '@clarusjs/ui-primitives/dialog.tscl' }
45
+ * @since 0.16.0
46
+ * @see https://clarusjs.com/guide/components#components-from-libraries
47
+ */
48
+ export declare function libraryNames(libraries: Library[]): ComponentNames;
49
+ /**
50
+ * The app's own component names with the libraries' added: a name the app's own components have stays theirs.
51
+ * @example
52
+ * withLibraries(componentIndex(files, COMPONENT_DIRS).names, libraryNames(libraries))
53
+ * @since 0.16.0
54
+ * @see https://clarusjs.com/guide/components#components-from-libraries
55
+ */
56
+ export declare function withLibraries(own: ComponentNames, libraries: ComponentNames): ComponentNames;
28
57
  /**
29
58
  * Add an import for each component tag the template uses that `names` knows and the file doesn't import itself (only
30
59
  * those). A tag that names two components is a located error. Other hyphenated tags stay HTML (web components).
@@ -29,6 +29,24 @@ export function componentIndex(files, dirs) {
29
29
  names[name] = paths.length === 1 ? paths[0] : paths;
30
30
  return { names, skipped };
31
31
  }
32
+ export function libraryNames(libraries) {
33
+ const found = new Map();
34
+ for (const lib of libraries) {
35
+ for (const file of [...lib.files].sort()) {
36
+ if (!file.endsWith('.tscl'))
37
+ continue;
38
+ const segments = [...(lib.prefix ? [lib.prefix] : []), ...file.slice(0, -'.tscl'.length).split('/')];
39
+ const name = segments.join('-');
40
+ if (!segments.every((s) => KEBAB.test(s)) || !name.includes('-'))
41
+ continue;
42
+ found.set(name, [...(found.get(name) ?? []), `${lib.name}/${file}`]);
43
+ }
44
+ }
45
+ return Object.fromEntries([...found].map(([name, paths]) => [name, paths.length === 1 ? paths[0] : paths]));
46
+ }
47
+ export function withLibraries(own, libraries) {
48
+ return { ...libraries, ...own };
49
+ }
32
50
  export function autoImport(parsed, names, file, source) {
33
51
  const imported = new Set(parsed.imports.map((i) => i.name));
34
52
  const walk = (nodes) => {
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Each supported element's own attributes (lowercase names) and their types.
3
+ * @internal The compiler and check read it.
4
+ */
5
+ export declare const ELEMENT_ATTRS: Record<string, Record<string, string>>;
6
+ /** The attributes `@extends tag` passes through: the element's and the global ones. */
7
+ export declare function extendedAttrs(tag: string): Record<string, string>;
@@ -0,0 +1,32 @@
1
+ const B = 'boolean';
2
+ const S = 'string';
3
+ const N = 'string | number';
4
+ const union = (...values) => values.map((v) => JSON.stringify(v)).join(' | ');
5
+ const GLOBAL = {
6
+ title: S, accesskey: S, autofocus: B, inert: B, popover: `${union('auto', 'manual', 'hint')} | ''`, spellcheck: `${B} | ${union('true', 'false')}`,
7
+ translate: union('yes', 'no'), draggable: union('true', 'false'), contenteditable: `${B} | ${union('true', 'false', 'plaintext-only')}`,
8
+ enterkeyhint: union('enter', 'done', 'go', 'next', 'previous', 'search', 'send'), inputmode: union('none', 'text', 'decimal', 'numeric', 'tel', 'search', 'email', 'url'),
9
+ autocapitalize: union('off', 'none', 'on', 'sentences', 'words', 'characters'),
10
+ };
11
+ const FORM_FIELD = { disabled: B, form: S, name: S };
12
+ const SUBMIT = { formaction: S, formenctype: S, formmethod: union('get', 'post', 'dialog'), formnovalidate: B, formtarget: S };
13
+ export const ELEMENT_ATTRS = {
14
+ button: { ...FORM_FIELD, ...SUBMIT, type: union('submit', 'reset', 'button'), value: N, popovertarget: S, popovertargetaction: union('toggle', 'show', 'hide'), command: S, commandfor: S },
15
+ input: {
16
+ ...FORM_FIELD, ...SUBMIT, type: S, value: N, checked: B, placeholder: S, required: B, readonly: B, multiple: B, min: N, max: N, step: N,
17
+ minlength: N, maxlength: N, pattern: S, size: N, accept: S, alt: S, src: S, width: N, height: N, list: S, autocomplete: S, dirname: S, capture: S,
18
+ popovertarget: S, popovertargetaction: union('toggle', 'show', 'hide'),
19
+ },
20
+ textarea: { ...FORM_FIELD, value: S, placeholder: S, required: B, readonly: B, rows: N, cols: N, minlength: N, maxlength: N, wrap: union('soft', 'hard', 'off'), autocomplete: S, dirname: S },
21
+ select: { ...FORM_FIELD, value: S, required: B, multiple: B, size: N, autocomplete: S },
22
+ option: { disabled: B, label: S, selected: B, value: N },
23
+ a: { href: S, target: S, download: `${S} | ${B}`, rel: S, hreflang: S, type: S, referrerpolicy: S, ping: S },
24
+ img: { src: S, alt: S, srcset: S, sizes: S, width: N, height: N, loading: union('eager', 'lazy'), decoding: union('sync', 'async', 'auto'), fetchpriority: union('high', 'low', 'auto'), crossorigin: S, referrerpolicy: S, usemap: S, ismap: B },
25
+ form: { action: S, method: union('get', 'post', 'dialog'), enctype: S, target: S, novalidate: B, autocomplete: union('on', 'off'), name: S, rel: S, 'accept-charset': S },
26
+ label: { for: S },
27
+ details: { open: B, name: S },
28
+ dialog: { open: B, closedby: union('any', 'closerequest', 'none') },
29
+ };
30
+ export function extendedAttrs(tag) {
31
+ return { ...GLOBAL, ...ELEMENT_ATTRS[tag] };
32
+ }
@@ -1,3 +1,4 @@
1
+ import { guardCode } from './events.js';
1
2
  import { FOR_IMPLICIT } from './parse.js';
2
3
  import { attrValueExpr, componentCall, htmlExpr, tagArg, walk, whichExpr, rowNames, rowParams, rowDerived } from './html-expr.js';
3
4
  import { formName, rewriteClient, rewriteClientExpr, wrapExpr } from './script.js';
@@ -19,17 +20,20 @@ export function emitClient(ir, hot) {
19
20
  hasHoles && 'holes as __cl_holes',
20
21
  hasHoles && 'text as __cl_text',
21
22
  ir.events.length > 0 && 'on as __cl_on',
23
+ ir.events.some((e) => /\$values\b/.test(e.handler)) && 'values as __cl_values',
22
24
  all.some((n) => n.kind === 'attr' && n.reactive && n.name !== '...') && 'attr as __cl_attr',
23
25
  all.some((n) => n.kind === 'attr' && n.reactive && n.name === '...') && 'spread as __cl_spread',
24
- hasBlocks && 'block as __cl_block',
26
+ all.some((n) => ((n.kind === 'if' && !n.transition) || n.kind === 'await') && n.block >= 0) && 'block as __cl_block',
25
27
  all.some((n) => n.kind === 'await' && n.block >= 0) && 'awaited as __cl_awaited',
26
- hasFors && 'forBlock as __cl_for',
28
+ all.some((n) => n.kind === 'for' && !n.transition && n.block >= 0) && 'forBlock as __cl_for',
27
29
  all.some((n) => n.kind === 'for' && n.block >= 0 && rowNames(n, ir.events).some((x) => x !== '$count')) && 'derived as __cl_derived',
28
30
  hasRegions && 'region as __cl_region',
31
+ all.some((n) => n.kind === 'component' && (n.children.length > 0 || n.fills.some((f) => !f.params))) && 'untrack as __cl_untrack',
29
32
  all.some((n) => n.kind === 'component' && !!n.models?.length) && 'model as __cl_model',
30
33
  all.some((n) => n.kind === 'component' && !!n.listens?.length) && 'listen as __cl_listen',
31
34
  all.some((n) => n.kind === 'use') && 'use as __cl_useOn',
32
35
  ir.sends && 'emit as __cl_emit',
36
+ ir.sends && 'declare as __cl_declare',
33
37
  ir.provides && 'provideOn as __cl_provideOn',
34
38
  kinds.has('model') && 'modelInput as __cl_modelInput',
35
39
  ir.inputs.some((i) => kinds.has('input') || i.model) && 'batch as __cl_batch',
@@ -43,6 +47,12 @@ export function emitClient(ir, hot) {
43
47
  all.some((n) => n.kind === 'attr' && JSON.stringify(n.value).includes('__cl_styleValue(')) && 'styleValue as __cl_styleValue',
44
48
  ].filter(Boolean);
45
49
  let out = used.length ? `import { ${used.join(', ')} } from 'clarusjs/runtime'\n` : '';
50
+ const motion = [
51
+ all.some((n) => n.kind === 'if' && n.transition && n.block >= 0) && 'transitionBlock as __cl_tb',
52
+ all.some((n) => n.kind === 'for' && n.transition && n.block >= 0) && 'transitionFor as __cl_tf',
53
+ ].filter(Boolean);
54
+ if (motion.length)
55
+ out += `import { ${motion.join(', ')} } from 'clarusjs/motion'\n`;
46
56
  if (hot)
47
57
  out += `import { swap as __cl_swap } from ${JSON.stringify(hot)}\n`;
48
58
  const usedComponents = new Set(all.flatMap((n) => (n.kind === 'component' ? [n.name] : [])));
@@ -58,6 +68,8 @@ export function emitClient(ir, hot) {
58
68
  out += `${line}\n`;
59
69
  out += `\nexport function attach(__cl_root, __cl_props = {}, __cl_state) {\n`;
60
70
  out += ` const __cl_class = __cl_props.__cl_class ? " " + __cl_props.__cl_class : ""\n`;
71
+ if (ir.sends)
72
+ out += ` __cl_declare(__cl_root, ${JSON.stringify(ir.sendNames)})\n`;
61
73
  if (ir.sends)
62
74
  out += ` const emit = (name, value, info) => __cl_emit(__cl_root, name, value, info)\n`;
63
75
  out += contextLines(ir, 'undefined');
@@ -110,9 +122,13 @@ function wiring(ir, nodes, scope, ctx, signals, depth) {
110
122
  lines.push(`__cl_useOn(${ctx}, ${a.index}, () => ${wrapExpr(rw.expr(a.expr))})`);
111
123
  }
112
124
  for (const e of ir.events.filter((ev) => ev.scope === scope)) {
113
- const body = rewriteClient(e.handler, signals).trim();
125
+ let body = rewriteClient(e.handler, signals).trim();
126
+ if (/\$values\b/.test(e.handler) && !/\b(?:const|let|var)\s+\$values\b/.test(e.handler))
127
+ body = `const $values = __cl_values(__cl_el, $event); ${body}`;
128
+ const guard = guardCode(e.mods ?? []);
114
129
  const end = body.includes('//') ? '\n ' : ' ';
115
- lines.push(`__cl_on(${ctx}, ${e.index}, ${JSON.stringify(e.type)}, ($event) => { ${body}${end}})`);
130
+ const fn = `(${/__cl_el\b/.test(guard + body) ? '$event, __cl_el' : '$event'}) => { ${guard}${body}${end}}`;
131
+ lines.push(`__cl_on(${ctx}, ${e.index}, ${JSON.stringify(e.type)}, ${e.mods?.some((m) => m.toLowerCase() === 'once') ? `((__cl_done) => ${fn})(false)` : fn})`);
116
132
  }
117
133
  const fn = (args, inner) => inner.length ? `(${args}) => {\n${inner.map((l) => ` ${l}`).join('\n')}\n }` : `(${args}) => {}`;
118
134
  for (const n of nodes) {
@@ -123,12 +139,19 @@ function wiring(ir, nodes, scope, ctx, signals, depth) {
123
139
  lines.push(`__cl_model(${ctx}, ${n.region}, ${JSON.stringify(m.name)}, (__cl_v) => { ${rewriteClient(m.set, signals).trim()} })`);
124
140
  for (const l of n.listens ?? []) {
125
141
  const body = rewriteClient(l.handler, signals).trim();
126
- lines.push(`__cl_listen(${ctx}, ${n.region}, ${JSON.stringify(l.name)}, ($event, $info) => { ${body}${body.includes('//') ? '\n ' : ' '}})`);
142
+ const from = ir.imports.find((i) => i.name === n.name)?.from ?? '';
143
+ const bound = (from.split(/[\\/]/).pop() ?? '').replace(/\.tscl$/, '').replace(/[^\w-]/g, '');
144
+ lines.push(`__cl_listen(${ctx}, ${n.region}, ${JSON.stringify(l.name)}, ($event, $info) => { ${body}${body.includes('//') ? '\n ' : ' '}}, ${JSON.stringify(bound)})`);
127
145
  }
128
146
  }
129
147
  if (n.kind === 'if' && n.block >= 0) {
130
148
  const branches = n.branches.map((b, i) => ` { html: () => ${htmlExpr(b.nodes, rw)}, wire: ${fn('', wiring(ir, b.nodes, `${n.block}.${i}`, ctx, signals, depth))} },`);
131
- lines.push(`__cl_block(${ctx}, ${n.block}, () => ${whichExpr(n, rw)}, [\n${branches.join('\n')}\n ])`);
149
+ if (n.transition) {
150
+ const arg = (x, none) => (x === null ? none : wrapExpr(rw.expr(x)));
151
+ lines.push(`__cl_tb(${ctx}, ${n.block}, () => ${whichExpr(n, rw)}, [\n${branches.join('\n')}\n ], ${arg(n.transition.name, '"cl"')}, ${arg(n.transition.options, 'undefined')})`);
152
+ }
153
+ else
154
+ lines.push(`__cl_block(${ctx}, ${n.block}, () => ${whichExpr(n, rw)}, [\n${branches.join('\n')}\n ])`);
132
155
  }
133
156
  if (n.kind === 'await' && n.block >= 0) {
134
157
  const a = `__cl_a${n.block}`;
@@ -148,15 +171,22 @@ function wiring(ir, nodes, scope, ctx, signals, depth) {
148
171
  const names = rowNames(n, ir.events);
149
172
  const derivedNames = names.filter((x) => x !== '$count');
150
173
  const loop = [n.item, '$index', ...(names.length ? ['$count'] : [])];
151
- const rowSignals = new Map([...signals, ...loop.map((name) => [name, 'state']), ...derivedNames.map((name) => [name, 'derived'])]);
152
- const plain = rw.without([n.item, ...FOR_IMPLICIT]);
174
+ const aliasKind = (of) => (of === '$index' || of === '$count' ? 'state' : 'derived');
175
+ const rowSignals = new Map([...signals, ...loop.map((name) => [name, 'state']), ...derivedNames.map((name) => [name, 'derived']), ...n.aliases.map((a) => [a.name, aliasKind(a.of)])]);
176
+ const plain = rw.without([n.item, ...FOR_IMPLICIT, ...n.aliases.map((a) => a.name)]);
153
177
  const key = n.track === null ? '$index' : wrapExpr(plain.expr(n.track));
154
178
  const wire = [...rowDerived(n, ir.events), ...wiring(ir, n.nodes, `f${n.block}`, rowCtx, rowSignals, depth + 1)];
155
179
  const row = `{\n html: (${rowParams(n)}) => ${htmlExpr(n.nodes, plain)},\n wire: ${fn(`${rowCtx}, ${loop.join(', ')}`, wire)},\n }`;
156
180
  const empty = n.empty
157
181
  ? `{\n html: () => ${htmlExpr(n.empty, rw)},\n wire: ${fn(rowCtx, wiring(ir, n.empty, `f${n.block}e`, rowCtx, signals, depth + 1))},\n }`
158
182
  : 'null';
159
- lines.push(`__cl_for(${ctx}, ${n.block}, () => ${wrapExpr(rw.expr(n.list))}, (${n.item}, $index) => ${key}, ${row}, ${empty})`);
183
+ const keyParams = [n.item, '$index', ...n.aliases.filter((a) => a.of === '$index').map((a) => `${a.name} = $index`)].join(', ');
184
+ if (n.transition) {
185
+ const arg = (x, none) => (x === null ? none : wrapExpr(rw.expr(x)));
186
+ lines.push(`__cl_tf(${ctx}, ${n.block}, () => ${wrapExpr(rw.expr(n.list))}, (${keyParams}) => ${key}, ${row}, ${empty}, ${arg(n.transition.name, '"cl"')}, ${arg(n.transition.options, 'undefined')})`);
187
+ }
188
+ else
189
+ lines.push(`__cl_for(${ctx}, ${n.block}, () => ${wrapExpr(rw.expr(n.list))}, (${keyParams}) => ${key}, ${row}, ${empty})`);
160
190
  }
161
191
  }
162
192
  return lines;
@@ -42,7 +42,7 @@ export function emitServer(ir, clientUrl, renderImports = false, loader) {
42
42
  out += inputsLine(ir);
43
43
  out += ` const __cl_class = __cl_opts?.class ? " " + __cl_opts.class : ""\n`;
44
44
  if (html.includes('__cl_attrs'))
45
- out += ` const __cl_attrs = __cl_passed(__cl_props, ${JSON.stringify(ir.inputs.map((i) => i.name))})\n`;
45
+ out += ` const __cl_attrs = __cl_passed(__cl_props, ${JSON.stringify(ir.inputs.map((i) => i.name))}${ir.extends ? `, ${JSON.stringify(ir.extends)}` : ''})\n`;
46
46
  out += contextLines(ir, '__cl_opts?.cx');
47
47
  if (ir.script)
48
48
  out += indentScript(rewriteServer(ir.script));
@@ -0,0 +1,9 @@
1
+ /** (name.mods): the event type, and its modifiers in the order written. */
2
+ export declare function splitEvent(name: string): {
3
+ type: string;
4
+ mods: string[];
5
+ };
6
+ /** Why a modifier list is wrong for this event, or null. */
7
+ export declare function modifierError(type: string, mods: string[]): string | null;
8
+ /** The guard: keys and .self first (a miss does nothing), then .once (`__cl_done`), .prevent, .stop. */
9
+ export declare function guardCode(mods: string[]): string;
@@ -0,0 +1,46 @@
1
+ const KEYS = {
2
+ enter: 'Enter', esc: 'Escape', escape: 'Escape', space: ' ', tab: 'Tab',
3
+ up: 'ArrowUp', down: 'ArrowDown', left: 'ArrowLeft', right: 'ArrowRight',
4
+ delete: 'Delete', backspace: 'Backspace', home: 'Home', end: 'End', pageup: 'PageUp', pagedown: 'PageDown',
5
+ };
6
+ const SYSTEM = ['ctrl', 'shift', 'alt', 'meta'];
7
+ const KEY_EVENTS = new Set(['keydown', 'keyup', 'keypress']);
8
+ const ORDER = ['prevent', 'stop', 'self', 'once'];
9
+ export function splitEvent(name) {
10
+ const [type, ...mods] = name.split('.');
11
+ return { type: type, mods };
12
+ }
13
+ export function modifierError(type, mods) {
14
+ for (const m of mods) {
15
+ const key = m.toLowerCase();
16
+ if (ORDER.includes(key))
17
+ continue;
18
+ if (KEYS[key] || SYSTEM.includes(key) || /^[a-z0-9]$/.test(key)) {
19
+ if (!KEY_EVENTS.has(type))
20
+ return `.${m} is a key: for (keydown) and (keyup)`;
21
+ continue;
22
+ }
23
+ return `unknown modifier .${m}: use ${ORDER.join(', ')}, a key (enter, esc, space, tab, up, down, left, right, a letter…) or ctrl, shift, alt, meta`;
24
+ }
25
+ return null;
26
+ }
27
+ export function guardCode(mods) {
28
+ const keys = mods.map((m) => m.toLowerCase());
29
+ const tests = [];
30
+ const named = keys.filter((k) => KEYS[k] || /^[a-z0-9]$/.test(k));
31
+ if (named.length)
32
+ tests.push(`(${named.map((k) => (KEYS[k] ? `$event.key === ${JSON.stringify(KEYS[k])}` : `$event.key?.toLowerCase() === ${JSON.stringify(k)}`)).join(' || ')})`);
33
+ for (const s of SYSTEM)
34
+ if (keys.includes(s))
35
+ tests.push(`$event.${s}Key`);
36
+ if (keys.includes('self'))
37
+ tests.push('$event.target === __cl_el');
38
+ let code = tests.length ? `if (!(${tests.join(' && ')})) return; ` : '';
39
+ if (keys.includes('once'))
40
+ code += 'if (__cl_done) return; __cl_done = true; ';
41
+ if (keys.includes('prevent'))
42
+ code += '$event.preventDefault(); ';
43
+ if (keys.includes('stop'))
44
+ code += '$event.stopPropagation(); ';
45
+ return code;
46
+ }
@@ -16,7 +16,7 @@ export function htmlExpr(nodes, rw = asWritten, top) {
16
16
  if (n.kind === 'connect' || n.kind === 'use')
17
17
  return '""';
18
18
  if (n.kind === 'attr' && n.name === '...' && 'expr' in n.value && n.value.expr === '__cl_attrs')
19
- return `__cl_passedHtml(__cl_attrs, ${JSON.stringify((n.skip ?? []).filter((x) => /^(id|role|tabindex|hidden|lang|dir|(data|aria)-.+)$/.test(x)))})`;
19
+ return `__cl_passedHtml(__cl_attrs, ${JSON.stringify((n.skip ?? []).filter((x) => x !== 'engine' && x !== 'use' && !x.includes('.')))})`;
20
20
  if (n.kind === 'attr' && n.name === '...')
21
21
  return `__cl_spreadHtml(${attrValueExpr(n.value, rw.expr)}, ${JSON.stringify(n.skip ?? [])}, ${JSON.stringify(n.tag)}${rw === asWritten && n.where ? `, ${JSON.stringify(n.where)}` : ''})`;
22
22
  if (n.kind === 'attr')
@@ -41,7 +41,7 @@ export function htmlExpr(nodes, rw = asWritten, top) {
41
41
  }
42
42
  if (n.kind === 'for') {
43
43
  const list = wrapExpr(rw.expr(n.list));
44
- const row = `(${rowParams(n)}) => ${htmlExpr(n.nodes, rw.without([n.item, ...FOR_IMPLICIT]), ctx)}`;
44
+ const row = `(${rowParams(n)}) => ${htmlExpr(n.nodes, rw.without([n.item, ...FOR_IMPLICIT, ...n.aliases.map((a) => a.name)]), ctx)}`;
45
45
  const empty = n.empty ? `() => ${htmlExpr(n.empty, rw, ctx)}` : 'null';
46
46
  if (n.block >= 0)
47
47
  return `__cl_forHtml(${n.block}, ${list}, ${row}, ${empty})`;
@@ -64,9 +64,10 @@ export function htmlExpr(nodes, rw = asWritten, top) {
64
64
  }
65
65
  export function componentCall(n, rw, ctx) {
66
66
  const props = n.props.map((p) => (p.name === '...' ? `...${wrapExpr(rw.expr(p.expr))}` : `${/^[A-Za-z_$][\w$]*$/.test(p.name) ? p.name : JSON.stringify(p.name)}: ${wrapExpr(rw.expr(p.expr))}`)).join(', ');
67
+ const untracked = (body) => (ctx ? body : `__cl_untrack(() => ${body})`);
67
68
  const slots = [
68
- ...(n.children.length ? [`"default": (_, __cl_cx) => ${htmlExpr(n.children, rw, ctx)}`] : []),
69
- ...n.fills.map((f) => `${JSON.stringify(f.name)}: (${f.params ?? '_'}, __cl_cx) => ${htmlExpr(f.nodes, rw, ctx)}`),
69
+ ...(n.children.length ? [`"default": (_, __cl_cx) => ${untracked(htmlExpr(n.children, rw, ctx))}`] : []),
70
+ ...n.fills.map((f) => `${JSON.stringify(f.name)}: (${f.params ?? '_'}, __cl_cx) => ${f.params ? htmlExpr(f.nodes, rw, ctx) : untracked(htmlExpr(f.nodes, rw, ctx))}`),
70
71
  ];
71
72
  const slotsArg = slots.length ? `{ ${slots.join(', ')} }` : undefined;
72
73
  const opts = ['cx: __cl_cx', ...(n.attach ? [`attach: ${JSON.stringify(n.attach)}`] : []), ...(n.class ? [`class: ${JSON.stringify(n.class)}`] : []), ...(n.paths ? [`paths: { ${n.paths.map((p) => `${JSON.stringify(p.name)}: ${wrapExpr(rw.expr(p.expr))}`).join(', ')} }`] : [])];
@@ -111,16 +112,20 @@ const DERIVED = {
111
112
  export function rowNames(n, events = []) {
112
113
  const rowEvents = events.filter((e) => e.scope === `f${n.block}` || e.scope?.startsWith(`f${n.block}.`)).map((e) => e.handler);
113
114
  const text = JSON.stringify(n.nodes) + JSON.stringify(rowEvents);
114
- const has = (name) => new RegExp(`(?<![\\w$.])\\${name}(?![\\w$])`).test(text);
115
+ const has = (name) => n.aliases.some((a) => a.of === name) || new RegExp(`(?<![\\w$.])\\${name}(?![\\w$])`).test(text);
115
116
  const used = Object.keys(DERIVED).filter(has);
116
117
  return has('$count') || used.includes('$last') ? ['$count', ...used] : used;
117
118
  }
118
119
  export function rowParams(n) {
119
120
  const names = rowNames(n);
121
+ const aliases = n.aliases.map((a) => `${a.name} = ${a.of}`);
120
122
  if (!names.length)
121
- return `${n.item}, $index`;
122
- return [n.item, '$index', '__cl_list', '$count = __cl_list.length', ...names.filter((x) => x !== '$count').map((x) => `${x} = ${DERIVED[x]}`)].join(', ');
123
+ return [n.item, '$index', ...(aliases.length ? ['__cl_list', ...aliases] : [])].join(', ');
124
+ return [n.item, '$index', '__cl_list', '$count = __cl_list.length', ...names.filter((x) => x !== '$count').map((x) => `${x} = ${DERIVED[x]}`), ...aliases].join(', ');
123
125
  }
124
126
  export function rowDerived(n, events = []) {
125
- return rowNames(n, events).filter((x) => x !== '$count').map((x) => `const ${x} = __cl_derived(() => ${DERIVED[x].replace(/\$index/g, '$index.get()').replace(/\$count/g, '$count.get()')})`);
127
+ return [
128
+ ...rowNames(n, events).filter((x) => x !== '$count').map((x) => `const ${x} = __cl_derived(() => ${DERIVED[x].replace(/\$index/g, '$index.get()').replace(/\$count/g, '$count.get()')})`),
129
+ ...n.aliases.map((a) => `const ${a.name} = ${a.of}`),
130
+ ];
126
131
  }
@@ -2,10 +2,10 @@ import { ClarusError } from './errors.ts';
2
2
  import { type ComponentNames } from './components.ts';
3
3
  export { ClarusError } from './errors.ts';
4
4
  export { parse } from './parse.ts';
5
- export { componentIndex, COMPONENT_DIRS, type ComponentNames } from './components.ts';
5
+ export { componentIndex, COMPONENT_DIRS, libraryNames, withLibraries, type ComponentNames, type Library } from './components.ts';
6
6
  export { checkIcons, type IconResolver } from './icon.ts';
7
7
  import type { IconResolver } from './icon.ts';
8
- export { lint, lintRules, type LintRule, type LintLevel, type LintConfig, type LintMessage, type LintRuleDef, type LintContext, type LintElement } from './lint.ts';
8
+ export { applyFixes, lint, lintRules, type LintFix, type LintRule, type LintLevel, type LintConfig, type LintMessage, type LintRuleDef, type LintContext, type LintElement } from './lint.ts';
9
9
  export type { ParsedFile, InputDecl, EventDecl, ImportDecl, TemplateNode, Attr } from './parse.ts';
10
10
  /**
11
11
  * `renderImports`: import child components' render functions with `?render`, for a render module that runs in the
@@ -3,22 +3,31 @@ import { ClarusError } from './errors.js';
3
3
  import { emitServer } from './emit-server.js';
4
4
  import { lower, SPREAD_REFUSED } from './ir.js';
5
5
  import { autoImport } from './components.js';
6
- import { awaitLists, parse } from './parse.js';
6
+ import { ELEMENT_ATTRS } from './element-attrs.js';
7
+ import { awaitLists, fragmentRoot, parse, rootNodes } from './parse.js';
7
8
  export { ClarusError } from './errors.js';
8
9
  export { parse } from './parse.js';
9
- export { componentIndex, COMPONENT_DIRS } from './components.js';
10
+ export { componentIndex, COMPONENT_DIRS, libraryNames, withLibraries } from './components.js';
10
11
  import { foldClass } from './class-style.js';
11
12
  export { checkIcons } from './icon.js';
12
- export { lint, lintRules } from './lint.js';
13
+ export { applyFixes, lint, lintRules } from './lint.js';
13
14
  export function compile(source, options) {
14
15
  const parsed = parse(source, options.file);
16
+ if (options.layouts?.length && parsed.layout !== 'none' && (parsed.script || parsed.inputs.some((i) => i.model)))
17
+ return compileIslandPage(parsed, source, options);
18
+ return compileParsed(parsed, source, options);
19
+ }
20
+ function compileParsed(parsed, source, options) {
21
+ checkExtends(parsed, options.file, source);
22
+ const fragmentRoot = unwrapFragments(parsed, options.file, source);
15
23
  if (options.components)
16
24
  autoImport(parsed, options.components, options.file, source);
17
25
  if (options.layouts?.length && parsed.layout !== 'none')
18
- wrapInLayouts(parsed, options.layouts, options.file, source);
26
+ wrapInLayouts(parsed, options.layouts);
19
27
  const warnings = [];
20
28
  const id = options.scope ?? scopeId(options.file);
21
- fallThrough(parsed);
29
+ if (!fragmentRoot)
30
+ fallThrough(parsed);
22
31
  foldClass(parsed.nodes, new Set(parsed.imports.map((imp) => imp.name)));
23
32
  markRoots(parsed.nodes, `cl-c-${id}`, new Set(parsed.imports.map((imp) => imp.name)), parsed.styles.some((st) => st.mode === 'scoped'));
24
33
  let css = '';
@@ -84,10 +93,93 @@ function markSlotContent(nodes, cls, components) {
84
93
  }
85
94
  }
86
95
  const ID_LISTS = ['aria-describedby', 'aria-labelledby', 'aria-controls', 'aria-owns'];
96
+ function checkExtends(parsed, file, source) {
97
+ const ext = parsed.extends;
98
+ if (!ext)
99
+ return;
100
+ const fail = (text, at) => { throw new ClarusError(text, file, source, at); };
101
+ if (!ELEMENT_ATTRS[ext.tag])
102
+ fail(`@extends ${ext.tag}: clarusjs knows the attributes of ${Object.keys(ELEMENT_ATTRS).join(', ')}`, ext.start);
103
+ const top = rootNodes;
104
+ const nodes = top(parsed.nodes);
105
+ const is = (list) => list.length === 1 && list[0].type === 'element' && list[0].tag === ext.tag;
106
+ const spread = (el) => el.type === 'element' && el.attrs.some((a) => a.kind === 'prop' && a.name === '...');
107
+ for (const r of [nodes, ...(nodes[0]?.type === 'if' ? nodes[0].branches.map((b) => top(b.children)) : [])])
108
+ if (is(r) && spread(r[0]))
109
+ fail(`@extends ${ext.tag}: its root has its own [...] spread, which takes the place of the attributes passed to it; pass what it spreads as inputs instead`, r[0].start);
110
+ if (is(nodes))
111
+ return;
112
+ const first = nodes[0];
113
+ const wrong = `@extends ${ext.tag}: the root must be a <${ext.tag}>, where the attributes land`;
114
+ if (nodes.length !== 1 || first.type !== 'if')
115
+ return fail(wrong, (nodes[0] ?? { start: ext.start }).start);
116
+ if (parsed.script || parsed.inputs.some((i) => i.model))
117
+ fail(`@extends ${ext.tag}: an island's root must be one <${ext.tag}> (it re-renders an @if in the browser, without the passed attributes)`, first.start);
118
+ if (first.branches.at(-1).cond !== null || !first.branches.every((b) => is(top(b.children))))
119
+ fail(wrong, first.start);
120
+ }
121
+ function unwrapFragments(parsed, file, source) {
122
+ const reserved = parsed.imports.find((i) => i.name === 'fragment');
123
+ if (reserved)
124
+ throw new ClarusError('fragment is reserved: <fragment> groups elements without rendering one; import the component under another name', file, source, reserved.start);
125
+ const isNode = (x) => !!x && typeof x === 'object' && 'type' in x;
126
+ const holders = (n) => {
127
+ const out = [];
128
+ for (const v of Object.values(n)) {
129
+ const items = Array.isArray(v) ? v : [v];
130
+ for (const x of items)
131
+ if (x && typeof x === 'object' && !isNode(x) && Array.isArray(x.children))
132
+ out.push(x);
133
+ }
134
+ return out;
135
+ };
136
+ const flat = (nodes) => nodes.flatMap((n) => {
137
+ if ('children' in n)
138
+ n.children = flat(n.children);
139
+ const r = n;
140
+ for (const key of ['pending', 'empty'])
141
+ if (Array.isArray(r[key]))
142
+ r[key] = flat(r[key]);
143
+ for (const h of holders(n))
144
+ h.children = flat(h.children);
145
+ if (n.type !== 'element' || n.tag !== 'fragment')
146
+ return [n];
147
+ if (n.attrs.length)
148
+ throw new ClarusError('<fragment> renders no element: attributes and events can\'t land on it', file, source, n.start);
149
+ return n.children;
150
+ });
151
+ const root = fragmentRoot(parsed.nodes);
152
+ parsed.nodes = parsed.nodes.flatMap((n) => {
153
+ if (n.type !== 'element' || n.tag !== 'fragment' || n.attrs.length)
154
+ return [n];
155
+ const kept = n.children.filter((c) => !(c.type === 'text' && !c.value.trim()));
156
+ const head = kept[0];
157
+ if (head?.type === 'text')
158
+ kept[0] = { ...head, value: head.value.replace(/^[ \t]*\r?\n/, '') };
159
+ return kept;
160
+ });
161
+ parsed.nodes = flat(parsed.nodes);
162
+ return root;
163
+ }
87
164
  function fallThrough(parsed) {
88
- const meaningful = parsed.nodes.filter((n) => !(n.type === 'text' && !n.value.trim()) && !(n.type === 'element' && UNMARKED.has(n.tag)));
89
- const root = meaningful[0];
90
- if (meaningful.length !== 1 || root?.type !== 'element' || SPREAD_REFUSED.has(root.tag.toLowerCase()))
165
+ const meaningfulOf = (nodes) => nodes.filter((n) => !(n.type === 'text' && !n.value.replace(/<!--[\s\S]*?-->/g, '').trim()) && !(n.type === 'element' && UNMARKED.has(n.tag)));
166
+ const meaningful = meaningfulOf(parsed.nodes);
167
+ if (meaningful.length !== 1)
168
+ return;
169
+ const top = meaningful[0];
170
+ if (top.type === 'if') {
171
+ const roots = top.branches.map((b) => meaningfulOf(b.children));
172
+ if (parsed.script || parsed.inputs.some((i) => i.model) || top.branches.at(-1).cond !== null || roots.some((r) => r.length !== 1 || r[0].type !== 'element'))
173
+ return;
174
+ for (const [r] of roots)
175
+ fallOnto(parsed, r);
176
+ return;
177
+ }
178
+ if (top.type === 'element')
179
+ fallOnto(parsed, top);
180
+ }
181
+ function fallOnto(parsed, root) {
182
+ if (SPREAD_REFUSED.has(root.tag.toLowerCase()))
91
183
  return;
92
184
  if (root.attrs.some((a) => a.kind === 'prop' && a.name === '...'))
93
185
  return;
@@ -147,10 +239,7 @@ function markRoots(nodes, cls, components, slots = false) {
147
239
  }
148
240
  }
149
241
  }
150
- function wrapInLayouts(parsed, layouts, file, source) {
151
- if (parsed.script || parsed.inputs.some((i) => i.model)) {
152
- throw new ClarusError('this page is an island (it has a <script> or a @model input), and folder or config layouts can\'t wrap an island yet: move the script into a component the page uses, or add @layout none', file, source, 0);
153
- }
242
+ function wrapInLayouts(parsed, layouts) {
154
243
  let nodes = parsed.nodes;
155
244
  for (let k = layouts.length - 1; k >= 0; k--) {
156
245
  const name = `__cl_layout_${k}`;
@@ -163,3 +252,28 @@ function wrapInLayouts(parsed, layouts, file, source) {
163
252
  }
164
253
  parsed.nodes = nodes;
165
254
  }
255
+ const SELF = '\0clarusjs-page';
256
+ function compileIslandPage(parsed, source, options) {
257
+ const fill = parsed.nodes.find((n) => n.type === 'fill');
258
+ if (fill)
259
+ throw new ClarusError("this island page can't fill its layouts' slots: its content is inside the island (put it in the layout, or move the script into a component the page uses)", options.file, source, fill.start);
260
+ if (options.renderImports)
261
+ throw new ClarusError('this page is an island (it has a <script> or a @model input), and its layouts are rendered in the browser here (a client route): make the route static or server, move the script into a component the page uses, or add @layout none', options.file, source, 0);
262
+ const page = compileParsed(parsed, source, { ...options, layouts: undefined });
263
+ if (options.target === 'client')
264
+ return page;
265
+ const outer = parse('', options.file);
266
+ outer.imports.push({ name: '__cl_page', from: SELF, start: 0 });
267
+ outer.nodes = [{ type: 'element', tag: '__cl_page', attrs: [{ kind: 'prop', name: '...', expr: '__cl_props', start: 0 }], children: [], start: 0 }];
268
+ wrapInLayouts(outer, options.layouts);
269
+ const wrapper = compileParsed(outer, '', { ...options, layouts: undefined, loader: undefined });
270
+ const inner = page.code.replace(/^export (async )?function render\(/m, '$1function __cl_page_render(');
271
+ const [innerHead, ...innerRest] = inner.split('\n');
272
+ const [outerHead, ...outerRest] = wrapper.code.split('\n');
273
+ const names = (line) => /\{(.*)\}/.exec(line)[1].split(',').map((x) => x.trim()).filter(Boolean);
274
+ const runtime = `import { ${[...new Set([...names(innerHead), ...names(outerHead)])].join(', ')} } from 'clarusjs/runtime/server'`;
275
+ const selfImport = outerRest.findIndex((l) => l.endsWith(` from '${SELF}'`));
276
+ const self = /render as (\w+)/.exec(outerRest[selfImport])[1];
277
+ outerRest.splice(selfImport, 1, `const ${self} = __cl_page_render`);
278
+ return { code: [runtime, ...innerRest, ...outerRest].join('\n'), stateful: page.stateful, css: page.css, warnings: [...page.warnings, ...wrapper.warnings] };
279
+ }
@@ -77,6 +77,10 @@ export type IRNode = {
77
77
  nodes: IRNode[];
78
78
  }[];
79
79
  block: number;
80
+ transition?: {
81
+ name: string | null;
82
+ options: string | null;
83
+ };
80
84
  } | {
81
85
  kind: 'await';
82
86
  expr: string;
@@ -95,20 +99,32 @@ export type IRNode = {
95
99
  item: string;
96
100
  list: string;
97
101
  track: string | null;
102
+ aliases: {
103
+ name: string;
104
+ of: string;
105
+ }[];
98
106
  nodes: IRNode[];
99
107
  empty: IRNode[] | null;
100
108
  block: number;
109
+ transition?: {
110
+ name: string | null;
111
+ options: string | null;
112
+ };
101
113
  };
114
+ /** An element's (type.mods)="handler"; mods are #444's modifiers, as written. */
102
115
  export type IREvent = {
103
116
  index: number;
104
117
  type: string;
105
118
  handler: string;
106
119
  scope?: string;
120
+ mods?: string[];
107
121
  };
108
122
  export type ComponentIR = {
109
123
  file: string;
110
124
  name: string;
111
125
  inputs: InputDecl[];
126
+ /** `@extends tag`: the attribute names passed through to the root besides the usual ones. */
127
+ extends?: string[];
112
128
  imports: ImportDecl[];
113
129
  script?: string;
114
130
  scriptImports: string[];
@@ -125,6 +141,8 @@ export type ComponentIR = {
125
141
  events: IREvent[];
126
142
  /** The component sends events to its parent (@event, #442): its script gets emit(). */
127
143
  sends: boolean;
144
+ /** Their names: the parent's (name) listens for these as component events, not DOM events. */
145
+ sendNames: string[];
128
146
  /** @context declarations (#465): values read from the components around this one. */
129
147
  contexts: InputDecl[];
130
148
  /** The script calls provide() (#465): this component adds to the context its children render with. */