clarusjs 0.12.0 → 0.13.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
@@ -6,6 +6,8 @@
6
6
 
7
7
  <p align="center"><strong>Clear, compiled views.</strong></p>
8
8
 
9
+ <p align="center">Pronounced <strong>KLAIR-us</strong> (/ˈklɛər.əs/), from the Latin <em>clarus</em>, “clear, bright”.</p>
10
+
9
11
  <p align="center"><a href="https://clarusjs.com">Documentation</a> · <a href="https://clarusjs.com/guide/getting-started">Getting started</a> · <a href="https://www.npmjs.com/package/clarusjs">npm</a></p>
10
12
 
11
13
  Write components in a familiar template language. clarusjs compiles them to plain server HTML and ships JavaScript
@@ -21,7 +21,9 @@ export function generateTs(source, file, options = {}) {
21
21
  emit('declare function __cl_use(value: unknown): void\n');
22
22
  emit('declare const __cl_bool: boolean\n');
23
23
  const text = 'string | number | boolean | null | undefined';
24
- emit(`type __cl_AttrOf<T extends string, P extends string> = T extends keyof HTMLElementTagNameMap ? P extends keyof HTMLElementTagNameMap[T] ? (HTMLElementTagNameMap[T][P] extends boolean ? boolean | null | undefined : ${text}) : ${text} : ${text}\n`);
24
+ emit(`export type __cl_Class = ${text} | readonly __cl_Class[] | { [name: string]: unknown }\n`);
25
+ emit(`export type __cl_Style = ${text} | __cl_Style[] | { [property: string]: ${text} }\n`);
26
+ emit(`type __cl_AttrOf<T extends string, P extends string> = P extends '...' ? { [name: string]: unknown } | null | undefined : P extends 'class' ? __cl_Class : P extends \`class.\${string}\` ? unknown : P extends 'style' ? __cl_Style : T extends keyof HTMLElementTagNameMap ? P extends keyof HTMLElementTagNameMap[T] ? (HTMLElementTagNameMap[T][P] extends boolean ? boolean | null | undefined : ${text}) : ${text} : ${text}\n`);
25
27
  emit('declare function __cl_attr<T extends string, P extends string>(value: __cl_AttrOf<T, P>): void\n');
26
28
  emit('export type __cl_El<T extends string> = T extends keyof HTMLElementTagNameMap ? HTMLElementTagNameMap[T] : T extends keyof SVGElementTagNameMap ? SVGElementTagNameMap[T] : HTMLElement\n');
27
29
  emit('export type __cl_Event<K extends string, E = HTMLElement> = (K extends keyof HTMLElementEventMap ? HTMLElementEventMap[K] : CustomEvent) & { target: any; currentTarget: E }\n');
@@ -184,7 +186,14 @@ export function generateTs(source, file, options = {}) {
184
186
  point('__cl_p', node.start, node.tag.length + 1);
185
187
  emit(`: __cl_Readonly<${alias(node.tag)}> = { `);
186
188
  for (const a of node.attrs) {
187
- if (a.kind !== 'prop' && a.kind !== 'model')
189
+ if (a.kind !== 'prop' || a.name !== '...')
190
+ continue;
191
+ emit('...(');
192
+ copy(a.expr, at(a.expr, attrValueStart(a)));
193
+ emit('), ');
194
+ }
195
+ for (const a of node.attrs) {
196
+ if ((a.kind !== 'prop' && a.kind !== 'model') || a.name === '...')
188
197
  continue;
189
198
  copy(a.name, a.start + (a.kind === 'model' ? 2 : 1));
190
199
  emit(': (');
@@ -277,7 +286,7 @@ export function viewsDeclaration(views) {
277
286
  const ns = `__cl_v${i}`;
278
287
  const body = [];
279
288
  for (const t of parsed.typeImports) {
280
- const from = t.from.startsWith('.') ? `../${joinPath(file.split('/').slice(0, -1).join('/'), t.from)}` : t.from;
289
+ const from = t.from.startsWith('.') ? `../${joinPath(file.split('/').slice(0, -1).join('/'), t.from)}` : t.from.startsWith('~/') ? `../src/${t.from.slice(2)}` : t.from;
281
290
  const clause = t.clause.trim();
282
291
  if (clause.startsWith('{')) {
283
292
  for (const part of clause.slice(1, -1).split(',').map((p) => p.trim().replace(/^type\s+/, '')).filter(Boolean)) {
package/dist/cli/check.js CHANGED
@@ -4,6 +4,9 @@ import { createRequire } from 'node:module';
4
4
  import { basename, dirname, relative, resolve, sep } from 'node:path';
5
5
  import { ClarusError } from '../compiler/errors.js';
6
6
  import { lint } from '../compiler/lint.js';
7
+ import { checkIcons } from '../compiler/icon.js';
8
+ import { parse } from '../compiler/parse.js';
9
+ import { resolveIcon } from '../icons.js';
7
10
  import { generateTs, routesDeclaration, toSourceOffset, viewsDeclaration } from '../check/generate.js';
8
11
  import { findClarusFiles, reachableComponents } from '../vite/build.js';
9
12
  import { projectAliases, resolveAlias } from '../vite/aliases.js';
@@ -77,6 +80,12 @@ export function check(options) {
77
80
  }
78
81
  catch { }
79
82
  }
83
+ const located = (err) => {
84
+ const message = err.message.slice(`${err.file}:${err.line}:${err.column} `.length);
85
+ const lines = source.split('\n');
86
+ const at = src ? inSource(original, source, lines.slice(0, err.line - 1).reduce((n, l) => n + l.length + 1, 0) + err.column - 1) : null;
87
+ diagnostics.push({ file, ...(src ? (at === null ? { line: 1, column: 1 } : position(original, at)) : { line: err.line, column: err.column }), severity: 'error', code: 'clarus', message });
88
+ };
80
89
  try {
81
90
  const loader = loaderOf(path);
82
91
  const { code, mappings, loaderSpan } = generateTs(source, file, loader ? { loader } : {});
@@ -88,11 +97,13 @@ export function check(options) {
88
97
  catch (err) {
89
98
  if (!(err instanceof ClarusError))
90
99
  throw err;
91
- const message = err.message.slice(`${err.file}:${err.line}:${err.column} `.length);
92
- const lines = source.split('\n');
93
- const at = src ? inSource(original, source, lines.slice(0, err.line - 1).reduce((n, l) => n + l.length + 1, 0) + err.column - 1) : null;
94
- diagnostics.push({ file, ...(src ? (at === null ? { line: 1, column: 1 } : position(original, at)) : { line: err.line, column: err.column }), severity: 'error', code: 'clarus', message });
100
+ located(err);
101
+ }
102
+ try {
103
+ for (const err of checkIcons(parse(source, file), file, source, (name) => resolveIcon(name, path)))
104
+ located(err);
95
105
  }
106
+ catch { }
96
107
  }
97
108
  const appRoot = realpathSync(root);
98
109
  const paths = {};
@@ -0,0 +1,2 @@
1
+ import type { TemplateNode } from './parse.ts';
2
+ export declare function foldClass(nodes: TemplateNode[], components: Set<string>): void;
@@ -0,0 +1,49 @@
1
+ const spreadOf = (node) => node.attrs.find((a) => a.kind === 'prop' && a.name === '...')?.expr;
2
+ const isSource = (a, name) => a.name === name && a.kind !== 'event';
3
+ function part(a) {
4
+ if (a.kind === 'static')
5
+ return JSON.stringify(a.value === true ? '' : a.value);
6
+ if (a.kind === 'interp')
7
+ return `[${a.parts.map((p) => (typeof p === 'string' ? JSON.stringify(p) : `(${p.expr})`)).join(', ')}].join('')`;
8
+ return `(${a.expr})`;
9
+ }
10
+ function foldStyle(node) {
11
+ const props = node.attrs.filter((a) => a.kind === 'prop' && a.name.startsWith('style.'));
12
+ const sources = node.attrs.filter((a) => isSource(a, 'style'));
13
+ const spread = spreadOf(node);
14
+ if (!spread && !props.length && !(sources.length > 1 && sources.some((a) => a.kind === 'prop')))
15
+ return;
16
+ const exprs = [...(spread ? [`((${spread}) || {}).style`] : []), ...sources.map(part), ...props.map((p) => `{ ${JSON.stringify(p.name.slice(6))}: (${p.expr}) }`)];
17
+ const start = (sources[0] ?? props[0] ?? node.attrs.find((a) => a.name === '...')).start;
18
+ node.attrs = [...node.attrs.filter((a) => !isSource(a, 'style') && !props.includes(a)), { kind: 'prop', name: 'style', expr: `__cl_styleValue([${exprs.join(', ')}])`, start }];
19
+ }
20
+ export function foldClass(nodes, components) {
21
+ for (const node of nodes) {
22
+ if (node.type === 'element') {
23
+ if (!components.has(node.tag))
24
+ foldStyle(node);
25
+ if (!components.has(node.tag)) {
26
+ const toggles = node.attrs.filter((a) => a.kind === 'prop' && a.name.startsWith('class.'));
27
+ const sources = node.attrs.filter((a) => isSource(a, 'class'));
28
+ const mixed = sources.length > 1 && sources.some((a) => a.kind === 'prop');
29
+ const spread = spreadOf(node);
30
+ if (toggles.length || mixed || spread) {
31
+ const exprs = [...(spread ? [`((${spread}) || {}).class`] : []), ...sources.map(part), ...toggles.map((t) => `{ ${JSON.stringify(t.name.slice(6))}: (${t.expr}) }`)];
32
+ const start = (sources[0] ?? toggles[0] ?? node.attrs.find((a) => a.name === '...')).start;
33
+ node.attrs = [...node.attrs.filter((a) => !isSource(a, 'class') && !toggles.includes(a)), { kind: 'prop', name: 'class', expr: `__cl_classValue([${exprs.join(', ')}])`, start }];
34
+ }
35
+ }
36
+ foldClass(node.children, components);
37
+ }
38
+ else if (node.type === 'if')
39
+ for (const b of node.branches)
40
+ foldClass(b.children, components);
41
+ else if (node.type === 'for') {
42
+ foldClass(node.children, components);
43
+ if (node.empty)
44
+ foldClass(node.empty, components);
45
+ }
46
+ else if (node.type === 'fill')
47
+ foldClass(node.children, components);
48
+ }
49
+ }
@@ -19,7 +19,8 @@ export function emitClient(ir, hot) {
19
19
  hasHoles && 'holes as __cl_holes',
20
20
  hasHoles && 'text as __cl_text',
21
21
  ir.events.length > 0 && 'on as __cl_on',
22
- all.some((n) => n.kind === 'attr' && n.reactive) && 'attr as __cl_attr',
22
+ all.some((n) => n.kind === 'attr' && n.reactive && n.name !== '...') && 'attr as __cl_attr',
23
+ all.some((n) => n.kind === 'attr' && n.reactive && n.name === '...') && 'spread as __cl_spread',
23
24
  hasBlocks && 'block as __cl_block',
24
25
  hasFors && 'forBlock as __cl_for',
25
26
  all.some((n) => n.kind === 'for' && n.block >= 0 && rowNames(n, ir.events).some((x) => x !== '$count')) && 'derived as __cl_derived',
@@ -28,10 +29,13 @@ export function emitClient(ir, hot) {
28
29
  kinds.has('model') && 'modelInput as __cl_modelInput',
29
30
  ir.inputs.some((i) => kinds.has('input') || i.model) && 'batch as __cl_batch',
30
31
  rendersHtml && 'escape as __cl_escape',
31
- rendersHtml && all.some((n) => n.kind === 'attr') && 'attrHtml as __cl_attrHtml',
32
+ rendersHtml && all.some((n) => n.kind === 'attr' && n.name !== '...') && 'attrHtml as __cl_attrHtml',
33
+ rendersHtml && all.some((n) => n.kind === 'attr' && n.name === '...') && 'spreadHtml as __cl_spreadHtml',
32
34
  rendersHtml && hasBlocks && 'blockHtml as __cl_blockHtml',
33
35
  rendersHtml && hasFors && 'forHtml as __cl_forHtml',
34
36
  hasRegions && 'regionHtml as __cl_regionHtml',
37
+ all.some((n) => n.kind === 'attr' && JSON.stringify(n.value).includes('__cl_classValue(')) && 'classValue as __cl_classValue',
38
+ all.some((n) => n.kind === 'attr' && JSON.stringify(n.value).includes('__cl_styleValue(')) && 'styleValue as __cl_styleValue',
35
39
  ].filter(Boolean);
36
40
  let out = used.length ? `import { ${used.join(', ')} } from 'clarusjs/runtime'\n` : '';
37
41
  if (hot)
@@ -86,7 +90,9 @@ function wiring(ir, nodes, scope, ctx, signals, depth) {
86
90
  for (const h of [...holes].sort((a, b) => a.index - b.index))
87
91
  lines.push(`__cl_text(__cl_h[${h.index}], () => ${wrapExpr(rw.expr(h.expr))})`);
88
92
  for (const a of nodes) {
89
- if (a.kind === 'attr' && a.reactive)
93
+ if (a.kind === 'attr' && a.reactive && a.name === '...')
94
+ lines.push(`__cl_spread(${ctx}, ${a.index}, () => ${attrValueExpr(a.value, rw.expr)}, ${JSON.stringify(a.skip ?? [])}, ${JSON.stringify(a.tag)})`);
95
+ else if (a.kind === 'attr' && a.reactive)
90
96
  lines.push(`__cl_attr(${ctx}, ${a.index}, ${JSON.stringify(a.name)}, () => ${attrValueExpr(a.value, rw.expr)}${tagArg(a)})`);
91
97
  if (a.kind === 'connect')
92
98
  lines.push(`__cl_connect(${ctx}, ${a.index}, () => ${wrapExpr(rw.expr(a.expr))})`);
@@ -7,7 +7,10 @@ export function emitServer(ir, clientUrl, renderImports = false, loader) {
7
7
  'escape as __cl_escape',
8
8
  all.some((n) => n.kind === 'hole' && n.json) && 'json as __cl_json',
9
9
  ir.stateful && 'island as __cl_island',
10
- all.some((n) => n.kind === 'attr') && 'attr as __cl_attrHtml',
10
+ all.some((n) => n.kind === 'attr' && n.name !== '...') && 'attr as __cl_attrHtml',
11
+ all.some((n) => n.kind === 'attr' && n.name === '...') && 'spreadHtml as __cl_spreadHtml',
12
+ all.some((n) => n.kind === 'attr' && JSON.stringify(n.value).includes('__cl_classValue(')) && 'classValue as __cl_classValue',
13
+ all.some((n) => n.kind === 'attr' && JSON.stringify(n.value).includes('__cl_styleValue(')) && 'styleValue as __cl_styleValue',
11
14
  all.some((n) => n.kind === 'if' && n.block >= 0) && 'blockHtml as __cl_blockHtml',
12
15
  all.some((n) => n.kind === 'for' && n.block >= 0) && 'forHtml as __cl_forHtml',
13
16
  all.some((n) => n.kind === 'component' && n.region >= 0) && 'regionHtml as __cl_regionHtml',
@@ -10,6 +10,8 @@ export function htmlExpr(nodes, rw = asWritten) {
10
10
  return `(__cl_slots?.[${JSON.stringify(n.name)}] ?? ${n.fallback.length ? `(${htmlExpr(n.fallback, rw)})` : '""'})`;
11
11
  if (n.kind === 'connect')
12
12
  return '""';
13
+ if (n.kind === 'attr' && n.name === '...')
14
+ return `__cl_spreadHtml(${attrValueExpr(n.value, rw.expr)}, ${JSON.stringify(n.skip ?? [])}, ${JSON.stringify(n.tag)}${rw === asWritten && n.where ? `, ${JSON.stringify(n.where)}` : ''})`;
13
15
  if (n.kind === 'attr')
14
16
  return `__cl_attrHtml(${JSON.stringify(n.name)}, ${attrValueExpr(n.value, rw.expr)}${tagArg(n)})`;
15
17
  if (n.kind === 'if') {
@@ -44,7 +46,7 @@ export function htmlExpr(nodes, rw = asWritten) {
44
46
  return parts.length ? parts.join(' + ') : '""';
45
47
  }
46
48
  export function componentCall(n, rw) {
47
- const props = n.props.map((p) => `${p.name}: ${wrapExpr(rw.expr(p.expr))}`).join(', ');
49
+ const props = n.props.map((p) => (p.name === '...' ? `...${wrapExpr(rw.expr(p.expr))}` : `${p.name}: ${wrapExpr(rw.expr(p.expr))}`)).join(', ');
48
50
  const slots = [
49
51
  ...(n.children.length ? [`"default": ${htmlExpr(n.children, rw)}`] : []),
50
52
  ...n.fills.map((f) => `${JSON.stringify(f.name)}: ${htmlExpr(f.nodes, rw)}`),
@@ -0,0 +1,24 @@
1
+ import type { IconLookup } from '../icons.ts';
2
+ import { ClarusError } from './errors.ts';
3
+ import type { ParsedFile, TemplateNode } from './parse.ts';
4
+ /**
5
+ * Finds an icon by `set:name` for `<icon>`: `resolveIcon` from clarusjs/icons, bound to the file being compiled.
6
+ * @see https://clarusjs.com/guide/icons
7
+ */
8
+ export type IconResolver = (name: string) => IconLookup;
9
+ type Element = Extract<TemplateNode, {
10
+ type: 'element';
11
+ }>;
12
+ /** `<icon>` as the `<svg>` it renders and the body that goes inside it; throws a located error when it can't. */
13
+ export declare function iconElement(node: Element, file: string, source: string, icon: IconResolver | undefined): {
14
+ svg: Element;
15
+ body: string;
16
+ };
17
+ /**
18
+ * Every `<icon>` error in a file (lower() stops at the first): `clarusjs check` reports them all.
19
+ * @example
20
+ * checkIcons(parse(source, file), file, source, (name) => resolveIcon(name, file)) // [ClarusError, …]
21
+ * @see https://clarusjs.com/guide/icons
22
+ */
23
+ export declare function checkIcons(parsed: ParsedFile, file: string, source: string, icon: IconResolver | undefined): ClarusError[];
24
+ export {};
@@ -0,0 +1,79 @@
1
+ import { ClarusError } from './errors.js';
2
+ const LABELS = new Set(['aria-label', 'aria-labelledby']);
3
+ export function iconElement(node, file, source, icon) {
4
+ const fail = (text) => { throw new ClarusError(text, file, source, node.start); };
5
+ const name = node.attrs.find((a) => a.name === 'name');
6
+ if (!name)
7
+ return fail('<icon> needs a name: <icon name="lucide:rocket" />');
8
+ if (name.kind !== 'static' || name.value === true)
9
+ return fail('a bound name: icons are chosen at build time; use @if between static icons');
10
+ if (node.children.some((c) => c.type !== 'text' || c.value.trim()))
11
+ return fail('<icon> takes no content');
12
+ if (!icon)
13
+ return fail('icons are resolved at build time: <icon> needs clarusjs/vite or clarusjs check (the playground has no icon sets)');
14
+ const id = name.value;
15
+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*:[a-z0-9]+(?:-[a-z0-9]+)*$/.test(id))
16
+ return fail(`<icon> name is set:icon, like lucide:rocket (got '${id}')`);
17
+ let found;
18
+ try {
19
+ found = icon(id);
20
+ }
21
+ catch (e) {
22
+ return fail(e.message);
23
+ }
24
+ if ('missing' in found) {
25
+ if (found.missing === 'set')
26
+ return fail(`no icon set '${found.set}': install it with pnpm add -D @iconify-json/${found.set}`);
27
+ const mean = found.suggestions.length ? ` (did you mean ${found.suggestions.map((s) => `'${s}'`).join(' or ')}?)` : '';
28
+ return fail(`no icon '${id.slice(found.set.length + 1)}' in ${found.set}${mean}`);
29
+ }
30
+ const { data } = found;
31
+ const own = node.attrs.filter((a) => a !== name);
32
+ const has = (n) => own.some((a) => a.name === n);
33
+ const at = node.start;
34
+ const fixed = (n, value) => (has(n) ? [] : [{ kind: 'static', name: n, value, start: at }]);
35
+ const a11y = has('role') || has('aria-hidden') ? [] : own.some((a) => LABELS.has(a.name)) ? fixed('role', 'img') : fixed('aria-hidden', 'true');
36
+ const attrs = [
37
+ ...fixed('xmlns', 'http://www.w3.org/2000/svg'),
38
+ ...fixed('width', `${+(data.width / data.height).toFixed(4)}em`),
39
+ ...fixed('height', '1em'),
40
+ ...fixed('viewBox', `${data.left} ${data.top} ${data.width} ${data.height}`),
41
+ ...a11y,
42
+ ...own,
43
+ ];
44
+ return { svg: { type: 'element', tag: 'svg', attrs, children: [], start: node.start }, body: data.body };
45
+ }
46
+ export function checkIcons(parsed, file, source, icon) {
47
+ const components = new Set(parsed.imports.map((i) => i.name));
48
+ const errors = [];
49
+ const walk = (nodes) => {
50
+ for (const node of nodes) {
51
+ if (node.type === 'element') {
52
+ if (node.tag === 'icon' && !components.has('icon')) {
53
+ try {
54
+ iconElement(node, file, source, icon);
55
+ }
56
+ catch (e) {
57
+ if (!(e instanceof ClarusError))
58
+ throw e;
59
+ errors.push(e);
60
+ }
61
+ continue;
62
+ }
63
+ walk(node.children);
64
+ }
65
+ else if (node.type === 'if')
66
+ for (const b of node.branches)
67
+ walk(b.children);
68
+ else if (node.type === 'for') {
69
+ walk(node.children);
70
+ if (node.empty)
71
+ walk(node.empty);
72
+ }
73
+ else if (node.type === 'fill')
74
+ walk(node.children);
75
+ }
76
+ };
77
+ walk(parsed.nodes);
78
+ return errors;
79
+ }
@@ -1,6 +1,8 @@
1
1
  import { ClarusError } from './errors.ts';
2
2
  export { ClarusError } from './errors.ts';
3
3
  export { parse } from './parse.ts';
4
+ export { checkIcons, type IconResolver } from './icon.ts';
5
+ import type { IconResolver } from './icon.ts';
4
6
  export { lint, lintRules, type LintRule, type LintLevel, type LintConfig, type LintMessage, type LintRuleDef, type LintContext, type LintElement } from './lint.ts';
5
7
  export type { ParsedFile, InputDecl, ImportDecl, TemplateNode, Attr } from './parse.ts';
6
8
  /**
@@ -22,6 +24,8 @@ export type CompileOptions = {
22
24
  collapseWhitespace?: boolean;
23
25
  loader?: string;
24
26
  hot?: string;
27
+ /** Finds `<icon name="set:name">` icons: `(name) => resolveIcon(name, file)` from clarusjs/icons. Without it, `<icon>` is an error. */
28
+ icon?: IconResolver;
25
29
  };
26
30
  /**
27
31
  * `css`: the component's stylesheet (`<style scoped>` blocks wrapped in @scope, the others as written); '' without
@@ -5,12 +5,15 @@ import { lower } from './ir.js';
5
5
  import { parse } from './parse.js';
6
6
  export { ClarusError } from './errors.js';
7
7
  export { parse } from './parse.js';
8
+ import { foldClass } from './class-style.js';
9
+ export { checkIcons } from './icon.js';
8
10
  export { lint, lintRules } from './lint.js';
9
11
  export function compile(source, options) {
10
12
  const parsed = parse(source, options.file);
11
13
  const warnings = [];
12
14
  const id = options.scope ?? scopeId(options.file);
13
- markRoots(parsed.nodes, `cl-c-${id}`, new Set(parsed.imports.map((imp) => imp.name)));
15
+ foldClass(parsed.nodes, new Set(parsed.imports.map((imp) => imp.name)));
16
+ markRoots(parsed.nodes, `cl-c-${id}`, new Set(parsed.imports.map((imp) => imp.name)), parsed.styles.some((st) => st.mode === 'scoped'));
14
17
  let css = '';
15
18
  for (const s of parsed.styles) {
16
19
  if (s.mode === 'plain') {
@@ -24,7 +27,7 @@ export function compile(source, options) {
24
27
  const statements = head.split(';').map((x) => x.trim()).filter(Boolean).map((x) => `${x};\n`).join('');
25
28
  css += `${statements}@scope (.cl-c-${id}) to ([class*="cl-c-"]:not(.cl-c-${id}) > *) {${s.css.slice(head.length).replace(/\s*$/, '')}\n}\n`;
26
29
  }
27
- const ir = lower(parsed, options.file, source, { collapseWhitespace: options.collapseWhitespace });
30
+ const ir = lower(parsed, options.file, source, { collapseWhitespace: options.collapseWhitespace, icon: options.icon });
28
31
  warnings.push(...ir.warnings);
29
32
  if (options.target === 'client')
30
33
  return { code: emitClient(ir, options.hot), stateful: ir.stateful, css, warnings };
@@ -40,10 +43,38 @@ export function scopeId(file) {
40
43
  return `${name}-${(h >>> 0).toString(36)}`;
41
44
  }
42
45
  const UNMARKED = new Set(['slot', 'cl-head', 'script', 'style', 'html', 'title', 'meta', 'link', 'base']);
43
- function markRoots(nodes, cls, components) {
46
+ function markSlotContent(nodes, cls, components) {
47
+ for (const node of nodes) {
48
+ if (node.type === 'fill')
49
+ markSlotContent(node.children, cls, components);
50
+ else if (node.type === 'if')
51
+ for (const b of node.branches)
52
+ markSlotContent(b.children, cls, components);
53
+ else if (node.type === 'for') {
54
+ markSlotContent(node.children, cls, components);
55
+ if (node.empty)
56
+ markSlotContent(node.empty, cls, components);
57
+ }
58
+ else if (node.type === 'element' && components.has(node.tag))
59
+ markSlotContent(node.children, cls, components);
60
+ else if (node.type === 'element' && !UNMARKED.has(node.tag)) {
61
+ const at = node.attrs.findIndex((a) => a.name === 'class' && a.kind !== 'event');
62
+ const own = node.attrs[at];
63
+ if (!own)
64
+ node.attrs.push({ kind: 'static', name: 'class', value: cls, start: node.start });
65
+ else if (own.kind === 'static')
66
+ node.attrs[at] = { ...own, value: own.value === true || !own.value ? cls : `${own.value} ${cls}` };
67
+ else if (own.kind === 'interp')
68
+ own.parts.push(` ${cls}`);
69
+ else if (own.kind === 'prop')
70
+ node.attrs[at] = { kind: 'interp', name: 'class', parts: [{ expr: own.expr.startsWith('__cl_classValue(') ? own.expr : `__cl_classValue((${own.expr}))`, start: own.start }, ` ${cls}`], start: own.start };
71
+ }
72
+ }
73
+ }
74
+ function markRoots(nodes, cls, components, slots = false) {
44
75
  for (const node of nodes) {
45
76
  if (node.type === 'element' && !components.has(node.tag) && !UNMARKED.has(node.tag)) {
46
- const at = node.attrs.findIndex((a) => a.name === 'class');
77
+ const at = node.attrs.findIndex((a) => a.name === 'class' && a.kind !== 'event');
47
78
  const own = node.attrs[at];
48
79
  const passed = { expr: '__cl_class', start: node.start };
49
80
  if (!own)
@@ -53,16 +84,20 @@ function markRoots(nodes, cls, components) {
53
84
  else if (own.kind === 'interp')
54
85
  own.parts.push(` ${cls}`, passed);
55
86
  else if (own.kind === 'prop')
56
- node.attrs[at] = { kind: 'interp', name: 'class', parts: [{ expr: own.expr, start: own.start }, ` ${cls}`, passed], start: own.start };
87
+ node.attrs[at] = { kind: 'interp', name: 'class', parts: [{ expr: own.expr.startsWith('__cl_classValue(') ? own.expr : `__cl_classValue((${own.expr}))`, start: own.start }, ` ${cls}`, passed], start: own.start };
88
+ }
89
+ else if (node.type === 'element' && components.has(node.tag)) {
90
+ if (slots)
91
+ markSlotContent(node.children, cls, components);
57
92
  }
58
93
  else if (node.type === 'if') {
59
94
  for (const b of node.branches)
60
- markRoots(b.children, cls, components);
95
+ markRoots(b.children, cls, components, slots);
61
96
  }
62
97
  else if (node.type === 'for') {
63
- markRoots(node.children, cls, components);
98
+ markRoots(node.children, cls, components, slots);
64
99
  if (node.empty)
65
- markRoots(node.empty, cls, components);
100
+ markRoots(node.empty, cls, components, slots);
66
101
  }
67
102
  }
68
103
  }
@@ -1,3 +1,4 @@
1
+ import { type IconResolver } from './icon.ts';
1
2
  import { ClarusError } from './errors.ts';
2
3
  import { type DataImport, type ImportDecl, type InputDecl, type ParsedFile } from './parse.ts';
3
4
  import { type Signals } from './script.ts';
@@ -50,6 +51,8 @@ export type IRNode = {
50
51
  reactive: boolean;
51
52
  index: number;
52
53
  tag: string;
54
+ skip?: string[];
55
+ where?: string;
53
56
  } | {
54
57
  kind: 'connect';
55
58
  expr: string;
@@ -93,4 +96,5 @@ export type ComponentIR = {
93
96
  };
94
97
  export declare function lower(parsed: ParsedFile, file: string, source: string, options?: {
95
98
  collapseWhitespace?: boolean;
99
+ icon?: IconResolver;
96
100
  }): ComponentIR;
@@ -1,9 +1,12 @@
1
1
  import { parseExpressionAt } from 'acorn';
2
+ import { iconElement } from './icon.js';
2
3
  import { ClarusError } from './errors.js';
3
4
  import { FOR_IMPLICIT, importNames } from './parse.js';
4
5
  import { analyzeScript, mutationsOf, writesTo, checkExpr, checkHandler, referencesNames, scriptNames, splitImports } from './script.js';
5
6
  const ATTACH_MODES = ['load', 'idle', 'visible', 'interaction'];
7
+ const SPREAD_REFUSED = new Set(['iframe', 'frame', 'embed', 'object', 'base', 'link', 'script', 'meta']);
6
8
  const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr']);
9
+ const iconBodies = new WeakMap();
7
10
  export function lower(parsed, file, source, options = {}) {
8
11
  const fail = (text, at) => { throw new ClarusError(text, file, source, at); };
9
12
  const stateful = !!parsed.script || parsed.inputs.some((i) => i.model);
@@ -167,13 +170,27 @@ export function lower(parsed, file, source, options = {}) {
167
170
  out.push({ kind: 'hole', expr: node.expr, reactive, index: reactive ? holeCount++ : -1 });
168
171
  return;
169
172
  }
170
- if (components.has(node.tag)) {
173
+ if (node.tag === 'icon' && !components.has('icon')) {
174
+ const { svg, body } = iconElement(node, file, source, options.icon);
175
+ iconBodies.set(svg, body);
176
+ return visit(svg, rawText);
177
+ }
178
+ if (components.has(node.tag) && !iconBodies.has(node)) {
171
179
  const props = [];
172
180
  const models = [];
173
181
  let attach;
174
182
  let cls;
175
183
  const paths = [];
176
184
  for (const a of node.attrs) {
185
+ if (/^(class|style)\./.test(a.name))
186
+ fail(`a component takes a static class="…" only: [${a.name}] is for elements`, a.start);
187
+ if (a.kind === 'prop' && a.name === '...') {
188
+ if (props.some((p) => p.name === '...'))
189
+ fail('one [...] per element', a.start);
190
+ checkExpr(a.expr, file, source, a.start);
191
+ props.unshift({ name: '...', expr: a.expr });
192
+ continue;
193
+ }
177
194
  if (a.name === 'class') {
178
195
  if (a.kind !== 'static' || typeof a.value !== 'string')
179
196
  fail('a component takes a static class="…" only ([class] and {{ }} in it aren\'t supported on a component yet)', a.start);
@@ -319,6 +336,17 @@ export function lower(parsed, file, source, options = {}) {
319
336
  attrs.push({ kind: 'prop', name: 'selected', expr: `((__cl_s, __cl_v) => (Array.isArray(__cl_s) ? __cl_s.map(String).includes(String(__cl_v)) : String(__cl_s) === String(__cl_v)))(${selectModel}, ${mine})`, start: own.start });
320
337
  }
321
338
  }
339
+ for (const a of node.attrs) {
340
+ if (a.name.startsWith('{'))
341
+ fail(`${a.name} isn't a binding: spread with [...]="${a.name.replace(/^\{\.*|\}$/g, '')}"`, a.start);
342
+ if (a.kind === 'prop' && a.name.includes('.') && a.name !== '...' && !/^(class|style)\./.test(a.name))
343
+ fail(`[${a.name}]: only class. and style. take a . ([class.name], [style.prop])`, a.start);
344
+ }
345
+ const spreads = node.attrs.filter((a) => a.kind === 'prop' && a.name === '...');
346
+ if (spreads.length > 1)
347
+ fail('one [...] per element', spreads[1].start);
348
+ if (spreads.length && SPREAD_REFUSED.has(node.tag.toLowerCase()))
349
+ fail(`[...] can't spread onto <${node.tag}>: it could set what the element loads (write its attributes one by one)`, spreads[0].start);
322
350
  emitStatic(`<${node.tag}`);
323
351
  const elementEvents = attrs.filter((a) => a.kind === 'event');
324
352
  const dynamic = [];
@@ -339,6 +367,16 @@ export function lower(parsed, file, source, options = {}) {
339
367
  for (const m of mutationsOf(a.expr, stateNames))
340
368
  warnings.push(new ClarusError(m.message, file, source, exprStart + m.start));
341
369
  }
370
+ else if (a.kind === 'prop' && a.name === '...') {
371
+ checkExpr(a.expr, file, source, a.start);
372
+ const reactive = stateful && (referencesNames(a.expr, scriptScope) || referencesNames(a.expr, loopNames));
373
+ const skip = [...new Set(attrs.filter((x) => x !== a && x.kind !== 'event').map((x) => x.name.toLowerCase()))];
374
+ const at = new ClarusError('', file, source, a.start);
375
+ const node_ = { kind: 'attr', name: '...', value: { expr: a.expr }, reactive, index: -1, tag: node.tag, skip, where: `${file}:${at.line}:${at.column}` };
376
+ if (reactive)
377
+ dynamic.push(node_);
378
+ out.push(node_);
379
+ }
342
380
  else if (a.kind === 'prop' && a.name === 'engine') {
343
381
  if (!stateful)
344
382
  fail('[engine] needs a <script> (an island): the forms engine runs in the browser', a.start);
@@ -380,6 +418,9 @@ export function lower(parsed, file, source, options = {}) {
380
418
  events.push({ index, type: a.name, handler: a.kind === 'event' ? a.expr : '', scope: scopeKey });
381
419
  }
382
420
  emitStatic('>');
421
+ const iconBody = iconBodies.get(node);
422
+ if (iconBody !== undefined)
423
+ emitStatic(iconBody);
383
424
  const outer = engineScope;
384
425
  if (engine)
385
426
  engineScope = { root: null };
@@ -0,0 +1,59 @@
1
+ /**
2
+ * An icon as the compiler draws it: its SVG body and its box (`viewBox="left top width height"`).
3
+ * @see https://clarusjs.com/guide/icons
4
+ */
5
+ export type IconData = {
6
+ body: string;
7
+ width: number;
8
+ height: number;
9
+ left: number;
10
+ top: number;
11
+ };
12
+ /**
13
+ * What a lookup found: the icon, or what's missing (the set, or the icon in it, with the closest names).
14
+ * @see https://clarusjs.com/guide/icons
15
+ */
16
+ export type IconLookup = {
17
+ data: IconData;
18
+ } | {
19
+ missing: 'set';
20
+ set: string;
21
+ } | {
22
+ missing: 'icon';
23
+ set: string;
24
+ suggestions: string[];
25
+ };
26
+ /**
27
+ * The icon `set:name` (Iconify naming), from the sets installed for the package `fromFile` is in. Throws for an alias
28
+ * that flips or rotates its icon (not supported yet).
29
+ * @example
30
+ * resolveIcon('lucide:rocket', '/app/src/pages/index.tscl') // { data: { body: '<path …/>', width: 24, … } }
31
+ * @see https://clarusjs.com/guide/icons
32
+ */
33
+ export declare function resolveIcon(name: string, fromFile: string): IconLookup;
34
+ /**
35
+ * The icon sets installed for the package `fromFile` is in (its `@iconify-json/*` dependencies, and those in its
36
+ * node_modules), for the editor's completion.
37
+ * @example
38
+ * iconSets('/app/src/pages/index.tscl') // [{ prefix: 'lucide', name: 'Lucide', total: 1600 }]
39
+ * @see https://clarusjs.com/guide/icons
40
+ */
41
+ export declare function iconSets(fromFile: string): {
42
+ prefix: string;
43
+ name: string;
44
+ total: number;
45
+ }[];
46
+ /**
47
+ * The names in an installed set (icons and aliases, sorted); none when it isn't installed.
48
+ * @example
49
+ * iconNames('lucide', '/app/src/pages/index.tscl') // ['a-arrow-down', …, 'rocket', …]
50
+ * @see https://clarusjs.com/guide/icons
51
+ */
52
+ export declare function iconNames(set: string, fromFile: string): string[];
53
+ /**
54
+ * A standalone `<svg>` for an icon, with extra attributes (`'width="48"'`); the editor's hover preview uses it.
55
+ * @example
56
+ * iconSvg(data, 'width="48" height="48"') // '<svg xmlns="…" viewBox="0 0 24 24" width="48" height="48">…</svg>'
57
+ * @see https://clarusjs.com/guide/icons
58
+ */
59
+ export declare function iconSvg(data: IconData, attrs?: string): string;