@rickycourtes/designrail 0.2.1 → 0.2.2
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 +33 -0
- package/README.md +50 -13
- package/kit/changes.json +7 -0
- package/package.json +1 -1
- package/schema.json +19 -1
- package/src/audit.js +76 -31
- package/src/css.js +8 -1
- package/src/fix.js +6 -2
- package/src/init.js +6 -2
- package/src/model.js +3 -3
- package/src/project.js +13 -3
- package/src/report.js +2 -2
- package/src/specimens.js +5 -0
- package/src/tokens.js +10 -4
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,39 @@
|
|
|
3
3
|
Every foundation release also has an entry in `kit/changes.json`, which
|
|
4
4
|
`designrail upgrade` reads to move a project forward.
|
|
5
5
|
|
|
6
|
+
## 0.2.2
|
|
7
|
+
|
|
8
|
+
No foundation changes. Five gaps found by auditing a real project:
|
|
9
|
+
|
|
10
|
+
- Exemption comments work. `/* designrail-ignore */` or `/* measured */`
|
|
11
|
+
inside a value now leaves that declaration out of the hardcoded, scale and
|
|
12
|
+
duplicate counts, and out of `fix`. Before, comments were blanked before
|
|
13
|
+
values were read, so the marker was never seen.
|
|
14
|
+
- `audit` groups part families by file. Inside the `parts` folder each file
|
|
15
|
+
is one part, its role taken from the file's name, and a class it defines
|
|
16
|
+
stays that part's wherever else it is styled. So `.field`, `.input`,
|
|
17
|
+
`input` and `textarea` in one `field.css` are one family, and
|
|
18
|
+
`.pf-banner` in `profile.css` is not a toast. Class-name heuristics still
|
|
19
|
+
apply outside `parts`.
|
|
20
|
+
- New config key `specimens` (globs): specimen pages are left out of the
|
|
21
|
+
repeated-markup and part-family checks. `init` sets it when it finds the
|
|
22
|
+
page `designrail specimens` writes, which now carries a
|
|
23
|
+
`<meta name="generator" content="designrail specimens">` tag.
|
|
24
|
+
- Rule blocks whose selectors differ only by vendor pseudo-elements
|
|
25
|
+
(`::-webkit-slider-thumb` and `::-moz-range-thumb`) are no longer
|
|
26
|
+
duplicates or near-duplicates: they can't share one selector list.
|
|
27
|
+
- `fix` keeps its own rules. With `semanticOnly` on it never writes a
|
|
28
|
+
primitive outside token files (`#0e1218` no longer becomes
|
|
29
|
+
`var(--gray-950)`), and a length maps only to a token of the property's
|
|
30
|
+
scale, read from the token's name first (`padding: 44px` no longer becomes
|
|
31
|
+
`var(--control)`). The foundation's palette now counts as primitives, so
|
|
32
|
+
`check` reports reading `--gray-950` directly as `primitive-direct`.
|
|
33
|
+
- Duplicate rule blocks have a floor, as copy-paste detectors have a minimum
|
|
34
|
+
size: identical blocks count from 3 declarations (was 2 outside state
|
|
35
|
+
rules), near pairs when they share 3. Two token reads in common
|
|
36
|
+
(`font-weight: 600; color: var(--text)`) are a type role, not a copy.
|
|
37
|
+
Configurable as `duplicates: { minDeclarations: 3 }`.
|
|
38
|
+
|
|
6
39
|
## 0.2.1
|
|
7
40
|
|
|
8
41
|
No foundation changes.
|
package/README.md
CHANGED
|
@@ -167,7 +167,8 @@ Writes `designrail.config.json` and `DESIGN.md`, the project's design rules
|
|
|
167
167
|
(see [Design rules](#design-rules)). If the project already has token files
|
|
168
168
|
(stylesheets that are mostly custom properties on `:root`), `init` finds them
|
|
169
169
|
and points `tokens` at them. `parts` is set to `src/ui` when there is a `src/`
|
|
170
|
-
folder, else `ui`.
|
|
170
|
+
folder, else `ui`. A page `designrail specimens` wrote (wherever `--out` put
|
|
171
|
+
it) is listed under `specimens`. When the foundation is installed (or `package.json`
|
|
171
172
|
depends on `designrail`), `init` records its version as `foundation` and
|
|
172
173
|
prints the import lines.
|
|
173
174
|
|
|
@@ -197,16 +198,35 @@ Then the details:
|
|
|
197
198
|
- **Families, weights, shadows, durations, z-index**: every distinct value.
|
|
198
199
|
- **Duplicate rule blocks**: selectors whose declarations are identical (`.card
|
|
199
200
|
≡ .panel`), and pairs that share most of them (60%+), with what differs.
|
|
201
|
+
Like a copy-paste detector's minimum size, a block counts only at
|
|
202
|
+
`duplicates.minDeclarations` (3) declarations, and a near pair only when it
|
|
203
|
+
shares that many: two rules that both read `font-weight: 600; color:
|
|
204
|
+
var(--text)` are a type role, and merging them would couple unrelated parts.
|
|
200
205
|
Near-identical colours count as equal here. Show/hide state rules
|
|
201
|
-
(`display`, `opacity`, `pointer-events`…) are left out
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
+
(`display`, `opacity`, `pointer-events`…) are left out, and so are rules
|
|
207
|
+
whose selectors differ only by vendor pseudo-elements
|
|
208
|
+
(`::-webkit-slider-thumb` and `::-moz-range-thumb`): they can't share one
|
|
209
|
+
selector list, since a browser drops the whole list over a pseudo-element
|
|
210
|
+
it doesn't know.
|
|
211
|
+
- **Parts drawn more than one way**: parts grouped by role (button, field,
|
|
212
|
+
card, pill, dialog, toast, dropdown) and by family.
|
|
213
|
+
- Inside the `parts` folder, each file is one part, so one family, whatever
|
|
214
|
+
its classes are called: `.field`, `.input`, `input` and `textarea` in
|
|
215
|
+
`ui/field.css` are the field part. The role comes from the file's name
|
|
216
|
+
(`field.css`, `value-field.css`). A file whose name is no role
|
|
217
|
+
(`profile.css`) is a part of its own, so its `.pf-banner` is not a toast.
|
|
218
|
+
- A class a part file defines stays that part's wherever else it is styled:
|
|
219
|
+
`.checkout .btn` restyles the button part, it is not another family.
|
|
220
|
+
- Elsewhere, class names say the role and family. For example,
|
|
221
|
+
`.btn`/`.btn-secondary` are one family while `.submit-button` and `.cta`
|
|
222
|
+
are others, so the report suggests one part with variants.
|
|
206
223
|
- **Repeated markup**: the same element structure (tags and classes) copied
|
|
207
224
|
in more than one place, and the same structure repeated with different
|
|
208
225
|
classes. Sibling repeats in a list are left out (render those from data).
|
|
209
226
|
|
|
227
|
+
Pages listed under `specimens` in the config show parts side by side on
|
|
228
|
+
purpose, so they're left out of the part-family and repeated-markup checks.
|
|
229
|
+
|
|
210
230
|
`--html file` writes a self-contained report page to share. `--limit n` sets
|
|
211
231
|
how many items each section shows (default 6).
|
|
212
232
|
|
|
@@ -278,10 +298,18 @@ Rewrites hardcoded values as the tokens that hold them. It shows a diff
|
|
|
278
298
|
A semantic token whose job is a different property is never used, so
|
|
279
299
|
`#1a1a1a` as a background never becomes `--text`.
|
|
280
300
|
- **Spacing, radius, font size**: an exact pixel match within the same scale
|
|
281
|
-
(rem converts at 16px; em is skipped).
|
|
301
|
+
(rem converts at 16px; em is skipped). A token's scale comes from its name
|
|
302
|
+
when the name says it (`--space-*`, `--gap`, `--radius-*`; `--control`,
|
|
303
|
+
`--icon-*` and `--*-h` are sizes, which `fix` never writes), else from the
|
|
304
|
+
properties that read it. So `padding: 44px` never becomes `--control`. With `--snap`, anything within
|
|
282
305
|
`snap` px of a step also matches, and the diff marks it `snapped`. A
|
|
283
306
|
negative margin becomes `calc(var(--space-8) * -1)`.
|
|
284
307
|
- **Families, shadows, durations**: an exact match.
|
|
308
|
+
- **Primitives**: every value lands outside token files, so with
|
|
309
|
+
`semanticOnly` on, `fix` never writes a primitive (the foundation's palette,
|
|
310
|
+
such as `--gray-950`, included), only semantic tokens and the
|
|
311
|
+
`allowPrimitives` steps. A colour only a primitive holds is listed as
|
|
312
|
+
having no token.
|
|
285
313
|
- **Where it writes**: CSS/SCSS/Less, `<style>` blocks, `style=""`
|
|
286
314
|
attributes, styled-components and `css`` ` templates, JSX style objects (a
|
|
287
315
|
number like `padding: 12` becomes `padding: 'var(--space-12)'`), and
|
|
@@ -298,8 +326,8 @@ The drift gate. It exits 1 if any rule set to `error` has a hit.
|
|
|
298
326
|
| --- | --- | --- |
|
|
299
327
|
| `hardcoded` | A colour, spacing, radius, font size, family or shadow typed by hand outside token files. Shows the token that holds it, if one does. | error |
|
|
300
328
|
| `unresolved` | A `var(--x)` with `--x` defined nowhere and not set from JS. | error |
|
|
301
|
-
| `primitive-direct` | A primitive read outside token files when a semantic layer exists (except `allowPrimitives` and contract names). | warn |
|
|
302
|
-
| `duplicate-block` | A rule block identical to another one. | error |
|
|
329
|
+
| `primitive-direct` | A primitive read outside token files when a semantic layer exists (except `allowPrimitives` and contract names). The foundation's palette (`--gray-950`, `--blue-500`…) counts as primitives. | warn |
|
|
330
|
+
| `duplicate-block` | A rule block identical to another one, at `duplicates.minDeclarations` (3) declarations or more. | error |
|
|
303
331
|
| `unused` | A token nobody reads (contract names are exempt: they are the parts' API). | warn |
|
|
304
332
|
| `tracked-caps` | `text-transform: uppercase` with letter-spacing. | warn |
|
|
305
333
|
| `contract` | With the foundation installed: a core token (`--surface`, `--text`, `--accent`, `--text-on-accent`, `--font-ui`) the project never sets, so it shows the foundation's default. | warn |
|
|
@@ -348,6 +376,10 @@ Writes one static page (default `.designrail/specimens.html`) showing:
|
|
|
348
376
|
*foundation*, *ejected* (the project's own copy) or, with no foundation
|
|
349
377
|
installed, *kit*.
|
|
350
378
|
|
|
379
|
+
If you write it into the project (`--out ui.html`), list it under `specimens`
|
|
380
|
+
in the config (`init` does this for a page it finds) so `audit` doesn't count
|
|
381
|
+
its parts as copies.
|
|
382
|
+
|
|
351
383
|
A light/dark toggle appears when the token files define a dark theme. With
|
|
352
384
|
no token files of its own, the project is shown in the foundation's default
|
|
353
385
|
theme.
|
|
@@ -695,6 +727,7 @@ optional, and `schema.json` validates it.
|
|
|
695
727
|
"exclude": ["dist", "build", "out", "coverage", "vendor", "**/*.min.*", "**/*.map"],
|
|
696
728
|
"tokens": ["tokens/primitives.css", "tokens/semantic.css"],
|
|
697
729
|
"parts": "ui",
|
|
730
|
+
"specimens": [],
|
|
698
731
|
"grid": 4,
|
|
699
732
|
"colorTolerance": 0.01,
|
|
700
733
|
"snap": 1,
|
|
@@ -711,6 +744,7 @@ optional, and `schema.json` validates it.
|
|
|
711
744
|
"contract": "warn",
|
|
712
745
|
"part-restyle": "warn"
|
|
713
746
|
},
|
|
747
|
+
"duplicates": { "minDeclarations": 3 },
|
|
714
748
|
"maxFileBytes": 1500000
|
|
715
749
|
}
|
|
716
750
|
```
|
|
@@ -722,19 +756,22 @@ optional, and `schema.json` validates it.
|
|
|
722
756
|
| `include` | Folders to scan. |
|
|
723
757
|
| `exclude` | Globs left out. `.gitignore` entries, `.git`, `node_modules` and `.designrail` are always left out too. |
|
|
724
758
|
| `tokens` | The token files. Stylesheets that are mostly custom properties on `:root` (or `html`, `:host`, `[data-theme]`) count as token files even if unlisted. |
|
|
725
|
-
| `parts` | Where the project's own parts live, and where `eject` copies one. |
|
|
759
|
+
| `parts` | Where the project's own parts live, and where `eject` copies one. Each file in it is one part to `audit`. |
|
|
760
|
+
| `specimens` | Globs for specimen pages, which show parts side by side on purpose. They're left out of `audit`'s part-family and repeated-markup checks. `init` sets it when it finds the page `specimens` writes. |
|
|
726
761
|
| `grid` | The spacing grid in px. |
|
|
727
762
|
| `colorTolerance` | ΔE (OKLab) below which two colours are the same colour. 0.01 merges `#3b82f6` and `#3b83f6` but keeps `#ffffff` and `#fafafa` apart. |
|
|
728
763
|
| `snap` | px within which `extract` merges lengths and `fix --snap` maps one to a step. |
|
|
729
|
-
| `semanticOnly` | Report primitives read outside token files. |
|
|
764
|
+
| `semanticOnly` | Report primitives read outside token files, and keep `fix` from writing them there. |
|
|
730
765
|
| `allowPrimitives` | Primitive prefixes allowed anywhere. |
|
|
731
766
|
| `runtimeTokens` | Custom properties set from JS, as names or prefixes, so they count as defined. Calls like `setProperty('--x', …)` are found on their own. |
|
|
732
767
|
| `rules` | `error`, `warn` or `off` per check rule. |
|
|
768
|
+
| `duplicates.minDeclarations` | How many declarations rule blocks must share to count as identical or near duplicates (default 3, at least 2). At 2, state rules (`:hover`, `:focus`…) still need 3. |
|
|
733
769
|
| `maxFileBytes` | Larger files are skipped. |
|
|
734
770
|
|
|
735
771
|
To exempt a single declaration, put `/* designrail-ignore */` (or
|
|
736
|
-
`/* measured */`) inside its value, for example
|
|
737
|
-
`margin-top: -3px /* measured */;`.
|
|
772
|
+
`/* measured */`) inside its value, before the `;`, for example
|
|
773
|
+
`margin-top: -3px /* measured */;`. It is then left out of the hardcoded,
|
|
774
|
+
scale and duplicate counts, and `fix` leaves it alone.
|
|
738
775
|
|
|
739
776
|
## What it reads
|
|
740
777
|
|
package/kit/changes.json
CHANGED
|
@@ -19,5 +19,12 @@
|
|
|
19
19
|
"renamed": {},
|
|
20
20
|
"added": { "tokens": [], "parts": [], "classes": [] },
|
|
21
21
|
"removed": { "tokens": [], "parts": [] }
|
|
22
|
+
},
|
|
23
|
+
{
|
|
24
|
+
"version": "0.2.2",
|
|
25
|
+
"notes": "No foundation changes. Audit and fix: exemption comments work, part families by file, a specimens config key, vendor-prefixed rules and blocks under duplicates.minDeclarations (3) are not duplicates, and fix never writes a primitive or a token from another scale.",
|
|
26
|
+
"renamed": {},
|
|
27
|
+
"added": { "tokens": [], "parts": [], "classes": [] },
|
|
28
|
+
"removed": { "tokens": [], "parts": [] }
|
|
22
29
|
}
|
|
23
30
|
]
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rickycourtes/designrail",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.2",
|
|
4
4
|
"description": "The design foundation for any web project: a token contract, layered parts every project builds on, and tooling to audit duplication, extract tokens, fix hardcoded values, gate drift and upgrade.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
package/schema.json
CHANGED
|
@@ -29,7 +29,14 @@
|
|
|
29
29
|
},
|
|
30
30
|
"parts": {
|
|
31
31
|
"type": "string",
|
|
32
|
-
"description": "Where `designrail
|
|
32
|
+
"description": "Where the project's own parts live (each file is one part), and where `designrail eject` copies one."
|
|
33
|
+
},
|
|
34
|
+
"specimens": {
|
|
35
|
+
"type": "array",
|
|
36
|
+
"items": {
|
|
37
|
+
"type": "string"
|
|
38
|
+
},
|
|
39
|
+
"description": "Globs for specimen pages (parts side by side on purpose), left out of the repeated-markup and part-family checks."
|
|
33
40
|
},
|
|
34
41
|
"grid": {
|
|
35
42
|
"type": "number",
|
|
@@ -81,6 +88,17 @@
|
|
|
81
88
|
"part-restyle": {}
|
|
82
89
|
}
|
|
83
90
|
},
|
|
91
|
+
"duplicates": {
|
|
92
|
+
"type": "object",
|
|
93
|
+
"properties": {
|
|
94
|
+
"minDeclarations": {
|
|
95
|
+
"type": "integer",
|
|
96
|
+
"minimum": 2,
|
|
97
|
+
"description": "Identical rule blocks count as duplicates at this many declarations or more, near-duplicates when they share this many (default 3)."
|
|
98
|
+
}
|
|
99
|
+
},
|
|
100
|
+
"additionalProperties": false
|
|
101
|
+
},
|
|
84
102
|
"maxFileBytes": {
|
|
85
103
|
"type": "number"
|
|
86
104
|
},
|
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/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,6 +6,7 @@ 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
11
|
const RULES = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'rules', 'DESIGN.md');
|
|
11
12
|
|
|
@@ -26,11 +27,14 @@ export function init(root, { agents = false, force = false } = {}) {
|
|
|
26
27
|
const found = listFiles(root, cfg).filter((f) => /\.(css|scss|less)$/.test(f))
|
|
27
28
|
.filter((f) => { try { return isTokenFile({ path: f, ...analyze(f, fs.readFileSync(path.join(root, f), 'utf8')) }, { ...cfg, tokens: [] }); } catch { return false; } });
|
|
28
29
|
const tokens = found.length ? found : cfg.tokens;
|
|
30
|
+
// Pages `designrail specimens` wrote (wherever --out put them).
|
|
31
|
+
const pages = listFiles(root, cfg).filter((f) => /\.html?$/.test(f))
|
|
32
|
+
.filter((f) => { try { return isSpecimenPage(fs.readFileSync(path.join(root, f), 'utf8')); } catch { return false; } });
|
|
29
33
|
if (!fs.existsSync(cfgPath) || force) {
|
|
30
34
|
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 };
|
|
35
|
+
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
36
|
fs.writeFileSync(cfgPath, JSON.stringify(out, null, 2) + '\n');
|
|
33
|
-
done.push(`designrail.config.json${found.length ? ` (tokens found in ${found.join(', ')})` : ''}`);
|
|
37
|
+
done.push(`designrail.config.json${found.length ? ` (tokens found in ${found.join(', ')})` : ''}${pages.length ? ` (specimens: ${pages.join(', ')})` : ''}`);
|
|
34
38
|
}
|
|
35
39
|
const rulesPath = path.join(root, 'DESIGN.md');
|
|
36
40
|
if (!fs.existsSync(rulesPath) || force) { fs.copyFileSync(RULES, rulesPath); done.push('DESIGN.md'); }
|
package/src/model.js
CHANGED
|
@@ -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,
|
|
@@ -34,6 +36,8 @@ export const DEFAULT_CONFIG = {
|
|
|
34
36
|
runtimeTokens: [],
|
|
35
37
|
rules: { hardcoded: 'error', unresolved: 'error', 'primitive-direct': 'warn', 'duplicate-block': 'error', unused: 'warn', 'tracked-caps': 'warn', contract: 'warn', 'part-restyle': 'warn' },
|
|
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,7 +46,7 @@ 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);
|
|
47
51
|
return cfg;
|
|
48
52
|
}
|
|
@@ -55,7 +59,13 @@ export function saveConfig(root, patch) {
|
|
|
55
59
|
fs.writeFileSync(file, JSON.stringify({ ...cur, ...patch }, null, 2) + '\n');
|
|
56
60
|
}
|
|
57
61
|
|
|
58
|
-
|
|
62
|
+
// A file inside the config's `parts` folder.
|
|
63
|
+
export const inParts = (file, cfg) => Boolean(cfg.parts) && file.startsWith(cfg.parts.replace(/^\.\/|\/$/g, '') + '/');
|
|
64
|
+
|
|
65
|
+
// A specimen page (`specimens` globs): parts shown side by side on purpose.
|
|
66
|
+
export const isSpecimen = (file, cfg) => (cfg.specimens ?? []).some((g) => globRe(g).test(file));
|
|
67
|
+
|
|
68
|
+
export function globRe(g) {
|
|
59
69
|
return new RegExp('(^|/)' + g.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*\*\//g, '(.*/)?').replace(/\*\*/g, '.*').replace(/\*/g, '[^/]*') + '($|/)');
|
|
60
70
|
}
|
|
61
71
|
|
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/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);
|
|
@@ -46,10 +50,12 @@ export function tokenIndex(model) {
|
|
|
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
52
|
// A literal token counts as a primitive when it lives in a primitives file or
|
|
49
|
-
// another token is built on it
|
|
53
|
+
// another token is built on it, or it is a foundation literal; a contract
|
|
54
|
+
// name is always API, never primitive.
|
|
50
55
|
export function primitivesOf(tokens) {
|
|
51
56
|
if (!tokens.some((t) => t.semantic)) return new Set();
|
|
52
57
|
const api = new Set(CONTRACT.map((c) => c.name));
|
|
53
58
|
const read = new Set(tokens.filter((t) => t.semantic).flatMap((t) => [...t.raw.matchAll(/var\(\s*(--[\w-]+)/g)].map((m) => m[1])));
|
|
54
|
-
|
|
59
|
+
// The foundation's own literals (--gray-950, --blue-500) are its primitives.
|
|
60
|
+
return new Set(tokens.filter((t) => !t.semantic && !api.has(t.name) && (t.external || /primitive/i.test(t.file) || read.has(t.name))).map((t) => t.name));
|
|
55
61
|
}
|