@rickycourtes/designrail 0.0.0-stage → 0.2.1
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/CHANGELOG.md +42 -0
- package/LICENSE +21 -0
- package/README.md +890 -2
- package/bin/designrail.js +11 -0
- package/kit/changes.json +23 -0
- package/kit/foundation.css +24 -0
- package/kit/foundation.js +4 -0
- package/kit/parts/base.css +34 -0
- package/kit/parts/button.css +85 -0
- package/kit/parts/card.css +35 -0
- package/kit/parts/dropdown.css +55 -0
- package/kit/parts/dropdown.js +38 -0
- package/kit/parts/field.css +67 -0
- package/kit/parts/pill.css +40 -0
- package/kit/parts/sheet.css +43 -0
- package/kit/parts/toast.css +40 -0
- package/kit/parts/toast.js +32 -0
- package/kit/tokens.css +110 -0
- package/package.json +52 -4
- package/rules/DESIGN.md +70 -0
- package/schema.json +100 -0
- package/src/audit.js +217 -0
- package/src/check.js +141 -0
- package/src/cli.js +261 -0
- package/src/contract.js +67 -0
- package/src/css.js +135 -0
- package/src/extract.js +271 -0
- package/src/fix.js +104 -0
- package/src/index.js +16 -0
- package/src/init.js +47 -0
- package/src/kit.js +99 -0
- package/src/markup.js +94 -0
- package/src/model.js +128 -0
- package/src/project.js +180 -0
- package/src/report.js +104 -0
- package/src/sources.js +145 -0
- package/src/specimens.js +94 -0
- package/src/tokens.js +55 -0
- package/src/trace.js +42 -0
- package/src/upgrade.js +69 -0
- package/src/values.js +204 -0
- package/src/worker.js +11 -0
package/src/cli.js
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
// designrail <command> [dir] [flags]. Flags are checked: a guessed one exits 2.
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { loadProject, VERSION } from './project.js';
|
|
5
|
+
import { buildModel } from './model.js';
|
|
6
|
+
import { audit } from './audit.js';
|
|
7
|
+
import { extract, toCss, toDtcg } from './extract.js';
|
|
8
|
+
import { planFix, applyFix } from './fix.js';
|
|
9
|
+
import { hits, baselines, added } from './check.js';
|
|
10
|
+
import { traceSelector, traceToken } from './trace.js';
|
|
11
|
+
import { specimens } from './specimens.js';
|
|
12
|
+
import { PARTS, partAbout, ejectParts } from './kit.js';
|
|
13
|
+
import { planUpgrade, applyUpgrade } from './upgrade.js';
|
|
14
|
+
import { saveConfig } from './project.js';
|
|
15
|
+
import { init } from './init.js';
|
|
16
|
+
import { auditText, auditHtml, hitsText, bold, dim, green, red, yellow, cyan } from './report.js';
|
|
17
|
+
|
|
18
|
+
const HELP = `${bold('designrail')} ${VERSION}: a design system for any web project, from what it already has.
|
|
19
|
+
|
|
20
|
+
${bold('designrail init')} [dir] [--agents] config + DESIGN.md (+ a pointer in CLAUDE.md/AGENTS.md)
|
|
21
|
+
${bold('designrail audit')} [dir] [--html f] health score, value sprawl, duplicate CSS and markup, parts drawn twice
|
|
22
|
+
${bold('designrail scan')} [dir] what was read and how fast
|
|
23
|
+
${bold('designrail extract')} [dir] [--dry] token files from the values the project already uses
|
|
24
|
+
${bold('designrail fix')} [dir] [--write] [--snap] hardcoded values → the tokens that hold them (a preview unless --write)
|
|
25
|
+
${bold('designrail check')} [dir] [--staged | --base REF] [--install-hook]
|
|
26
|
+
the drift gate; with git, only what a change adds
|
|
27
|
+
${bold('designrail trace')} <selector | --token> [-C dir] a value down its token chain, or a token's reach
|
|
28
|
+
${bold('designrail specimens')} [dir] [--out f] one page with every token and part
|
|
29
|
+
${bold('designrail upgrade')} [dir] [--write] move to the installed foundation: renames rewritten, changes listed
|
|
30
|
+
${bold('designrail eject')} <part…> [-C dir] copy a foundation part in to own it (it stops getting updates)
|
|
31
|
+
${bold('designrail kit')} list the foundation's parts
|
|
32
|
+
|
|
33
|
+
--json machine output --no-cache reparse everything --all every hit, not the first few
|
|
34
|
+
`;
|
|
35
|
+
|
|
36
|
+
const FLAGS = {
|
|
37
|
+
init: { '--agents': 0, '--force': 0 },
|
|
38
|
+
audit: { '--html': 1, '--limit': 1 },
|
|
39
|
+
scan: {},
|
|
40
|
+
extract: { '--dry': 0, '--force': 0, '--out': 1 },
|
|
41
|
+
fix: { '--write': 0, '--snap': 0, '--limit': 1 },
|
|
42
|
+
check: { '--staged': 0, '--base': 1, '--install-hook': 0 },
|
|
43
|
+
trace: { '-C': 1 },
|
|
44
|
+
specimens: { '--out': 1 },
|
|
45
|
+
eject: { '-C': 1, '--force': 0, '--dry': 0 },
|
|
46
|
+
upgrade: { '--write': 0 },
|
|
47
|
+
kit: {},
|
|
48
|
+
};
|
|
49
|
+
const COMMON = { '--json': 0, '--no-cache': 0, '--all': 0, '--help': 0, '-h': 0 };
|
|
50
|
+
|
|
51
|
+
function parse(argv) {
|
|
52
|
+
const [cmd = 'help', ...rest] = argv;
|
|
53
|
+
if (cmd === '--version' || cmd === '-v') return { cmd: 'version' };
|
|
54
|
+
if (cmd === 'help' || cmd === '--help' || cmd === '-h') return { cmd: 'help' };
|
|
55
|
+
if (cmd === 'add') fail('add is now eject: the foundation already holds every part; import @rickycourtes/designrail/foundation.css, or eject <part> to own a copy');
|
|
56
|
+
if (!FLAGS[cmd]) fail(`unknown command "${cmd}"`);
|
|
57
|
+
const spec = { ...COMMON, ...FLAGS[cmd] };
|
|
58
|
+
const flags = {}, pos = [];
|
|
59
|
+
for (let i = 0; i < rest.length; i++) {
|
|
60
|
+
const a = rest[i];
|
|
61
|
+
if (a in spec) flags[a] = spec[a] ? rest[++i] ?? fail(`${a} needs a value`) : true;
|
|
62
|
+
else if (a.startsWith('--') && cmd === 'trace') pos.push(a);
|
|
63
|
+
else if (a.startsWith('-')) fail(`unknown flag ${a} for ${cmd} (designrail --help)`);
|
|
64
|
+
else pos.push(a);
|
|
65
|
+
}
|
|
66
|
+
return { cmd, flags, pos };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function fail(msg) {
|
|
70
|
+
process.stderr.write(`${red('error')} ${msg}\n`);
|
|
71
|
+
process.exit(2);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const say = (s = '') => process.stdout.write(s + '\n');
|
|
75
|
+
|
|
76
|
+
export async function main(argv) {
|
|
77
|
+
const { cmd, flags = {}, pos = [] } = parse(argv);
|
|
78
|
+
if (cmd === 'help' || flags['--help'] || flags['-h']) return say(HELP);
|
|
79
|
+
if (cmd === 'version') return say(VERSION);
|
|
80
|
+
const json = flags['--json'];
|
|
81
|
+
const all = flags['--all'];
|
|
82
|
+
const dirArg = ['trace', 'eject'].includes(cmd) ? flags['-C'] ?? '.' : pos[0] ?? '.';
|
|
83
|
+
const root = path.resolve(dirArg);
|
|
84
|
+
if (!fs.existsSync(root)) fail(`no such directory ${root}`);
|
|
85
|
+
const load = async () => buildModel(await loadProject(root, { cache: !flags['--no-cache'] }));
|
|
86
|
+
|
|
87
|
+
if (cmd === 'kit') {
|
|
88
|
+
if (json) return say(JSON.stringify(Object.fromEntries(Object.entries(PARTS).map(([n, f]) => [n, { files: f, about: partAbout(n) }]))));
|
|
89
|
+
say(bold('Foundation parts') + dim(" · all in @rickycourtes/designrail/foundation.css; designrail eject <part> copies one to own it"));
|
|
90
|
+
for (const n of Object.keys(PARTS)) say(` ${cyan(n.padEnd(10))} ${partAbout(n)}`);
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
if (cmd === 'init') {
|
|
95
|
+
const done = init(root, { agents: flags['--agents'], force: flags['--force'] });
|
|
96
|
+
say(done.length ? `${green('wrote')} ${done.join(', ')}` : dim('nothing to do (already set up; --force rewrites)'));
|
|
97
|
+
const { findFoundation, loadConfig } = await import('./project.js');
|
|
98
|
+
const f = findFoundation(root, loadConfig(root));
|
|
99
|
+
if (f) say(`${bold('Foundation')} ${f.version}${f.installed ? '' : dim(' (declared, not installed: npm install)')}. Load it before your own styles:\n ${cyan("@import '@rickycourtes/designrail/foundation.css';")} ${dim('then your token files, then your parts')}\n ${cyan("import { dropdowns, toast } from '@rickycourtes/designrail/foundation.js';")}`);
|
|
100
|
+
else say(dim('To build on the foundation: npm i -D @rickycourtes/designrail, then designrail init again.'));
|
|
101
|
+
say(dim('next: designrail audit'));
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const model = await load();
|
|
106
|
+
|
|
107
|
+
if (cmd === 'scan') {
|
|
108
|
+
const by = {};
|
|
109
|
+
for (const f of model.files) { const e = f.path.split('.').pop(); by[e] = (by[e] ?? 0) + 1; }
|
|
110
|
+
const out = { ...model.stats, foundation: model.foundation?.version ?? null, byType: by, tokenFiles: [...model.tokenFiles], tokens: [...model.defs.keys()].length, designValues: model.slots, fromTokens: model.tokenized, literals: model.occ.length };
|
|
111
|
+
if (json) return say(JSON.stringify(out));
|
|
112
|
+
say(`${bold(model.stats.files)} files in ${bold(model.stats.ms + 'ms')} ${dim(`(${model.stats.parsed} parsed, ${model.stats.cached} from cache)`)}`);
|
|
113
|
+
say(dim(' ' + Object.entries(by).sort((a, b) => b[1] - a[1]).map(([e, n]) => `${e} ${n}`).join(' · ')));
|
|
114
|
+
say(`${out.tokens} custom properties, ${out.tokenFiles.length} token files ${dim(out.tokenFiles.join(', '))}`);
|
|
115
|
+
say(model.foundation ? `foundation ${model.foundation.version}${model.cfg.foundation && model.cfg.foundation !== model.foundation.version ? yellow(` (project is on ${model.cfg.foundation}: designrail upgrade)`) : ''}${model.foundation.installed ? '' : dim(' (not installed)')}` : dim('no foundation (npm i -D @rickycourtes/designrail)'));
|
|
116
|
+
say(`${out.fromTokens}/${out.designValues} design values read a token · ${out.literals} literals outside token files`);
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
if (cmd === 'audit') {
|
|
121
|
+
const a = audit(model);
|
|
122
|
+
if (flags['--html']) { fs.writeFileSync(path.resolve(flags['--html']), auditHtml(a, model)); }
|
|
123
|
+
if (json) {
|
|
124
|
+
const strip = (x) => JSON.parse(JSON.stringify(x, (k, v) => (v instanceof Set ? [...v] : k === 'facts' ? undefined : v)));
|
|
125
|
+
return say(JSON.stringify(strip({ score: a.score, breakdown: a.breakdown, colors: { distinct: a.colors.items.length, near: a.colors.near.map((g) => g.members.map((m) => m.value)) }, scales: Object.fromEntries(Object.entries(a.scales).map(([k, s]) => [k, { values: s.items.map((i) => [i.value, i.count]), offGrid: s.offGrid.map((i) => i.value) }])), duplicates: a.blocks.groups.map((g) => g.rules.map((r) => `${r.file}:${r.line} ${r.sel}`)), near: a.blocks.near.map((n) => [`${n.a.file}:${n.a.line} ${n.a.sel}`, `${n.b.file}:${n.b.line} ${n.b.sel}`, +n.similarity.toFixed(2)]), parts: a.parts, markup: a.markup })));
|
|
126
|
+
}
|
|
127
|
+
say(auditText(a, model, { limit: all ? 1e9 : Number(flags['--limit'] ?? 6) }));
|
|
128
|
+
if (flags['--html']) say(`\n${green('wrote')} ${flags['--html']}`);
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
if (cmd === 'extract') {
|
|
133
|
+
if (model.tokenFiles.size && !flags['--force'] && !flags['--out']) {
|
|
134
|
+
say(`${yellow('already has tokens')} in ${[...model.tokenFiles].join(', ')}.`);
|
|
135
|
+
say(dim('designrail fix maps literals onto them; --out <dir> writes a fresh set elsewhere, --force overwrites.'));
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
const t = extract(model);
|
|
139
|
+
const dir = flags['--out'] ?? path.dirname(model.cfg.tokens[0]);
|
|
140
|
+
const header = (kind) => `/* Designrail ${kind}: ${kind === 'primitives' ? 'raw values, named for what they ARE. Only token files and the --space-/--radius-/--font-size- steps read these.' : 'what each value is FOR. Parts and pages read these; a theme re-points them.'}\n Extracted from ${path.basename(root)} by designrail extract. Edit freely: fix and check read whatever is here. */`;
|
|
141
|
+
const files = { [path.join(dir, 'primitives.css')]: toCss(t.primitives, header('primitives')), [path.join(dir, 'semantic.css')]: toCss(t.semantic, header('semantic')), [path.join(dir, 'tokens.json')]: toDtcg(t) };
|
|
142
|
+
if (json) return say(JSON.stringify({ primitives: t.primitives, semantic: t.semantic, dark: t.dark }));
|
|
143
|
+
if (flags['--dry']) { for (const [f, text] of Object.entries(files)) say(`${bold(f)}\n${text}`); return; }
|
|
144
|
+
for (const [f, text] of Object.entries(files)) { fs.mkdirSync(path.join(root, path.dirname(f)), { recursive: true }); fs.writeFileSync(path.join(root, f), text); }
|
|
145
|
+
const derived = t.semantic.filter((s) => s.note?.startsWith('derived')).length;
|
|
146
|
+
say(`${green('wrote')} ${Object.keys(files).join(', ')}`);
|
|
147
|
+
say(` ${t.primitives.length} primitives, ${t.semantic.length} semantic tokens ${dim(`(${derived} derived from the contract, the rest found in the project)`)}`);
|
|
148
|
+
say(dim(` import ${path.join(dir, 'primitives.css')} then semantic.css before your styles; next: designrail fix`));
|
|
149
|
+
if (!model.cfg.exists) say(dim(' no designrail.config.json yet: designrail init records where the tokens live'));
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
if (cmd === 'fix') {
|
|
154
|
+
const plan = planFix(model, { snap: flags['--snap'] });
|
|
155
|
+
const total = [...plan.edits.values()].reduce((a, l) => a + l.length, 0);
|
|
156
|
+
if (json) return say(JSON.stringify({ edits: Object.fromEntries([...plan.edits].map(([f, l]) => [f, l.map(({ line, from, text }) => ({ line, from, to: text }))])), missed: Object.fromEntries(Object.entries(plan.missed).map(([k, m]) => [k, Object.fromEntries(m)])) }));
|
|
157
|
+
if (!plan.tokens) { say(`${yellow('no tokens')} to map onto. Run ${bold('designrail extract')} first, or point "tokens" in designrail.config.json at your token files.`); return; }
|
|
158
|
+
const limit = all ? Infinity : Number(flags['--limit'] ?? 12);
|
|
159
|
+
for (const [f, list] of plan.edits) {
|
|
160
|
+
say(bold(f) + dim(` · ${list.length}`));
|
|
161
|
+
for (const e of list.slice(0, limit)) say(` ${dim(String(e.line).padStart(4))} ${red(e.from)} → ${green(e.text)}${e.exact ? '' : yellow(' snapped')}`);
|
|
162
|
+
if (list.length > limit) say(dim(` … ${list.length - limit} more`));
|
|
163
|
+
}
|
|
164
|
+
const missed = Object.entries(plan.missed).map(([k, m]) => `${k} ${m.size}`).join(', ');
|
|
165
|
+
if (flags['--write']) { const n = applyFix(root, plan.edits); say(`\n${green('rewrote')} ${n} values in ${plan.edits.size} files`); }
|
|
166
|
+
else say(`\n${bold(total)} values in ${plan.edits.size} files map to tokens. ${dim('designrail fix --write applies them.')}`);
|
|
167
|
+
if (missed) say(dim(`No token holds: ${missed} distinct values${flags['--snap'] ? '' : ' (--snap maps ones within ' + model.cfg.snap + 'px of a step)'}. Add them to the token files, or run designrail extract --out.`));
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
if (cmd === 'check') {
|
|
172
|
+
if (flags['--install-hook']) {
|
|
173
|
+
const hook = path.join(root, '.git', 'hooks', 'pre-commit');
|
|
174
|
+
if (!fs.existsSync(path.join(root, '.git'))) fail('not a git repository');
|
|
175
|
+
const line = 'npx --no-install designrail check --staged || exit 1';
|
|
176
|
+
const now = fs.existsSync(hook) ? fs.readFileSync(hook, 'utf8') : '#!/bin/sh\n';
|
|
177
|
+
if (!now.includes('designrail check')) { fs.writeFileSync(hook, now.trimEnd() + '\n' + line + '\n'); fs.chmodSync(hook, 0o755); }
|
|
178
|
+
say(`${green('installed')} .git/hooks/pre-commit: ${dim(line)}`);
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
let list, title;
|
|
182
|
+
if (flags['--staged'] || flags['--base']) {
|
|
183
|
+
const b = baselines(model, { base: flags['--base'] ?? 'HEAD', staged: flags['--staged'] });
|
|
184
|
+
list = added(hits(b.then), hits(b.now));
|
|
185
|
+
title = `${list.length} new hit${list.length === 1 ? '' : 's'} in ${b.changed.length} changed file${b.changed.length === 1 ? '' : 's'} (against ${flags['--base'] ?? 'HEAD'})`;
|
|
186
|
+
} else {
|
|
187
|
+
list = hits(model);
|
|
188
|
+
title = `${list.length} hit${list.length === 1 ? '' : 's'} in the whole project`;
|
|
189
|
+
}
|
|
190
|
+
const errors = list.filter((h) => h.level === 'error');
|
|
191
|
+
if (json) say(JSON.stringify({ errors: errors.length, warnings: list.length - errors.length, hits: list }));
|
|
192
|
+
else {
|
|
193
|
+
if (list.length) say(hitsText(list, { title, limit: all ? Infinity : 8 }));
|
|
194
|
+
say(errors.length ? red(bold(`✗ ${errors.length} error${errors.length === 1 ? '' : 's'}`)) + dim(' · designrail fix rewrites hardcoded values that have a token') : green(bold('✓ check passed')) + (list.length ? dim(` · ${list.length} warnings`) : ''));
|
|
195
|
+
}
|
|
196
|
+
process.exitCode = errors.length ? 1 : 0;
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
if (cmd === 'trace') {
|
|
201
|
+
const q = pos[0] ?? fail('trace needs a selector (.btn) or a token (--accent)');
|
|
202
|
+
if (q.startsWith('--')) {
|
|
203
|
+
const t = traceToken(model, q);
|
|
204
|
+
if (json) return say(JSON.stringify(t));
|
|
205
|
+
say(bold(q));
|
|
206
|
+
for (const s of t.chain) say(` ${s.missing ? red(s.name + ' (defined nowhere)') : s.runtime ? yellow(s.name + ' (set from JS)') : `${cyan(s.name)}: ${s.value} ${dim(s.at)}`}`);
|
|
207
|
+
if (t.builtOn.length) say(`${dim('built on it:')} ${t.builtOn.join(', ')}`);
|
|
208
|
+
say(`${dim('read in')} ${t.uses.length} place${t.uses.length === 1 ? '' : 's'}${t.reach.length > 1 ? dim(` (through ${t.reach.length - 1} tokens built on it)`) : ''}`);
|
|
209
|
+
for (const u of t.uses.slice(0, all ? Infinity : 20)) say(` ${dim(`${u.file}:${u.line}`)}${u.via !== q ? dim(` via ${u.via}`) : ''}`);
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
const rs = traceSelector(model, q);
|
|
213
|
+
if (json) return say(JSON.stringify(rs));
|
|
214
|
+
if (!rs.length) say(dim(`no rule matches ${q}`));
|
|
215
|
+
for (const r of rs) {
|
|
216
|
+
say(`${cyan(r.sel)}${r.media ? dim(' ' + r.media) : ''} ${dim(r.at)}`);
|
|
217
|
+
for (const d of r.decls) {
|
|
218
|
+
say(` ${d.prop}: ${d.value}`);
|
|
219
|
+
for (const ch of d.chains) say(` ${ch.map((s, i) => (s.missing ? red(`${s.name} ✗`) : s.runtime ? yellow(`${s.name} (JS)`) : `${s.name}${i === ch.length - 1 ? ` = ${bold(s.value)}` : ''} ${dim(s.at)}`)).join(dim(' → '))}`);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
if (cmd === 'specimens') {
|
|
226
|
+
const out = path.resolve(root, flags['--out'] ?? '.designrail/specimens.html');
|
|
227
|
+
fs.mkdirSync(path.dirname(out), { recursive: true });
|
|
228
|
+
fs.writeFileSync(out, specimens(model));
|
|
229
|
+
say(`${green('wrote')} ${path.relative(process.cwd(), out)}`);
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
if (cmd === 'eject') {
|
|
234
|
+
if (!pos.length) fail(`eject needs a part: ${Object.keys(PARTS).join(', ')}`);
|
|
235
|
+
let r;
|
|
236
|
+
try { r = ejectParts(model, pos, { force: flags['--force'], dry: flags['--dry'] }); } catch (e) { fail(e.message); }
|
|
237
|
+
if (json) return say(JSON.stringify(r));
|
|
238
|
+
for (const f of r.copied) say(`${green(flags['--dry'] ? 'would copy' : 'copied')} ${f}`);
|
|
239
|
+
for (const f of r.skipped) say(`${yellow('kept')} ${f} ${dim('(exists; --force replaces)')}`);
|
|
240
|
+
if (r.missing.length) say(`${green(flags['--dry'] ? 'would add' : 'added')} ${r.missing.length} tokens to ${r.tokenFile}: ${dim(r.missing.map(([n]) => n).join(' '))}`);
|
|
241
|
+
say(dim(model.foundation ? 'Import the copy after @rickycourtes/designrail/foundation.css. It no longer follows foundation updates; designrail upgrade names it when the foundation\'s version moves on.' : 'Import the CSS once (and the .js where there is one).'));
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
if (cmd === 'upgrade') {
|
|
246
|
+
const plan = planUpgrade(model);
|
|
247
|
+
if (!plan) fail('no foundation here: npm i -D @rickycourtes/designrail, then designrail init');
|
|
248
|
+
if (json) return say(JSON.stringify({ ...plan, edits: Object.fromEntries([...plan.edits].map(([f, e]) => [f, e.count])), added: Object.fromEntries(Object.entries(plan.added).map(([k, v]) => [k, [...v]])), removed: Object.fromEntries(Object.entries(plan.removed).map(([k, v]) => [k, [...v]])) }));
|
|
249
|
+
say(`${bold('Foundation')} ${plan.from} → ${bold(plan.to)}${plan.current ? dim(' · already current') : ''}`);
|
|
250
|
+
for (const s of plan.steps) say(` ${cyan(s.version)} ${s.notes ?? ''}`);
|
|
251
|
+
if (plan.renames.length) say(`${bold('Renamed')} ${plan.renames.map(([a, b]) => `${a} → ${b}`).join(', ')}`);
|
|
252
|
+
for (const [f, e] of plan.edits) say(` ${dim(f)} ${e.count} rename${e.count === 1 ? '' : 's'}`);
|
|
253
|
+
const list = (label, set) => set.size && say(`${bold(label)} ${[...set].join(', ')}`);
|
|
254
|
+
list('New parts', plan.added.parts); list('New tokens', plan.added.tokens); list('New classes', plan.added.classes);
|
|
255
|
+
if (plan.stillRead.length) say(`${red('Removed but still read:')} ${plan.stillRead.join(', ')}`);
|
|
256
|
+
if (plan.drifted.length) say(`${yellow('Ejected parts that no longer match the foundation:')} ${plan.drifted.join(', ')} ${dim('(diff them against node_modules/@rickycourtes/designrail/kit/parts)')}`);
|
|
257
|
+
if (flags['--write']) { applyUpgrade(root, plan); saveConfig(root, { foundation: plan.to }); say(`${green('upgraded')} to ${plan.to}${plan.edits.size ? `, ${plan.edits.size} files rewritten` : ''}; now run designrail check`); }
|
|
258
|
+
else if (!plan.current) say(dim('designrail upgrade --write applies the renames and records the version.'));
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
}
|
package/src/contract.js
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
// The semantic vocabulary: what `extract` names a project's values and what
|
|
2
|
+
// every kit part reads. A project that defines these can take any part as is.
|
|
3
|
+
// `derive` is the fallback when a project has no value of its own for one.
|
|
4
|
+
|
|
5
|
+
export const CONTRACT = [
|
|
6
|
+
// colour: surfaces and fills
|
|
7
|
+
{ name: '--surface', group: 'colour', role: 'bg', about: 'The page and the plainest box.' },
|
|
8
|
+
{ name: '--surface-raised', group: 'colour', role: 'bg', about: 'A card, menu or sheet over the page.', derive: 'var(--surface)' },
|
|
9
|
+
{ name: '--surface-sunken', group: 'colour', role: 'bg', about: 'A well: code, a tray, an inset field.', derive: 'color-mix(in oklab, var(--surface), var(--text) 4%)' },
|
|
10
|
+
{ name: '--surface-scrim', group: 'colour', role: 'bg', about: 'Dims the page behind a dialog.', derive: 'color-mix(in srgb, #000 45%, transparent)' },
|
|
11
|
+
{ name: '--fill', group: 'colour', role: 'bg', about: 'A control at rest: one shade off what it sits on.', derive: 'color-mix(in srgb, var(--text) 6%, transparent)' },
|
|
12
|
+
{ name: '--fill-hover', group: 'colour', role: 'bg', about: 'The next shade, under the pointer.', derive: 'color-mix(in srgb, var(--text) 10%, transparent)' },
|
|
13
|
+
{ name: '--fill-press', group: 'colour', role: 'bg', about: 'Pressed or selected.', derive: 'color-mix(in srgb, var(--text) 14%, transparent)' },
|
|
14
|
+
// colour: text
|
|
15
|
+
{ name: '--text', group: 'colour', role: 'text', about: 'Body text.' },
|
|
16
|
+
{ name: '--text-muted', group: 'colour', role: 'text', about: 'Secondary text: hints, meta.', derive: 'color-mix(in oklab, var(--text) 70%, var(--surface))' },
|
|
17
|
+
{ name: '--text-faint', group: 'colour', role: 'text', about: 'Placeholders and disabled.', derive: 'color-mix(in oklab, var(--text) 45%, var(--surface))' },
|
|
18
|
+
{ name: '--text-on-accent', group: 'colour', role: 'text', about: 'Text on an accent fill.' },
|
|
19
|
+
// colour: lines and states
|
|
20
|
+
{ name: '--border', group: 'colour', role: 'border', about: 'A quiet rim or divider.', derive: 'color-mix(in oklab, var(--text) 13%, var(--surface))' },
|
|
21
|
+
{ name: '--border-strong', group: 'colour', role: 'border', about: 'A field rim, a rim that must read.', derive: 'color-mix(in oklab, var(--text) 25%, var(--surface))' },
|
|
22
|
+
{ name: '--accent', group: 'colour', role: 'any', about: 'The one accent: go, selected, primary.' },
|
|
23
|
+
{ name: '--accent-hover', group: 'colour', role: 'any', about: 'The accent under the pointer.', derive: 'color-mix(in oklab, var(--accent), var(--text) 14%)' },
|
|
24
|
+
{ name: '--danger', group: 'colour', role: 'any', about: 'Something went wrong or will be lost.', derive: '#dc2626' },
|
|
25
|
+
{ name: '--success', group: 'colour', role: 'any', about: 'Something worked.', derive: '#16a34a' },
|
|
26
|
+
{ name: '--warning', group: 'colour', role: 'any', about: 'Careful.', derive: '#d97706' },
|
|
27
|
+
{ name: '--focus', group: 'colour', role: 'any', about: 'The keyboard focus ring.', derive: 'var(--accent)' },
|
|
28
|
+
// type
|
|
29
|
+
{ name: '--font-ui', group: 'type', about: 'Every label and paragraph.', derive: "system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif" },
|
|
30
|
+
{ name: '--font-display', group: 'type', about: 'Headings.', derive: 'var(--font-ui)' },
|
|
31
|
+
{ name: '--font-mono', group: 'type', about: 'Code.', derive: "ui-monospace, 'SF Mono', Menlo, Consolas, monospace" },
|
|
32
|
+
{ name: '--font-size-small', group: 'type', about: 'Hints, captions, pills.', derive: '13px' },
|
|
33
|
+
{ name: '--font-size-body', group: 'type', about: 'Body and controls.', derive: '15px' },
|
|
34
|
+
{ name: '--font-size-title', group: 'type', about: 'A card or sheet title.', derive: '20px' },
|
|
35
|
+
{ name: '--weight-strong', group: 'type', about: 'Labels on buttons, titles.', derive: '600' },
|
|
36
|
+
// shape
|
|
37
|
+
{ name: '--radius-control', group: 'shape', about: 'Buttons and fields.', derive: '8px' },
|
|
38
|
+
{ name: '--radius-card', group: 'shape', about: 'Cards, menus, sheets. Inner radius = this − padding.', derive: '12px' },
|
|
39
|
+
{ name: '--radius-full', group: 'shape', about: 'Pills and round buttons.', derive: '999px' },
|
|
40
|
+
{ name: '--control-h', group: 'shape', about: 'Every control’s height; 44px is a whole fingertip.', derive: '44px' },
|
|
41
|
+
{ name: '--shadow-raised', group: 'shape', about: 'A card off the page.', derive: '0 1px 2px rgb(0 0 0 / 0.08), 0 2px 8px rgb(0 0 0 / 0.06)' },
|
|
42
|
+
{ name: '--shadow-overlay', group: 'shape', about: 'A menu, toast or dialog over everything.', derive: '0 8px 32px rgb(0 0 0 / 0.18)' },
|
|
43
|
+
// motion
|
|
44
|
+
{ name: '--duration-fast', group: 'motion', about: 'Hover and press.', derive: '120ms' },
|
|
45
|
+
{ name: '--duration-base', group: 'motion', about: 'Open and close.', derive: '220ms' },
|
|
46
|
+
{ name: '--ease-out', group: 'motion', about: 'Things arriving.', derive: 'cubic-bezier(0.2, 0, 0, 1)' },
|
|
47
|
+
];
|
|
48
|
+
|
|
49
|
+
// The spacing steps every part uses directly (a step on the grid says all a gap needs).
|
|
50
|
+
export const KIT_SPACE = [4, 6, 8, 12, 16, 24];
|
|
51
|
+
|
|
52
|
+
// What a semantic name is for, from its name, so `fix` can pick the token
|
|
53
|
+
// whose job matches the property it is replacing in.
|
|
54
|
+
export function roleOfName(name) {
|
|
55
|
+
if (/surface|(^|-)bg|background|fill|scrim|canvas|panel/.test(name)) return 'bg';
|
|
56
|
+
if (/text|(^|-)fg|ink|foreground|copy|label/.test(name)) return 'text';
|
|
57
|
+
if (/border|rim|line|divider|outline|stroke|hairline/.test(name)) return 'border';
|
|
58
|
+
return 'any';
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function roleOfProp(prop) {
|
|
62
|
+
if (/^background/.test(prop)) return 'bg';
|
|
63
|
+
if (prop === 'color' || prop === 'caret-color' || prop.startsWith('text-decoration')) return 'text';
|
|
64
|
+
if (/^(border|outline|column-rule)/.test(prop)) return 'border';
|
|
65
|
+
if (prop === 'fill' || prop === 'stroke') return 'text';
|
|
66
|
+
return 'any';
|
|
67
|
+
}
|
package/src/css.js
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
// A small, forgiving CSS reader: rules, nesting (SCSS, Less, native) and
|
|
2
|
+
// at-rules, every declaration with its value's offsets in the source so `fix`
|
|
3
|
+
// can rewrite it in place. Pure: no fs. Never throws on bad input.
|
|
4
|
+
|
|
5
|
+
// Comments become spaces (offsets kept). `//` line comments only where the
|
|
6
|
+
// dialect has them, never inside a string or url().
|
|
7
|
+
export function blankComments(text, lineComments = false) {
|
|
8
|
+
let out = '';
|
|
9
|
+
let i = 0;
|
|
10
|
+
let quote = '';
|
|
11
|
+
while (i < text.length) {
|
|
12
|
+
const c = text[i];
|
|
13
|
+
if (quote) {
|
|
14
|
+
out += c;
|
|
15
|
+
if (c === '\\') { out += text[i + 1] ?? ''; i += 2; continue; }
|
|
16
|
+
if (c === quote || c === '\n') quote = '';
|
|
17
|
+
i++;
|
|
18
|
+
continue;
|
|
19
|
+
}
|
|
20
|
+
if (c === '"' || c === "'") { quote = c; out += c; i++; continue; }
|
|
21
|
+
if (c === '/' && text[i + 1] === '*') {
|
|
22
|
+
const end = text.indexOf('*/', i + 2);
|
|
23
|
+
const stop = end < 0 ? text.length : end + 2;
|
|
24
|
+
out += text.slice(i, stop).replace(/[^\n]/g, ' ');
|
|
25
|
+
i = stop;
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
if (lineComments && c === '/' && text[i + 1] === '/' && !/url\(\s*['"]?[\w.:-]*$/i.test(text.slice(Math.max(0, i - 40), i)) && text[i - 1] !== ':') {
|
|
29
|
+
const end = text.indexOf('\n', i);
|
|
30
|
+
const stop = end < 0 ? text.length : end;
|
|
31
|
+
out += ' '.repeat(stop - i);
|
|
32
|
+
i = stop;
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
out += c;
|
|
36
|
+
i++;
|
|
37
|
+
}
|
|
38
|
+
return out;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export const splitTop = (s) => {
|
|
42
|
+
const parts = [];
|
|
43
|
+
let depth = 0, start = 0;
|
|
44
|
+
for (let i = 0; i < s.length; i++) {
|
|
45
|
+
const c = s[i];
|
|
46
|
+
if (c === '(' || c === '[') depth++;
|
|
47
|
+
else if (c === ')' || c === ']') depth--;
|
|
48
|
+
else if (c === ',' && depth === 0) { parts.push(s.slice(start, i)); start = i + 1; }
|
|
49
|
+
}
|
|
50
|
+
parts.push(s.slice(start));
|
|
51
|
+
return parts.map((p) => p.trim()).filter(Boolean);
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
function resolveSelector(child, parent) {
|
|
55
|
+
const kids = splitTop(child.replace(/\s+/g, ' '));
|
|
56
|
+
if (!parent) return kids.join(', ');
|
|
57
|
+
const parents = splitTop(parent);
|
|
58
|
+
return parents.flatMap((p) => kids.map((k) => (k.includes('&') ? k.replace(/&/g, p) : `${p} ${k}`))).join(', ');
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const lineAt = (lines, i) => {
|
|
62
|
+
let lo = 0, hi = lines.length - 1;
|
|
63
|
+
while (lo < hi) { const mid = (lo + hi + 1) >> 1; if (lines[mid] <= i) lo = mid; else hi = mid - 1; }
|
|
64
|
+
return lo + 1;
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
export function lineStarts(text) {
|
|
68
|
+
const starts = [0];
|
|
69
|
+
for (let i = 0; i < text.length; i++) if (text.charCodeAt(i) === 10) starts.push(i + 1);
|
|
70
|
+
return starts;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// → { rules: [{ sel, media, line, decls: [{ prop, value, line, vstart, vend }] }], media: [query] }
|
|
74
|
+
// `base` shifts every offset (CSS embedded in a larger file); `inline` reads a
|
|
75
|
+
// bare declaration list (style="", css`` bodies) as one rule named `inline`.
|
|
76
|
+
export function parseCss(text, { base = 0, starts, lineComments = false, inline = null } = {}) {
|
|
77
|
+
const bare = blankComments(text, lineComments);
|
|
78
|
+
starts ??= lineStarts(text);
|
|
79
|
+
const at = (i) => lineAt(starts, i + base);
|
|
80
|
+
const rules = [];
|
|
81
|
+
const stack = [{ sel: inline, media: [], rule: null }];
|
|
82
|
+
const top = () => stack[stack.length - 1];
|
|
83
|
+
const ruleOf = (ctx) => {
|
|
84
|
+
if (!ctx.rule && ctx.sel) { ctx.rule = { sel: ctx.sel, media: ctx.media.join(' and ') || null, line: ctx.line ?? at(0), decls: [] }; rules.push(ctx.rule); }
|
|
85
|
+
return ctx.rule;
|
|
86
|
+
};
|
|
87
|
+
let start = 0, depth = 0, quote = '';
|
|
88
|
+
|
|
89
|
+
const statement = (end) => {
|
|
90
|
+
const raw = bare.slice(start, end);
|
|
91
|
+
const m = /^(\s*)(-?-?[a-zA-Z][\w-]*|--[\w-]+)(\s*):/.exec(raw);
|
|
92
|
+
if (m && top().sel && !/^\s*@/.test(raw)) {
|
|
93
|
+
const colon = m[0].length;
|
|
94
|
+
let vs = start + colon, ve = end;
|
|
95
|
+
while (vs < ve && /\s/.test(bare[vs])) vs++;
|
|
96
|
+
while (ve > vs && /\s/.test(bare[ve - 1])) ve--;
|
|
97
|
+
let value = text.slice(vs, ve);
|
|
98
|
+
const imp = /\s*!important\s*$/i.exec(bare.slice(vs, ve));
|
|
99
|
+
if (imp) { ve -= imp[0].length; value = text.slice(vs, ve); }
|
|
100
|
+
if (value) ruleOf(top()).decls.push({ prop: m[2].toLowerCase(), value, line: at(start + m[1].length), vstart: vs + base, vend: ve + base });
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
for (let i = 0; i < bare.length; i++) {
|
|
105
|
+
const c = bare[i];
|
|
106
|
+
if (quote) { if (c === '\\') i++; else if (c === quote) quote = ''; continue; }
|
|
107
|
+
if (c === '"' || c === "'") { quote = c; continue; }
|
|
108
|
+
if (c === '(') { depth++; continue; }
|
|
109
|
+
if (c === ')') { depth = Math.max(0, depth - 1); continue; }
|
|
110
|
+
if (depth) continue;
|
|
111
|
+
if (c === ';') { statement(i); start = i + 1; }
|
|
112
|
+
else if (c === '{') {
|
|
113
|
+
const header = bare.slice(start, i).trim().replace(/\s+/g, ' ');
|
|
114
|
+
const parent = top();
|
|
115
|
+
const lead = start + (bare.slice(start, i).length - bare.slice(start, i).trimStart().length);
|
|
116
|
+
if (header.startsWith('@')) {
|
|
117
|
+
const media = /^@(media|container|supports|layer)\b/.test(header) ? [...parent.media, header] : parent.media;
|
|
118
|
+
// @keyframes, @font-face and the like hold no selectors of ours.
|
|
119
|
+
const sel = /^@(media|container|supports|layer|scope)\b/.test(header) ? parent.sel : /^@font-face/.test(header) ? '@font-face' : null;
|
|
120
|
+
stack.push({ sel, media, rule: null, line: at(lead), skip: !sel && !/^@(media|container|supports|layer)/.test(header) });
|
|
121
|
+
} else if (parent.skip) {
|
|
122
|
+
stack.push({ sel: null, media: parent.media, rule: null, skip: true });
|
|
123
|
+
} else {
|
|
124
|
+
stack.push({ sel: resolveSelector(header, parent.sel === inline ? null : parent.sel) || inline, media: parent.media, rule: null, line: at(lead) });
|
|
125
|
+
}
|
|
126
|
+
start = i + 1;
|
|
127
|
+
} else if (c === '}') {
|
|
128
|
+
statement(i);
|
|
129
|
+
if (stack.length > 1) stack.pop();
|
|
130
|
+
start = i + 1;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
statement(bare.length);
|
|
134
|
+
return { rules };
|
|
135
|
+
}
|