@threadlabs/looma 0.49.1 → 0.49.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/docs/catalog.mjs CHANGED
@@ -45,7 +45,7 @@ async function resources(directory) {
45
45
  /** Discover only explicitly selected roots through HTML Next's public parser. */
46
46
  export async function discoverComponents({ root, directory, packageName, groups = [] }) {
47
47
  if (!packageName || !directory) throw new Error('A discovery root requires packageName and directory.');
48
- const { parseComponentResource, typeScriptType } = await import('@nextwebwg/html-next');
48
+ const { parseComponentResource, typeScriptType, normalizeType } = await import('@nextwebwg/html-next');
49
49
  const components = [];
50
50
  for (const source of await resources(path.resolve(root, directory))) {
51
51
  const html = await readFile(source, 'utf8');
@@ -57,7 +57,7 @@ export async function discoverComponents({ root, directory, packageName, groups
57
57
  const docs = metadata.components?.[contract.tag] ?? metadata;
58
58
  const id = `${packageName}/${contract.tag}`;
59
59
  const properties = Object.entries(contract.props).map(([name, prop]) => ({ name, type: typeScriptType(prop.type), description: prop.description ?? '', ...(Object.hasOwn(prop, 'default') ? { default: prop.default } : {}), ...(prop.values ? { options: prop.values } : {}) }));
60
- const attributes = properties.map(prop => ({ ...prop, property: prop.name, name: prop.name.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`) }));
60
+ const attributes = properties.map(prop => ({ ...prop, property: prop.name, name: prop.name.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`), valueType: normalizeType(contract.props[prop.name].type) }));
61
61
  const events = (definition.declarations ?? []).filter(item => item.kind === 'event').map(event => ({ name: event.name, detailType: event.shape ? typeScriptType(event.shape) : String(event.type), detailDocs: docs.events?.[event.name] ?? '' }));
62
62
  const slots = (definition.slots ?? []).map(slot => ({ name: slot.name ?? 'default', description: docs.slots?.[slot.name ?? 'default'] ?? '' }));
63
63
  const tokens = [...new Set([...definition.css.matchAll(/var\(\s*(--[\w-]+)/g)].map(match => match[1]))].sort();
@@ -0,0 +1,63 @@
1
+ import { parseFragment } from 'parse5';
2
+ import { parseTypedValue } from '@nextwebwg/html-next';
3
+
4
+ export const componentName = tag => tag.split('-').map(word => word[0].toUpperCase() + word.slice(1)).join('');
5
+ export const camel = name => name.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
6
+ export const nativeBooleans = new Set(['allowfullscreen', 'async', 'autofocus', 'autoplay', 'checked', 'controls', 'default', 'defer', 'disabled', 'formnovalidate', 'hidden', 'inert', 'ismap', 'itemscope', 'loop', 'multiple', 'muted', 'nomodule', 'novalidate', 'open', 'playsinline', 'readonly', 'required', 'reversed', 'selected']);
7
+ const scalarTypes = new Set(['boolean', 'number', 'string']);
8
+
9
+ /** Parse authored invocations once; every printer consumes the same props, slot groups and text. */
10
+ export function exampleInvocations(markup, components) {
11
+ const byTag = new Map(components.map(component => [component.tag, component]));
12
+ const used = new Set();
13
+
14
+ function readAttribute(input, component, attributes) {
15
+ const contract = component?.attributes?.find(value => value.name === input.name);
16
+ // Catalogs carry the parser's type node. `type` remains the human-readable API description.
17
+ let type = contract?.valueType ?? (scalarTypes.has(contract?.type) ? contract.type : undefined);
18
+ if (type?.kind === 'selected') {
19
+ const selector = component.attributes.find(candidate => (candidate.property ?? candidate.name) === type.from);
20
+ const supplied = attributes.find(candidate => candidate.name === selector?.name);
21
+ const selected = supplied ? readAttribute(supplied, component, attributes).value : selector?.default;
22
+ type = type.options.find(option => option.value === selected)?.type;
23
+ }
24
+ let value = input.value;
25
+ if (type) {
26
+ const parsed = parseTypedValue(value, type, `${component.tag}.${contract.property ?? input.name}`, 'html');
27
+ if (!parsed.ok) throw new TypeError(parsed.issues.map(issue => `${issue.path}: ${issue.message}`).join('; '));
28
+ value = parsed.value;
29
+ } else if (!contract && nativeBooleans.has(input.name)) value = true;
30
+ return { name: input.name, property: contract?.property ?? input.name, value };
31
+ }
32
+
33
+ function visit(node, omitSlot = false, preserve = false) {
34
+ if (node.nodeName === '#text') return { kind: 'text', value: node.value, preserve };
35
+ if (node.nodeName === '#comment') return { kind: 'comment', value: node.data };
36
+ const component = byTag.get(node.tagName);
37
+ if (component) used.add(component);
38
+ const children = [];
39
+ const slots = new Map();
40
+ for (const child of node.content?.childNodes ?? node.childNodes ?? []) {
41
+ const slotName = component && child.attrs?.find(attribute => attribute.name === 'slot')?.value;
42
+ const projected = visit(child, Boolean(slotName), preserve || ['pre', 'textarea'].includes(node.tagName));
43
+ if (slotName) {
44
+ let slot = slots.get(slotName);
45
+ if (!slot) {
46
+ slot = { kind: 'slot', name: slotName, owner: component, children: [] };
47
+ slots.set(slotName, slot);
48
+ children.push(slot);
49
+ }
50
+ if (child.tagName === 'template') slot.children.push(...projected.children);
51
+ else slot.children.push(projected);
52
+ } else children.push(projected);
53
+ }
54
+ return {
55
+ kind: 'element', tag: component ? componentName(component.tag) : node.tagName, component,
56
+ attributes: node.attrs.filter(attribute => !omitSlot || attribute.name !== 'slot').map(value => readAttribute(value, component, node.attrs)),
57
+ children, slots: [...slots.values()],
58
+ };
59
+ }
60
+
61
+ const nodes = parseFragment(markup).childNodes.map(node => visit(node));
62
+ return { nodes, components: [...used] };
63
+ }
@@ -1,7 +1,9 @@
1
+ import type { TypeNode } from '@nextwebwg/html-next';
2
+
1
3
  export type Framework = 'html-next' | 'vue' | 'react' | 'svelte';
2
4
  export interface FrameworkExample { language: 'html' | 'vue' | 'tsx' | 'svelte'; code: string; }
3
5
  export const frameworkLabels: Readonly<Record<Framework, string>>;
4
6
  export function frameworkExamples(
5
7
  example: { markup: string; frameworks?: Partial<Record<Framework, FrameworkExample>> },
6
- components: readonly { tag: string; package: string; resource?: string; importSource?: string; attributes?: readonly { name: string; property?: string; type?: string }[] }[],
8
+ components: readonly { tag: string; package: string; root?: string; resource?: string; importSource?: string; attributes?: readonly { name: string; property?: string; type?: string; valueType?: TypeNode }[] }[],
7
9
  ): Record<Framework, FrameworkExample>;
@@ -1,89 +1,170 @@
1
- import { parseFragment } from 'parse5';
1
+ import { camel, componentName, exampleInvocations, nativeBooleans } from './example-invocations.mjs';
2
+
2
3
  const escapeHtml = value => String(value).replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;');
4
+ const indent = depth => ' '.repeat(depth);
5
+ const textValue = node => node.preserve ? node.value : node.value.replace(/[\t\n\r\f ]+/g, ' ');
6
+ const key = value => /^[a-zA-Z_$][\w$]*$/.test(value) ? value : JSON.stringify(value);
7
+ const kebab = value => value.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`);
8
+ const voidElements = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source', 'track', 'wbr']);
9
+ const reactAttributes = { class: 'className', for: 'htmlFor', readonly: 'readOnly', tabindex: 'tabIndex', autofocus: 'autoFocus', maxlength: 'maxLength', minlength: 'minLength', colspan: 'colSpan', rowspan: 'rowSpan', srcset: 'srcSet', crossorigin: 'crossOrigin', spellcheck: 'spellCheck', contenteditable: 'contentEditable', allowfullscreen: 'allowFullScreen', formnovalidate: 'formNoValidate', novalidate: 'noValidate', playsinline: 'playsInline' };
10
+ const numericAttributes = new Set(['cols', 'rows', 'size', 'span', 'rowSpan', 'colSpan', 'tabIndex', 'maxLength', 'minLength', 'start']);
11
+ const inlineElements = new Set('a abbr b bdi bdo br button cite code del em i img input ins kbd label mark q s samp small span strong sub sup time u var wbr'.split(' '));
12
+ const reserved = new Set('await break case catch class const continue debugger default delete do else enum export extends false finally for function if implements import in instanceof interface let new null package private protected public return static super switch this throw true try typeof var void while with yield arguments eval'.split(' '));
3
13
 
4
14
  export const frameworkLabels = { 'html-next': 'HTML Next', vue: 'Vue', react: 'React', svelte: 'Svelte' };
5
- const componentName = tag => tag.split('-').map(word => word[0].toUpperCase() + word.slice(1)).join('');
6
- const camel = name => name.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
7
- const voidElements = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source', 'track', 'wbr']);
8
- const nativeBooleans = new Set(['checked', 'disabled', 'hidden', 'multiple', 'open', 'readonly', 'required', 'selected', 'autofocus']);
9
- const reactAttributes = { class: 'className', for: 'htmlFor', readonly: 'readOnly', tabindex: 'tabIndex', autofocus: 'autoFocus', maxlength: 'maxLength', minlength: 'minLength', colspan: 'colSpan', rowspan: 'rowSpan', srcset: 'srcSet', crossorigin: 'crossOrigin', spellcheck: 'spellCheck', contenteditable: 'contentEditable' };
15
+
16
+ // Newline-only indentation can be rebuilt. Mixed text and explicit inline spaces stay together.
17
+ function layout(nodes, owner) {
18
+ const formattingSpace = node => node.kind === 'text' && !node.preserve && /^[\t\n\r\f ]*$/.test(node.value);
19
+ const inline = !owner?.component && nodes.every(node => node.kind === 'text' || node.kind === 'element' && inlineElements.has(node.component?.root ?? node.tag));
20
+ const multiline = !inline && nodes.some(node => formattingSpace(node) && node.value.includes('\n'))
21
+ && !nodes.some(node => node.kind === 'text' && !formattingSpace(node));
22
+ return { multiline, nodes: multiline ? nodes.filter(node => !formattingSpace(node)) : nodes };
23
+ }
24
+
25
+ function text(node, target) {
26
+ const value = textValue(node);
27
+ if (target === 'react') {
28
+ if (node.preserve || /[\n\r\t]/.test(node.value)) {
29
+ return `{${JSON.stringify(value)}}`;
30
+ }
31
+ return escapeHtml(value).replace(/[{}]/g, char => `{${JSON.stringify(char)}}`);
32
+ }
33
+ const escaped = escapeHtml(value);
34
+ return target === 'svelte' ? escaped.replaceAll('{', "{'{'}") : escaped.replaceAll('{', '&#123;');
35
+ }
36
+
37
+ function attribute(value, target, component) {
38
+ let name = value.property;
39
+ let data = value.value;
40
+ if (target === 'react') {
41
+ name = reactAttributes[name] ?? name;
42
+ if (name === 'style') {
43
+ data = Object.fromEntries(String(data).split(';').filter(part => part.includes(':')).map(part => {
44
+ const at = part.indexOf(':');
45
+ const property = part.slice(0, at).trim();
46
+ return [property.startsWith('--') ? property : camel(property), part.slice(at + 1).trim()];
47
+ }));
48
+ } else if (!component && numericAttributes.has(name) && /^[-+]?\d+$/.test(data)) data = Number(data);
49
+ if (data === true) return name;
50
+ return typeof data === 'string' ? `${name}="${escapeHtml(data)}"` : `${name}={${JSON.stringify(data)}}`;
51
+ }
52
+ if (target === 'svelte') {
53
+ if (data === true) return name;
54
+ return typeof data === 'string' ? `${name}="${escapeHtml(data).replaceAll('{', '&#123;')}"` : `${name}={${JSON.stringify(data)}}`;
55
+ }
56
+ name = component ? kebab(name) : value.name;
57
+ if (data === true && nativeBooleans.has(name) && !component) return name;
58
+ return typeof data === 'string' ? `${name}="${escapeHtml(data).replaceAll('{', '&#123;')}"` : `:${name}="${escapeHtml(JSON.stringify(data))}"`;
59
+ }
60
+
61
+ function snippetBindings(model) {
62
+ const taken = new Set([...reserved, ...model.components.map(component => componentName(component.tag))]);
63
+ const bindings = new Map();
64
+ function visit(nodes) {
65
+ for (const node of nodes) {
66
+ if (node.kind === 'slot') {
67
+ let base = camel(node.name.replace(/[^\w$-]/g, '-')).replace(/-/g, '');
68
+ if (!/^[a-zA-Z_$]/.test(base)) base = `slot${base}`;
69
+ if (reserved.has(base)) base += 'Content';
70
+ let name = base;
71
+ if (taken.has(name)) {
72
+ const owner = componentName(node.owner.tag).replace(/^Ui/, '');
73
+ base = owner[0].toLowerCase() + owner.slice(1) + base[0].toUpperCase() + base.slice(1);
74
+ name = base;
75
+ for (let index = 2; taken.has(name); index++) name = `${base}${index}`;
76
+ }
77
+ taken.add(name);
78
+ bindings.set(node, name);
79
+ }
80
+ if (node.children) visit(node.children);
81
+ }
82
+ }
83
+ visit(model.nodes);
84
+ return bindings;
85
+ }
86
+
87
+ /** Print the public invocation API, keeping framework-specific syntax out of the parsed model. */
88
+ function printer(model, target) {
89
+ const bindings = target === 'svelte' ? snippetBindings(model) : new Map();
90
+
91
+ function sequence(nodes, depth, forceLines = false, owner) {
92
+ const arranged = layout(nodes, owner);
93
+ const content = arranged.nodes.map(node => (arranged.multiline ? indent(depth) : '') + render(node, depth)).join(arranged.multiline ? '\n' : '');
94
+ return (forceLines && !arranged.multiline ? indent(depth) : '') + content;
95
+ }
96
+
97
+ function reactValue(nodes, depth) {
98
+ const arranged = layout(nodes);
99
+ if (!arranged.nodes.length) return 'null';
100
+ if (arranged.nodes.length === 1) {
101
+ const node = arranged.nodes[0];
102
+ if (node.kind === 'text') return JSON.stringify(textValue(node));
103
+ if (node.kind === 'comment') return `null /*${node.value}*/`;
104
+ return render(node, depth);
105
+ }
106
+ return arranged.multiline
107
+ ? `<>\n${sequence(nodes, depth + 1)}\n${indent(depth)}</>`
108
+ : `<>${sequence(nodes, depth)}</>`;
109
+ }
110
+
111
+ function render(node, depth) {
112
+ if (node.kind === 'text') return text(node, target);
113
+ if (node.kind === 'comment') return target === 'react' ? `{/*${node.value}*/}` : `<!--${node.value}-->`;
114
+ if (node.kind === 'slot') {
115
+ return `<template #${node.name}>\n${sequence(node.children, depth + 1, true)}\n${indent(depth)}</template>`;
116
+ }
117
+ const attrs = node.attributes.map(value => attribute(value, target, node.component));
118
+ if (node.slots.length && target === 'svelte') {
119
+ attrs.push(`slots={{ ${node.slots.map(slot => slot.name === bindings.get(slot) ? slot.name : `${key(slot.name)}: ${bindings.get(slot)}`).join(', ')} }}`);
120
+ }
121
+ if (node.slots.length && target === 'react') {
122
+ attrs.push(`slots={{\n${node.slots.map(slot => `${indent(depth + 2)}${key(slot.name)}: ${reactValue(slot.children, depth + 2)},`).join('\n')}\n${indent(depth + 1)}}}`);
123
+ }
124
+ const opening = `<${node.tag}${attrs.length ? ' ' + attrs.join(' ') : ''}`;
125
+ const wrapped = attrs.some(value => value.includes('\n')) || indent(depth).length + opening.length + 2 > 100;
126
+ const start = wrapped ? `<${node.tag}\n${attrs.map(value => indent(depth + 1) + value).join('\n')}\n${indent(depth)}` : opening;
127
+ const children = target === 'vue' ? node.children : node.children.filter(child => child.kind !== 'slot');
128
+ const arranged = layout(children, node);
129
+ if (!arranged.nodes.length && (node.component || target === 'react')) return `${start}${wrapped ? '' : ' '}/>`;
130
+ if (voidElements.has(node.tag)) return `${start}>`;
131
+ const content = sequence(children, depth + 1, false, node);
132
+ return arranged.multiline
133
+ ? `${start}>\n${content}\n${indent(depth)}</${node.tag}>`
134
+ : `${start}>${content}</${node.tag}>`;
135
+ }
136
+
137
+ function body(depth) {
138
+ const arranged = layout(model.nodes);
139
+ if (target !== 'react') return (arranged.multiline ? '' : indent(depth)) + sequence(model.nodes, depth);
140
+ return reactValue(model.nodes, depth);
141
+ }
142
+
143
+ return {
144
+ body,
145
+ snippets: () => [...bindings].map(([slot, name]) => `{#snippet ${name}()}\n${sequence(slot.children, 1, true)}\n{/snippet}`).join('\n\n'),
146
+ };
147
+ }
10
148
 
11
149
  /** Present invocations using the public APIs produced by each Vite framework target. */
12
150
  export function frameworkExamples(example, components) {
13
- const byTag = new Map(components.map(component => [component.tag, component]));
14
- const tags = [...new Set([...example.markup.matchAll(/<([a-z][\w]*-[\w-]+)\b/g)].map(match => match[1]))].filter(tag => byTag.has(tag));
15
- const importSource = tag => byTag.get(tag).importSource ?? byTag.get(tag).package;
16
- const imports = [...new Set(tags.map(importSource))].map(owner =>
17
- `import { ${tags.filter(tag => importSource(tag) === owner).map(componentName).sort().join(', ')} } from ${JSON.stringify(owner)};`).join('\n');
18
- const links = tags.map(tag => `<link rel="component" href="${byTag.get(tag).resource ?? `${byTag.get(tag).package}/components/${tag}/${tag}.html`}">`).join('\n');
19
- const fragment = parseFragment(example.markup);
151
+ const model = exampleInvocations(example.markup, components);
152
+ const importSource = component => component.importSource ?? component.package;
153
+ const imports = [...new Set(model.components.map(importSource))].map(owner => {
154
+ const names = model.components.filter(component => importSource(component) === owner).map(component => componentName(component.tag)).sort();
155
+ const line = `import { ${names.join(', ')} } from ${JSON.stringify(owner)};`;
156
+ return line.length <= 100 ? line : `import {\n${names.map(name => ` ${name},`).join('\n')}\n} from ${JSON.stringify(owner)};`;
157
+ }).join('\n');
158
+ const links = model.components.map(component => `<link rel="component" href="${component.resource ?? `${component.package}/components/${component.tag}/${component.tag}.html`}">`).join('\n');
20
159
  const codes = { 'html-next': { language: 'html', code: `${links}\n\n${example.markup}` } };
21
160
  for (const target of ['vue', 'react', 'svelte']) {
22
- const snippets = [];
23
- function render(node, omitSlot = false) {
24
- if (node.nodeName === '#text') {
25
- const text = escapeHtml(node.value);
26
- return target === 'react' ? text.replace(/[{}]/g, char => `{${JSON.stringify(char)}}`) : target === 'svelte' ? text.replaceAll('{', "{'{'}") : text;
27
- }
28
- if (!node.tagName) return '';
29
- const component = byTag.get(node.tagName);
30
- const tag = component ? componentName(node.tagName) : node.tagName;
31
- const children = node.content?.childNodes ?? node.childNodes ?? [];
32
- const slots = new Map();
33
- const ordinary = [];
34
- for (const child of children) {
35
- const slot = component && child.attrs?.find(attribute => attribute.name === 'slot')?.value;
36
- if (slot) slots.set(slot, [...slots.get(slot) ?? [], child]);
37
- else ordinary.push(child);
38
- }
39
- const attrs = node.attrs.filter(attribute => !omitSlot || attribute.name !== 'slot').map(attribute => {
40
- const contract = component?.attributes?.find(value => value.name === attribute.name);
41
- const property = component ? contract?.property ?? camel(attribute.name) : attribute.name;
42
- let value = attribute.value;
43
- let typed = false;
44
- if (contract?.type === 'boolean' || !contract && nativeBooleans.has(attribute.name)) { value = value !== 'false'; typed = true; }
45
- else if (contract?.type === 'number' && value.trim() !== '' && Number.isFinite(Number(value))) { value = Number(value); typed = true; }
46
- else if (component && /^[\[{]/.test(value)) {
47
- try { value = JSON.parse(value); typed = true; } catch { /* Ordinary strings remain strings. */ }
48
- }
49
- if (target === 'react') {
50
- const name = reactAttributes[property] ?? property;
51
- if (name === 'style') {
52
- value = Object.fromEntries(value.split(';').filter(part => part.includes(':')).map(part => {
53
- const at = part.indexOf(':'); const key = part.slice(0, at).trim();
54
- return [key.startsWith('--') ? key : camel(key), part.slice(at + 1).trim()];
55
- }));
56
- typed = true;
57
- }
58
- return typed ? `${name}={${JSON.stringify(value)}}` : `${name}=${JSON.stringify(value)}`;
59
- }
60
- if (target === 'svelte') return typed ? `${property}={${JSON.stringify(value)}}` : `${property}="${escapeHtml(value).replaceAll('{', '&#123;')}"`;
61
- return typed ? `:${property}="${escapeHtml(JSON.stringify(value))}"` : `${attribute.name}="${escapeHtml(value)}"`;
62
- });
63
- let content = ordinary.map(child => render(child)).join('');
64
- if (slots.size) {
65
- if (target === 'vue') content += [...slots].map(([name, nodes]) => `<template #${name}>${nodes.map(child => render(child, true)).join('')}</template>`).join('');
66
- else if (target === 'react') attrs.push(`slots={{${[...slots].map(([name, nodes]) => `${JSON.stringify(name)}: <>${nodes.map(child => render(child, true)).join('')}</>`).join(', ')}}}`);
67
- else {
68
- const bindings = [...slots].map(([name, nodes]) => {
69
- // Render descendants first, since they may declare their own named slots.
70
- const markup = nodes.map(child => render(child, true)).join('');
71
- const identifier = `slot${snippets.length}`;
72
- snippets.push(`{#snippet ${identifier}()}${markup}{/snippet}`);
73
- return `${JSON.stringify(name)}: ${identifier}`;
74
- });
75
- attrs.push(`slots={{${bindings.join(', ')}}}`);
76
- }
77
- }
78
- const start = `<${tag}${attrs.length ? ' ' + attrs.join(' ') : ''}`;
79
- if (voidElements.has(tag)) return `${start}${target === 'react' ? ' /' : ''}>`;
80
- if (node.tagName === 'template' && omitSlot) return content;
81
- return `${start}>${content}</${tag}>`;
82
- }
83
- const markup = fragment.childNodes.map(node => render(node)).join('');
161
+ const output = printer(model, target);
162
+ const script = imports ? `<script${target === 'vue' ? ' setup' : ''}>\n${imports.split('\n').map(line => ' ' + line).join('\n')}\n</script>\n\n` : '';
163
+ const jsx = target === 'react' ? output.body(2) : '';
164
+ const reactReturn = jsx.includes('\n') || jsx.length + 10 > 100 ? `return (\n ${jsx}\n );` : `return ${jsx};`;
84
165
  codes[target] = target === 'react'
85
- ? { language: 'tsx', code: `${imports}\n\nexport default function Example() {\n return (<>${markup}</>);\n}` }
86
- : { language: target, code: `<script${target === 'vue' ? ' setup' : ''}>\n${imports}\n</script>\n\n${target === 'vue' ? `<template>\n${markup}\n</template>` : `${snippets.join('\n')}\n${markup}`}` };
166
+ ? { language: 'tsx', code: `${imports ? imports + '\n\n' : ''}export default function Example() {\n ${reactReturn}\n}` }
167
+ : { language: target, code: script + (target === 'vue' ? `<template>\n${output.body(1)}\n</template>` : [output.snippets(), output.body(0)].filter(Boolean).join('\n\n')) };
87
168
  }
88
169
  return { ...codes, ...example.frameworks };
89
170
  }
package/docs/render.mjs CHANGED
@@ -85,13 +85,13 @@ export function referencePage(component, catalog, cardResource, base) {
85
85
  const owner = catalog.components.find(c => c.examples.some(e => e.id === example.id)) ?? component;
86
86
  // Blank lines let Markupress parse real fences inside the projected HTML slots.
87
87
  // A fence longer than any authored run keeps snippets literal, including nested fences.
88
- const tabs = Object.entries(exampleCodes(example, owner, catalog.components)).map(([mode, value]) => {
88
+ const tabs = Object.entries(exampleCodes(example, owner, [...catalog.resources ?? [], ...catalog.components])).map(([mode, value]) => {
89
89
  const fence = '~'.repeat(Math.max(3, ...[...value.code.matchAll(/~+/g)].map(match => match[0].length + 1)));
90
90
  const language = /^[\w+-]+$/.test(value.language) ? value.language : 'text';
91
91
  return `<section aria-label="${frameworkLabels[mode]}"><div data-theme="dark" style="--ui-surface-sunken: #0d1117">\n\n${fence}${language}\n${value.code}\n${fence}\n\n</div></section>`;
92
92
  }).join('\n');
93
93
  return `<ui-tabs slot="code" label="Example syntax" group="syntax" style="--ui-tabs-panel-padding: 0px">${tabs}</ui-tabs>`;
94
94
  };
95
- const body = `<div class="looma-reference-examples"><ui-stack gap="xl">${examples.map(example => `<ui-card as="section" variant="subtle" padding="lg">${cardMarkup(example, base, catalog.components.find(c => c.examples.some(e => e.id === example.id)) ?? component, { reference: true, code: codes(example) })}</ui-card>`).join('')}</ui-stack></div>`;
95
+ const body = `<div class="looma-reference-examples"><ui-stack gap="xl">${examples.map(example => cardMarkup(example, base, catalog.components.find(c => c.examples.some(e => e.id === example.id)) ?? component, { reference: true, code: codes(example) })).join('')}</ui-stack></div>`;
96
96
  return `---\ntitle: ${JSON.stringify(component.title)}\ndescription: ${JSON.stringify(component.description || `${component.title} component reference.`)}\nid: ${JSON.stringify(component.id)}\n---\n\n# ${escape(component.title)}\n\n<div class="component-description">${descriptionHtml(component.description)}</div>\n\n<link rel="component" href="${cardResource}">\n${exampleResources(examples, catalog)}\n<link rel="component" href="${cardResource.replace(/card\.html$/, 'reference.html')}">\n<link rel="component" href="@threadlabs/looma/components/ui-card/ui-card.html">\n<link rel="component" href="@threadlabs/looma/components/ui-tabs/ui-tabs.html">\n<link rel="component" href="@threadlabs/looma/components/ui-disclosure/ui-disclosure.html">\n<link rel="component" href="@threadlabs/looma/components/ui-stack/ui-stack.html">\n\n<looma-reference>\n\n<div class="looma-reference-tabs"><ui-tabs label="Component reference" style="--ui-tabs-panel-padding: 0px; --ui-tabs-tab-min-block-size: var(--ui-control-size-lg)"><section aria-label="Examples">${body}</section><section aria-label="API"><h2 id="api">API</h2>\n${apiBody(component)}\n${parts.map(part => `<h2 id="${part.tag}-api">${literal(part.title)} API</h2><p>${literal(part.description)}</p>${apiBody(part, part.tag + '-')}`).join('\n')}</section></ui-tabs></div>\n\n</looma-reference>\n`;
97
97
  }
package/docs/site.mjs CHANGED
@@ -88,7 +88,9 @@ export async function prepareDocumentation({ root, config = {}, catalog }) {
88
88
  await writeFile(path.join(generated, 'catalog-view.html'), catalogResource(catalogGroups, base));
89
89
  await cp(own('catalog-view.js'), path.join(generated, 'catalog-view.js'));
90
90
  for (const file of ['reference.html', 'reference.js']) await cp(own(file), path.join(generated, file));
91
- for (const file of ['customizer.js', 'theme.mjs', 'theme-session.mjs', 'value-editors.mjs', 'palette.mjs', 'fonts.mjs']) await cp(own(file), path.join(generated, file));
91
+ for (const file of ['theme.mjs', 'theme-session.mjs', 'value-editors.mjs', 'palette.mjs', 'fonts.mjs']) await cp(own(file), path.join(generated, file));
92
+ // Keep the controller's imports in Looma's package scope, where its runtime dependency lives.
93
+ await writeFile(path.join(generated, 'customizer.js'), `export { connect } from ${JSON.stringify(own('customizer.js'))};\n`);
92
94
  const write = async (file, source) => { await mkdir(path.dirname(file), { recursive: true }); await writeFile(file, source); };
93
95
  const examples = [];
94
96
  // MarkupKit route groups retain their labels/order in navigation without changing public URLs.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@threadlabs/looma",
3
- "version": "0.49.1",
3
+ "version": "0.49.3",
4
4
  "type": "module",
5
5
  "description": "HTML Next UI components, native DOM support and design tokens.",
6
6
  "license": "MIT",
@@ -102,6 +102,7 @@
102
102
  "**/*.css"
103
103
  ],
104
104
  "dependencies": {
105
+ "@nextwebwg/html-next": ">=1.0.0-alpha.74",
105
106
  "dompurify": "3.4.15",
106
107
  "expressmark": ">=0.5.1",
107
108
  "highlight.js": "11.11.2",
@@ -110,7 +111,6 @@
110
111
  "parse5": "^8.0.1"
111
112
  },
112
113
  "peerDependencies": {
113
- "@nextwebwg/html-next": ">=1.0.0-alpha.74",
114
114
  "@threadlabs/markupkit": ">=0.4.2",
115
115
  "@tiptap/core": ">=2 <3",
116
116
  "@tiptap/pm": ">=2 <3",
@@ -135,7 +135,6 @@
135
135
  }
136
136
  },
137
137
  "devDependencies": {
138
- "@nextwebwg/html-next": ">=1.0.0-alpha.74",
139
138
  "@nextwebwg/html-next-unplugin": ">=1.0.0-alpha.76",
140
139
  "@tiptap/core": "^2.11.5",
141
140
  "@tiptap/extension-blockquote": "^2.11.5",
@@ -22,7 +22,7 @@
22
22
  border-radius: var(--ui-selection-radius);
23
23
  color: inherit;
24
24
  cursor: pointer;
25
- text-align: left;
25
+ text-align: start;
26
26
  transition: background-color var(--ui-motion-fast) var(--ui-motion-ease);
27
27
  }
28
28
 
@@ -11,7 +11,9 @@ export interface UiCycleButtonElement extends HTMLSpanElement {
11
11
  removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;
12
12
  }
13
13
  export interface UiCycleButtonProps {
14
+ description?: string | null;
14
15
  disabled?: boolean | null;
16
+ emptyLabel?: string | null;
15
17
  index?: number | null;
16
18
  items: readonly ({ readonly value: string; readonly label: string; readonly icon: string })[];
17
19
  label?: string | null;
@@ -3,10 +3,10 @@ import { attachGeneratedController, stateInitializers, binaryValue, buildTemplat
3
3
  import * as controller from "../components/ui-cycle-button/ui-cycle-button.js";
4
4
  import "../styles/ui-cycle-button.css";
5
5
 
6
- const T0 = ["",[],["ui-icon-button",["tone","neutral","aria-description","Activate to choose the next state."],["ui-icon",[]]]];
6
+ const T0 = ["",[],["ui-icon-button",["tone","neutral"],["ui-icon",[]]]];
7
7
  let P0;
8
8
  const S = { n: ["current","selected"], t: ["n","?"], f: import.meta.url, g: "ui-cycle-button", k: 1, d: { "change": [detailCheck(checkObject([["value", checkString, false], ["index", checkNumber, false]], false)), true, true, false] }, x: dispatchDeclared, r: readonlyView, a: (host, I) => C(host, I), b: generatedInputs };
9
- const D = { g: "ui-cycle-button", props: { "disabled": { "required":false,"default":false, c: checkBoolean, t: "boolean", j: 0, m: "b" }, "index": { "required":false,"default":0, c: checkNumber, t: "number", j: 0, m: "n" }, "items": { "required":true, c: checkList(checkObject([["value", checkString, false], ["label", checkString, false], ["icon", checkString, false]], false)), j: 1, m: ["l",["o",["value","s","label","s","icon","s"]]] }, "label": { "required":false,"default":"State", c: checkString, t: "string", j: 0, m: "s" }, "size": { "required":false,"values":["sm","md","lg"],"default":"md", c: checkFormat("keyword", keywordFormat), t: "keyword", j: 0, m: ["p",formatOf(keywordFormat)] }, "variant": { "required":false,"values":["ghost","outline","solid"],"default":"outline", c: checkFormat("keyword", keywordFormat), t: "keyword", j: 0, m: ["p",formatOf(keywordFormat)] } } };
9
+ const D = { g: "ui-cycle-button", props: { "description": { "required":false,"default":"Activate to choose the next state.", c: checkString, t: "string", j: 0, m: "s" }, "disabled": { "required":false,"default":false, c: checkBoolean, t: "boolean", j: 0, m: "b" }, "emptyLabel": { "required":false,"default":"No choices", c: checkString, t: "string", j: 0, m: "s" }, "index": { "required":false,"default":0, c: checkNumber, t: "number", j: 0, m: "n" }, "items": { "required":true, c: checkList(checkObject([["value", checkString, false], ["label", checkString, false], ["icon", checkString, false]], false)), j: 1, m: ["l",["o",["value","s","label","s","icon","s"]]] }, "label": { "required":false,"default":"State", c: checkString, t: "string", j: 0, m: "s" }, "size": { "required":false,"values":["sm","md","lg"],"default":"md", c: checkFormat("keyword", keywordFormat), t: "keyword", j: 0, m: ["p",formatOf(keywordFormat)] }, "variant": { "required":false,"values":["ghost","outline","solid"],"default":"outline", c: checkFormat("keyword", keywordFormat), t: "keyword", j: 0, m: ["p",formatOf(keywordFormat)] } } };
10
10
  const C = (host) => activateModule(controller, host);
11
11
 
12
12
  export function createUiCycleButton(options, html) {
@@ -18,13 +18,13 @@ export function createUiCycleButton(options, html) {
18
18
  }
19
19
  element.setAttribute("data-component", "ui-cycle-button");
20
20
  element.append((P0 ??= buildTemplate(T0)).cloneNode(true));
21
- const v = [null, undefined, null, null, null, null, null, null];
21
+ const v = [null, undefined, null, null, null, null, null, null, null, null];
22
22
  const B = acceptProps(element, D, S.n, v, componentProps, [], html);
23
23
  const CS = [];
24
- const inputStatus = (j) => { if (j === 0) return E.status(j); if (j >= 1 && j < 2) { g(j); return CS[j] ?? UNRESOLVED_INPUT; } if (j === 2) return awaitInput(B, "disabled", true); if (j === 3) return awaitInput(B, "index", true); if (j === 4) return awaitInput(B, "items", true); if (j === 5) return awaitInput(B, "label", true); if (j === 6) return awaitInput(B, "size", true); if (j === 7) return awaitInput(B, "variant", true); return v[j] === undefined ? UNRESOLVED_INPUT : READY_INPUT; };
24
+ const inputStatus = (j) => { if (j === 0) return E.status(j); if (j >= 1 && j < 2) { g(j); return CS[j] ?? UNRESOLVED_INPUT; } if (j === 2) return awaitInput(B, "description", true); if (j === 3) return awaitInput(B, "disabled", true); if (j === 4) return awaitInput(B, "emptyLabel", true); if (j === 5) return awaitInput(B, "index", true); if (j === 6) return awaitInput(B, "items", true); if (j === 7) return awaitInput(B, "label", true); if (j === 8) return awaitInput(B, "size", true); if (j === 9) return awaitInput(B, "variant", true); return v[j] === undefined ? UNRESOLVED_INPUT : READY_INPUT; };
25
25
  const X = { e: 0, g: (j) => g(j), w: new Set(), a: CS, i: inputStatus };
26
26
  const ke = [];
27
- const K = [() => (checkReference(S, v[0], "n", "expression:default($items[default($current, 0)], $items[0]):current", "Reference `current` must satisfy number.") && checkReference(S, readDeclared(v[4], ["0"]), ["o",["value","s","label","s","icon","s"]], "expression:default($items[default($current, 0)], $items[0]):items.0", "Reference `items.0` must satisfy object({ value: string, label: string, icon: string }).") ? inputDefault(() => readIndex(inputRead(v[4], inputStatus(4)), inputDefault(() => inputRead(E.read(0), inputStatus(0)), () => 0, ABSENT)), () => readIndex(inputRead(v[4], inputStatus(4)), 0), ABSENT) : NONCONFORMING)];
27
+ const K = [() => (checkReference(S, v[0], "n", "expression:default($items[default($current, 0)], $items[0]):current", "Reference `current` must satisfy number.") && checkReference(S, readDeclared(v[6], ["0"]), ["o",["value","s","label","s","icon","s"]], "expression:default($items[default($current, 0)], $items[0]):items.0", "Reference `items.0` must satisfy object({ value: string, label: string, icon: string }).") ? inputDefault(() => readIndex(inputRead(v[6], inputStatus(6)), inputDefault(() => inputRead(E.read(0), inputStatus(0)), () => 0, ABSENT)), () => readIndex(inputRead(v[6], inputStatus(6)), 0), ABSENT) : NONCONFORMING)];
28
28
  const g = (j) => {
29
29
  const i = j - 1;
30
30
  if (ke[i] === X.e) return v[j];
@@ -37,10 +37,10 @@ export function createUiCycleButton(options, html) {
37
37
  if (!Object.is(previous, next)) { v[j] = next; X.n?.(j, previous, next); }
38
38
  return next;
39
39
  };
40
- const E = stateInitializers(S, v, X, { 0: () => inputRead(v[3], inputStatus(3)) });
40
+ const E = stateInitializers(S, v, X, { 0: () => inputRead(v[5], inputStatus(5)) });
41
41
  const p0 = (r, c, d) => {
42
- if (c & 1073741873) {
43
- const x0 = textCall("concat", [v[5], ": ", defaultValue(readFailing(g(1), "label"), "No choices")]);
42
+ if (c & 1073742033) {
43
+ const x0 = textCall("concat", [v[7], ": ", defaultValue(readFailing(g(1), "label"), v[4])]);
44
44
  if (x0 !== NONCONFORMING) {
45
45
  const s0 = toAttribute(x0, "label");
46
46
  if (s0 !== r.v0) writeAttribute(r.a0, "label", r.v0 = s0);
@@ -50,36 +50,41 @@ export function createUiCycleButton(options, html) {
50
50
  if (s1 !== r.v1) writeAttribute(r.a0, "title", r.v1 = s1);
51
51
  }
52
52
  }
53
- if (c & 1073741888) {
54
- const x1 = v[6];
53
+ if (c & 1073742080) {
54
+ const x1 = v[8];
55
55
  const s2 = toAttribute(x1, "size");
56
56
  if (s2 !== r.v2) writeAttribute(r.a0, "size", r.v2 = s2);
57
57
  }
58
- if (c & 1073741952) {
59
- const x2 = v[7];
58
+ if (c & 1073742336) {
59
+ const x2 = v[9];
60
60
  const s3 = toAttribute(x2, "variant");
61
61
  if (s3 !== r.v3) writeAttribute(r.a0, "variant", r.v3 = s3);
62
62
  }
63
- if (c & 1073741844) {
64
- const x3 = (truthy(v[2]) || truthy(binaryValue("<", readMember(v[4], "length"), 2)));
63
+ if (c & 1073741896) {
64
+ const x3 = (truthy(v[3]) || truthy(binaryValue("<", readMember(v[6], "length"), 2)));
65
65
  const s4 = toAttribute(x3, "disabled");
66
66
  if (s4 !== r.v4) writeAttribute(r.a0, "disabled", r.v4 = s4);
67
67
  }
68
- if (c & 1073741841) {
69
- const x4 = defaultValue(readFailing(g(1), "icon"), "");
70
- if (x4 !== NONCONFORMING) {
71
- const s5 = toAttribute(x4, "name");
72
- if (s5 !== r.v5) writeAttribute(r.a1, "name", r.v5 = s5);
68
+ if (c & 4) {
69
+ const x4 = v[2];
70
+ const s5 = toAttribute(x4, "aria-description");
71
+ if (s5 !== r.v5) writeAttribute(r.a0, "aria-description", r.v5 = s5);
72
+ }
73
+ if (c & 1073741889) {
74
+ const x5 = defaultValue(readFailing(g(1), "icon"), "");
75
+ if (x5 !== NONCONFORMING) {
76
+ const s6 = toAttribute(x5, "name");
77
+ if (s6 !== r.v6) writeAttribute(r.a1, "name", r.v6 = s6);
73
78
  }
74
79
  }
75
80
  };
76
81
  const t0 = element.firstChild;
77
82
  const t1 = t0.firstChild;
78
- const R = { a0: t0, a1: t1, v0: null, v1: null, v2: null, v3: null, v4: null, v5: null };
83
+ const R = { a0: t0, a1: t1, v0: null, v1: null, v2: null, v3: null, v4: null, v5: null, v6: null };
79
84
  const I = { B, U: E };
80
85
  I.R = new Set();
81
86
  attachGeneratedController(element, S, v, (c, d) => { ((c, d) => p0(R, c, d))(c, d); for (const f of I.R) f(c, d); }, undefined, X, I);
82
87
  manageProps(I);
83
88
  return element;
84
89
  }
85
- defineComponent("ui-cycle-button", createUiCycleButton, ["disabled","index","items","label","size","variant"]);
90
+ defineComponent("ui-cycle-button", createUiCycleButton, ["description","disabled","emptyLabel","index","items","label","size","variant"]);