@aliens-syndicate/cli 0.1.2 → 0.1.4

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 (39) hide show
  1. package/README.es-ES.md +53 -10
  2. package/README.md +53 -10
  3. package/README.pt-BR.md +53 -10
  4. package/README.zh-CN.md +53 -10
  5. package/package.json +6 -1
  6. package/tools/build.mjs +372 -36
  7. package/tools/cache.mjs +41 -0
  8. package/tools/cli-shared.mjs +237 -0
  9. package/tools/cli.mjs +145 -48
  10. package/tools/create.mjs +207 -78
  11. package/tools/doctor.mjs +139 -0
  12. package/tools/generate.mjs +175 -0
  13. package/tools/icon-docs.mjs +132 -0
  14. package/tools/project-layout.mjs +3 -3
  15. package/tools/runtime.mjs +216 -8
  16. package/tools/serve.mjs +152 -0
  17. package/tools/starter/ai/agents/codingbot.agent +5 -0
  18. package/tools/starter/ai/rules/architecture.rule +12 -0
  19. package/tools/starter/ai/skills/create-element.skill +7 -0
  20. package/tools/starter/app/elements/molecules/kit-card-link/kit-card-link.markup +0 -2
  21. package/tools/starter/app/pages/kit-overview/kit-overview.markup +6 -6
  22. package/tools/starter/app/pages/style-guide/style-guide.style +57 -57
  23. package/tools/starter/styles/components/alerts.style +6 -5
  24. package/tools/starter/styles/components/badges.style +6 -5
  25. package/tools/starter/styles/components/borders.style +2 -1
  26. package/tools/starter/styles/components/buttons.style +14 -13
  27. package/tools/starter/styles/components/cards.style +1 -1
  28. package/tools/starter/styles/components/feedback.style +3 -2
  29. package/tools/starter/styles/components/forms.style +5 -4
  30. package/tools/starter/styles/components/tables.style +4 -3
  31. package/tools/starter/styles/components/typography.style +6 -5
  32. package/tools/starter/styles/generic/ui-base.style +1 -1
  33. package/tools/starter/styles/objects/ui-layout.style +1 -1
  34. package/tools/style-docs.mjs +274 -0
  35. package/tools/update.mjs +110 -0
  36. package/tools/vscode-space/package.json +5 -8
  37. package/tools/vscode-space/space.tmLanguage.json +1 -1
  38. package/tools/vscode-space/syntax.cjs +103 -62
  39. package/tools/watch.mjs +48 -0
