@reqvire-org/ads 0.3.45 → 0.3.47
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/README.md +23 -11
- package/dist/a11y.mjs +102 -0
- package/dist/assets.mjs +37 -8
- package/dist/atomic-composition.mjs +3 -2
- package/dist/brand-assets.mjs +48 -11
- package/dist/brands.mjs +82 -0
- package/dist/browser-audit/worker.mjs +45 -0
- package/dist/browser-audit.mjs +117 -0
- package/dist/capture/worker.mjs +2 -1
- package/dist/capture-store.mjs +4 -1
- package/dist/capture.mjs +10 -4
- package/dist/check.mjs +40 -9
- package/dist/cli.mjs +55 -8
- package/dist/color-values.mjs +325 -0
- package/dist/config.mjs +19 -2
- package/dist/contracts/tokens.json +1 -1
- package/dist/control-padding.mjs +93 -0
- package/dist/design-values.mjs +11 -4
- package/dist/finding-rules.mjs +61 -0
- package/dist/foundation.mjs +17 -1
- package/dist/icons.mjs +107 -0
- package/dist/init.mjs +3 -0
- package/dist/mcp/apps.mjs +9 -6
- package/dist/mcp/drafts.mjs +3 -0
- package/dist/mcp/mutations.mjs +17 -1
- package/dist/mcp/preview-widget.bundle.js +45 -39
- package/dist/mcp/project-widget.bundle.js +26 -26
- package/dist/mcp/server.mjs +23 -9
- package/dist/mcp/widget.bundle.js +17 -17
- package/dist/palette-generated.mjs +180 -0
- package/dist/preview-resources.mjs +12 -3
- package/dist/render-color-probe.mjs +148 -0
- package/dist/runtime-contracts.mjs +14 -4
- package/dist/scenarios.mjs +1 -1
- package/dist/showcase/client.bundle.js +28 -28
- package/dist/showcase/icons.js +146 -0
- package/dist/showcase/index.html +2 -1
- package/dist/showcase/style.css +19 -2
- package/dist/skills/README.md +2 -1
- package/dist/skills/ads-break-ui/SKILL.md +6 -5
- package/dist/skills/ads-break-ui/references/atomic-styles.md +12 -12
- package/dist/skills/ads-break-ui/references/captures.md +3 -2
- package/dist/skills/ads-break-ui/references/contracts.md +13 -10
- package/dist/skills/ads-break-ui/references/design-data.md +199 -2
- package/dist/skills/ads-break-ui/references/validation.md +8 -4
- package/dist/skills/ads-designer/SKILL.md +32 -15
- package/dist/skills/ads-designer/references/accessibility.md +77 -0
- package/dist/skills/ads-designer/references/atomic-styles.md +12 -12
- package/dist/skills/ads-designer/references/branding.md +61 -6
- package/dist/skills/ads-designer/references/captures.md +3 -2
- package/dist/skills/ads-designer/references/cli.md +8 -2
- package/dist/skills/ads-designer/references/contracts.md +13 -10
- package/dist/skills/ads-designer/references/design-data.md +199 -2
- package/dist/skills/ads-designer/references/validation.md +8 -4
- package/dist/skills/ads-import/SKILL.md +9 -8
- package/dist/skills/ads-import/references/atomic-styles.md +12 -12
- package/dist/skills/ads-import/references/captures.md +3 -2
- package/dist/skills/ads-import/references/cli.md +8 -2
- package/dist/skills/ads-import/references/contracts.md +13 -10
- package/dist/skills/ads-import/references/design-data.md +199 -2
- package/dist/skills/ads-import/references/tokens.md +7 -3
- package/dist/skills/ads-import/references/validation.md +8 -4
- package/dist/skills/ads-motion/SKILL.md +6 -5
- package/dist/skills/ads-motion/references/atomic-styles.md +12 -12
- package/dist/skills/ads-motion/references/build.md +33 -0
- package/dist/skills/ads-motion/references/captures.md +3 -2
- package/dist/skills/ads-motion/references/contracts.md +13 -10
- package/dist/skills/ads-motion/references/design-data.md +199 -2
- package/dist/skills/ads-motion/references/motion-review.md +2 -2
- package/dist/skills/ads-motion/references/validation.md +8 -4
- package/dist/skills/ads-port/SKILL.md +6 -5
- package/dist/skills/ads-port/references/atomic-styles.md +12 -12
- package/dist/skills/ads-port/references/captures.md +3 -2
- package/dist/skills/ads-port/references/cli.md +8 -2
- package/dist/skills/ads-port/references/contracts.md +13 -10
- package/dist/skills/ads-port/references/design-data.md +199 -2
- package/dist/skills/ads-port/references/validation.md +8 -4
- package/dist/starters/preact/design-system/components/Layout/Grid/Grid.tsx +76 -0
- package/dist/starters/preact/design-system/review/token-preview/TokenPreview.tsx +19 -1
- package/dist/starters/preact/ds.config.json +13 -1
- package/dist/starters/react/ADS.md +43 -10
- package/dist/starters/react/README.md +61 -9
- package/dist/starters/react/design-system/assets/brand/README.md +8 -3
- package/dist/starters/react/design-system/assets/glyphs/README.md +15 -0
- package/dist/starters/react/design-system/assets/glyphs/aliases.json +1 -0
- package/dist/starters/react/design-system/assets/glyphs/check.svg +1 -0
- package/dist/starters/react/design-system/assets/glyphs/chevron-down.svg +1 -0
- package/dist/starters/react/design-system/assets/glyphs/chevron-right.svg +1 -0
- package/dist/starters/react/design-system/assets/glyphs/close.svg +1 -0
- package/dist/starters/react/design-system/assets/glyphs/external-link.svg +1 -0
- package/dist/starters/react/design-system/assets/glyphs/info.svg +1 -0
- package/dist/starters/react/design-system/assets/glyphs/menu.svg +1 -0
- package/dist/starters/react/design-system/assets/glyphs/plus.svg +1 -0
- package/dist/starters/react/design-system/assets/glyphs/search.svg +1 -0
- package/dist/starters/react/design-system/assets/glyphs/warning.svg +1 -0
- package/dist/starters/react/design-system/components/Actions/Button/Button.tsx +11 -4
- package/dist/starters/react/design-system/components/Actions/IconButton/IconButton.ads.fixture.ts +9 -0
- package/dist/starters/react/design-system/components/Actions/IconButton/IconButton.ads.scenario.tsx +16 -0
- package/dist/starters/react/design-system/components/Actions/IconButton/IconButton.tsx +44 -0
- package/dist/starters/react/design-system/components/Actions/IconButton/README.md +14 -0
- package/dist/starters/react/design-system/components/Content/Icon/Icon.ads.fixture.ts +6 -0
- package/dist/starters/react/design-system/components/Content/Icon/Icon.ads.scenario.tsx +16 -0
- package/dist/starters/react/design-system/components/Content/Icon/Icon.tsx +42 -0
- package/dist/starters/react/design-system/components/Content/Icon/README.md +17 -0
- package/dist/starters/react/design-system/components/Content/Icon/glyphs.ts +17 -0
- package/dist/starters/react/design-system/components/Content/Logo/Logo.tsx +3 -9
- package/dist/starters/react/design-system/components/Content/Logo/README.md +4 -2
- package/dist/starters/react/design-system/components/Forms/TextField/TextField.tsx +9 -5
- package/dist/starters/react/design-system/components/Layout/Grid/Grid.ads.fixture.ts +12 -0
- package/dist/starters/react/design-system/components/Layout/Grid/Grid.ads.scenario.tsx +17 -0
- package/dist/starters/react/design-system/components/Layout/Grid/Grid.tsx +75 -0
- package/dist/starters/react/design-system/components/Layout/Grid/README.md +21 -0
- package/dist/starters/react/design-system/controllers/Palette/Palette.ts +164 -0
- package/dist/starters/react/design-system/index.ts +6 -0
- package/dist/starters/react/design-system/review/brand-preview/BrandPreview.tsx +2 -5
- package/dist/starters/react/design-system/review/grid-cell/GridCell.tsx +18 -0
- package/dist/starters/react/design-system/review/index.ts +1 -0
- package/dist/starters/react/design-system/review/token-preview/TokenPreview.tsx +19 -1
- package/dist/starters/react/design-system/styles.css +1 -0
- package/dist/starters/react/design-system/tokens/Color.ads.fixture.ts +114 -8
- package/dist/starters/react/design-system/tokens/Layout.ads.fixture.ts +23 -0
- package/dist/starters/react/design-system/tokens/{SpaceTypeMotion.ads.scenario.tsx → Layout.ads.scenario.tsx} +1 -1
- package/dist/starters/react/design-system/tokens/Motion.ads.fixture.ts +18 -0
- package/dist/starters/react/design-system/tokens/Motion.ads.scenario.tsx +4 -0
- package/dist/starters/react/design-system/tokens/Shape.ads.fixture.ts +30 -0
- package/dist/starters/react/design-system/tokens/Shape.ads.scenario.tsx +4 -0
- package/dist/starters/react/design-system/tokens/Space.ads.fixture.ts +37 -0
- package/dist/starters/react/design-system/tokens/Space.ads.scenario.tsx +4 -0
- package/dist/starters/react/design-system/tokens/Type.ads.fixture.ts +29 -0
- package/dist/starters/react/design-system/tokens/Type.ads.scenario.tsx +4 -0
- package/dist/starters/react/design-system/tokens/base.css +9 -3
- package/dist/starters/react/design-system/tokens/colors.css +210 -24
- package/dist/starters/react/design-system/tokens/elevation.css +44 -6
- package/dist/starters/react/design-system/tokens/spacing.css +67 -3
- package/dist/starters/react/design-system/tokens/themes.generated.css +142 -0
- package/dist/starters/react/design-system/tokens/themes.generated.ts +402 -0
- package/dist/starters/react/design-system/tokens/typography.css +25 -7
- package/dist/starters/react/ds.config.json +13 -1
- package/dist/style-boundaries.mjs +2 -1
- package/dist/themes-generated.mjs +150 -0
- package/dist/themes-watch.mjs +42 -0
- package/dist/themes.mjs +257 -0
- package/dist/token-export.mjs +69 -0
- package/dist/token-policy.mjs +2 -1
- package/dist/token-quality.mjs +112 -0
- package/dist/tokens.mjs +32 -30
- package/dist/validation.mjs +18 -1
- package/dist/verification/browser.mjs +14 -3
- package/docs/ADS.md +56 -13
- package/docs/ARCHITECTURE.md +82 -10
- package/docs/CACHING.md +2 -3
- package/docs/CHANGELOG.md +149 -13
- package/docs/CONTRACTS.md +13 -10
- package/docs/GUIDE.md +104 -8
- package/docs/MCP.md +46 -27
- package/docs/benchmarks/bun-previews.md +5 -5
- package/docs/benchmarks/{gidi-preview-memory.md → preview-memory.md} +14 -12
- package/docs/benchmarks/turbo-poc.md +24 -6
- package/package.json +2 -1
- package/dist/starters/react/design-system/tokens/SpaceTypeMotion.ads.fixture.ts +0 -36
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { watch } from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { loadConfig } from "./config.mjs";
|
|
4
|
+
import { inspectTokens } from "./tokens.mjs";
|
|
5
|
+
import { generatedThemeFiles, generatedThemesFile, writeThemesCss } from "./themes-generated.mjs";
|
|
6
|
+
|
|
7
|
+
/** Rewrites the project's themes.generated.css and themes.generated.ts from its token sheets and config when stale. */
|
|
8
|
+
export function refreshThemesCss(directory) {
|
|
9
|
+
const options = loadConfig(directory);
|
|
10
|
+
return { ...writeThemesCss(options, inspectTokens(directory, options)), root: options.root };
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Keeps themes.generated.css and .ts current: once now, then on every token sheet or config change. */
|
|
14
|
+
export function watchThemesCss(directory, { log = () => {} } = {}) {
|
|
15
|
+
const watchers = [];
|
|
16
|
+
let timer;
|
|
17
|
+
const refresh = () => {
|
|
18
|
+
try {
|
|
19
|
+
const result = refreshThemesCss(directory);
|
|
20
|
+
for (const item of result.files ?? []) if (item.written) log(`ADS wrote ${path.relative(result.root, item.file).replaceAll("\\", "/")}`);
|
|
21
|
+
} catch (error) { log(`ADS could not write ${generatedThemesFile}: ${error.message}`); }
|
|
22
|
+
};
|
|
23
|
+
const changed = file => {
|
|
24
|
+
const name = path.basename(String(file ?? ""));
|
|
25
|
+
if (generatedThemeFiles.some(generated => name === generated || name.startsWith(`${generated}.`))) return;
|
|
26
|
+
clearTimeout(timer);
|
|
27
|
+
timer = setTimeout(refresh, 50);
|
|
28
|
+
timer.unref?.();
|
|
29
|
+
};
|
|
30
|
+
refresh();
|
|
31
|
+
try {
|
|
32
|
+
const { root, dsRoot, config } = loadConfig(directory);
|
|
33
|
+
for (const [folder, filter] of [[path.join(dsRoot, config.tokenDir), file => String(file).endsWith(".css")], [root, file => String(file) === "ds.config.json"]]) {
|
|
34
|
+
try {
|
|
35
|
+
const watcher = watch(folder, { recursive: folder !== root }, (_event, file) => { if (filter(file)) changed(file); });
|
|
36
|
+
watcher.unref(); watcher.on("error", () => watcher.close());
|
|
37
|
+
watchers.push(watcher);
|
|
38
|
+
} catch { /* A missing token folder has nothing to generate from. */ }
|
|
39
|
+
}
|
|
40
|
+
} catch { /* An invalid configuration is reported by the server itself. */ }
|
|
41
|
+
return { refresh, close() { clearTimeout(timer); for (const watcher of watchers) watcher.close(); } };
|
|
42
|
+
}
|
package/dist/themes.mjs
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
import selectorParser from "postcss-selector-parser";
|
|
2
|
+
import valueParser from "postcss-value-parser";
|
|
3
|
+
import { findingSeverity } from "./finding-rules.mjs";
|
|
4
|
+
|
|
5
|
+
// A theme is a named set of token values: roles keep their names, values change. A token that
|
|
6
|
+
// differs per theme is written as one half per declared theme, plain values on :root (and on
|
|
7
|
+
// [data-brand="<name>"] for a brand): --color-accent-9-light, --color-accent-9-dark. ADS
|
|
8
|
+
// generates themes.generated.css from the halves: one switch per theme on [data-theme="<name>"]
|
|
9
|
+
// and a resolver that picks the active theme's half on every themed or branded element, so
|
|
10
|
+
// themes and brands nest at any depth, each following its nearest ancestor.
|
|
11
|
+
|
|
12
|
+
export const defaultThemes = [{ name: "light", scheme: "light" }, { name: "dark", scheme: "dark" }];
|
|
13
|
+
|
|
14
|
+
export function validateThemes(themes) {
|
|
15
|
+
if (!Array.isArray(themes) || !themes.length || themes.length > 8) throw new Error("themes must list 1–8 themes; the first is the default.");
|
|
16
|
+
const names = new Set();
|
|
17
|
+
for (const [index, theme] of themes.entries()) {
|
|
18
|
+
const field = `themes[${index}]`;
|
|
19
|
+
if (!theme || typeof theme !== "object" || Array.isArray(theme)) throw new Error(`${field} must be an object with name and scheme.`);
|
|
20
|
+
const unknown = Object.keys(theme).filter(key => !["name", "scheme"].includes(key));
|
|
21
|
+
if (unknown.length) throw new Error(`${field} has unknown keys: ${unknown.join(", ")}.`);
|
|
22
|
+
if (typeof theme.name !== "string" || !/^[a-z][a-z0-9-]{0,31}$/.test(theme.name)) throw new Error(`${field}.name must be a lowercase name such as "dark" or "high-contrast".`);
|
|
23
|
+
if (!["light", "dark"].includes(theme.scheme)) throw new Error(`${field}.scheme must be "light" or "dark": the color scheme browsers use for native controls.`);
|
|
24
|
+
if (names.has(theme.name)) throw new Error(`Theme "${theme.name}" is declared twice.`);
|
|
25
|
+
names.add(theme.name);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const cache = new Map();
|
|
30
|
+
const rootNode = node => node.type === "pseudo" && node.value.toLowerCase() === ":root" || node.type === "tag" && node.value.toLowerCase() === "html";
|
|
31
|
+
const unquote = value => value.replace(/^["']|["']$/g, "");
|
|
32
|
+
|
|
33
|
+
/** Where a token declaration applies: the default brand ({ kind: "root" }: :root or html, or the
|
|
34
|
+
* default brand's [data-brand]), one brand ({ kind: "brand", brand }), the old theme form
|
|
35
|
+
* ({ kind: "old" }: a [data-theme] value block, a prefers-color-scheme block, a valueless or
|
|
36
|
+
* combined [data-brand]), or anything else ({ kind: "conditional" }: @media and other selectors). */
|
|
37
|
+
export function classifyScope(scope, defaultBrand) {
|
|
38
|
+
const key = `${defaultBrand ?? ""}\0${scope}`;
|
|
39
|
+
if (cache.has(key)) return cache.get(key);
|
|
40
|
+
let result;
|
|
41
|
+
if (/data-theme|prefers-color-scheme/i.test(scope)) result = { kind: "old" };
|
|
42
|
+
else if (scope.includes("@") || scope.includes(" > ")) result = { kind: "conditional" };
|
|
43
|
+
else {
|
|
44
|
+
try {
|
|
45
|
+
let old = false, other = false;
|
|
46
|
+
const brands = [];
|
|
47
|
+
selectorParser(root => {
|
|
48
|
+
for (const selector of root.nodes) {
|
|
49
|
+
let brand = null;
|
|
50
|
+
for (const node of selector.nodes) {
|
|
51
|
+
if (node.type === "comment" || rootNode(node)) continue;
|
|
52
|
+
if (node.type === "attribute" && node.attribute === "data-brand") {
|
|
53
|
+
if (node.value === undefined || node.operator !== "=" || brand !== null) old = true;
|
|
54
|
+
else brand = unquote(node.value);
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
if (node.type === "combinator" && /data-brand/.test(scope)) old = true;
|
|
58
|
+
other = true;
|
|
59
|
+
}
|
|
60
|
+
brands.push(brand === defaultBrand ? null : brand);
|
|
61
|
+
}
|
|
62
|
+
}).processSync(scope);
|
|
63
|
+
result = old ? { kind: "old" } : other ? { kind: "conditional" } : new Set(brands).size > 1 ? { kind: "old" }
|
|
64
|
+
: brands[0] === null ? { kind: "root" } : { kind: "brand", brand: brands[0] };
|
|
65
|
+
} catch { result = { kind: "conditional" }; }
|
|
66
|
+
}
|
|
67
|
+
cache.set(key, result);
|
|
68
|
+
return result;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const plainScope = where => where.kind === "root" || where.kind === "brand";
|
|
72
|
+
|
|
73
|
+
/** Token definitions from the token sheets' custom property declarations ({ prop, value, file,
|
|
74
|
+
* line, column, scope }, in source order). A name ending in a declared theme's name is a half
|
|
75
|
+
* when another theme's half of the same token exists: --x-light and --x-dark form the themed
|
|
76
|
+
* token --x, whose definitions carry their theme. Definitions carry their brand (null for the
|
|
77
|
+
* default brand); a half's value names other halves of its own theme by their token name, and
|
|
78
|
+
* keeps the authored text and property. */
|
|
79
|
+
export function buildTokens(declarations, { themes = defaultThemes, brands = [] } = {}) {
|
|
80
|
+
const names = themes.map(theme => theme.name).sort((a, b) => b.length - a.length);
|
|
81
|
+
const split = prop => {
|
|
82
|
+
if (themes.length < 2) return null;
|
|
83
|
+
for (const name of names) if (prop.endsWith(`-${name}`) && prop.length > name.length + 3) return { base: prop.slice(0, -name.length - 1), theme: name };
|
|
84
|
+
return null;
|
|
85
|
+
};
|
|
86
|
+
const entries = declarations.map(declaration => ({ ...declaration, where: classifyScope(declaration.scope, brands[0]?.name) }));
|
|
87
|
+
const halves = new Map();
|
|
88
|
+
for (const entry of entries) {
|
|
89
|
+
const half = plainScope(entry.where) && split(entry.prop);
|
|
90
|
+
if (!half) continue;
|
|
91
|
+
if (!halves.has(half.base)) halves.set(half.base, new Set());
|
|
92
|
+
halves.get(half.base).add(half.theme);
|
|
93
|
+
}
|
|
94
|
+
const themed = new Set([...halves].filter(([, set]) => set.size > 1).map(([base]) => base));
|
|
95
|
+
const halfOf = prop => { const half = split(prop); return half && themed.has(half.base) ? half : null; };
|
|
96
|
+
const normalize = (value, theme) => {
|
|
97
|
+
const parsed = valueParser(value);
|
|
98
|
+
parsed.walk(node => {
|
|
99
|
+
if (node.type !== "function" || node.value !== "var") return;
|
|
100
|
+
const word = node.nodes.find(child => child.type === "word");
|
|
101
|
+
const half = word && halfOf(word.value);
|
|
102
|
+
if (half?.theme === theme) word.value = half.base;
|
|
103
|
+
});
|
|
104
|
+
return parsed.toString();
|
|
105
|
+
};
|
|
106
|
+
const tokens = new Map();
|
|
107
|
+
for (const entry of entries) {
|
|
108
|
+
const half = halfOf(entry.prop), name = half ? half.base : entry.prop;
|
|
109
|
+
const definition = { file: entry.file, line: entry.line, column: entry.column, scope: entry.scope, value: half ? normalize(entry.value, half.theme) : entry.value,
|
|
110
|
+
theme: half?.theme ?? null, brand: entry.where.kind === "brand" ? entry.where.brand : null,
|
|
111
|
+
...(half ? { property: entry.prop, authored: entry.value } : {}),
|
|
112
|
+
...(entry.where.kind === "conditional" ? { conditional: true } : entry.where.kind === "old" ? { conditional: true, old: true } : {}) };
|
|
113
|
+
if (!tokens.has(name)) tokens.set(name, []);
|
|
114
|
+
tokens.get(name).push(definition);
|
|
115
|
+
}
|
|
116
|
+
return [...tokens].sort(([a], [b]) => a.localeCompare(b)).map(([name, definitions]) => ({ name, ...(themed.has(name) ? { themed: true } : {}), definitions }));
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const applies = definition => !definition.conditional;
|
|
120
|
+
|
|
121
|
+
/** A token's definition where a theme and a brand apply: the brand's own one, else the default
|
|
122
|
+
* brand's; within a brand the theme's half, else the single value. Undefined brand = default. */
|
|
123
|
+
export function contextDefinition(token, { theme, brand } = {}) {
|
|
124
|
+
const matches = definition => applies(definition) && (definition.theme === null || definition.theme === theme);
|
|
125
|
+
return (brand !== undefined && brand !== null ? token.definitions.findLast(definition => definition.brand === brand && matches(definition)) : undefined)
|
|
126
|
+
?? token.definitions.findLast(definition => definition.brand === null && matches(definition));
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** A token's default-brand definition: its single value, else its half for the named theme
|
|
130
|
+
* (the first half when no theme is named). */
|
|
131
|
+
export function baseDefinition(token, theme) {
|
|
132
|
+
const own = token.definitions.filter(definition => applies(definition) && definition.brand === null);
|
|
133
|
+
return own.findLast(definition => definition.theme === null) ?? own.find(definition => theme === undefined || definition.theme === theme);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** A token's default-brand definition in one theme. */
|
|
137
|
+
export const themeDefinition = (token, theme) => contextDefinition(token, { theme });
|
|
138
|
+
|
|
139
|
+
/** Every token and half by name in one theme and brand, each with its authored value, so
|
|
140
|
+
* var() references resolve the way the browser does there. */
|
|
141
|
+
export function contextValues(tokens, { theme, brand, themes }) {
|
|
142
|
+
const values = new Map();
|
|
143
|
+
for (const token of tokens) {
|
|
144
|
+
const own = contextDefinition(token, { theme, brand });
|
|
145
|
+
if (own) values.set(token.name, { ...own, value: own.authored ?? own.value });
|
|
146
|
+
if (!token.themed) continue;
|
|
147
|
+
for (const { name } of themes) {
|
|
148
|
+
const half = contextDefinition(token, { theme: name, brand });
|
|
149
|
+
if (half) values.set(`${token.name}-${name}`, { ...half, value: half.authored ?? half.value });
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return values;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** A value with its single var() aliases followed in one context; null when unresolved. */
|
|
156
|
+
export function resolveValue(values, name, seen = new Set()) {
|
|
157
|
+
if (seen.has(name)) return null;
|
|
158
|
+
const value = values.get(name)?.value?.trim();
|
|
159
|
+
const reference = value?.match(/^var\(\s*(--[\w-]+)\s*(?:,([^)]*))?\)$/);
|
|
160
|
+
if (!reference) return value ?? null;
|
|
161
|
+
return values.has(reference[1]) ? resolveValue(values, reference[1], new Set([...seen, name])) : reference[2]?.trim() || null;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export const referencedTokens = value => {
|
|
165
|
+
const names = [];
|
|
166
|
+
valueParser(value).walk(node => { if (node.type === "function" && node.value === "var") { const word = node.nodes.find(child => child.type === "word"); if (word?.value.startsWith("--")) names.push(word.value); } });
|
|
167
|
+
return names;
|
|
168
|
+
};
|
|
169
|
+
|
|
170
|
+
/** Tokens that follow the theme: themed tokens and every default single value that refers to
|
|
171
|
+
* one, directly or through other tokens. The generated resolver re-resolves them per element. */
|
|
172
|
+
export function themeDependents(tokens) {
|
|
173
|
+
const dependent = new Set(tokens.filter(token => token.themed).map(token => token.name));
|
|
174
|
+
for (let changed = true; changed;) {
|
|
175
|
+
changed = false;
|
|
176
|
+
for (const token of tokens) {
|
|
177
|
+
if (dependent.has(token.name)) continue;
|
|
178
|
+
const base = baseDefinition(token);
|
|
179
|
+
if (base && base.theme === null && referencedTokens(base.value).some(name => dependent.has(name))) { dependent.add(token.name); changed = true; }
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
return dependent;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
export const nameList = names => names.length === 1 ? names[0] : `${names.length} tokens (${names.slice(0, 3).join(", ")}${names.length > 3 ? ", …" : ""})`;
|
|
186
|
+
|
|
187
|
+
/** The theme form: old [data-theme] value blocks are errors; a themed token has a default half
|
|
188
|
+
* for every declared theme, only halves, and halves that refer to other halves. */
|
|
189
|
+
export function themeFindings(tokens, themes, { dsDir } = {}) {
|
|
190
|
+
const diagnostics = [], advisories = [];
|
|
191
|
+
const error = (rule, at, message, names) => diagnostics.push({ rule, file: at.file, line: at.line, column: at.column, ...(names ? { tokens: names } : {}), message });
|
|
192
|
+
const finding = (rule, at, message, names) => (findingSeverity(rule) === "error" ? diagnostics : advisories).push({ rule, severity: findingSeverity(rule), file: at.file, line: at.line, column: at.column, ...(names ? { tokens: names } : {}), guidanceUri: "ads://guides/tokens", message });
|
|
193
|
+
// One finding per old rule, naming what it sets.
|
|
194
|
+
const old = new Map();
|
|
195
|
+
for (const token of tokens) for (const definition of token.definitions.filter(definition => definition.old)) {
|
|
196
|
+
const key = `${definition.file}\0${definition.scope}`;
|
|
197
|
+
if (!old.has(key)) old.set(key, { at: definition, names: [] });
|
|
198
|
+
old.get(key).names.push(token.name);
|
|
199
|
+
}
|
|
200
|
+
for (const { at, names } of [...old.values()].sort((a, b) => a.at.file.localeCompare(b.at.file) || a.at.line - b.at.line)) {
|
|
201
|
+
const theme = at.scope.match(/data-theme\s*=\s*["']?([\w-]+)/)?.[1] ?? (/prefers-color-scheme\s*:\s*dark/.test(at.scope) ? "dark" : themes[1]?.name ?? themes[0].name);
|
|
202
|
+
error("theme-old-form", at, `Old theme form: ${at.scope} sets ${nameList(names)}. Write per-theme halves on :root (or [data-brand="<name>"]) instead, such as ${names[0]}-${theme}; ADS generates the theme switches.`, names);
|
|
203
|
+
}
|
|
204
|
+
if (themes.length < 2) return { diagnostics, advisories };
|
|
205
|
+
const dependent = themeDependents(tokens);
|
|
206
|
+
for (const token of tokens.filter(token => token.themed)) {
|
|
207
|
+
const own = token.definitions.filter(definition => applies(definition) && definition.brand === null);
|
|
208
|
+
const single = own.find(definition => definition.theme === null);
|
|
209
|
+
if (single) error("theme-half-conflict", single, `${token.name} is set both as one value and as per-theme halves (${token.definitions.find(definition => definition.property)?.property}, …); keep only the halves.`, [token.name]);
|
|
210
|
+
const missing = own.length ? themes.filter(theme => !own.some(definition => definition.theme === theme.name)).map(theme => theme.name) : [];
|
|
211
|
+
if (missing.length) error("theme-coverage", own.find(definition => definition.theme !== null) ?? own[0], `${token.name} has no ${missing.map(name => `${token.name}-${name}`).join(", ")} on :root; a themed token needs a half for every declared theme, or it is unset in ${missing.join(", ")}.`, [token.name]);
|
|
212
|
+
}
|
|
213
|
+
// A half is resolved where it is declared, on :root or a brand: it names halves, not tokens that follow the theme.
|
|
214
|
+
const byName = new Map(tokens.map(token => [token.name, token]));
|
|
215
|
+
// The half a theme-following alias stands for: --accent → --color-accent-9 → --color-accent-9-dark.
|
|
216
|
+
const halfFor = (name, theme, seen = new Set()) => {
|
|
217
|
+
const token = byName.get(name);
|
|
218
|
+
if (token?.themed) return `${name}-${theme}`;
|
|
219
|
+
const alias = !seen.has(name) && baseDefinition(token ?? { definitions: [] })?.value.trim().match(/^var\(\s*(--[\w-]+)\s*\)$/)?.[1];
|
|
220
|
+
return alias ? halfFor(alias, theme, new Set([...seen, name])) : null;
|
|
221
|
+
};
|
|
222
|
+
for (const token of tokens.filter(token => token.themed)) for (const definition of token.definitions.filter(definition => applies(definition) && definition.authored)) {
|
|
223
|
+
const wrong = referencedTokens(definition.authored).filter(name => dependent.has(name));
|
|
224
|
+
if (wrong.length) error("theme-half-reference", definition, `${definition.property} refers to ${wrong.join(", ")}, which follows the theme; a half is resolved where it is declared, so refer to ${wrong.map(name => halfFor(name, definition.theme) ?? `halves of ${name}`).join(", ")}.`, [token.name]);
|
|
225
|
+
}
|
|
226
|
+
// A lone half-like name: the other themes' halves are missing, so it is a plain token.
|
|
227
|
+
const declared = new Set(tokens.map(token => token.name));
|
|
228
|
+
for (const token of tokens.filter(token => !token.themed)) {
|
|
229
|
+
const theme = themes.slice(1).find(theme => token.name.endsWith(`-${theme.name}`));
|
|
230
|
+
const base = theme && token.name.slice(0, -theme.name.length - 1);
|
|
231
|
+
const at = token.definitions.find(applies);
|
|
232
|
+
if (base && at && !declared.has(base)) finding("theme-new-token", at, `${token.name} reads as the ${theme.name} half of ${base}, but no other theme gives ${base}; add ${themes.filter(item => item !== theme).map(item => `${base}-${item.name}`).join(", ")} on :root, or rename it.`, [token.name]);
|
|
233
|
+
}
|
|
234
|
+
// While the old form remains, theme-old-form already names what to write.
|
|
235
|
+
if (!tokens.some(token => token.themed) && !old.size && dsDir) for (const theme of themes.slice(1)) finding("theme-empty", { file: dsDir, line: 1, column: 1 }, `Theme "${theme.name}" is declared but no token has a ${theme.name} half; give the tokens that change per theme halves such as --color-accent-9-${themes[0].name} and --color-accent-9-${theme.name}, or remove it from ds.config.json.`);
|
|
236
|
+
return { diagnostics, advisories };
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** Whether a component/pattern selector reads the theme or brand from an ancestor or the root
|
|
240
|
+
* ([data-theme="dark"] &, :root[data-theme="dark"] &, :is([data-brand="acme"]) &): such a
|
|
241
|
+
* selector matches the outermost themed ancestor, not the nearest section, so it is an error. */
|
|
242
|
+
export function themeAncestorSelector(selector) {
|
|
243
|
+
let found = false;
|
|
244
|
+
try {
|
|
245
|
+
selectorParser(root => root.walkAttributes(node => {
|
|
246
|
+
if (!["data-theme", "data-brand"].includes(node.attribute)) return;
|
|
247
|
+
// The selector's own subject compound (&[data-theme="dark"]) is the section itself.
|
|
248
|
+
let top = node;
|
|
249
|
+
while (top.parent && top.parent.type !== "root") top = top.parent;
|
|
250
|
+
const compound = top.nodes, index = compound.indexOf(node);
|
|
251
|
+
const own = index >= 0 && !compound.slice(index).some(part => part.type === "combinator")
|
|
252
|
+
&& !compound.some(part => part.type === "pseudo" && part.value.toLowerCase() === ":root");
|
|
253
|
+
if (!own) found = true;
|
|
254
|
+
})).processSync(selector);
|
|
255
|
+
} catch { /* CSS syntax diagnostics are owned by the parser/build. */ }
|
|
256
|
+
return found;
|
|
257
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { inspectTokens } from "./tokens.mjs";
|
|
2
|
+
import { parseColor } from "./token-quality.mjs";
|
|
3
|
+
import { contextDefinition, contextValues, resolveValue } from "./themes.mjs";
|
|
4
|
+
|
|
5
|
+
// The W3C Design Tokens Community Group format (draft): JSON groups of tokens with $value,
|
|
6
|
+
// $type and {group.token} references. The format has no themes yet: a document holds one
|
|
7
|
+
// theme's (and one brand's) values, and the other themes' and brands' values travel in this
|
|
8
|
+
// tool's $extensions entry (values, keyed "dark", "acme" or "acme/dark"), as do CSS values the
|
|
9
|
+
// format cannot express.
|
|
10
|
+
const extension = "org.reqvire.ads";
|
|
11
|
+
|
|
12
|
+
/** A token's path in the export: its family, then the rest of its name. */
|
|
13
|
+
function tokenPath(name) {
|
|
14
|
+
const bare = name.slice(2), dash = bare.indexOf("-");
|
|
15
|
+
return dash < 0 ? [bare, "$root"] : [bare.slice(0, dash), bare.slice(dash + 1)];
|
|
16
|
+
}
|
|
17
|
+
const reference = name => `{${tokenPath(name).join(".")}}`;
|
|
18
|
+
|
|
19
|
+
/** A CSS value as a DTCG value and type, or null when the format cannot express it. */
|
|
20
|
+
function typed(name, value) {
|
|
21
|
+
const text = value.trim();
|
|
22
|
+
const alias = text.match(/^var\(\s*(--[\w-]+)\s*\)$/);
|
|
23
|
+
if (alias) return { $value: reference(alias[1]) };
|
|
24
|
+
const color = parseColor(text);
|
|
25
|
+
if (color && !/^(?:--font-|--weight-|--leading-|--z-)/.test(name)) {
|
|
26
|
+
const hex = `#${color.slice(0, 3).map(channel => Math.round(channel).toString(16).padStart(2, "0")).join("")}`;
|
|
27
|
+
return { $type: "color", $value: { colorSpace: "srgb", components: color.slice(0, 3).map(channel => Number((channel / 255).toFixed(4))), ...(color[3] < 1 ? { alpha: color[3] } : {}), hex } };
|
|
28
|
+
}
|
|
29
|
+
let match = text.match(/^(-?\d*\.?\d+)(px|rem)$/);
|
|
30
|
+
if (match) return { $type: "dimension", $value: { value: Number(match[1]), unit: match[2] } };
|
|
31
|
+
match = text.match(/^(\d*\.?\d+)(ms|s)$/);
|
|
32
|
+
if (match) return { $type: "duration", $value: { value: Number(match[1]), unit: match[2] } };
|
|
33
|
+
match = text.match(/^cubic-bezier\(([^)]*)\)$/);
|
|
34
|
+
if (match) return { $type: "cubicBezier", $value: match[1].split(",").map(Number) };
|
|
35
|
+
if (name.startsWith("--font-")) return { $type: "fontFamily", $value: text.split(",").map(family => family.trim().replace(/^["']|["']$/g, "")) };
|
|
36
|
+
if (name.startsWith("--weight-") && /^\d+$/.test(text)) return { $type: "fontWeight", $value: Number(text) };
|
|
37
|
+
if (/^-?\d*\.?\d+$/.test(text)) return { $type: "number", $value: Number(text) };
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The project's tokens as one DTCG document, with the values of one theme and one brand
|
|
42
|
+
* (default: the first of each). */
|
|
43
|
+
export function exportTokensDtcg(directory, { theme, brand } = {}) {
|
|
44
|
+
const { tokens, themes, brands = [] } = inspectTokens(directory);
|
|
45
|
+
if (theme !== undefined && !themes.some(item => item.name === theme)) throw new Error(`Unknown theme "${theme}"; the project declares ${themes.map(item => item.name).join(", ")}.`);
|
|
46
|
+
if (brand !== undefined && !brands.some(item => item.name === brand)) throw new Error(`Unknown brand "${brand}"; ${brands.length ? `the project declares ${brands.map(item => item.name).join(", ")}` : "the project declares no brands"}.`);
|
|
47
|
+
const selected = theme ?? themes[0].name, own = brand === brands[0]?.name ? undefined : brand;
|
|
48
|
+
const names = new Set(tokens.map(token => token.name));
|
|
49
|
+
let values;
|
|
50
|
+
const document = {};
|
|
51
|
+
for (const token of tokens) {
|
|
52
|
+
const base = contextDefinition(token, { theme: selected, brand: own });
|
|
53
|
+
if (!base) continue;
|
|
54
|
+
// A half that names another theme's half has no DTCG alias; export its resolved value.
|
|
55
|
+
const alias = base.value.trim().match(/^var\(\s*(--[\w-]+)\s*\)$/)?.[1];
|
|
56
|
+
const value = alias && !names.has(alias) ? resolveValue(values ??= contextValues(tokens, { theme: selected, brand: own, themes }), token.name) ?? base.value : base.value;
|
|
57
|
+
const entry = typed(token.name, value) ?? { $value: value.trim() };
|
|
58
|
+
if (!("$type" in entry) && !entry.$value.toString().startsWith("{")) entry.$extensions = { [extension]: { css: value.trim() } };
|
|
59
|
+
if (token.meaning) entry.$description = token.meaning;
|
|
60
|
+
// The other contexts: a theme ("dark"), a brand ("acme") or both ("acme/dark"), or a condition.
|
|
61
|
+
const label = definition => definition.conditional ? definition.scope : [definition.brand, definition.theme].filter(Boolean).join("/") || "default";
|
|
62
|
+
const others = Object.fromEntries(token.definitions.filter(definition => definition !== base).map(definition => [label(definition), (typed(token.name, definition.value) ?? { $value: definition.value.trim() }).$value]));
|
|
63
|
+
if (Object.keys(others).length) entry.$extensions = { ...entry.$extensions, [extension]: { ...entry.$extensions?.[extension], values: others } };
|
|
64
|
+
const [group, key] = tokenPath(token.name);
|
|
65
|
+
document[group] ??= {};
|
|
66
|
+
document[group][key] = entry;
|
|
67
|
+
}
|
|
68
|
+
return document;
|
|
69
|
+
}
|
package/dist/token-policy.mjs
CHANGED
|
@@ -9,7 +9,8 @@ export function isSharedToken(name) {
|
|
|
9
9
|
|| tokenContract.naming.prefixes.some((prefix) => name.startsWith(prefix) && name.length > prefix.length);
|
|
10
10
|
}
|
|
11
11
|
|
|
12
|
-
|
|
12
|
+
// The foundation sheets in import order; themes.generated.css comes last, after every sheet it re-applies.
|
|
13
|
+
export const foundationFiles = ["fonts.css", "colors.css", "typography.css", "spacing.css", "elevation.css", "base.css", "themes.generated.css"];
|
|
13
14
|
|
|
14
15
|
/** The foundation entry accepts only a single, unconditional local import. */
|
|
15
16
|
export function foundationImportTarget(node, file) {
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { contextValues, defaultThemes, resolveValue } from "./themes.mjs";
|
|
2
|
+
import { findingSeverity } from "./finding-rules.mjs";
|
|
3
|
+
|
|
4
|
+
/** Accessibility and rhythm reviews of token values: WCAG contrast between the roles that
|
|
5
|
+
* meet on screen, in every theme, and spacing steps on the 2 px grid. Both are errors. */
|
|
6
|
+
|
|
7
|
+
const named = { white: [255, 255, 255, 1], black: [0, 0, 0, 1] };
|
|
8
|
+
|
|
9
|
+
/** sRGB channels and alpha of a hex, rgb()/rgba() or hsl()/hsla() color; null otherwise. */
|
|
10
|
+
export function parseColor(value) {
|
|
11
|
+
const text = value.trim().toLowerCase();
|
|
12
|
+
if (named[text]) return named[text];
|
|
13
|
+
let match = text.match(/^#([0-9a-f]{3,8})$/);
|
|
14
|
+
if (match) {
|
|
15
|
+
let hex = match[1];
|
|
16
|
+
if (hex.length === 3 || hex.length === 4) hex = [...hex].map(digit => digit + digit).join("");
|
|
17
|
+
if (hex.length !== 6 && hex.length !== 8) return null;
|
|
18
|
+
const channels = [0, 2, 4].map(index => parseInt(hex.slice(index, index + 2), 16));
|
|
19
|
+
return [...channels, hex.length === 8 ? parseInt(hex.slice(6), 16) / 255 : 1];
|
|
20
|
+
}
|
|
21
|
+
match = text.match(/^(rgba?|hsla?)\((.*)\)$/);
|
|
22
|
+
if (!match) return null;
|
|
23
|
+
const parts = match[2].split(/[\s,/]+/).filter(Boolean);
|
|
24
|
+
if (parts.length < 3) return null;
|
|
25
|
+
const alpha = parts[3] === undefined ? 1 : parts[3].endsWith("%") ? parseFloat(parts[3]) / 100 : parseFloat(parts[3]);
|
|
26
|
+
if (match[1].startsWith("rgb")) {
|
|
27
|
+
const channels = parts.slice(0, 3).map(part => part.endsWith("%") ? parseFloat(part) * 2.55 : parseFloat(part));
|
|
28
|
+
return channels.some(Number.isNaN) ? null : [...channels, alpha];
|
|
29
|
+
}
|
|
30
|
+
const [h, s, l] = [parseFloat(parts[0]), parseFloat(parts[1]) / 100, parseFloat(parts[2]) / 100];
|
|
31
|
+
if ([h, s, l].some(Number.isNaN)) return null;
|
|
32
|
+
const k = n => (n + h / 30) % 12, a = s * Math.min(l, 1 - l);
|
|
33
|
+
const f = n => 255 * (l - a * Math.max(-1, Math.min(k(n) - 3, 9 - k(n), 1)));
|
|
34
|
+
return [f(0), f(8), f(4), alpha];
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const luminance = ([r, g, b]) => {
|
|
38
|
+
const channel = value => { value /= 255; return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4; };
|
|
39
|
+
return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b);
|
|
40
|
+
};
|
|
41
|
+
const over = (top, bottom) => [0, 1, 2].map(index => top[index] * top[3] + bottom[index] * (1 - top[3])).concat(1);
|
|
42
|
+
/** WCAG 2 contrast ratio of a foreground over an opaque background. */
|
|
43
|
+
export function contrastRatio(foreground, background) {
|
|
44
|
+
const [a, b] = [luminance(over(foreground, background)), luminance(background)];
|
|
45
|
+
return (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const textBackgrounds = ["--bg-canvas", "--bg-surface", "--bg-raised", "--bg-field", "--bg-hover"];
|
|
49
|
+
/** The roles that meet on screen. Text needs 4.5:1 (WCAG 1.4.3); focus indicators and the
|
|
50
|
+
* borders that identify controls need 3:1 (1.4.11). */
|
|
51
|
+
function contrastPairs(names) {
|
|
52
|
+
const pairs = [];
|
|
53
|
+
for (const text of ["--text-strong", "--text-body", "--text-muted", "--text-link", "--accent-text"]) for (const background of textBackgrounds) pairs.push([text, background, 4.5]);
|
|
54
|
+
pairs.push(["--accent-fg", "--accent", 4.5], ["--accent-fg", "--accent-hover", 4.5]);
|
|
55
|
+
for (const status of ["success", "warning", "danger", "info"]) pairs.push([`--${status}-fg`, `--${status}`, 4.5], [`--${status}-text`, `--${status}-bg`, 4.5]);
|
|
56
|
+
for (const ui of ["--border-focus", "--border-strong"]) for (const background of ["--bg-canvas", "--bg-surface"]) pairs.push([ui, background, 3]);
|
|
57
|
+
return pairs.filter(([foreground, background]) => names.has(foreground) && names.has(background));
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function tokenContrastAdvisories(tokens, themes = defaultThemes, brands = []) {
|
|
61
|
+
const names = new Set(tokens.map(token => token.name));
|
|
62
|
+
const advisories = [];
|
|
63
|
+
const pairs = contrastPairs(names);
|
|
64
|
+
// Every brand in every theme; a brand other than the default reports only the pairs it changes.
|
|
65
|
+
for (const { name: scope } of themes) {
|
|
66
|
+
const defaults = contextValues(tokens, { theme: scope, themes });
|
|
67
|
+
for (const brand of brands.length ? brands.map(item => item.name) : [undefined]) {
|
|
68
|
+
const own = brand === undefined || brand === brands[0].name;
|
|
69
|
+
const values = own ? defaults : contextValues(tokens, { theme: scope, brand, themes });
|
|
70
|
+
for (const [foreground, background, minimum] of pairs) {
|
|
71
|
+
const fore = resolveValue(values, foreground), backValue = resolveValue(values, background);
|
|
72
|
+
const front = parseColor(fore ?? ""), back = parseColor(backValue ?? "");
|
|
73
|
+
if (!front || !back) continue;
|
|
74
|
+
if (!own && fore === resolveValue(defaults, foreground) && backValue === resolveValue(defaults, background)) continue;
|
|
75
|
+
const ratio = contrastRatio(front, back[3] < 1 ? over(back, [255, 255, 255, 1]) : back);
|
|
76
|
+
if (ratio + 1e-9 >= minimum) continue;
|
|
77
|
+
const at = values.get(foreground);
|
|
78
|
+
if (!at) continue;
|
|
79
|
+
const { file, line, column } = at;
|
|
80
|
+
const where = own ? `the ${scope} theme` : `the ${scope} theme of brand "${brand}"`;
|
|
81
|
+
advisories.push({ rule: "token-contrast", severity: findingSeverity("token-contrast"), file, line, column, tokens: [foreground, background], guidanceUri: "ads://guides/tokens",
|
|
82
|
+
message: `${foreground} on ${background} is ${ratio.toFixed(2)}:1 in ${where}; ${minimum === 4.5 ? "text needs 4.5:1 (WCAG 1.4.3)" : "focus indicators and control borders need 3:1 (WCAG 1.4.11)"}.` });
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return advisories;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Pixels of a px/rem/0 length, or null. */
|
|
90
|
+
const pixels = value => {
|
|
91
|
+
const match = value.trim().match(/^(-?\d*\.?\d+)(px|rem)?$/);
|
|
92
|
+
if (!match || (!match[2] && Number(match[1]) !== 0)) return null;
|
|
93
|
+
return Number(match[1]) * (match[2] === "rem" ? 16 : 1);
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
/** Numbered spacing steps sit on the 2 px grid, --space-N at N × 2 px. */
|
|
97
|
+
export function tokenRhythmAdvisories(tokens) {
|
|
98
|
+
const advisories = [];
|
|
99
|
+
for (const token of tokens) {
|
|
100
|
+
const step = token.name.match(/^--space-(\d+)$/)?.[1];
|
|
101
|
+
if (step === undefined) continue;
|
|
102
|
+
for (const { file, line, column, value, scope, property } of token.definitions) {
|
|
103
|
+
const size = pixels(value);
|
|
104
|
+
if (size === null) continue;
|
|
105
|
+
const expected = Number(step) * 2;
|
|
106
|
+
if (size % 2 === 0 && size === expected) continue;
|
|
107
|
+
advisories.push({ rule: "token-rhythm", severity: findingSeverity("token-rhythm"), file, line, column, tokens: [token.name], guidanceUri: "ads://guides/tokens",
|
|
108
|
+
message: `${token.name} is ${size}px${property ? ` as ${property}` : ""}${scope === ":root" ? "" : ` in ${scope}`}; the spacing scale is --space-N = N × 2 px (${expected}px), on a 2 px grid.` });
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return advisories;
|
|
112
|
+
}
|
package/dist/tokens.mjs
CHANGED
|
@@ -1,4 +1,9 @@
|
|
|
1
1
|
import { readFileSync } from "node:fs";
|
|
2
|
+
import { tokenContrastAdvisories, tokenRhythmAdvisories } from "./token-quality.mjs";
|
|
3
|
+
import { a11yTokenAdvisories } from "./a11y.mjs";
|
|
4
|
+
import { buildTokens, contextValues, themeFindings } from "./themes.mjs";
|
|
5
|
+
import { generatedThemesFile, themesCssDiagnostics } from "./themes-generated.mjs";
|
|
6
|
+
import { brandFindings } from "./brands.mjs";
|
|
2
7
|
import path from "node:path";
|
|
3
8
|
import postcss from "postcss";
|
|
4
9
|
import valueParser from "postcss-value-parser";
|
|
@@ -7,6 +12,7 @@ import { foundationFiles, isSharedToken, tokenContract } from "./token-policy.mj
|
|
|
7
12
|
import { dimensionValue, numericCssUnit } from "./css-values.mjs";
|
|
8
13
|
import { checkComponentVariable } from "./boundaries.mjs";
|
|
9
14
|
import { tokenOverlapAdvisories } from "./design-values.mjs";
|
|
15
|
+
import { routeFindings } from "./finding-rules.mjs";
|
|
10
16
|
|
|
11
17
|
export { tokenContract };
|
|
12
18
|
|
|
@@ -49,9 +55,9 @@ export function inspectTokens(directory, suppliedOptions) {
|
|
|
49
55
|
const options = suppliedOptions ?? loadConfig(directory);
|
|
50
56
|
if(options.tokenInventory)return options.tokenInventory;
|
|
51
57
|
const { root, dsRoot, config } = options;
|
|
52
|
-
const
|
|
58
|
+
const declarations = [];
|
|
53
59
|
const diagnostics = [];
|
|
54
|
-
const files = sourceFiles(path.join(dsRoot, config.tokenDir)).filter((file) => file.endsWith(".css"));
|
|
60
|
+
const files = sourceFiles(path.join(dsRoot, config.tokenDir)).filter((file) => file.endsWith(".css") && path.basename(file) !== generatedThemesFile);
|
|
55
61
|
files.sort((a, b) => foundationFiles.indexOf(path.basename(a)) - foundationFiles.indexOf(path.basename(b)) || a.localeCompare(b));
|
|
56
62
|
for (const file of files) {
|
|
57
63
|
let css;
|
|
@@ -64,40 +70,26 @@ export function inspectTokens(directory, suppliedOptions) {
|
|
|
64
70
|
if (!decl.prop.startsWith("--")) return;
|
|
65
71
|
const ownership = checkComponentVariable(decl.prop, file, options);
|
|
66
72
|
if (ownership) diagnostics.push({ rule: ownership.rule, file: path.relative(root, file), line: decl.source.start.line, column: decl.source.start.column, message: ownership.message });
|
|
67
|
-
|
|
68
|
-
file: path.relative(root, file).replaceAll("\\", "/"),
|
|
69
|
-
line: decl.source.start.line,
|
|
70
|
-
column: decl.source.start.column,
|
|
71
|
-
scope: context(decl),
|
|
72
|
-
value: decl.value,
|
|
73
|
-
};
|
|
74
|
-
if (!definitions.has(decl.prop)) definitions.set(decl.prop, []);
|
|
75
|
-
definitions.get(decl.prop).push(definition);
|
|
73
|
+
declarations.push({ prop: decl.prop, value: decl.value, file: path.relative(root, file).replaceAll("\\", "/"), line: decl.source.start.line, column: decl.source.start.column, scope: context(decl) });
|
|
76
74
|
});
|
|
77
75
|
}
|
|
78
|
-
const
|
|
79
|
-
const
|
|
80
|
-
for (const [name, entries] of definitions) {
|
|
81
|
-
for (const entry of entries) {
|
|
82
|
-
if (entry.scope === ":root") base.set(name, entry);
|
|
83
|
-
else {
|
|
84
|
-
if (!scopes.has(entry.scope)) scopes.set(entry.scope, new Map());
|
|
85
|
-
scopes.get(entry.scope).set(name, entry);
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
}
|
|
76
|
+
const tokens = buildTokens(declarations, config).map((token) => ({ ...token, ...tokenContract.tokens[token.name], owner: "tokens" }));
|
|
77
|
+
const defined = new Set(tokens.filter((token) => token.definitions.some((definition) => !definition.conditional && definition.brand === null)).map((token) => token.name));
|
|
89
78
|
for (const name of Object.keys(tokenContract.tokens)) {
|
|
90
|
-
if (!
|
|
79
|
+
if (!defined.has(name)) diagnostics.push({ rule: "missing-token", file: config.dsDir, line: 1, column: 1, message: `Define ${name} in :root using the project's chosen value.` });
|
|
91
80
|
}
|
|
92
81
|
const emitted = new Set();
|
|
93
82
|
function report(rule, name, entry, message) {
|
|
94
83
|
const key = `${rule}:${name}:${entry.file}:${entry.line}:${message}`;
|
|
95
84
|
if (emitted.has(key)) return;
|
|
96
85
|
emitted.add(key);
|
|
97
|
-
|
|
86
|
+
const { file, line, column, scope, value } = entry;
|
|
87
|
+
diagnostics.push({ rule, file, line, column, scope, value, message });
|
|
98
88
|
}
|
|
99
|
-
|
|
100
|
-
|
|
89
|
+
// Every theme in every brand, as the browser resolves it there; halves are names too.
|
|
90
|
+
const contexts = config.themes.flatMap(({ name: theme }) => [undefined, ...config.brands.slice(1).map((brand) => brand.name)].map((brand) => contextValues(tokens, { theme, brand, themes: config.themes })));
|
|
91
|
+
const themedNames = new Set(tokens.filter((token) => token.themed).map((token) => token.name));
|
|
92
|
+
for (const scope of contexts) {
|
|
101
93
|
const cache = new Map();
|
|
102
94
|
function resolveAlias(name, chain = []) {
|
|
103
95
|
if (cache.has(name)) return cache.get(name);
|
|
@@ -109,7 +101,8 @@ export function inspectTokens(directory, suppliedOptions) {
|
|
|
109
101
|
}
|
|
110
102
|
const resolvedReferences = new Map();
|
|
111
103
|
for (const ref of references(entry.value)) {
|
|
112
|
-
|
|
104
|
+
const half = !themedNames.has(ref.name) && [...themedNames].some((base) => ref.name.startsWith(`${base}-`) && scope.has(ref.name));
|
|
105
|
+
if (!half && !isSharedToken(ref.name)) report("token-name", name, entry, `${name} references ${ref.name} outside the shared Data token contract.`);
|
|
113
106
|
if (!scope.has(ref.name) && !ref.fallback) report("token-reference", name, entry, `${name} references undefined ${ref.name}.`);
|
|
114
107
|
else if (scope.has(ref.name)) resolvedReferences.set(ref.name, resolveAlias(ref.name, [...chain, name]));
|
|
115
108
|
}
|
|
@@ -137,11 +130,20 @@ export function inspectTokens(directory, suppliedOptions) {
|
|
|
137
130
|
if (type && resolved !== undefined && !matchesType(resolved, type)) report("token-type", name, entry, `${name} expects ${type}; found ${resolved}.`);
|
|
138
131
|
}
|
|
139
132
|
}
|
|
140
|
-
const
|
|
133
|
+
const themes = themeFindings(tokens, config.themes, { dsDir: config.dsDir });
|
|
134
|
+
diagnostics.push(...themes.diagnostics);
|
|
135
|
+
const brands = brandFindings(tokens, config.brands, config.themes, { dsDir: config.dsDir });
|
|
136
|
+
diagnostics.push(...brands.diagnostics);
|
|
137
|
+
diagnostics.push(...themesCssDiagnostics(options, { tokens }));
|
|
138
|
+
// Token-value findings are errors or review items by rule; errors join the diagnostics.
|
|
139
|
+
const findings = routeFindings(diagnostics, [...tokenOverlapAdvisories(tokens), ...tokenContrastAdvisories(tokens, config.themes, config.brands), ...tokenRhythmAdvisories(tokens), ...themes.advisories, ...brands.advisories,
|
|
140
|
+
...a11yTokenAdvisories(tokens, { root, foundationFile: path.join(dsRoot, config.tokenDir, "base.css") })]);
|
|
141
141
|
return options.tokenInventory = {
|
|
142
142
|
contractVersion: tokenContract.version,
|
|
143
|
+
themes: config.themes,
|
|
144
|
+
...(config.brands.length ? { brands: config.brands } : {}),
|
|
143
145
|
tokens,
|
|
144
|
-
advisories:
|
|
145
|
-
diagnostics,
|
|
146
|
+
advisories: findings.advisories,
|
|
147
|
+
diagnostics: findings.diagnostics,
|
|
146
148
|
};
|
|
147
149
|
}
|