@rickycourtes/designrail 0.2.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +103 -0
- package/README.md +146 -34
- package/kit/changes.json +157 -7
- package/kit/parts/base.css +6 -2
- package/kit/parts/button.css +65 -13
- package/kit/parts/card.css +16 -1
- package/kit/parts/dropdown.css +16 -5
- package/kit/parts/field.css +48 -9
- package/kit/parts/pill.css +35 -11
- package/kit/parts/sheet.css +36 -9
- package/kit/parts/toast.css +22 -6
- package/kit/tokens.css +3 -0
- package/package.json +2 -1
- package/rules/DESIGN.md +7 -2
- package/schema.json +21 -2
- package/src/audit.js +76 -31
- package/src/check.js +45 -4
- package/src/cli.js +7 -0
- package/src/contract.js +2 -0
- package/src/css.js +8 -1
- package/src/fix.js +6 -2
- package/src/init.js +26 -5
- package/src/model.js +5 -5
- package/src/project.js +38 -4
- package/src/report.js +2 -2
- package/src/sources.js +7 -1
- package/src/specimens.js +5 -0
- package/src/tokens.js +15 -5
package/src/audit.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// blocks and markup repeat, and which parts are drawn more than one way.
|
|
3
3
|
import { colorFacts, colorDistance } from './values.js';
|
|
4
4
|
import { declSet } from './model.js';
|
|
5
|
+
import { inParts, isSpecimen } from './project.js';
|
|
5
6
|
|
|
6
7
|
const STYLE_ORIGINS = new Set(['css', 'style', 'css-in-js']);
|
|
7
8
|
|
|
@@ -50,7 +51,16 @@ export function scaleOf(model, cat) {
|
|
|
50
51
|
const STATE = /^(display|visibility|opacity|pointer-events|transition(-[\w-]+)?|transform|z-index|cursor)$/;
|
|
51
52
|
const IGNORE_SEL = /^(@font-face|style@|css@|styled@|keyframes@|createGlobalStyle@|injectGlobal@)/;
|
|
52
53
|
|
|
54
|
+
// Selectors that differ only by vendor pseudo-elements (::-webkit-slider-thumb,
|
|
55
|
+
// ::-moz-range-thumb, ::placeholder) cannot share one selector list: a browser
|
|
56
|
+
// drops the whole list over the one it does not know.
|
|
57
|
+
const VENDOR = /::?-(webkit|moz|ms|o)-[\w-]+/;
|
|
58
|
+
const pseudoless = (sel) => sel.replace(/::?-(webkit|moz|ms|o)-[\w-]+|::[\w-]+/g, '::*').replace(/\s+/g, ' ');
|
|
59
|
+
export const unmergeable = (a, b) => a.sel !== b.sel && (VENDOR.test(a.sel) || VENDOR.test(b.sel)) && pseudoless(a.sel) === pseudoless(b.sel);
|
|
60
|
+
|
|
53
61
|
export function duplicateBlocks(model, colors = colorsOf(model)) {
|
|
62
|
+
// The copy-paste floor: rules must share this many declarations to count.
|
|
63
|
+
const min = Math.max(2, model.cfg.duplicates?.minDeclarations ?? 3);
|
|
54
64
|
const colorMap = new Map();
|
|
55
65
|
for (const g of colors.groups) for (const m of g.members) colorMap.set(m.value, g.centre.value);
|
|
56
66
|
const rules = [];
|
|
@@ -60,8 +70,10 @@ export function duplicateBlocks(model, colors = colorsOf(model)) {
|
|
|
60
70
|
if (!STYLE_ORIGINS.has(r.origin) || !r.sel || IGNORE_SEL.test(r.sel)) continue;
|
|
61
71
|
if (r.decls.every((d) => STATE.test(d.prop) || d.prop.startsWith('--'))) continue;
|
|
62
72
|
const set = declSet(r, colorMap);
|
|
63
|
-
//
|
|
64
|
-
|
|
73
|
+
// Below `min` declarations two rules agreeing is a coincidence (two token
|
|
74
|
+
// reads make a type role), not a copied block; a 2 floor still leaves state
|
|
75
|
+
// rules (:hover, :focus…) out at two.
|
|
76
|
+
if (set.length >= Math.max(3, min) || (min <= 2 && set.length === 2 && !/:(?!:)/.test(r.sel.replace(/:(is|where|not|has)\(/g, '')))) rules.push({ file: f.path, sel: r.sel, line: r.line, media: r.media, set });
|
|
65
77
|
}
|
|
66
78
|
}
|
|
67
79
|
const exact = new Map();
|
|
@@ -70,7 +82,9 @@ export function duplicateBlocks(model, colors = colorsOf(model)) {
|
|
|
70
82
|
if (!exact.has(k)) exact.set(k, []);
|
|
71
83
|
exact.get(k).push(r);
|
|
72
84
|
}
|
|
73
|
-
|
|
85
|
+
// A group counts when two of its rules could be one: another selector or file, and not vendor twins.
|
|
86
|
+
const mergeable = (g) => g.some((a, i) => g.some((b, j) => j > i && (a.file !== b.file || a.sel !== b.sel) && !unmergeable(a, b)));
|
|
87
|
+
const groups = [...exact.values()].filter((g) => g.length > 1 && mergeable(g))
|
|
74
88
|
.map((g) => ({ rules: g, decls: g[0].set })).sort((a, b) => b.rules.length * b.decls.length - a.rules.length * a.decls.length);
|
|
75
89
|
const inExact = new Set(groups.flatMap((g) => g.rules));
|
|
76
90
|
|
|
@@ -91,13 +105,13 @@ export function duplicateBlocks(model, colors = colorsOf(model)) {
|
|
|
91
105
|
}
|
|
92
106
|
for (const [j, shared] of counts) {
|
|
93
107
|
const o = rules[j];
|
|
94
|
-
if (o.sel === r.sel) continue;
|
|
108
|
+
if (o.sel === r.sel || unmergeable(r, o)) continue;
|
|
95
109
|
if (inExact.has(r) && inExact.has(o) && r.set.join() === o.set.join()) continue;
|
|
96
110
|
const jac = shared / (r.set.length + o.set.length - shared);
|
|
97
111
|
const pair = [rep.get(r) ?? r, rep.get(o) ?? o];
|
|
98
112
|
const pk = rules.indexOf(pair[0]) + ':' + rules.indexOf(pair[1]);
|
|
99
113
|
if (pair[0] === pair[1] || seenPair.has(pk)) continue;
|
|
100
|
-
if (shared >= 3 && r.set.length >= 3 && o.set.length >= 3 && jac >= 0.6 && seenPair.add(pk)) near.push({ a: r, b: o, shared, similarity: jac, diff: [...r.set.filter((d) => !o.set.includes(d)), ...o.set.filter((d) => !r.set.includes(d))] });
|
|
114
|
+
if (shared >= Math.max(3, min) && r.set.length >= 3 && o.set.length >= 3 && jac >= 0.6 && seenPair.add(pk)) near.push({ a: r, b: o, shared, similarity: jac, diff: [...r.set.filter((d) => !o.set.includes(d)), ...o.set.filter((d) => !r.set.includes(d))] });
|
|
101
115
|
}
|
|
102
116
|
});
|
|
103
117
|
near.sort((x, y) => y.similarity * y.shared - x.similarity * x.shared);
|
|
@@ -117,35 +131,66 @@ export const ROLES = {
|
|
|
117
131
|
const STRUCTURE = /^(group|groups|wrap|wrapper|container|list|row|rows|col|grid|icon|label|text|title|header|footer|body|content|inner|outer|area|bar|nav|item|items|close|overlay|backdrop|trigger|toggle|arrow|caret|link|image|img|actions|section|holder|box)$/;
|
|
118
132
|
const PAINT = /^(background|background-color|border|border-color|border-radius|padding|padding-inline|padding-block|box-shadow|color)$/;
|
|
119
133
|
|
|
134
|
+
// A class or element at the end of each selector in a rule, with the role its name suggests.
|
|
135
|
+
function roleHits(sel) {
|
|
136
|
+
const out = [];
|
|
137
|
+
for (const part of sel.split(',')) {
|
|
138
|
+
const last = part.trim().split(/[\s>+~]+/).pop() ?? '';
|
|
139
|
+
const classes = [...last.matchAll(/\.([\w-]+)/g)].map((m) => m[1]).filter((c) => !c.includes('__'));
|
|
140
|
+
const el = /^(button|input|select|textarea|dialog)\b/.exec(last)?.[1];
|
|
141
|
+
for (const c of classes) {
|
|
142
|
+
const words = c.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase().split(/[-_]+/).filter(Boolean);
|
|
143
|
+
const k = words.findIndex((w) => Object.values(ROLES).some((re) => re.test(w)));
|
|
144
|
+
const role = k < 0 || words.slice(k + 1).some((w) => STRUCTURE.test(w)) ? null : Object.keys(ROLES).find((n) => ROLES[n].test(words[k]));
|
|
145
|
+
const family = role && c.split('--')[0].replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase().split(/[-_]+/).slice(0, k + 1).join('-');
|
|
146
|
+
out.push({ cls: c, role, family });
|
|
147
|
+
}
|
|
148
|
+
if (el && !classes.length) out.push({ cls: `<${el}>`, el: true, role: { input: 'field', select: 'field', textarea: 'field' }[el] ?? el, family: `<${el}>` });
|
|
149
|
+
}
|
|
150
|
+
return out;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// The role a part file is, from its name (field.css, value-field.css, sheets.css).
|
|
154
|
+
export function roleOfFile(file) {
|
|
155
|
+
const words = file.split('/').pop().replace(/\.[^.]+$/, '').replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase().split(/[-_.]+/).filter(Boolean);
|
|
156
|
+
for (const w of [...words].reverse()) {
|
|
157
|
+
const role = Object.keys(ROLES).find((n) => ROLES[n].test(w) || ROLES[n].test(w.replace(/s$/, '')));
|
|
158
|
+
if (role) return role;
|
|
159
|
+
}
|
|
160
|
+
return null;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// Parts by role. Inside the `parts` folder a file is one part, so one family,
|
|
164
|
+
// whatever its classes are called; its role comes from the file's name, and a
|
|
165
|
+
// file whose name is no role (profile.css) is a part of its own, not a redraw.
|
|
166
|
+
// A class a part file defines stays that part's wherever else it is styled.
|
|
167
|
+
// Elsewhere, class names say the role and family.
|
|
120
168
|
export function redraws(model) {
|
|
121
169
|
const roles = {};
|
|
170
|
+
const skip = (f) => model.tokenFiles.has(f.path) || isSpecimen(f.path, model.cfg);
|
|
171
|
+
const painted = (r) => STYLE_ORIGINS.has(r.origin) && r.sel && r.decls.some((d) => PAINT.test(d.prop) && !d.ignored);
|
|
172
|
+
const owner = new Map();
|
|
122
173
|
for (const f of model.files) {
|
|
123
|
-
if (
|
|
174
|
+
if (skip(f) || !inParts(f.path, model.cfg)) continue;
|
|
175
|
+
for (const r of f.rules) if (painted(r)) for (const h of roleHits(r.sel)) if (!h.el && !owner.has(h.cls)) owner.set(h.cls, f.path);
|
|
176
|
+
}
|
|
177
|
+
const add = (role, family, cls, f, r) => {
|
|
178
|
+
roles[role] ??= new Map();
|
|
179
|
+
if (!roles[role].has(family)) roles[role].set(family, { family, classes: new Set(), at: [], files: new Set() });
|
|
180
|
+
const fam = roles[role].get(family);
|
|
181
|
+
fam.classes.add(cls);
|
|
182
|
+
fam.files.add(f.path);
|
|
183
|
+
if (fam.at.length < 4) fam.at.push(`${f.path}:${r.line}`);
|
|
184
|
+
};
|
|
185
|
+
for (const f of model.files) {
|
|
186
|
+
if (skip(f)) continue;
|
|
187
|
+
const part = inParts(f.path, model.cfg) ? f.path : null;
|
|
124
188
|
for (const r of f.rules) {
|
|
125
|
-
if (!
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
const
|
|
129
|
-
|
|
130
|
-
const el = /^(button|input|select|textarea|dialog)\b/.exec(last)?.[1];
|
|
131
|
-
const found = new Map();
|
|
132
|
-
for (const c of classes) {
|
|
133
|
-
const words = c.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase().split(/[-_]+/).filter(Boolean);
|
|
134
|
-
const k = words.findIndex((w) => Object.values(ROLES).some((re) => re.test(w)));
|
|
135
|
-
if (k < 0 || words.slice(k + 1).some((w) => STRUCTURE.test(w))) continue;
|
|
136
|
-
const role = Object.keys(ROLES).find((n) => ROLES[n].test(words[k]));
|
|
137
|
-
const family = c.split('--')[0].replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase().split(/[-_]+/).slice(0, k + 1).join('-');
|
|
138
|
-
found.set(role, { family, cls: c });
|
|
139
|
-
}
|
|
140
|
-
if (el && !classes.length) found.set({ input: 'field', select: 'field', textarea: 'field' }[el] ?? el, { family: `<${el}>`, cls: el });
|
|
141
|
-
for (const [role, { family, cls }] of found) {
|
|
142
|
-
roles[role] ??= new Map();
|
|
143
|
-
if (!roles[role].has(family)) roles[role].set(family, { family, classes: new Set(), at: [], files: new Set() });
|
|
144
|
-
const fam = roles[role].get(family);
|
|
145
|
-
fam.classes.add(cls);
|
|
146
|
-
fam.files.add(f.path);
|
|
147
|
-
if (fam.at.length < 4) fam.at.push(`${f.path}:${r.line}`);
|
|
148
|
-
}
|
|
189
|
+
if (!painted(r)) continue;
|
|
190
|
+
for (const h of roleHits(r.sel)) {
|
|
191
|
+
const file = part ?? (!h.el && owner.get(h.cls));
|
|
192
|
+
if (file) { const role = roleOfFile(file); if (role && (h.role || file === part)) add(role, file, h.cls, f, r); }
|
|
193
|
+
else if (h.role) add(h.role, h.family, h.cls, f, r);
|
|
149
194
|
}
|
|
150
195
|
}
|
|
151
196
|
}
|
|
@@ -156,7 +201,7 @@ export function redraws(model) {
|
|
|
156
201
|
|
|
157
202
|
export function markupDupes(model) {
|
|
158
203
|
const occ = [];
|
|
159
|
-
for (const f of model.files) f.trees.forEach((t, i) => occ.push({ ...t, file: f.path, key: `${f.path}#${i}`, pkey: t.p >= 0 ? `${f.path}#${t.p}` : null }));
|
|
204
|
+
for (const f of model.files) if (!isSpecimen(f.path, model.cfg)) f.trees.forEach((t, i) => occ.push({ ...t, file: f.path, key: `${f.path}#${i}`, pkey: t.p >= 0 ? `${f.path}#${t.p}` : null }));
|
|
160
205
|
const by = (k, min) => {
|
|
161
206
|
const m = new Map();
|
|
162
207
|
for (const o of occ) if (o.size >= min) { if (!m.has(o[k])) m.set(o[k], []); m.get(o[k]).push(o); }
|
package/src/check.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
// Check: the drift gate. Every rule's hits on the project; with --staged or
|
|
2
2
|
// --base REF, only the hits the change adds (git is the baseline, there is no
|
|
3
3
|
// baseline file), so a messy codebase can adopt it today and only get cleaner.
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
4
6
|
import { spawnSync } from 'node:child_process';
|
|
5
7
|
import { buildModel, slotOf } from './model.js';
|
|
6
8
|
import { analyze, ALL_EXT } from './sources.js';
|
|
@@ -13,8 +15,22 @@ import { splitTop } from './css.js';
|
|
|
13
15
|
|
|
14
16
|
// The tokens that make a project look like itself; the rest derive from them.
|
|
15
17
|
const CORE = ['--surface', '--text', '--accent', '--text-on-accent', '--font-ui'];
|
|
16
|
-
// Where a part is used may place it, never restyle it.
|
|
17
|
-
|
|
18
|
+
// Where a part is used may place it, never restyle it. Interaction
|
|
19
|
+
// properties (cursor, touch-action, overflow, scroll-*) aren't look either.
|
|
20
|
+
// The subject compound of one selector: :has()/:not() arguments dropped, then the part after the last combinator.
|
|
21
|
+
function subjectOf(sel) {
|
|
22
|
+
let out = '', i = 0;
|
|
23
|
+
const s = sel.trim();
|
|
24
|
+
while (i < s.length) {
|
|
25
|
+
const m = /^:(has|not)\(/.exec(s.slice(i));
|
|
26
|
+
if (!m) { out += s[i++]; continue; }
|
|
27
|
+
let depth = 0, j = i + m[0].length - 1;
|
|
28
|
+
for (; j < s.length; j++) { if (s[j] === '(') depth++; else if (s[j] === ')' && --depth === 0) break; }
|
|
29
|
+
i = j + 1;
|
|
30
|
+
}
|
|
31
|
+
return out.split(/[\s>+~]+/).filter(Boolean).pop() ?? '';
|
|
32
|
+
}
|
|
33
|
+
const LAYOUT = /^(margin(-[\w-]+)?|grid(-[\w-]+)?|flex(-[\w-]+)?|order|align-self|justify-self|place-self|(min-|max-)?(width|height|inline-size|block-size)|position|inset(-[\w-]+)?|top|right|bottom|left|z-index|display|visibility|opacity|pointer-events|transition(-[\w-]+)?|transform|animation(-[\w-]+)?|view-transition-name|contain|cursor|(-webkit-)?user-select|touch-action|-webkit-tap-highlight-color|-webkit-touch-callout|will-change|overflow(-x|-y)?|overscroll-behavior(-[\w-]+)?|scroll-[\w-]+)$/;
|
|
18
34
|
const HELPERS = new Set(['stack', 'row', 'tight', 'loose', 'muted', 'small', 'dot', 'inset', 'end', 'actions']);
|
|
19
35
|
|
|
20
36
|
// Classes the foundation's parts own: the first class each selector names
|
|
@@ -31,6 +47,21 @@ export function foundationClasses(foundation) {
|
|
|
31
47
|
return out;
|
|
32
48
|
}
|
|
33
49
|
|
|
50
|
+
// The `{id · checks}` tags of a rules file, with the line each sits on.
|
|
51
|
+
const BASE_RULES = new URL('../rules/DESIGN.md', import.meta.url);
|
|
52
|
+
export function ruleIds(text) {
|
|
53
|
+
const out = [];
|
|
54
|
+
text.split('\n').forEach((l, i) => { for (const m of l.matchAll(/\{([a-z][\w-]*\.[\w.-]+)\s*(?:·[^}]*)?\}/g)) out.push({ id: m[1], line: i + 1 }); });
|
|
55
|
+
return out;
|
|
56
|
+
}
|
|
57
|
+
let baseIds;
|
|
58
|
+
const baseRuleIds = () => (baseIds ??= new Set(ruleIds(fs.readFileSync(BASE_RULES, 'utf8')).map((r) => r.id)));
|
|
59
|
+
// The project's DESIGN.md: what `baselines` read from git, else the file.
|
|
60
|
+
function projectRules(model) {
|
|
61
|
+
if (model.designRules !== undefined) return model.designRules;
|
|
62
|
+
try { return fs.readFileSync(path.join(model.root, 'DESIGN.md'), 'utf8'); } catch { return null; }
|
|
63
|
+
}
|
|
64
|
+
|
|
34
65
|
const SLOTS = new Set(['color', 'space', 'radius', 'font-size', 'font', 'shadow']);
|
|
35
66
|
|
|
36
67
|
export function hits(model) {
|
|
@@ -89,7 +120,8 @@ export function hits(model) {
|
|
|
89
120
|
const looks = r.decls.filter((d) => !d.prop.startsWith('--') && !LAYOUT.test(d.prop));
|
|
90
121
|
if (!looks.length) continue;
|
|
91
122
|
for (const part of splitTop(r.sel)) {
|
|
92
|
-
|
|
123
|
+
// Only the subject compound counts: a class inside :has() or :not() is a condition, not what gets styled.
|
|
124
|
+
const last = subjectOf(part);
|
|
93
125
|
const classes = [...last.matchAll(/\.([\w-]+)/g)].map((m) => m[1]);
|
|
94
126
|
const hitPart = classes.find((c) => parts.has(c));
|
|
95
127
|
if (!hitPart) continue;
|
|
@@ -99,6 +131,12 @@ export function hits(model) {
|
|
|
99
131
|
}
|
|
100
132
|
}
|
|
101
133
|
}
|
|
134
|
+
if (on('rules-override') && model.root) {
|
|
135
|
+
// A project's rules extend the base; reusing a base id overrides it.
|
|
136
|
+
const text = projectRules(model);
|
|
137
|
+
const base = baseRuleIds();
|
|
138
|
+
if (text) for (const r of ruleIds(text)) if (base.has(r.id)) hit('rules-override', 'DESIGN.md', r.line, `{${r.id}} is a designrail base rule; a project rule adds to the base under an id of its own, never restates or overrides one`, r.id);
|
|
139
|
+
}
|
|
102
140
|
if (on('tracked-caps')) {
|
|
103
141
|
for (const f of model.files) for (const r of f.rules) {
|
|
104
142
|
const up = r.decls.some((d) => d.prop === 'text-transform' && /uppercase/.test(d.value));
|
|
@@ -122,6 +160,9 @@ export function baselines(project, { base = 'HEAD', staged = false }) {
|
|
|
122
160
|
const changed = new Set(git(root, staged ? ['diff', '--cached', '--name-only', base] : ['diff', '--name-only', base]).split('\n').filter((f) => ALL_EXT.test(f)));
|
|
123
161
|
if (!staged) for (const f of git(root, ['ls-files', '--others', '--exclude-standard']).split('\n')) if (ALL_EXT.test(f)) changed.add(f);
|
|
124
162
|
const show = (spec) => { const r = spawnSync('git', ['show', spec], { cwd: root, maxBuffer: 1 << 28, encoding: 'utf8' }); return r.status ? null : r.stdout; };
|
|
163
|
+
// DESIGN.md as it was and as it is, so rules-override counts only new overrides.
|
|
164
|
+
const rulesThen = show(`${base}:DESIGN.md`);
|
|
165
|
+
const rulesNow = staged ? show(':DESIGN.md') : undefined;
|
|
125
166
|
const keep = project.files.filter((f) => !changed.has(f.path));
|
|
126
167
|
const then = [...keep], now = staged ? [...keep] : [...project.files];
|
|
127
168
|
for (const rel of changed) {
|
|
@@ -129,7 +170,7 @@ export function baselines(project, { base = 'HEAD', staged = false }) {
|
|
|
129
170
|
if (was != null) then.push({ path: rel, ...analyze(rel, was) });
|
|
130
171
|
if (staged) { const is = show(`:${rel}`); if (is != null) now.push({ path: rel, ...analyze(rel, is) }); }
|
|
131
172
|
}
|
|
132
|
-
return { then: buildModel({ ...project, files: then }), now: buildModel({ ...project, files: now }), changed: [...changed] };
|
|
173
|
+
return { then: buildModel({ ...project, files: then, designRules: rulesThen }), now: buildModel({ ...project, files: now, ...(staged ? { designRules: rulesNow } : {}) }), changed: [...changed] };
|
|
133
174
|
}
|
|
134
175
|
|
|
135
176
|
// Hits in `now` beyond what `then` had: a count per key, so one more use of a
|
package/src/cli.js
CHANGED
|
@@ -102,6 +102,13 @@ export async function main(argv) {
|
|
|
102
102
|
return;
|
|
103
103
|
}
|
|
104
104
|
|
|
105
|
+
if ((cmd === 'check' && !flags['--install-hook']) || cmd === 'audit') {
|
|
106
|
+
const { loadConfig, loosenedError } = await import('./project.js');
|
|
107
|
+
let msg;
|
|
108
|
+
try { msg = loosenedError(loadConfig(root)); } catch (e) { fail(e.message); }
|
|
109
|
+
if (msg) fail(msg);
|
|
110
|
+
}
|
|
111
|
+
|
|
105
112
|
const model = await load();
|
|
106
113
|
|
|
107
114
|
if (cmd === 'scan') {
|
package/src/contract.js
CHANGED
|
@@ -25,6 +25,8 @@ export const CONTRACT = [
|
|
|
25
25
|
{ name: '--success', group: 'colour', role: 'any', about: 'Something worked.', derive: '#16a34a' },
|
|
26
26
|
{ name: '--warning', group: 'colour', role: 'any', about: 'Careful.', derive: '#d97706' },
|
|
27
27
|
{ name: '--focus', group: 'colour', role: 'any', about: 'The keyboard focus ring.', derive: 'var(--accent)' },
|
|
28
|
+
{ name: '--focus-ring', group: 'colour', role: 'border', about: 'The focus outline (`none` for a glow only).', derive: '2px solid var(--focus)' },
|
|
29
|
+
{ name: '--focus-glow', group: 'colour', role: 'any', about: 'A focus glow, as a box-shadow (`none` by default).', derive: 'none' },
|
|
28
30
|
// type
|
|
29
31
|
{ name: '--font-ui', group: 'type', about: 'Every label and paragraph.', derive: "system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif" },
|
|
30
32
|
{ name: '--font-display', group: 'type', about: 'Headings.', derive: 'var(--font-ui)' },
|
package/src/css.js
CHANGED
|
@@ -38,6 +38,9 @@ export function blankComments(text, lineComments = false) {
|
|
|
38
38
|
return out;
|
|
39
39
|
}
|
|
40
40
|
|
|
41
|
+
// `/* designrail-ignore */` or `/* measured */` inside a value exempts that declaration.
|
|
42
|
+
export const EXEMPT = /\/\*[^]*?(designrail-ignore|\bmeasured\b)[^]*?\*\//;
|
|
43
|
+
|
|
41
44
|
export const splitTop = (s) => {
|
|
42
45
|
const parts = [];
|
|
43
46
|
let depth = 0, start = 0;
|
|
@@ -97,7 +100,11 @@ export function parseCss(text, { base = 0, starts, lineComments = false, inline
|
|
|
97
100
|
let value = text.slice(vs, ve);
|
|
98
101
|
const imp = /\s*!important\s*$/i.exec(bare.slice(vs, ve));
|
|
99
102
|
if (imp) { ve -= imp[0].length; value = text.slice(vs, ve); }
|
|
100
|
-
if (value)
|
|
103
|
+
if (!value) return;
|
|
104
|
+
const d = { prop: m[2].toLowerCase(), value, line: at(start + m[1].length), vstart: vs + base, vend: ve + base };
|
|
105
|
+
// An exemption comment inside the value (blanked above, so read from the source).
|
|
106
|
+
if (EXEMPT.test(text.slice(start + colon, end))) d.ignored = true;
|
|
107
|
+
ruleOf(top()).decls.push(d);
|
|
101
108
|
}
|
|
102
109
|
};
|
|
103
110
|
|
package/src/fix.js
CHANGED
|
@@ -6,11 +6,15 @@ import fs from 'node:fs';
|
|
|
6
6
|
import path from 'node:path';
|
|
7
7
|
import { colorDistance, colorFacts } from './values.js';
|
|
8
8
|
import { roleOfProp } from './contract.js';
|
|
9
|
-
import { tokenIndex, firstFamily } from './tokens.js';
|
|
9
|
+
import { tokenIndex, firstFamily, primitivesOf } from './tokens.js';
|
|
10
10
|
|
|
11
11
|
export function matcher(model, { snap = false } = {}) {
|
|
12
|
-
const tokens = tokenIndex(model);
|
|
13
12
|
const allowed = (t) => model.cfg.allowPrimitives.some((p) => t.name.startsWith(p));
|
|
13
|
+
// Every value fix writes lands outside token files: with semanticOnly, never
|
|
14
|
+
// a primitive there (allowPrimitives aside), or fix makes primitive-direct hits.
|
|
15
|
+
const all = tokenIndex(model);
|
|
16
|
+
const prims = model.cfg.semanticOnly ? primitivesOf(all) : new Set();
|
|
17
|
+
const tokens = all.filter((t) => !prims.has(t.name) || allowed(t));
|
|
14
18
|
const pick = (o) => {
|
|
15
19
|
const { lit, prop } = o;
|
|
16
20
|
if (lit.kind === 'color') {
|
package/src/init.js
CHANGED
|
@@ -6,13 +6,31 @@ import { fileURLToPath } from 'node:url';
|
|
|
6
6
|
import { listFiles, DEFAULT_CONFIG, findFoundation } from './project.js';
|
|
7
7
|
import { isTokenFile } from './model.js';
|
|
8
8
|
import { analyze } from './sources.js';
|
|
9
|
+
import { isSpecimenPage } from './specimens.js';
|
|
9
10
|
|
|
10
|
-
const
|
|
11
|
+
export const BASE_RULES = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'rules', 'DESIGN.md');
|
|
12
|
+
|
|
13
|
+
// The project's own rules file: it extends the base and starts empty.
|
|
14
|
+
export const PROJECT_RULES = `Extends @rickycourtes/designrail/rules/DESIGN.md
|
|
15
|
+
|
|
16
|
+
# Design rules
|
|
17
|
+
|
|
18
|
+
designrail's base rules (\`node_modules/@rickycourtes/designrail/rules/DESIGN.md\`)
|
|
19
|
+
hold for this project as written. This file only adds to them: a rule here
|
|
20
|
+
says something the base doesn't, and never reuses a base \`{id}\`
|
|
21
|
+
(\`designrail check\` fails that: rules-override). End each bullet with a tag
|
|
22
|
+
\`{id · checks}\` as the base does: \`check\`, \`audit\` or \`eye\`.
|
|
23
|
+
|
|
24
|
+
## Project rules
|
|
25
|
+
|
|
26
|
+
`;
|
|
11
27
|
|
|
12
28
|
const AGENT_BLOCK = `
|
|
13
29
|
## Design system (designrail)
|
|
14
30
|
|
|
15
|
-
Before touching UI, read
|
|
31
|
+
Before touching UI, read both rule files: designrail's base rules
|
|
32
|
+
(\`node_modules/@rickycourtes/designrail/rules/DESIGN.md\`) and this project's
|
|
33
|
+
\`DESIGN.md\`, which extends them. Build from the parts in \`{parts}/\` and
|
|
16
34
|
the tokens in {tokens}, on top of the designrail foundation (\`@rickycourtes/designrail/foundation.css\`). Restyle a foundation part with its knobs on a variant, never by editing it; never type a colour, spacing, radius or font size by
|
|
17
35
|
hand. Run \`npx designrail check\` before committing; \`npx designrail trace <selector>\`
|
|
18
36
|
shows where a value comes from. A part the foundation lacks: write it in \`{parts}/\` from tokens; \`npx designrail eject <part>\` only to own a copy.
|
|
@@ -26,14 +44,17 @@ export function init(root, { agents = false, force = false } = {}) {
|
|
|
26
44
|
const found = listFiles(root, cfg).filter((f) => /\.(css|scss|less)$/.test(f))
|
|
27
45
|
.filter((f) => { try { return isTokenFile({ path: f, ...analyze(f, fs.readFileSync(path.join(root, f), 'utf8')) }, { ...cfg, tokens: [] }); } catch { return false; } });
|
|
28
46
|
const tokens = found.length ? found : cfg.tokens;
|
|
47
|
+
// Pages `designrail specimens` wrote (wherever --out put them).
|
|
48
|
+
const pages = listFiles(root, cfg).filter((f) => /\.html?$/.test(f))
|
|
49
|
+
.filter((f) => { try { return isSpecimenPage(fs.readFileSync(path.join(root, f), 'utf8')); } catch { return false; } });
|
|
29
50
|
if (!fs.existsSync(cfgPath) || force) {
|
|
30
51
|
const foundation = findFoundation(root, cfg);
|
|
31
|
-
const out = { ...(foundation ? { foundation: foundation.version } : {}), $schema: 'https://raw.githubusercontent.com/rickycourtes/designrail/main/schema.json', include: cfg.include, exclude: cfg.exclude.filter((e) => !['.git', '.designrail', 'node_modules'].includes(e)), tokens, parts: fs.existsSync(path.join(root, 'src')) ? 'src/ui' : 'ui', grid: cfg.grid, semanticOnly: cfg.semanticOnly, allowPrimitives: cfg.allowPrimitives, runtimeTokens: [], rules: cfg.rules };
|
|
52
|
+
const out = { ...(foundation ? { foundation: foundation.version } : {}), $schema: 'https://raw.githubusercontent.com/rickycourtes/designrail/main/schema.json', include: cfg.include, exclude: cfg.exclude.filter((e) => !['.git', '.designrail', 'node_modules'].includes(e)), tokens, parts: fs.existsSync(path.join(root, 'src')) ? 'src/ui' : 'ui', ...(pages.length ? { specimens: pages } : {}), grid: cfg.grid, semanticOnly: cfg.semanticOnly, allowPrimitives: cfg.allowPrimitives, runtimeTokens: [], rules: cfg.rules };
|
|
32
53
|
fs.writeFileSync(cfgPath, JSON.stringify(out, null, 2) + '\n');
|
|
33
|
-
done.push(`designrail.config.json${found.length ? ` (tokens found in ${found.join(', ')})` : ''}`);
|
|
54
|
+
done.push(`designrail.config.json${found.length ? ` (tokens found in ${found.join(', ')})` : ''}${pages.length ? ` (specimens: ${pages.join(', ')})` : ''}`);
|
|
34
55
|
}
|
|
35
56
|
const rulesPath = path.join(root, 'DESIGN.md');
|
|
36
|
-
if (!fs.existsSync(rulesPath) || force) { fs.
|
|
57
|
+
if (!fs.existsSync(rulesPath) || force) { fs.writeFileSync(rulesPath, PROJECT_RULES); done.push('DESIGN.md'); }
|
|
37
58
|
if (agents) {
|
|
38
59
|
const target = ['CLAUDE.md', 'AGENTS.md'].map((f) => path.join(root, f)).find((f) => fs.existsSync(f)) ?? path.join(root, 'CLAUDE.md');
|
|
39
60
|
const now = fs.existsSync(target) ? fs.readFileSync(target, 'utf8') : '';
|
package/src/model.js
CHANGED
|
@@ -44,9 +44,9 @@ export function buildModel(project) {
|
|
|
44
44
|
// A var() in a plain JS file may be a string in a test or a tool: it
|
|
45
45
|
// counts as a read (unused) but never fails unresolved or primitive-direct.
|
|
46
46
|
const js = JS_EXT.test(f.path);
|
|
47
|
-
for (const [name, line, fallback] of f.uses) {
|
|
47
|
+
for (const [name, line, fallback, quoted] of f.uses) {
|
|
48
48
|
if (!uses.has(name)) uses.set(name, []);
|
|
49
|
-
uses.get(name).push({ file: f.path, line, inTokens, js, fallback: Boolean(fallback) });
|
|
49
|
+
uses.get(name).push({ file: f.path, line, inTokens, js: js || Boolean(quoted), fallback: Boolean(fallback) });
|
|
50
50
|
}
|
|
51
51
|
for (const r of f.rules) {
|
|
52
52
|
if (r.sel === '@font-face') continue;
|
|
@@ -56,7 +56,7 @@ export function buildModel(project) {
|
|
|
56
56
|
defs.get(d.prop).push({ value: d.value, file: f.path, line: d.line, sel: r.sel, media: r.media, inTokens });
|
|
57
57
|
}
|
|
58
58
|
if (inTokens) continue;
|
|
59
|
-
if (
|
|
59
|
+
if (d.ignored) continue;
|
|
60
60
|
decls.push({ file: f.path, rule: r, d });
|
|
61
61
|
const slot = designSlot(d.prop);
|
|
62
62
|
const lits = literals(d.prop, d.value);
|
|
@@ -121,8 +121,8 @@ export function slotOf(lit) {
|
|
|
121
121
|
return lit.cat;
|
|
122
122
|
}
|
|
123
123
|
|
|
124
|
-
// A rule's declarations as one comparable set (custom props and
|
|
124
|
+
// A rule's declarations as one comparable set (custom props and exempted ones left out).
|
|
125
125
|
export function declSet(rule, colorMap = null) {
|
|
126
126
|
const norm = (v) => { const n = normValue(v); return colorMap ? n.replace(/#[0-9a-f]{6,8}\b/g, (h) => colorMap.get(h) ?? h) : n; };
|
|
127
|
-
return [...new Set(rule.decls.filter((d) => !d.prop.startsWith('--')).map((d) => `${d.prop}:${norm(d.value)}`))].sort();
|
|
127
|
+
return [...new Set(rule.decls.filter((d) => !d.prop.startsWith('--') && !d.ignored).map((d) => `${d.prop}:${norm(d.value)}`))].sort();
|
|
128
128
|
}
|
package/src/project.js
CHANGED
|
@@ -10,7 +10,7 @@ import { analyze, ALL_EXT } from './sources.js';
|
|
|
10
10
|
const PKG = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
|
|
11
11
|
export const VERSION = PKG.version;
|
|
12
12
|
export const OWN_KIT = fileURLToPath(new URL('../kit', import.meta.url));
|
|
13
|
-
const CACHE_VERSION = `${VERSION}-
|
|
13
|
+
const CACHE_VERSION = `${VERSION}-2`;
|
|
14
14
|
|
|
15
15
|
// Never project source, whatever the config says.
|
|
16
16
|
const ALWAYS = ['.git', '.designrail', 'node_modules'];
|
|
@@ -22,6 +22,8 @@ export const DEFAULT_CONFIG = {
|
|
|
22
22
|
tokens: ['tokens/primitives.css', 'tokens/semantic.css'],
|
|
23
23
|
// Where `add` copies kit parts.
|
|
24
24
|
parts: 'ui',
|
|
25
|
+
// Specimen pages (globs): parts side by side on purpose, so not repeated markup.
|
|
26
|
+
specimens: [],
|
|
25
27
|
grid: 4,
|
|
26
28
|
// ΔE OK below which two colours count as the same colour.
|
|
27
29
|
colorTolerance: 0.01,
|
|
@@ -32,8 +34,10 @@ export const DEFAULT_CONFIG = {
|
|
|
32
34
|
allowPrimitives: ['--space-', '--radius-', '--font-size-'],
|
|
33
35
|
// Custom properties set from JS at runtime (resolve without a CSS definition).
|
|
34
36
|
runtimeTokens: [],
|
|
35
|
-
rules: { hardcoded: 'error', unresolved: 'error', 'primitive-direct': 'warn', 'duplicate-block': 'error', unused: 'warn', 'tracked-caps': 'warn', contract: 'warn', 'part-restyle': 'warn' },
|
|
37
|
+
rules: { hardcoded: 'error', unresolved: 'error', 'primitive-direct': 'warn', 'duplicate-block': 'error', unused: 'warn', 'tracked-caps': 'warn', contract: 'warn', 'part-restyle': 'warn', 'rules-override': 'error' },
|
|
36
38
|
maxFileBytes: 1_500_000,
|
|
39
|
+
// Rule blocks count as duplicates only when they share this many declarations.
|
|
40
|
+
duplicates: { minDeclarations: 3 },
|
|
37
41
|
};
|
|
38
42
|
|
|
39
43
|
export function loadConfig(root) {
|
|
@@ -42,11 +46,35 @@ export function loadConfig(root) {
|
|
|
42
46
|
if (fs.existsSync(file)) {
|
|
43
47
|
try { user = JSON.parse(fs.readFileSync(file, 'utf8')); } catch (e) { throw new Error(`designrail.config.json: ${e.message}`); }
|
|
44
48
|
}
|
|
45
|
-
const cfg = { ...DEFAULT_CONFIG, ...user, rules: { ...DEFAULT_CONFIG.rules, ...(user.rules ?? {}) } };
|
|
49
|
+
const cfg = { ...DEFAULT_CONFIG, ...user, rules: { ...DEFAULT_CONFIG.rules, ...(user.rules ?? {}) }, duplicates: { ...DEFAULT_CONFIG.duplicates, ...(user.duplicates ?? {}) } };
|
|
46
50
|
cfg.exists = fs.existsSync(file);
|
|
51
|
+
cfg.loosened = loosened(user);
|
|
47
52
|
return cfg;
|
|
48
53
|
}
|
|
49
54
|
|
|
55
|
+
// A project can turn a foundation rule up, never down: what in its config
|
|
56
|
+
// is laxer than DEFAULT_CONFIG. `check` and `audit` refuse to run on it.
|
|
57
|
+
const LEVEL = { off: 0, warn: 1, error: 2 };
|
|
58
|
+
function loosened(user) {
|
|
59
|
+
const out = [];
|
|
60
|
+
for (const [rule, level] of Object.entries(user.rules ?? {})) {
|
|
61
|
+
const base = DEFAULT_CONFIG.rules[rule];
|
|
62
|
+
if (base && (LEVEL[level] ?? 0) < LEVEL[base]) out.push(`rules.${rule} ${JSON.stringify(level)}`);
|
|
63
|
+
}
|
|
64
|
+
if (user.semanticOnly === false) out.push('semanticOnly false');
|
|
65
|
+
for (const p of user.allowPrimitives ?? []) if (!DEFAULT_CONFIG.allowPrimitives.includes(p)) out.push(`allowPrimitives ${JSON.stringify(p)}`);
|
|
66
|
+
const min = user.duplicates?.minDeclarations;
|
|
67
|
+
if (min !== undefined && !(min <= DEFAULT_CONFIG.duplicates.minDeclarations)) out.push(`duplicates.minDeclarations ${min}`);
|
|
68
|
+
return out;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// The one line `check` and `audit` exit 2 with, or null when nothing loosens.
|
|
72
|
+
export function loosenedError(cfg) {
|
|
73
|
+
const l = cfg.loosened ?? [];
|
|
74
|
+
if (!l.length) return null;
|
|
75
|
+
return `designrail.config.json: ${l.join(', ')} ${l.length === 1 ? 'loosens a foundation rule' : 'loosen foundation rules'}; a project can turn a rule up, never down`;
|
|
76
|
+
}
|
|
77
|
+
|
|
50
78
|
// Merge keys into designrail.config.json (created when missing).
|
|
51
79
|
export function saveConfig(root, patch) {
|
|
52
80
|
const file = path.join(root, 'designrail.config.json');
|
|
@@ -55,7 +83,13 @@ export function saveConfig(root, patch) {
|
|
|
55
83
|
fs.writeFileSync(file, JSON.stringify({ ...cur, ...patch }, null, 2) + '\n');
|
|
56
84
|
}
|
|
57
85
|
|
|
58
|
-
|
|
86
|
+
// A file inside the config's `parts` folder.
|
|
87
|
+
export const inParts = (file, cfg) => Boolean(cfg.parts) && file.startsWith(cfg.parts.replace(/^\.\/|\/$/g, '') + '/');
|
|
88
|
+
|
|
89
|
+
// A specimen page (`specimens` globs): parts shown side by side on purpose.
|
|
90
|
+
export const isSpecimen = (file, cfg) => (cfg.specimens ?? []).some((g) => globRe(g).test(file));
|
|
91
|
+
|
|
92
|
+
export function globRe(g) {
|
|
59
93
|
return new RegExp('(^|/)' + g.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*\*\//g, '(.*/)?').replace(/\*\*/g, '.*').replace(/\*/g, '[^/]*') + '($|/)');
|
|
60
94
|
}
|
|
61
95
|
|
package/src/report.js
CHANGED
|
@@ -39,7 +39,7 @@ export function auditText(a, model, { limit = 6 } = {}) {
|
|
|
39
39
|
if (!a.parts.length) p(dim(' none found'));
|
|
40
40
|
for (const r of a.parts.slice(0, limit)) {
|
|
41
41
|
p(' ', bold(r.role), dim(` · ${`${r.families.length} families`} → one part with variants: the foundation's ${{ button: '.btn', field: '.input', card: '.card', pill: '.pill', dialog: '.sheet', toast: '.toast', dropdown: '.menu' }[r.role]}`));
|
|
42
|
-
for (const f of r.families.slice(0, 5)) p(' ', cyan(f.family.padEnd(
|
|
42
|
+
for (const f of r.families.slice(0, 5)) p(' ', cyan(f.family.padEnd(17) + ' '), dim(`${[...f.classes].slice(0, 4).map((x) => (x[0] === '<' ? x : '.' + x)).join(' ')} ${f.at[0]}`));
|
|
43
43
|
}
|
|
44
44
|
p('');
|
|
45
45
|
|
|
@@ -97,7 +97,7 @@ ${a.colors.near.length ? `<p class="mute">Near-identical groups: each could be o
|
|
|
97
97
|
<div class="card"><h2>Duplicate rule blocks <span class="mute">· ${a.blocks.groups.length} identical groups, ${a.blocks.near.length} near pairs</span></h2><table><tr><th>Selectors</th><th>Declarations</th><th>Where</th></tr>
|
|
98
98
|
${rows(a.blocks.groups.slice(0, 40), (g) => `<tr><td><code>${esc(g.rules.map((r) => r.sel).join(' ≡ '))}</code></td><td>${g.decls.length}</td><td class="mute">${esc(g.rules.map((r) => `${r.file}:${r.line}`).join(', '))}</td></tr>`)}
|
|
99
99
|
${rows(a.blocks.near.slice(0, 40), (n) => `<tr><td><code>${esc(n.a.sel)} ≈ ${esc(n.b.sel)}</code> <span class="mute">${Math.round(n.similarity * 100)}%</span></td><td>${n.shared}</td><td class="mute">${esc(`${n.a.file}:${n.a.line}, ${n.b.file}:${n.b.line}`)}</td></tr>`)}</table></div>
|
|
100
|
-
<div class="card"><h2>Parts drawn more than one way</h2>${a.parts.length ? `<table><tr><th>Part</th><th>Families</th><th>Where</th></tr>${rows(a.parts, (r) => `<tr><td><b>${r.role}</b></td><td>${r.families.map((f) => `<code>${esc(f.family)}</code> <span class="mute">(${[...f.classes].slice(0, 4).map((x) => '.' +
|
|
100
|
+
<div class="card"><h2>Parts drawn more than one way</h2>${a.parts.length ? `<table><tr><th>Part</th><th>Families</th><th>Where</th></tr>${rows(a.parts, (r) => `<tr><td><b>${r.role}</b></td><td>${r.families.map((f) => `<code>${esc(f.family)}</code> <span class="mute">(${[...f.classes].slice(0, 4).map((x) => esc(x[0] === '<' ? x : '.' + x)).join(' ')})</span>`).join('<br>')}</td><td class="mute">${r.families.map((f) => esc(f.at[0])).join('<br>')}</td></tr>`)}</table>` : '<p class="mute">None found.</p>'}</div>
|
|
101
101
|
<div class="card"><h2>Repeated markup</h2>${a.markup.exact.length + a.markup.shape.length ? `<table><tr><th>Block</th><th>Copies</th><th>Where</th></tr>${rows(a.markup.exact.slice(0, 30), (m) => `<tr><td><code>${esc(m.label)}</code> <span class="mute">${m.size} elements: ${esc(m.kids)}</span></td><td>${m.count}</td><td class="mute">${esc(m.at.join(', '))}</td></tr>`)}${rows(a.markup.shape.slice(0, 15), (m) => `<tr><td><code>${esc(m.label)}</code> <span class="mute">same shape, other classes</span></td><td>${m.count}</td><td class="mute">${esc(m.at.join(', '))}</td></tr>`)}</table>` : '<p class="mute">None found.</p>'}</div>
|
|
102
102
|
<p class="mute" style="text-align:center">Generated by Designrail</p>
|
|
103
103
|
</main></body></html>`;
|
package/src/sources.js
CHANGED
|
@@ -136,7 +136,13 @@ export function analyze(path, text) {
|
|
|
136
136
|
// Custom properties read, and set at runtime (setProperty / style vars).
|
|
137
137
|
const uses = [];
|
|
138
138
|
for (const m of text.matchAll(/var\(\s*(--[\w-]+)\s*(,)?/g)) uses.push([m[1], lineAt(starts, m.index), m[2] ? 1 : 0]);
|
|
139
|
-
const
|
|
139
|
+
const setters = [...script.matchAll(/(?:setProperty|style\.setProperty|live)\(\s*[^,]*?['"](--[\w-]+)['"]/g), ...script.matchAll(/['"](--[\w-]+)['"]\s*:/g)];
|
|
140
|
+
const runtime = [...new Set(setters.map((m) => m[1]))];
|
|
141
|
+
// A quoted name script reads (getPropertyValue('--x'), tok('--x')) is a use:
|
|
142
|
+
// it keeps the token off `unused`, and like a var() in JS never fails
|
|
143
|
+
// unresolved or primitive-direct (the 4th field marks it).
|
|
144
|
+
const set = new Set(setters.map((m) => m.index + m[0].lastIndexOf(m[1]) - 1));
|
|
145
|
+
for (const m of script.matchAll(/(['"`])(--[\w-]+)\1(?!\s*:)/g)) if (!set.has(m.index)) uses.push([m[2], lineAt(starts, m.index), 0, 1]);
|
|
140
146
|
|
|
141
147
|
const trees = SFC_EXT.test(path) || /\.[jt]sx$/.test(path) || (JS_EXT.test(path) && /<[A-Za-z][\w.]*[\s>/]/.test(text) && /return\s*\(?\s*</.test(text))
|
|
142
148
|
? markupTrees(text, starts, path) : [];
|
package/src/specimens.js
CHANGED
|
@@ -5,6 +5,10 @@ import path from 'node:path';
|
|
|
5
5
|
import { tokenIndex } from './tokens.js';
|
|
6
6
|
import { KIT, PARTS } from './kit.js';
|
|
7
7
|
|
|
8
|
+
// Marks the page so `init` can find it wherever --out put it.
|
|
9
|
+
export const GENERATOR = 'designrail specimens';
|
|
10
|
+
export const isSpecimenPage = (html) => html.includes(`<meta name="generator" content="${GENERATOR}">`) || /class="dr-top"[^]*generated by Designrail/.test(html);
|
|
11
|
+
|
|
8
12
|
const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
|
|
9
13
|
|
|
10
14
|
const DEMO = {
|
|
@@ -57,6 +61,7 @@ export function specimens(model) {
|
|
|
57
61
|
<head>
|
|
58
62
|
<meta charset="utf-8">
|
|
59
63
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
64
|
+
<meta name="generator" content="${GENERATOR}">
|
|
60
65
|
<title>${esc(path.basename(model.root))} · design system</title>
|
|
61
66
|
<style>
|
|
62
67
|
@layer designrail.tokens, designrail.base, designrail.parts;
|
package/src/tokens.js
CHANGED
|
@@ -4,7 +4,11 @@ import { parseColor, colorFacts, normShadow, lengthCategory } from './values.js'
|
|
|
4
4
|
import { roleOfName, CONTRACT } from './contract.js';
|
|
5
5
|
import { pickDef } from './model.js';
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
// A length token's scale, from its name when the name says it: a control
|
|
8
|
+
// height is a size, never a spacing step, however it is read.
|
|
9
|
+
const nameCat = (n) => (/space|gap|pad|margin|inset|gutter|spacing/.test(n) ? 'space' : /radius|(^|-)round(ed)?(-|$)|corner/.test(n) ? 'radius'
|
|
10
|
+
: /control|icon|avatar|(^|-)(box|tap|target|thumb)(-|$)/.test(n) ? 'size' : /font-size|text-size|(^--)(size|fs|type)-|-size-?\d/.test(n) ? 'font-size'
|
|
11
|
+
: /(^|-)(size|height|width|[hw])(-|$)/.test(n) ? 'size' : null);
|
|
8
12
|
export const firstFamily = (stack) => stack.split(',')[0].trim().replace(/^['"]|['"]$/g, '').toLowerCase();
|
|
9
13
|
|
|
10
14
|
export function tokenIndex(model) {
|
|
@@ -32,7 +36,7 @@ export function tokenIndex(model) {
|
|
|
32
36
|
if (len) {
|
|
33
37
|
t.px = len[2] === 'px' ? parseFloat(len[1]) : parseFloat(len[1]) * 16;
|
|
34
38
|
const u = usedIn.get(name);
|
|
35
|
-
t.cat = u ? Object.entries(u).sort((a, b) => b[1] - a[1])[0][0] :
|
|
39
|
+
t.cat = nameCat(name) ?? (u ? Object.entries(u).sort((a, b) => b[1] - a[1])[0][0] : null);
|
|
36
40
|
}
|
|
37
41
|
if (/\d+px/.test(value) && /(#|rgb|hsl|oklch|inset|\d+px\s+-?\d+px)/.test(value) && /shadow|elev|depth/.test(name)) t.shadow = normShadow(value);
|
|
38
42
|
if (/font|family|face|typeface/.test(name) && !/size|weight|track|leading|line/.test(name) && /[a-z]/i.test(value) && !len) t.font = firstFamily(value);
|
|
@@ -45,11 +49,17 @@ export function tokenIndex(model) {
|
|
|
45
49
|
|
|
46
50
|
// Primitive: a token holding a literal, read by semantic tokens. A project with
|
|
47
51
|
// no semantic layer has no primitives in this sense (everything is the API).
|
|
48
|
-
// A literal token counts as a primitive when it
|
|
49
|
-
//
|
|
52
|
+
// A literal token counts as a primitive when it is a foundation literal or
|
|
53
|
+
// lives in a primitives file. A project with no primitives file has only
|
|
54
|
+
// its literals that another token is built on. A contract name is always
|
|
55
|
+
// API, never primitive. With a primitives file, a literal in the semantic
|
|
56
|
+
// file that other tokens compose (`--safe-t`, `--icon-stroke`) is API.
|
|
50
57
|
export function primitivesOf(tokens) {
|
|
51
58
|
if (!tokens.some((t) => t.semantic)) return new Set();
|
|
52
59
|
const api = new Set(CONTRACT.map((c) => c.name));
|
|
60
|
+
const isPrimFile = (t) => !t.external && /primitive/i.test(t.file);
|
|
61
|
+
const split = tokens.some(isPrimFile);
|
|
53
62
|
const read = new Set(tokens.filter((t) => t.semantic).flatMap((t) => [...t.raw.matchAll(/var\(\s*(--[\w-]+)/g)].map((m) => m[1])));
|
|
54
|
-
|
|
63
|
+
// The foundation's own literals (--gray-950, --blue-500) are its primitives.
|
|
64
|
+
return new Set(tokens.filter((t) => !t.semantic && !api.has(t.name) && (t.external || isPrimFile(t) || (!split && read.has(t.name)))).map((t) => t.name));
|
|
55
65
|
}
|