@@ -0,0 +1,175 @@
1
+ // aliens generate (g) <kind> <name>: writes Space files that already follow the declaration, folder and name rules.
2
+ import { existsSync } from 'node:fs';
3
+ import { mkdir, readdir, writeFile } from 'node:fs/promises';
4
+ import { dirname, join, relative } from 'node:path';
5
+ import { agentByType, applicationByType, elementLevels } from './project-layout.mjs';
6
+ import {
7
+ CliError, bold, cyan, dim, green, interactive, kebab, parseFlags, pascal, pick, readConfig, requireProject, select,
8
+ ask, validName, yellow
9
+ } from './cli-shared.mjs';
10
+
11
+ const text = {
12
+ en: {
13
+ usage: 'Usage: aliens generate <kind> <name>. Kinds: {kinds}.', kind: 'What do you want to generate?', name: 'Name',
14
+ unknownKind: 'Unknown kind "{kind}". Kinds: {kinds}.', badName: '"{name}" is not a valid name. Use lowercase words separated by hyphens, like hero-card.',
15
+ level: 'Which level is the Element?', needLevel: 'Tell the level in the name, like aliens g element molecules/{name}. Levels: {levels}.',
16
+ badLevel: '"{level}" is not a level. Levels: {levels}.', exists: 'already exists', create: 'CREATE', skip: 'SKIP',
17
+ nothing: 'Nothing to create: every file of {name} already exists.', conflict: '{name} already exists as {other} in {path}. Choose another name.',
18
+ dryRun: 'Dry run: no file was written.', renamed: 'Using the name {name}.',
19
+ useElement: 'Use it in any .markup with the tag {name}.', usePage: 'Add it to project/app/app.route to open it at a path.',
20
+ useFile: 'Run aliens build: ai/.map will list the new file.'
21
+ },
22
+ pt: {
23
+ usage: 'Uso: aliens generate <tipo> <nome>. Tipos: {kinds}.', kind: 'O que você quer gerar?', name: 'Nome',
24
+ unknownKind: 'Tipo desconhecido "{kind}". Tipos: {kinds}.', badName: '"{name}" não é um nome válido. Use palavras minúsculas separadas por hífen, como hero-card.',
25
+ level: 'Em qual nível fica o Element?', needLevel: 'Informe o nível no nome, como aliens g element molecules/{name}. Níveis: {levels}.',
26
+ badLevel: '"{level}" não é um nível. Níveis: {levels}.', exists: 'já existe', create: 'CRIADO', skip: 'IGNORADO',
27
+ nothing: 'Nada para criar: todos os arquivos de {name} já existem.', conflict: '{name} já existe como {other} em {path}. Escolha outro nome.',
28
+ dryRun: 'Simulação: nenhum arquivo foi gravado.', renamed: 'Usando o nome {name}.',
29
+ useElement: 'Use em qualquer .markup com a tag {name}.', usePage: 'Adicione em project/app/app.route para abrir num caminho.',
30
+ useFile: 'Rode aliens build: o ai/.map vai listar o arquivo novo.'
31
+ },
32
+ es: {
33
+ usage: 'Uso: aliens generate <tipo> <nombre>. Tipos: {kinds}.', kind: '¿Qué quieres generar?', name: 'Nombre',
34
+ unknownKind: 'Tipo desconocido "{kind}". Tipos: {kinds}.', badName: '"{name}" no es un nombre válido. Usa palabras en minúsculas separadas por guiones, como hero-card.',
35
+ level: '¿En qué nivel va el Element?', needLevel: 'Indica el nivel en el nombre, como aliens g element molecules/{name}. Niveles: {levels}.',
36
+ badLevel: '"{level}" no es un nivel. Niveles: {levels}.', exists: 'ya existe', create: 'CREADO', skip: 'OMITIDO',
37
+ nothing: 'Nada que crear: todos los archivos de {name} ya existen.', conflict: '{name} ya existe como {other} en {path}. Elige otro nombre.',
38
+ dryRun: 'Simulación: no se escribió ningún archivo.', renamed: 'Usando el nombre {name}.',
39
+ useElement: 'Úsalo en cualquier .markup con la etiqueta {name}.', usePage: 'Agrégala en project/app/app.route para abrirla en una ruta.',
40
+ useFile: 'Ejecuta aliens build: ai/.map listará el archivo nuevo.'
41
+ },
42
+ zh: {
43
+ usage: '用法:aliens generate <类型> <名称>。类型:{kinds}。', kind: '要生成什么?', name: '名称',
44
+ unknownKind: '未知类型“{kind}”。类型:{kinds}。', badName: '“{name}”不是有效名称。请使用以连字符分隔的小写单词,例如 hero-card。',
45
+ level: 'Element 放在哪个层级?', needLevel: '请在名称中写明层级,例如 aliens g element molecules/{name}。层级:{levels}。',
46
+ badLevel: '“{level}”不是层级。层级:{levels}。', exists: '已存在', create: '已创建', skip: '已跳过',
47
+ nothing: '无需创建:{name} 的所有文件都已存在。', conflict: '{name} 已作为 {other} 存在于 {path}。请换一个名称。',
48
+ dryRun: '试运行:没有写入任何文件。', renamed: '使用名称 {name}。',
49
+ useElement: '在任意 .markup 中用标签 {name} 使用它。', usePage: '把它加到 project/app/app.route,即可通过路径打开。',
50
+ useFile: '运行 aliens build:ai/.map 会列出新文件。'
51
+ }
52
+ };
53
+ const t = (key, values = {}) => Object.entries(values).reduce((message, [name, value]) => message.replaceAll(`{${name}}`, value), pick(text)[key]);
54
+
55
+ // Short aliases for the kinds people generate most. The other kinds go by their full name.
56
+ const aliases = { e: 'element', p: 'page', s: 'service', d: 'directive', i: 'interface', m: 'model', v: 'validator', r: 'route' };
57
+ const componentKinds = ['element', 'page'];
58
+ const fileKinds = [...Object.keys(applicationByType), ...Object.keys(agentByType)];
59
+ const kinds = [...componentKinds, ...fileKinds];
60
+ const kindList = () => kinds.map(kind => {
61
+ const alias = Object.entries(aliases).find(([, value]) => value === kind)?.[0];
62
+ return alias ? `${kind} (${alias})` : kind;
63
+ }).join(', ');
64
+ const levelOf = word => elementLevels.find(level => level === word || level === word + 's');
65
+
66
+ const camel = name => name.replace(/-([a-z0-9])/g, (_, letter) => letter.toUpperCase());
67
+
68
+ // Each template matches the shape of the Hero examples, so the file builds as soon as it is written.
69
+ const bodies = {
70
+ markup: name => ` section id="${name}"\n p={${name} works}\n`,
71
+ logic: () => ' import:\n signal: aliens/core\n',
72
+ style: name => ` ${name}\n display: block\n`,
73
+ test: name => ` scenario: ${name} renders\n given: The page shows ${name}\n when: The page opens\n then: ${name} is visible\n`,
74
+ animation: () => ' durationMs: number = 180\n easing: string = "ease-out"\n fromOpacity: number = 0\n toOpacity: number = 1\n',
75
+ api: name => ` method: string = "GET"\n timeoutMs: number = 5000\n\n function path(id: number): string\n return "/api/${name}/" + id\n`,
76
+ directive: name => ` function className(active: boolean): string\n if active\n return "${name}-active"\n return "${name}"\n`,
77
+ enum: () => ' Active: string = "active"\n Inactive: string = "inactive"\n',
78
+ error: name => ` code: string = "${name.replaceAll('-', '_').toUpperCase()}"\n httpStatus: number = 500\n message: string = "${pascal(name)} failed."\n`,
79
+ guard: name => ` guard:\n name: ${name}\n require: authenticated\n redirectTo: home\n`,
80
+ interceptor: name => ` header: string = "X-Request-Id"\n\n function headerValue(id: number): string\n return "${name}-" + id\n`,
81
+ interface: () => ' id: number\n name: string\n',
82
+ mock: () => ' id: number = 1\n name: string = "Example"\n',
83
+ model: () => ' id: number = 0\n name: string = ""\n',
84
+ pipe: () => ' function transform(value: string): string\n return value\n',
85
+ route: name => ` routes:\n ${camel(name)}:\n path: /${name}\n element: ${name}\n`,
86
+ service: name => ` function describe(): string\n return "${name}"\n`,
87
+ storage: name => ` prefix: string = "${name}."\n\n function key(id: number): string\n return prefix + id\n`,
88
+ validator: () => ' function validate(value: string): boolean\n return value.length > 0\n',
89
+ agent: () => ' # Describe what this agent does, which files it reads first and which rules it follows.\n',
90
+ rule: () => ' # Write one rule per comment line, as a plain instruction.\n',
91
+ skill: () => ' # List the steps of this skill, one per comment line.\n'
92
+ };
93
+ const source = (kind, name) => `${pascal(kind)} ${pascal(name)}\n${bodies[kind](name)}`;
94
+
95
+ async function folders(directory) {
96
+ if (!existsSync(directory)) return [];
97
+ const entries = await readdir(directory, { withFileTypes: true });
98
+ const found = await Promise.all(entries.filter(entry => entry.isDirectory()).map(async entry => {
99
+ const path = join(directory, entry.name);
100
+ return [path, ...await folders(path)];
101
+ }));
102
+ return found.flat();
103
+ }
104
+
105
+ export async function generate(args) {
106
+ const { flags, positionals } = parseFlags(args, { booleans: ['dry-run'] });
107
+ if (positionals.length > 2) throw new CliError(t('usage', { kinds: kindList() }));
108
+ const root = requireProject();
109
+ const config = readConfig(root);
110
+ const appDirectory = dirname(config.files?.entry ?? 'project/app/app.logic');
111
+ const agentDirectory = dirname(config.files?.agent ?? 'ai/.map');
112
+
113
+ let [kind, target] = positionals;
114
+ if (!kind) {
115
+ if (!interactive()) throw new CliError(t('usage', { kinds: kindList() }));
116
+ kind = kinds[await select(t('kind'), kinds)];
117
+ }
118
+ kind = aliases[kind] ?? kind;
119
+ if (!kinds.includes(kind)) throw new CliError(t('unknownKind', { kind, kinds: kindList() }));
120
+ if (!target) {
121
+ if (!interactive()) throw new CliError(t('usage', { kinds: kindList() }));
122
+ target = await ask(t('name'), kind === 'element' ? 'molecules/my-element' : `my-${kind}`);
123
+ }
124
+
125
+ const parts = target.split(/[\\/]/).filter(Boolean);
126
+ const name = kebab(parts.pop() ?? '');
127
+ if (!validName(name)) throw new CliError(t('badName', { name: target }));
128
+ if (name !== target.split(/[\\/]/).pop()) console.log(dim(t('renamed', { name })));
129
+
130
+ // Pages and Elements share one namespace: the build stops on two Elements with the same name.
131
+ const componentFolders = [...await folders(join(root, appDirectory, 'pages')), ...await folders(join(root, appDirectory, 'elements'))];
132
+ const existing = componentFolders.find(folder => folder.split(/[\\/]/).pop() === name && !elementLevels.includes(name));
133
+ let files;
134
+ if (kind === 'element' || kind === 'page') {
135
+ let folder;
136
+ if (existing) {
137
+ const other = existing.startsWith(join(root, appDirectory, 'pages')) ? 'page' : 'element';
138
+ if (other !== kind) throw new CliError(t('conflict', { name, other, path: relative(root, existing) }));
139
+ folder = existing;
140
+ } else if (kind === 'page') {
141
+ folder = join(root, appDirectory, 'pages', name);
142
+ } else {
143
+ let level = parts.length ? levelOf(parts[0]) : null;
144
+ if (parts.length && !level) throw new CliError(t('badLevel', { level: parts[0], levels: elementLevels.join(', ') }));
145
+ if (!level) {
146
+ if (!interactive()) throw new CliError(t('needLevel', { name, levels: elementLevels.join(', ') }));
147
+ level = elementLevels[await select(t('level'), elementLevels, 1)];
148
+ }
149
+ folder = join(root, appDirectory, 'elements', level, ...parts.slice(1).map(kebab), name);
150
+ }
151
+ files = ['markup', 'logic', 'style', 'test'].map(extension => [join(folder, `${name}.${extension}`), source(extension, name)]);
152
+ } else {
153
+ const directory = applicationByType[kind] ? join(root, appDirectory, applicationByType[kind]) : join(root, agentDirectory, agentByType[kind]);
154
+ files = [[join(directory, `${name}.${kind}`), source(kind, name)]];
155
+ }
156
+
157
+ const pending = files.filter(([path]) => !existsSync(path));
158
+ for (const [path] of files) {
159
+ const shown = relative(root, path);
160
+ console.log(pending.some(([file]) => file === path) ? `${green(t('create').padEnd(9))}${shown}` : `${yellow(t('skip').padEnd(9))}${shown} ${dim(`(${t('exists')})`)}`);
161
+ }
162
+ if (!pending.length) {
163
+ console.log(t('nothing', { name }));
164
+ return;
165
+ }
166
+ if (flags['dry-run']) {
167
+ console.log(dim(t('dryRun')));
168
+ return;
169
+ }
170
+ for (const [path, content] of pending) {
171
+ await mkdir(dirname(path), { recursive: true });
172
+ await writeFile(path, content, { flag: 'wx' });
173
+ }
174
+ console.log('\n' + (kind === 'element' ? t('useElement', { name: bold(cyan(name)) }) : kind === 'page' ? t('usePage') : t('useFile')));
175
+ }
@@ -0,0 +1,132 @@
1
+ // Generates the Icons page (project/app/pages/icon-docs) from the catalog of the icon package that .config declares
2
+ // under icons: from:. The sidebar lists every category; the runtime fills each one with its icons when the page opens,
3
+ // so the catalog stays out of index.html. Run it after updating the package: node tools/icon-docs.mjs
4
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
5
+ import { createRequire } from 'node:module';
6
+ import { join, resolve } from 'node:path';
7
+ import { pathToFileURL } from 'node:url';
8
+
9
+ const workspace = resolve(import.meta.dirname, '..');
10
+ const config = await readFile(join(workspace, '.config'), 'utf8');
11
+ const from = /^icons:\n(?: {3}.*\n)*? {3}from: (.+)$/m.exec(config)?.[1].trim();
12
+ if (!from) throw new Error('icon-docs: declare the icon package in .config under icons: from:.');
13
+ const entry = /^\.{1,2}\//.test(from) ? join(workspace, from, 'index.mjs') : createRequire(join(workspace, 'package.json')).resolve(from);
14
+ const { createIconRenderer, readCatalog } = await import(pathToFileURL(entry).href);
15
+ const { categories, icons } = await readCatalog();
16
+ const { families } = createIconRenderer();
17
+ const page = join(workspace, 'project/app/pages/icon-docs');
18
+ const total = Object.keys(icons).length;
19
+ const number = value => value.toLocaleString('en-US');
20
+
21
+ const indent = level => ' '.repeat(level);
22
+ const lines = [];
23
+ const add = (level, text) => lines.push(indent(level) + text);
24
+ const title = word => word[0].toUpperCase() + word.slice(1);
25
+
26
+ lines.push('Markup IconDocs');
27
+ add(1, 'article variant="home-view" id="icon-docs" data-view data-search-entry hidden tabindex="-1"');
28
+ add(2, 'aside id="icon-docs-sidebar"');
29
+ add(3, 'div id="icon-docs-finder"');
30
+ add(4, 'form id="icon-docs-finder-form" role="search"');
31
+ add(5, 'label={@iconDocs.searchLabel} for="icon-docs-finder-input" id="icon-docs-finder-label"');
32
+ add(5, 'icon search-01 id="icon-docs-finder-icon"');
33
+ add(5, 'input type="search" id="icon-docs-finder-input" placeholder={@iconDocs.searchPlaceholder} autocomplete="off" spellcheck="false" data-filter');
34
+ add(4, 'p id="icon-docs-finder-status" data-filter-status aria-live="polite" hidden');
35
+ add(5, 'span text="0" id="icon-docs-finder-count" data-filter-count');
36
+ add(5, 'span={@iconDocs.searchResults}');
37
+ add(3, 'nav id="icon-docs-nav" aria-label={@iconDocs.navLabel} data-toc');
38
+ add(4, 'p={@iconDocs.groupStart} variant="icon-docs-nav-title"');
39
+ for (const [anchor, key] of [['overview', 'overviewNav'], ['styles', 'stylesNav'], ['usage', 'usageNav']]) {
40
+ add(4, `a={@iconDocs.${key}} href="#icon-docs-${anchor}" variant="icon-docs-nav-link"`);
41
+ }
42
+ add(4, 'p={@iconDocs.categoriesNav} variant="icon-docs-nav-title"');
43
+ add(4, 'for category in categories');
44
+ add(5, 'a href={$category.href} variant="icon-docs-nav-link"');
45
+ add(6, 'span={$category.label}');
46
+ add(6, 'span={$category.count} variant="icon-docs-nav-count"');
47
+
48
+ add(2, 'div id="icon-docs-main"');
49
+ add(3, 'header id="icon-docs-overview"');
50
+ add(4, 'p variant="home-breadcrumb"');
51
+ add(5, 'a={@nav.home} href="#home-guide"');
52
+ add(5, 'span={/} aria-hidden="true"');
53
+ add(5, 'span={@nav.icons}');
54
+ add(4, 'p={@iconDocs.eyebrow} id="icon-docs-eyebrow"');
55
+ add(4, 'h1={@iconDocs.title} data-search-label');
56
+ add(4, 'p={@iconDocs.lead} variant="home-topic-lead" data-search-summary');
57
+ add(4, 'ul id="icon-docs-stats"');
58
+ for (const [value, key] of [[number(total), 'statIcons'], [String(families.reduce((sum, [, kinds]) => sum + kinds.length, 0)), 'statStyles'],
59
+ [String(categories.length), 'statCategories']]) {
60
+ add(5, 'li');
61
+ add(6, `strong={${value}}`);
62
+ add(6, `span={@iconDocs.${key}}`);
63
+ }
64
+
65
+ // The picker groups the styles as hugeicons.com does: Rounded, Standard and Sharp. The runtime keeps one pressed.
66
+ add(3, 'section variant="icon-docs-block" id="icon-docs-styles"');
67
+ add(4, 'h2={@iconDocs.stylesTitle}');
68
+ add(4, 'p={@iconDocs.stylesDetail} variant="icon-docs-lead"');
69
+ add(4, 'div id="icon-docs-picker" role="group" aria-label={@iconDocs.stylesTitle}');
70
+ for (const [family, kinds] of families) {
71
+ add(5, 'div variant="icon-docs-family"');
72
+ add(6, `span={${title(family)}:} variant="icon-docs-family-label"`);
73
+ add(6, 'div variant="icon-docs-family-styles"');
74
+ for (const kind of kinds) add(7, `button={${title(kind)}} variant="icon-docs-style" data-icon-style="${kind}-${family}" aria-pressed="false"`);
75
+ }
76
+ add(4, 'p={@iconDocs.stylesNote} variant="icon-docs-note"');
77
+
78
+ add(3, 'section variant="icon-docs-block" id="icon-docs-usage"');
79
+ add(4, 'h2={@iconDocs.usageTitle}');
80
+ add(4, 'p={@iconDocs.usageDetail} variant="icon-docs-lead"');
81
+ add(4, 'ol variant="icon-docs-steps"');
82
+ for (const [key, code] of [['usageInstall', 'npm install @aliens-syndicate/icons'], ['usageConfig', null], ['usageVariant', null]]) {
83
+ add(5, 'li');
84
+ add(6, `p={@iconDocs.${key}}`);
85
+ if (code) {
86
+ add(6, 'pre variant="icon-docs-code" tabindex="0"');
87
+ add(7, `code={${code}}`);
88
+ } else if (key === 'usageConfig') {
89
+ add(6, 'pre variant="icon-docs-code" tabindex="0"');
90
+ add(7, 'code');
91
+ add(8, 'span={icons:} variant="icon-docs-code-line"');
92
+ add(8, 'span={ from: @aliens-syndicate/icons} variant="icon-docs-code-line"');
93
+ add(8, 'span variant="icon-docs-code-line"');
94
+ add(9, 'span={ style: }');
95
+ add(9, 'span={stroke-rounded} data-icon-style-name');
96
+ } else {
97
+ add(6, 'pre variant="icon-docs-code" tabindex="0"');
98
+ add(7, 'code');
99
+ add(8, 'span={icon search-01} variant="icon-docs-code-line"');
100
+ add(8, 'span variant="icon-docs-code-line"');
101
+ add(9, 'span={icon search-01 }');
102
+ add(9, 'span={stroke-rounded} data-icon-style-name');
103
+ add(9, 'span={ size-6 blue-600 blue-200}');
104
+ add(8, 'span={icon search-01 disabled} variant="icon-docs-code-line"');
105
+ }
106
+ }
107
+ add(4, 'p={@iconDocs.usageCopy} variant="icon-docs-note"');
108
+
109
+ add(3, 'p={@iconDocs.searchEmpty} id="icon-docs-finder-empty" data-filter-empty hidden');
110
+ add(3, 'p={@iconDocs.loading} id="icon-docs-loading" aria-live="polite"');
111
+ add(3, 'div id="icon-docs-catalog" data-icon-catalog="./icons.json" data-icon-copied={@iconDocs.copied}');
112
+ add(4, 'for category in categories');
113
+ add(5, 'section variant="icon-docs-category" id={$category.anchor} data-filter-group');
114
+ add(6, 'h2');
115
+ add(7, 'span={$category.label}');
116
+ add(7, 'span={$category.count} variant="icon-docs-category-count"');
117
+ add(6, 'ul variant="icon-docs-grid" data-icon-category={$category.key}');
118
+ add(3, 'p id="icon-docs-toast" role="status" aria-live="polite" hidden');
119
+ add(3, 'p={@iconDocs.license} variant="icon-docs-note" id="icon-docs-license"');
120
+
121
+ await mkdir(page, { recursive: true });
122
+ await writeFile(join(page, 'icon-docs.markup'), lines.join('\n') + '\n');
123
+ await writeFile(join(page, 'icon-docs.logic'), `Logic IconDocs
124
+ # Generated by tools/icon-docs.mjs from the catalog of ${from}. Update the package, not this file.
125
+ list categories:
126
+ ${categories.map(({ id, label, icons: names }) => ` ${id}:
127
+ label: ${label}
128
+ count: ${names.length}
129
+ anchor: icon-docs-${id}
130
+ href: #icon-docs-${id}`).join('\n')}
131
+ `);
132
+ console.log(`Icons page generated: ${number(total)} icons in ${categories.length} categories.`);
@@ -1,7 +1,7 @@
1
1
  import { mkdir } from 'node:fs/promises';
2
2
  import { join } from 'node:path';
3
3
 
4
- const applicationByType = {
4
+ export const applicationByType = {
5
5
  animation: 'animations',
6
6
  api: 'apis',
7
7
  directive: 'directives',
@@ -18,13 +18,13 @@ const applicationByType = {
18
18
  storage: 'storage',
19
19
  validator: 'validators'
20
20
  };
21
- const agentByType = { agent: 'agents', rule: 'rules', skill: 'skills' };
21
+ export const agentByType = { agent: 'agents', rule: 'rules', skill: 'skills' };
22
22
 
23
23
  export const namedKinds = new Set([...Object.keys(applicationByType), ...Object.keys(agentByType), 'logic', 'markup', 'style', 'test']);
24
24
  export const sharedDirectory = 'shared';
25
25
  export const exampleMarker = '# Aliens example: Hero';
26
26
  export const styleLayers = ['settings', 'tools', 'generic', 'elements', 'objects', 'components', 'utilities'];
27
- const elementLevels = ['atoms', 'molecules', 'organisms', 'templates'];
27
+ export const elementLevels = ['atoms', 'molecules', 'organisms', 'templates'];
28
28
 
29
29
  export async function createProjectDirectories(workspace) {
30
30
  const directories = [
package/tools/runtime.mjs CHANGED
@@ -38,7 +38,8 @@ function render(instance) {
38
38
  for (const { node, name, read } of current.binds) {
39
39
  const value = read.call(current.state);
40
40
  if (name === 'text') node.textContent = String(value);
41
- if (name === 'show') node.hidden = !value;
41
+ // toggleAttribute also reaches the svg of an icon tag, which has no hidden property.
42
+ if (name === 'show') node.toggleAttribute('hidden', !value);
42
43
  if (name === 'pressed' || name === 'expanded') node.setAttribute('aria-' + name, String(Boolean(value)));
43
44
  if (name.startsWith('_')) node.classList.toggle(node.id + name, Boolean(value));
44
45
  }
@@ -89,13 +90,19 @@ const copyButtons = [...document.querySelectorAll('pre')].map(pre => {
89
90
  frame.className = 'space-copy-frame';
90
91
  button.type = 'button';
91
92
  button.className = 'space-copy';
92
- button.textContent = '⧉';
93
+ // With an icon package in .config the button shows the icons the build drew; without one it shows the word.
94
+ const copy = copyIcons?.copy ?? '';
95
+ const copied = copyIcons?.copied ?? '✓';
96
+ button.innerHTML = copy;
93
97
  let timer;
94
98
  button.addEventListener('click', () => {
95
99
  navigator.clipboard?.writeText(pre.textContent).catch(() => {});
96
- button.textContent = '✓';
100
+ button.innerHTML = copied;
97
101
  clearTimeout(timer);
98
- timer = setTimeout(() => { button.textContent = '⧉'; }, 1600);
102
+ timer = setTimeout(() => {
103
+ button.innerHTML = copy;
104
+ if (!copyIcons) button.textContent = button.title;
105
+ }, 1600);
99
106
  });
100
107
  pre.replaceWith(frame);
101
108
  frame.append(pre, button);
@@ -108,6 +115,7 @@ function applyLocale(locale) {
108
115
  for (const button of copyButtons) {
109
116
  button.setAttribute('aria-label', dictionary['code.copy']);
110
117
  button.title = dictionary['code.copy'];
118
+ if (!copyIcons) button.textContent = dictionary['code.copy'];
111
119
  }
112
120
  document.documentElement.lang = locale;
113
121
  document.title = dictionary['site.title'];
@@ -144,8 +152,8 @@ function applyTheme(name, persist = false) {
144
152
  if (persist) savePreference(themeKey, theme);
145
153
  }
146
154
 
147
- // Short fragments from older links: #agent opens type-index-agent, #logic opens logic-guide.
148
- const shortViews = new Map([['home', 'home-guide'], ['logic', 'logic-guide'], ['markup', 'markup-reference']]);
155
+ // Short fragments from older links: #logic opens logic-guide, #mock opens type-index-mock.
156
+ const shortViews = new Map([['home', 'home-guide'], ['logic', 'logic-guide'], ['markup', 'markup-reference'], ['search', 'site-search']]);
149
157
  const legacyViews = new Map([...shortViews, ['style-kit', 'kit-overview'], ['styles', 'type-index-style'], ['mockup', 'type-index-mock']]);
150
158
  // The search shows a view by its short name: type-index-agent is .agent, logic-guide is .logic.
151
159
  function shortName(id) {
@@ -232,13 +240,193 @@ function setupSearch(form) {
232
240
 
233
241
  const searchForm = document.querySelector('[data-doc-search]');
234
242
  const refreshSearch = searchForm && setupSearch(searchForm);
243
+
244
+ // A field with data-filter filters its view while the reader types. Each [data-filter-group] stays when its heading
245
+ // or lead matches every word, showing all its [data-filter-item]s, or when some of its items match, showing only those.
246
+ // A group without items matches by its whole text. A [data-filter-set] stays while one of its groups stays, and the
247
+ // links of a [data-toc] follow the sections they point to.
248
+ function setupFilter(input) {
249
+ const view = input.closest('[data-view]') ?? document.body;
250
+ const form = input.closest('form');
251
+ const status = view.querySelector('[data-filter-status]');
252
+ const count = view.querySelector('[data-filter-count]');
253
+ const empty = view.querySelector('[data-filter-empty]');
254
+ const toc = view.querySelector('[data-toc]');
255
+ const text = element => normalizeSearch(element?.textContent ?? '');
256
+ const heading = element => text(element.querySelector('h2, h3')) + ' ' + text(element.querySelector(':scope > p'));
257
+
258
+ function refresh() {
259
+ const terms = normalizeSearch(input.value).split(/\s+/).filter(Boolean);
260
+ const matches = value => terms.every(term => value.includes(term));
261
+ let total = 0;
262
+ for (const group of view.querySelectorAll('[data-filter-group]')) {
263
+ const items = [...group.querySelectorAll('[data-filter-item]')];
264
+ if (!terms.length) {
265
+ group.hidden = false;
266
+ for (const item of items) item.hidden = false;
267
+ continue;
268
+ }
269
+ const set = group.closest('[data-filter-set]');
270
+ const titled = matches(heading(group)) || Boolean(set && matches(text(set.querySelector('h2'))));
271
+ if (items.length) {
272
+ let shown = 0;
273
+ for (const item of items) {
274
+ item.hidden = !titled && !matches(text(item));
275
+ if (!item.hidden) shown++;
276
+ }
277
+ group.hidden = shown === 0;
278
+ total += shown;
279
+ } else {
280
+ group.hidden = !titled && !matches(text(group));
281
+ if (!group.hidden) total++;
282
+ }
283
+ }
284
+ for (const set of view.querySelectorAll('[data-filter-set]')) {
285
+ set.hidden = terms.length > 0 && !set.querySelector('[data-filter-group]:not([hidden])');
286
+ }
287
+ if (toc) {
288
+ let title = null;
289
+ let titleHasLinks = false;
290
+ const closeTitle = () => { if (title) title.hidden = !titleHasLinks; };
291
+ for (const child of toc.children) {
292
+ if (child.tagName !== 'A') {
293
+ closeTitle();
294
+ title = child;
295
+ titleHasLinks = false;
296
+ continue;
297
+ }
298
+ const target = child.hash && view.querySelector(child.hash);
299
+ child.hidden = Boolean(target?.closest('[hidden]') && target.closest('[data-view]') === view);
300
+ if (!child.hidden) titleHasLinks = true;
301
+ }
302
+ closeTitle();
303
+ }
304
+ if (count) count.textContent = String(total);
305
+ if (status) status.hidden = !terms.length;
306
+ if (empty) empty.hidden = !terms.length || total > 0;
307
+ // The first section left by the search comes into view when the reader is past it or below it.
308
+ const first = terms.length && view.querySelector('[data-filter-group]:not([hidden])');
309
+ if (first) {
310
+ const { top } = first.getBoundingClientRect();
311
+ if (top < 0 || top > window.innerHeight) first.scrollIntoView();
312
+ }
313
+ }
314
+
315
+ input.addEventListener('input', refresh);
316
+ form?.addEventListener('submit', event => {
317
+ event.preventDefault();
318
+ view.querySelector('[data-filter-group]:not([hidden])')?.scrollIntoView();
319
+ });
320
+ input.addEventListener('keydown', event => {
321
+ if (event.key !== 'Escape' || !input.value) return;
322
+ event.preventDefault();
323
+ input.value = '';
324
+ refresh();
325
+ });
326
+ return refresh;
327
+ }
328
+ const filterRefreshers = [...document.querySelectorAll('[data-filter]')].map(setupFilter);
329
+
330
+ // A [data-icon-catalog] lists the icons of the package that .config declares. It loads the catalog the first time its
331
+ // view opens, draws each [data-icon-category] list with the icons of that category, and redraws them in the style of
332
+ // the pressed [data-icon-style] button. A click on an icon copies the markup that shows it.
333
+ const iconStyleKey = 'aliens-docs-icon-style';
334
+ function setupIconCatalog(root) {
335
+ const view = root.closest('[data-view]') ?? document.body;
336
+ const buttons = [...view.querySelectorAll('[data-icon-style]')];
337
+ const names = [...view.querySelectorAll('[data-icon-style-name]')];
338
+ const loading = view.querySelector('#icon-docs-loading');
339
+ const toast = view.querySelector('#icon-docs-toast');
340
+ const saved = preference(iconStyleKey);
341
+ let style = iconRenderer.styles.includes(saved) ? saved : iconStyle;
342
+ let icons = null;
343
+ let state = 'idle';
344
+ let toastTimer;
345
+
346
+ function paint() {
347
+ for (const button of buttons) button.setAttribute('aria-pressed', String(button.dataset.iconStyle === style));
348
+ for (const name of names) name.textContent = style;
349
+ if (!icons) return;
350
+ let index = 0;
351
+ for (const glyph of root.querySelectorAll('[data-icon]')) {
352
+ glyph.firstElementChild.outerHTML = iconRenderer.svg(icons[glyph.dataset.icon], style, 'catalog' + index++)
353
+ .replace('<svg ', '<svg aria-hidden="true" focusable="false" ');
354
+ }
355
+ }
356
+
357
+ async function load() {
358
+ if (state !== 'idle') return;
359
+ state = 'loading';
360
+ try {
361
+ const catalog = await fetch(root.dataset.iconCatalog).then(response => {
362
+ if (!response.ok) throw new Error(response.statusText);
363
+ return response.json();
364
+ });
365
+ icons = catalog.icons;
366
+ const lists = new Map([...root.querySelectorAll('[data-icon-category]')].map(list => [list.dataset.iconCategory, list]));
367
+ for (const { id, icons: members } of catalog.categories) {
368
+ lists.get(id)?.replaceChildren(...members.map(name => {
369
+ const item = document.createElement('li');
370
+ const button = document.createElement('button');
371
+ const label = document.createElement('span');
372
+ item.dataset.filterItem = '';
373
+ button.type = 'button';
374
+ button.dataset.icon = name;
375
+ button.title = name;
376
+ label.textContent = name;
377
+ button.append(document.createElement('svg'), label);
378
+ item.append(button);
379
+ return item;
380
+ }));
381
+ }
382
+ state = 'ready';
383
+ if (loading) loading.hidden = true;
384
+ paint();
385
+ for (const refreshFilter of filterRefreshers) refreshFilter();
386
+ } catch {
387
+ state = 'idle';
388
+ if (loading) loading.textContent = 'The icon catalog could not be loaded.';
389
+ }
390
+ }
391
+
392
+ view.addEventListener('click', event => {
393
+ const choice = event.target.closest('[data-icon-style]');
394
+ if (choice && view.contains(choice)) {
395
+ style = choice.dataset.iconStyle;
396
+ savePreference(iconStyleKey, style);
397
+ paint();
398
+ return;
399
+ }
400
+ const icon = event.target.closest('[data-icon]');
401
+ if (!icon || !root.contains(icon)) return;
402
+ const markup = style === iconStyle ? `icon ${icon.dataset.icon}` : `icon ${icon.dataset.icon} ${style}`;
403
+ navigator.clipboard?.writeText(markup).catch(() => {});
404
+ for (const copied of root.querySelectorAll('[data-copied]')) delete copied.dataset.copied;
405
+ icon.dataset.copied = '';
406
+ if (toast) {
407
+ toast.textContent = `${root.dataset.iconCopied} ${markup}`;
408
+ toast.hidden = false;
409
+ clearTimeout(toastTimer);
410
+ toastTimer = setTimeout(() => {
411
+ toast.hidden = true;
412
+ delete icon.dataset.copied;
413
+ }, 1800);
414
+ }
415
+ });
416
+ paint();
417
+ return { load, visible: () => !view.hidden };
418
+ }
419
+ const iconCatalogs = iconRenderer ? [...document.querySelectorAll('[data-icon-catalog]')].map(setupIconCatalog) : [];
235
420
  // ⌘K on Apple devices, Ctrl+K elsewhere, focuses the documentation search from anywhere on the page.
236
421
  const searchShortcut = document.getElementById('doc-search-shortcut');
237
422
  if (searchShortcut && !/Mac|iPhone|iPad/.test(navigator.platform)) searchShortcut.textContent = 'Ctrl K';
423
+ // When the search lives in its own view, the shortcut opens that view first.
238
424
  document.addEventListener('keydown', event => {
239
425
  if (!searchForm || event.key.toLowerCase() !== 'k' || !(event.metaKey || event.ctrlKey)) return;
240
426
  event.preventDefault();
241
- searchForm.querySelector('input').focus();
427
+ const view = searchForm.closest('[data-view]');
428
+ if (view?.hidden) location.hash = view.id;
429
+ else searchForm.querySelector('input').focus();
242
430
  });
243
431
  const views = [...document.querySelectorAll('[data-view]')];
244
432
  const navigation = [...document.querySelectorAll('[data-nav]')];
@@ -257,13 +445,32 @@ function showView({ scroll = false } = {}) {
257
445
  const requested = target?.closest('[data-view]') ?? views[0];
258
446
  for (const view of views) view.hidden = view !== requested;
259
447
  for (const link of navigation) {
260
- if (link.hash === '#' + requested?.id) link.setAttribute('aria-current', 'page');
448
+ // A short fragment such as #search marks its link as current like the full view id does.
449
+ if (link.hash === '#' + requested?.id || shortViews.get(link.hash.slice(1)) === requested?.id) link.setAttribute('aria-current', 'page');
261
450
  else link.removeAttribute('aria-current');
262
451
  }
452
+ // A table of contents (data-toc) marks the link to the section in the address as the current location.
453
+ for (const link of document.querySelectorAll('[data-toc] a')) {
454
+ if (link.hash !== location.hash || !location.hash) {
455
+ link.removeAttribute('aria-current');
456
+ continue;
457
+ }
458
+ link.setAttribute('aria-current', 'location');
459
+ // Keeps the current link visible inside a scrolling table of contents, without moving the page.
460
+ let box = link.parentElement;
461
+ while (box && box !== document.body && box.scrollHeight <= box.clientHeight) box = box.parentElement;
462
+ if (box && box !== document.body) {
463
+ const offset = link.getBoundingClientRect().top - box.getBoundingClientRect().top;
464
+ if (offset < 0 || offset > box.clientHeight - link.offsetHeight) box.scrollTop += offset - box.clientHeight / 2;
465
+ }
466
+ }
263
467
  if (scroll && target && !target.closest('[hidden]')) {
264
468
  target.scrollIntoView();
265
469
  target.focus({ preventScroll: true });
266
470
  }
471
+ // A view that holds the search focuses its field, ready to type.
472
+ requested?.querySelector('[data-doc-search] input')?.focus({ preventScroll: true });
473
+ for (const catalog of iconCatalogs) if (catalog.visible()) catalog.load();
267
474
  }
268
475
 
269
476
  document.addEventListener('click', event => {
@@ -278,6 +485,7 @@ document.addEventListener('click', event => {
278
485
  const updatedLocale = localeModel.state[localeField];
279
486
  applyLocale(updatedLocale);
280
487
  refreshSearch?.();
488
+ for (const refreshFilter of filterRefreshers) refreshFilter();
281
489
  savePreference(localeKey, updatedLocale);
282
490
  }
283
491
  if (handler === themeModel) {