@reqvire-org/ads 0.3.46 → 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 +21 -11
- package/dist/a11y.mjs +4 -2
- package/dist/assets.mjs +20 -15
- 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 +1 -0
- package/dist/capture-store.mjs +2 -0
- package/dist/capture.mjs +7 -4
- package/dist/check.mjs +38 -8
- package/dist/cli.mjs +45 -10
- package/dist/color-values.mjs +325 -0
- package/dist/config.mjs +16 -2
- package/dist/control-padding.mjs +93 -0
- package/dist/design-values.mjs +3 -2
- package/dist/finding-rules.mjs +61 -0
- package/dist/foundation.mjs +17 -4
- 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 +36 -36
- package/dist/mcp/project-widget.bundle.js +12 -12
- package/dist/mcp/server.mjs +21 -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/contracts.md +13 -10
- package/dist/skills/ads-break-ui/references/design-data.md +137 -29
- package/dist/skills/ads-break-ui/references/validation.md +8 -4
- package/dist/skills/ads-designer/SKILL.md +23 -16
- package/dist/skills/ads-designer/references/accessibility.md +39 -5
- package/dist/skills/ads-designer/references/atomic-styles.md +12 -12
- package/dist/skills/ads-designer/references/branding.md +37 -10
- 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 +137 -29
- 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/cli.md +8 -2
- package/dist/skills/ads-import/references/contracts.md +13 -10
- package/dist/skills/ads-import/references/design-data.md +137 -29
- 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/contracts.md +13 -10
- package/dist/skills/ads-motion/references/design-data.md +137 -29
- 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/cli.md +8 -2
- package/dist/skills/ads-port/references/contracts.md +13 -10
- package/dist/skills/ads-port/references/design-data.md +137 -29
- package/dist/skills/ads-port/references/validation.md +8 -4
- package/dist/starters/preact/design-system/review/token-preview/TokenPreview.tsx +11 -2
- package/dist/starters/react/ADS.md +43 -10
- package/dist/starters/react/README.md +14 -9
- package/dist/starters/react/design-system/assets/brand/README.md +8 -3
- package/dist/starters/react/design-system/assets/glyphs/README.md +4 -1
- package/dist/starters/react/design-system/components/Content/Icon/Icon.ads.fixture.ts +6 -1
- package/dist/starters/react/design-system/components/Content/Icon/Icon.ads.scenario.tsx +3 -2
- package/dist/starters/react/design-system/components/Content/Icon/README.md +2 -1
- 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/controllers/Palette/Palette.ts +164 -0
- package/dist/starters/react/design-system/index.ts +3 -0
- package/dist/starters/react/design-system/review/brand-preview/BrandPreview.tsx +2 -5
- package/dist/starters/react/design-system/review/token-preview/TokenPreview.tsx +11 -2
- package/dist/starters/react/design-system/styles.css +1 -0
- package/dist/starters/react/design-system/tokens/base.css +8 -5
- package/dist/starters/react/design-system/tokens/colors.css +167 -175
- package/dist/starters/react/design-system/tokens/elevation.css +14 -21
- 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/style-boundaries.mjs +2 -1
- package/dist/themes-generated.mjs +150 -0
- package/dist/themes-watch.mjs +42 -0
- package/dist/themes.mjs +214 -63
- package/dist/token-export.mjs +22 -11
- package/dist/token-policy.mjs +2 -1
- package/dist/token-quality.mjs +28 -25
- package/dist/tokens.mjs +27 -32
- package/dist/validation.mjs +18 -1
- package/dist/verification/browser.mjs +14 -3
- package/docs/ADS.md +41 -27
- package/docs/ARCHITECTURE.md +49 -22
- package/docs/CACHING.md +2 -3
- package/docs/CHANGELOG.md +97 -13
- package/docs/CONTRACTS.md +13 -10
- package/docs/GUIDE.md +89 -21
- package/docs/MCP.md +35 -25
- 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/check.mjs
CHANGED
|
@@ -5,6 +5,9 @@ import postcss from "postcss";
|
|
|
5
5
|
import valueParser from "postcss-value-parser";
|
|
6
6
|
import { importViolation, isInside, loadConfig, sourceFiles, isDevelopmentFile, isTestFile, isReviewFile } from "./config.mjs";
|
|
7
7
|
import { inspectTokens, references } from "./tokens.mjs";
|
|
8
|
+
import { displaySwitches, generatedPaletteFile, generatedThemeFiles } from "./themes-generated.mjs";
|
|
9
|
+
import { createRenderColorProbe } from "./render-color-probe.mjs";
|
|
10
|
+
import { themeAncestorSelector } from "./themes.mjs";
|
|
8
11
|
import { foundationFiles, foundationImportTarget, isSharedToken } from "./token-policy.mjs";
|
|
9
12
|
import { inspectAssets } from "./assets.mjs";
|
|
10
13
|
import { a11ySourceAdvisories } from "./a11y.mjs";
|
|
@@ -35,6 +38,8 @@ import { createDesignValues, inspectDesignAliases, isColorKeyword } from "./desi
|
|
|
35
38
|
import { inspectTestBoundaries } from "./test-boundaries.mjs";
|
|
36
39
|
import { inspectBehaviorLibraries } from "./behavior-libraries.mjs";
|
|
37
40
|
import { inspectUsage } from "./usage.mjs";
|
|
41
|
+
import { controlPaddingAdvisories } from "./control-padding.mjs";
|
|
42
|
+
import { findingSeverity, routeFindings } from "./finding-rules.mjs";
|
|
38
43
|
|
|
39
44
|
const scenarioLayoutGuidance = "Put demo-only sizing and framing in the development-only review/ layer, imported through the separate review entry. Patterns are production UI. Keep required behavior in the runtime owner; add component props for deliberate product API needs.";
|
|
40
45
|
const inlineStyleGuidance = `Own visual styles in component/pattern Linaria. ${scenarioLayoutGuidance} Reserve inlineStyleFiles for documented measured geometry, not demo layout.`;
|
|
@@ -54,10 +59,12 @@ export function checkProject(directory, { trackingRoot } = {}) {
|
|
|
54
59
|
if (diagnostics.length) return architectureEvidence({ ok: false, diagnostics });
|
|
55
60
|
const tokenInventory = inspectTokens(root, options);
|
|
56
61
|
const declaredTokens = new Set(tokenInventory.tokens.map((token) => token.name));
|
|
62
|
+
// Display switches are defined by the generated themes.generated.css, not a token sheet.
|
|
63
|
+
const generatedSwitches = new Set(displaySwitches(config));
|
|
57
64
|
diagnostics.push(...tokenInventory.diagnostics);
|
|
58
65
|
const assetFindings = inspectAssets(options);
|
|
59
|
-
diagnostics.push(...assetFindings.filter(finding => finding.severity
|
|
60
|
-
const assetAdvisories = assetFindings.filter(finding => finding.severity
|
|
66
|
+
diagnostics.push(...assetFindings.filter(finding => !finding.severity || finding.severity === "error"));
|
|
67
|
+
const assetAdvisories = assetFindings.filter(finding => finding.severity && finding.severity !== "error");
|
|
61
68
|
const resolveImport = importResolver(options);
|
|
62
69
|
const units = inspectUnits(options);
|
|
63
70
|
options.testOwner = file => units.owner(units.relative(path.relative(root,file)));
|
|
@@ -76,6 +83,7 @@ export function checkProject(directory, { trackingRoot } = {}) {
|
|
|
76
83
|
const runtimeContracts = inspectRuntimeContracts(options, program);
|
|
77
84
|
diagnostics.push(...runtimeContracts.diagnostics);
|
|
78
85
|
const atomicCompositionReview = createAtomicCompositionReview(program, options);
|
|
86
|
+
const renderColorProbe = createRenderColorProbe(program);
|
|
79
87
|
const scenarioTrace = createScenarioTrace(program, options);
|
|
80
88
|
let scenarioSlot, scenarioSelector;
|
|
81
89
|
function report(file, rule, message, line = 1, column = 1, detail = {}) {
|
|
@@ -96,7 +104,7 @@ export function checkProject(directory, { trackingRoot } = {}) {
|
|
|
96
104
|
inspectControllers(options, program, report, behaviors.contracts);
|
|
97
105
|
// The foundation remains a fixed import-only entry, not an extra styling layer.
|
|
98
106
|
const foundationEntry = path.join(dsRoot, config.stylesEntry);
|
|
99
|
-
const registeredProperties=new Map();
|
|
107
|
+
const registeredProperties=new Map(), controlPaddingSeen=new Set();
|
|
100
108
|
function checkRegistrations(file,css,offset={line:1}){
|
|
101
109
|
css.walkAtRules(/^property$/i,rule=>{
|
|
102
110
|
const line=offset.line+(rule.source?.start.line??1)-1;
|
|
@@ -124,7 +132,7 @@ export function checkProject(directory, { trackingRoot } = {}) {
|
|
|
124
132
|
const imports = css.nodes.filter((node) => node.type !== "comment");
|
|
125
133
|
const expected = foundationFiles.filter((name) => name !== "fonts.css" || existsSync(path.join(dsRoot, config.tokenDir, name))).map((name) => path.join(dsRoot, config.tokenDir, name));
|
|
126
134
|
const actual = imports.map(node => foundationImportTarget(node, foundationEntry));
|
|
127
|
-
if (actual.length !== expected.length || actual.some((file, index) => file !== expected[index] || !existsSync(file))) report(foundationEntry, "styles-entry", "Foundation CSS must import only fonts (when present), colors, typography, spacing, elevation, and
|
|
135
|
+
if (actual.length !== expected.length || actual.some((file, index) => file !== expected[index] || !existsSync(file))) report(foundationEntry, "styles-entry", "Foundation CSS must import only fonts (when present), colors, typography, spacing, elevation, base and the generated themes.generated.css, in that order.");
|
|
128
136
|
} catch (error) { report(foundationEntry, "css-syntax", error.reason ?? error.message, error.line ?? 1); }
|
|
129
137
|
function checkCss(file, text, offset = { line: 1, column: 1 }, foundation = false) {
|
|
130
138
|
let css;
|
|
@@ -133,6 +141,11 @@ export function checkProject(directory, { trackingRoot } = {}) {
|
|
|
133
141
|
layers.collectComponentStyles(file, css);
|
|
134
142
|
layerStyles.push({ file, css, offset });
|
|
135
143
|
checkRegistrations(file,css,offset);
|
|
144
|
+
// Linaria templates are checked once per resolved interpolation variant.
|
|
145
|
+
if (!foundation) for (const finding of controlPaddingAdvisories(css, { tokens: declaredTokens, file: path.relative(root, file).replaceAll("\\", "/"), offset })) {
|
|
146
|
+
const key = JSON.stringify([finding.file, finding.line, finding.column, finding.message]);
|
|
147
|
+
if (!controlPaddingSeen.has(key)) { controlPaddingSeen.add(key); advisories.push(finding); }
|
|
148
|
+
}
|
|
136
149
|
if (!foundation && !isReviewFile(file, options) && (isDevelopmentFile(file, options) || !isInside(path.join(dsRoot, "components"), file) && !isInside(path.join(dsRoot, "patterns"), file) && file !== foundationEntry)) report(file, "style-ownership", "Visual CSS belongs to the local ADS's runtime components/patterns or development review implementations.");
|
|
137
150
|
if (isDevelopmentFile(file, options) && !isReviewFile(file, options) && css.nodes.some((node) => node.type !== "comment" && !(node.type === "atrule" && node.name === "import"))) report(file, "showcase-style", `Scenarios and fixtures define no styles. ${scenarioLayoutGuidance}`, offset.line);
|
|
138
151
|
css.walkAtRules("import", (rule) => {
|
|
@@ -151,6 +164,7 @@ export function checkProject(directory, { trackingRoot } = {}) {
|
|
|
151
164
|
if (violation) report(file, "foundation-selector", violation, rule.source.start.line, rule.source.start.column);
|
|
152
165
|
}
|
|
153
166
|
if (isInside(path.join(dsRoot, "showcase"), file) && /:(?:hover|active|focus(?:-visible|-within)?|checked|disabled|enabled)\b|\[(?:aria-(?:selected|pressed|checked|disabled|expanded)|data-state)\b/.test(rule.selector)) report(file, "showcase-state", "Interactive state styling belongs to the real ADS component or pattern, not showcase or mock styles.", offset.line + rule.source.start.line - 1);
|
|
167
|
+
if (!foundation && (isReviewFile(file, options) || ["components", "patterns"].some(layer => isInside(path.join(dsRoot, layer), file))) && themeAncestorSelector(rule.selector)) report(file, "theme-selector", "Theme and brand selectors don't follow the nearest section; show theme- or brand-specific content with display: var(--display-<theme>, <display>), and give theme- or brand-specific values as token halves.", offset.line + rule.source.start.line - 1, rule.source.start.column, { severity: findingSeverity("theme-selector") });
|
|
154
168
|
if (/\.ads-[\w-]+/.test(rule.selector) && !isInside(path.join(dsRoot, "components"), file)) report(file, "style-ownership", "ADS component internals are owned by components, not app or showcase CSS.", offset.line + rule.source.start.line - 1);
|
|
155
169
|
if (/\.ux-[\w-]+/.test(rule.selector) && !isInside(path.join(dsRoot, "patterns"), file) && !isReviewFile(file, options)) report(file, "style-ownership", "Pattern internals are owned by patterns, not app or scenario CSS.", offset.line + rule.source.start.line - 1);
|
|
156
170
|
if (/\.showcase-[\w-]+/.test(rule.selector) && !isInside(path.join(dsRoot, "showcase"), file)) report(file, "style-ownership", "Showcase internals are owned by showcase scaffolding.", offset.line + rule.source.start.line - 1);
|
|
@@ -161,6 +175,7 @@ export function checkProject(directory, { trackingRoot } = {}) {
|
|
|
161
175
|
});
|
|
162
176
|
css.walkDecls((decl) => {
|
|
163
177
|
const propertyDescriptor=decl.parent.type==="atrule"&&decl.parent.name.toLowerCase()==="property";
|
|
178
|
+
if ((foundation || ["components", "patterns"].some(layer => isInside(path.join(dsRoot, layer), file))) && /\blight-dark\(/i.test(decl.value)) report(file, "theme-light-dark", "Give per-theme values as token halves (--x-light, --x-dark); light-dark() is limited to two schemes.", offset.line + decl.source.start.line - 1, decl.source.start.column, { severity: findingSeverity("theme-light-dark") });
|
|
164
179
|
if (foundation && decl.prop.startsWith("--")) {
|
|
165
180
|
if (path.basename(file) === "base.css") report(file, "foundation-role", "Shared token definitions belong in value sheets, not base.css.", decl.source.start.line, decl.source.start.column);
|
|
166
181
|
return; // Definition names, values and aliases are validated by inspectTokens.
|
|
@@ -179,6 +194,8 @@ export function checkProject(directory, { trackingRoot } = {}) {
|
|
|
179
194
|
if (units.owner(units.relative(path.relative(root, file))) !== binding.unit) report(file, "binding-ownership", `${ref.name} is an instance binding owned by ${binding.unit}, not a shared design token.`, offset.line + decl.source.start.line - 1, decl.source.start.column);
|
|
180
195
|
continue;
|
|
181
196
|
}
|
|
197
|
+
if (generatedSwitches.has(ref.name)) continue;
|
|
198
|
+
if (ref.name.startsWith("--display-")) { report(file, "token-reference", `${ref.name} is not a display switch; themes.generated.css defines ${[...generatedSwitches].join(", ")} from ds.config.json themes and brands.`, offset.line + decl.source.start.line - 1, decl.source.start.column); continue; }
|
|
182
199
|
const local = /^(?:--ds-|--ux-|--showcase-)/.test(ref.name);
|
|
183
200
|
if (foundation && local) report(file, "foundation-role", "Foundation defaults consume shared tokens, not component, pattern or scenario-local variables.", offset.line + decl.source.start.line - 1, decl.source.start.column);
|
|
184
201
|
if (!local && !isSharedToken(ref.name)) report(file, "token-name", `${ref.name} does not follow ADS's fixed token naming contract.`, offset.line + decl.source.start.line - 1, decl.source.start.column);
|
|
@@ -204,6 +221,8 @@ export function checkProject(directory, { trackingRoot } = {}) {
|
|
|
204
221
|
const role = adsFileRole(file);
|
|
205
222
|
const roleExtension=role==="contract"?/\.[cm]?ts$/.test(file):["fixture","fixtures"].includes(role)?/\.(?:[cm]?[jt]sx?|json)$/.test(file):/\.[cm]?[jt]sx?$/.test(file);
|
|
206
223
|
if (role && !configurationScripts.has(file) && (!["contract", "scenario", "fixture", "fixtures", "helpers", "test", "spec", "behavior.spec"].includes(role)||!roleExtension)) report(file, "development-role", `Unknown .ads. role or unsupported extension: ${role}. Use a TypeScript contract, a script scenario/fixture/helpers/test/behavior.spec, or JSON fixture; marking development code does not grant styling or mutation permissions.`);
|
|
224
|
+
// The generated theme sheet and palette are checked for freshness with the tokens, not authored.
|
|
225
|
+
if (generatedThemeFiles.some(generated => file === path.join(dsRoot, config.tokenDir, generated))) continue;
|
|
207
226
|
if (file.endsWith(".css") && isInside(path.join(dsRoot, config.tokenDir), file) && !isDevelopmentFile(file, options)) { checkCss(file, readFileSync(file, "utf8"), undefined, true); continue; }
|
|
208
227
|
if (file.endsWith(".html")) { inspectHtml(readFileSync(file, "utf8"), (rule, message, line) => report(file, rule, message, line)); continue; }
|
|
209
228
|
if (file.endsWith(".css")) {
|
|
@@ -215,6 +234,7 @@ export function checkProject(directory, { trackingRoot } = {}) {
|
|
|
215
234
|
if (!source) continue;
|
|
216
235
|
advisories.push(...pointerCaptureAdvisories(source).map(entry => ({ file: path.relative(root, file).replaceAll("\\", "/"), ...entry })));
|
|
217
236
|
advisories.push(...atomicCompositionReview(source).map(entry => ({ file: path.relative(root, file).replaceAll("\\", "/"), ...entry })));
|
|
237
|
+
if (["components", "patterns"].some(section => isInside(path.join(dsRoot, section), file)) && !isDevelopmentFile(file, options)) advisories.push(...renderColorProbe(source).map(entry => ({ file: path.relative(root, file).replaceAll("\\", "/"), ...entry })));
|
|
218
238
|
for (const diagnostic of program.getSyntacticDiagnostics(source)) {
|
|
219
239
|
const position = source.getLineAndCharacterOfPosition(diagnostic.start ?? 0);
|
|
220
240
|
report(file, "source-syntax", ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"), position.line + 1, position.character + 1);
|
|
@@ -273,6 +293,12 @@ export function checkProject(directory, { trackingRoot } = {}) {
|
|
|
273
293
|
function checkSvgAttribute(node, name) {
|
|
274
294
|
if (svgPresentation.has(name)) nodeReport(node, "svg-attribute", `Native Preact SVG needs ${name.replace(/[A-Z]/g, letter => "-" + letter.toLowerCase())}; React-style ${name} is not normalized by its native renderer.`);
|
|
275
295
|
}
|
|
296
|
+
const lightDarkLiterals = ["components", "patterns"].some(section => isInside(path.join(dsRoot, section), file)) && !isDevelopmentFile(file, options);
|
|
297
|
+
function inLinariaTemplate(node) {
|
|
298
|
+
const template = ts.isTemplateMiddle(node) || ts.isTemplateTail(node) ? node.parent.parent : node.parent;
|
|
299
|
+
const tagged = ts.isTemplateExpression(template) ? template.parent : template;
|
|
300
|
+
return ts.isTaggedTemplateExpression(tagged) && isLinariaTag(tagged.tag);
|
|
301
|
+
}
|
|
276
302
|
function visit(node) {
|
|
277
303
|
if (nativePreact && ts.isJsxAttribute(node) && ts.isIdentifier(node.name)) {
|
|
278
304
|
const parent = node.parent.parent;
|
|
@@ -326,6 +352,10 @@ export function checkProject(directory, { trackingRoot } = {}) {
|
|
|
326
352
|
if (ts.isJsxAttribute(node) && ts.isIdentifier(node.name) && node.name.text === "className" && node.initializer) {
|
|
327
353
|
inspectClass(node.initializer);
|
|
328
354
|
}
|
|
355
|
+
// Runtime inline values (style objects, inline custom properties, <style> text) give
|
|
356
|
+
// per-theme values with the generated themed(), not light-dark(); Linaria templates are
|
|
357
|
+
// checked as CSS above.
|
|
358
|
+
if (lightDarkLiterals && (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node) || ts.isTemplateHead(node) || ts.isTemplateMiddle(node) || ts.isTemplateTail(node)) && /\blight-dark\(/i.test(node.text) && !inLinariaTemplate(node)) nodeReport(node, "theme-light-dark", `Give per-theme values as token halves (--x-light, --x-dark); light-dark() is limited to two schemes; for runtime values use themed() from ${config.tokenDir}/${generatedPaletteFile}.`, { severity: findingSeverity("theme-light-dark") });
|
|
329
359
|
if (ts.isTaggedTemplateExpression(node) && isLinariaTag(node.tag)) {
|
|
330
360
|
const template = node.template;
|
|
331
361
|
const texts = ts.isNoSubstitutionTemplateLiteral(template) ? [template.text] : template.templateSpans.reduce((prefixes,span)=>{const parts=designValues(span.expression);return prefixes.flatMap(prefix=>(parts.length?parts:["__ds_expression__"]).map(value=>prefix+value+span.literal.text)).slice(0,32);},[template.head.text]);
|
|
@@ -337,10 +367,10 @@ export function checkProject(directory, { trackingRoot } = {}) {
|
|
|
337
367
|
visit(source);
|
|
338
368
|
}
|
|
339
369
|
inspectDesignAliases(layerStyles,options,report);
|
|
340
|
-
// Bounded clients should see actionable warnings before source-analysis limits.
|
|
341
370
|
for (const { file, css, offset } of layerStyles) layers.inspectStyles(file, css, offset);
|
|
342
371
|
advisories.push(...(tokenInventory.advisories??[]), ...assetAdvisories, ...a11ySourceAdvisories(options));
|
|
343
|
-
|
|
344
|
-
const
|
|
345
|
-
|
|
372
|
+
// Errors block by class; bounded clients see review items before informational limits.
|
|
373
|
+
const routed=routeFindings(diagnostics,advisories);
|
|
374
|
+
const uniqueDiagnostics=[...new Map(routed.diagnostics.map(diagnostic=>[JSON.stringify([diagnostic.file,diagnostic.rule,diagnostic.line,diagnostic.column,diagnostic.message]),diagnostic])).values()];
|
|
375
|
+
return architectureEvidence({ ok: uniqueDiagnostics.length === 0, diagnostics:uniqueDiagnostics, ...(routed.advisories.length ? { advisories: routed.advisories } : {}) });
|
|
346
376
|
}
|
package/dist/cli.mjs
CHANGED
|
@@ -20,10 +20,13 @@ Usage: ads create <directory> --framework react|preact New design-system proje
|
|
|
20
20
|
--policy acceptance|validation (default validation)
|
|
21
21
|
behaviors [dir] Inspect behavior contracts and current verification evidence
|
|
22
22
|
verify [directory] Run registered behavior checks (--unit and --check select)
|
|
23
|
+
audit [directory] Run axe-core in each rendered scenario, once per brand and theme
|
|
24
|
+
(--scenario, --theme and --brand select; findings are errors)
|
|
23
25
|
tokens [directory] Inspect local token values and theme definitions
|
|
24
26
|
--format dtcg prints them as W3C Design Tokens JSON;
|
|
25
27
|
--theme <name> exports that theme's values (default: the first)
|
|
26
|
-
|
|
28
|
+
--brand <name> exports that brand's values (default: the first)
|
|
29
|
+
assets [directory] Generate configured brand assets, glyphs, themes.generated.css and .ts
|
|
27
30
|
lint-config [dir] Generate .ds/oxlintrc.json with core and project plugins
|
|
28
31
|
mcp [directory] Serve stdio MCP tools/Apps and the local showcase website
|
|
29
32
|
showcase [directory] Serve the built-in MCP client website (no stdio connection)
|
|
@@ -39,6 +42,7 @@ Usage: ads create <directory> --framework react|preact New design-system proje
|
|
|
39
42
|
--mutations MCP only: enable guarded ADS source editing
|
|
40
43
|
--unit id Verify only: select one discovered behavior contract owner
|
|
41
44
|
--check id Verify only: select a registered check (repeatable)
|
|
45
|
+
--scenario id Audit only: select a discovered scenario (repeatable)
|
|
42
46
|
--changed Validate only: select affected checks since the last full audit
|
|
43
47
|
--fresh Check/validate: execute batch checks without task-cache reads
|
|
44
48
|
|
|
@@ -56,9 +60,10 @@ async function main(args) {
|
|
|
56
60
|
let framework;
|
|
57
61
|
let name;
|
|
58
62
|
let format, theme;
|
|
63
|
+
let brand;
|
|
59
64
|
let port;
|
|
60
65
|
let unit;
|
|
61
|
-
const selectedChecks = [];
|
|
66
|
+
const selectedChecks = [], selectedScenarios = [];
|
|
62
67
|
let showcase = true;
|
|
63
68
|
let mutations = false;
|
|
64
69
|
let changed = false, watched = false, policy, fresh = false;
|
|
@@ -78,6 +83,11 @@ async function main(args) {
|
|
|
78
83
|
if (argument === "--unit") { if (unit) throw new Error("Specify one --unit."); unit = value; }
|
|
79
84
|
else selectedChecks.push(value);
|
|
80
85
|
}
|
|
86
|
+
else if (argument === "--scenario") {
|
|
87
|
+
const value = args[++index];
|
|
88
|
+
if (!value || value.startsWith("-")) throw new Error("--scenario needs a discovered scenario ID.");
|
|
89
|
+
selectedScenarios.push(value);
|
|
90
|
+
}
|
|
81
91
|
else if (argument === "--port") {
|
|
82
92
|
const value = args[++index];
|
|
83
93
|
if (port !== undefined || !/^\d+$/.test(value ?? "") || Number(value) > 65535) throw new Error("--port requires one port between 0 and 65535.");
|
|
@@ -92,6 +102,9 @@ async function main(args) {
|
|
|
92
102
|
} else if (argument === "--theme") {
|
|
93
103
|
if (theme !== undefined || !args[index + 1] || args[index + 1].startsWith("--")) throw new Error("Specify --theme <name>.");
|
|
94
104
|
theme = args[++index];
|
|
105
|
+
} else if (argument === "--brand") {
|
|
106
|
+
if (brand !== undefined || !args[index + 1] || args[index + 1].startsWith("--")) throw new Error("Specify --brand <name>.");
|
|
107
|
+
brand = args[++index];
|
|
95
108
|
} else if (argument === "--format") {
|
|
96
109
|
if (format !== undefined || args[index + 1] !== "dtcg") throw new Error("Specify --format dtcg (the W3C Design Tokens format).");
|
|
97
110
|
format = args[++index];
|
|
@@ -125,7 +138,9 @@ async function main(args) {
|
|
|
125
138
|
if (framework !== undefined && !setup) throw new Error("--framework is supported only by create and init.");
|
|
126
139
|
if (name !== undefined && command !== "create") throw new Error("--name is supported only by create.");
|
|
127
140
|
if (format !== undefined && command !== "tokens") throw new Error("--format is supported only by tokens.");
|
|
128
|
-
if (theme !== undefined && format !== "dtcg") throw new Error("--theme is supported only by tokens --format dtcg.");
|
|
141
|
+
if (theme !== undefined && format !== "dtcg" && command !== "audit") throw new Error("--theme is supported only by tokens --format dtcg and audit.");
|
|
142
|
+
if (brand !== undefined && format !== "dtcg" && command !== "audit") throw new Error("--brand is supported only by tokens --format dtcg and audit.");
|
|
143
|
+
if (selectedScenarios.length && command !== "audit") throw new Error("--scenario is supported only by audit.");
|
|
129
144
|
if (command === "create" && !directory) throw new Error("Name the new project's folder: ads create <directory> --framework react|preact.");
|
|
130
145
|
if (command === "init" && directory) throw new Error("Run ads init inside the project, without a directory argument.");
|
|
131
146
|
if ((unit || selectedChecks.length) && command !== "verify") throw new Error("--unit and --check are supported only by verify.");
|
|
@@ -149,26 +164,46 @@ async function main(args) {
|
|
|
149
164
|
}
|
|
150
165
|
else if (command === "behaviors") { const {behaviorStatus}=await import("./verification.mjs"); const {loadConfig}=await import("./config.mjs"); result=behaviorStatus(loadConfig(target)); }
|
|
151
166
|
else if (command === "verify") { const {createVerificationController}=await import("./verification.mjs"); const verification=createVerificationController(target); try {result=await verification.run({...(unit?{unit}:{}),...(selectedChecks.length?{checks:selectedChecks}:{})});} finally {await verification.close();} }
|
|
152
|
-
else if (command === "
|
|
167
|
+
else if (command === "audit") {
|
|
168
|
+
const { runBrowserAudit } = await import("./browser-audit.mjs");
|
|
169
|
+
const controller = new AbortController(), abort = () => controller.abort();
|
|
170
|
+
process.once("SIGINT", abort); process.once("SIGTERM", abort);
|
|
171
|
+
try {
|
|
172
|
+
const { routeFindings } = await import("./finding-rules.mjs");
|
|
173
|
+
const audit = await runBrowserAudit(target, { scenarios: selectedScenarios, themes: theme ? [theme] : undefined, brands: brand ? [brand] : undefined, signal: controller.signal });
|
|
174
|
+
// a11y-axe findings are errors, as in validation; any review-class finding stays nonblocking.
|
|
175
|
+
const routed = routeFindings([], audit.findings);
|
|
176
|
+
result = { ...audit, ok: !routed.diagnostics.length, findings: routed.advisories, diagnostics: routed.diagnostics };
|
|
177
|
+
}
|
|
178
|
+
finally { process.removeListener("SIGINT", abort); process.removeListener("SIGTERM", abort); }
|
|
179
|
+
}
|
|
180
|
+
else if (command === "tokens" && format === "dtcg") { const { exportTokensDtcg } = await import("./token-export.mjs"); console.log(JSON.stringify(exportTokensDtcg(target, { theme, brand }), null, 2)); return; }
|
|
153
181
|
else if (command === "tokens") result = inspectTokens(target);
|
|
154
|
-
else if (command === "assets") result = await generateBrandAssets(target);
|
|
182
|
+
else if (command === "assets") { const { refreshThemesCss } = await import("./themes-watch.mjs"); const themes = refreshThemesCss(target); result = { ...await generateBrandAssets(target), themes: { file: themes.file, written: themes.files[0]?.written ?? false, ...(themes.skipped ? { skipped: themes.skipped } : {}) }, ...(themes.files[1] ? { palette: { file: themes.files[1].file, written: themes.files[1].written } } : {}) }; }
|
|
155
183
|
else if (command === "lint-config") result = generateLintConfig(target);
|
|
156
184
|
else throw new Error(`Unknown command: ${command}. Run ads --help.`);
|
|
157
185
|
if (json) console.log(JSON.stringify(result, null, 2));
|
|
158
186
|
else if (command === "create") console.log(`Created ${result.name} in ${target}\nFramework: ${result.framework}\nNext: cd ${((folder) => /[\s'"$`\\]/.test(folder) ? JSON.stringify(folder) : folder)(path.relative(process.cwd(), target) || ".")} && ${result.packageManager} install && ${result.packageManager} run build && ${result.packageManager} run dev:showcase`);
|
|
159
187
|
else if (command === "init") console.log(`Initialized ${target}\nFramework: ${result.framework}\nAdded ${result.toolDependency.name} (${result.toolDependency.spec}) as a development dependency.\nRun ${result.packageManager} install and ${result.packageManager} run build; the build runs ADS checks and generates configured brand assets automatically.`);
|
|
160
|
-
else if (command === "assets")
|
|
188
|
+
else if (command === "assets") {
|
|
189
|
+
console.log(result.skipped ? "No assets.iconSource configured; brand generation skipped." : `Generated ${result.files.length} brand assets in ${result.directory}.`);
|
|
190
|
+
const themesFile = path.relative(process.cwd(), result.themes.file) || result.themes.file;
|
|
191
|
+
console.log(result.themes.skipped ? `Skipped ${themesFile}: the token sheets still use the old theme form.` : `${result.themes.written ? "Wrote" : "Unchanged"} ${themesFile}.`);
|
|
192
|
+
if (result.palette) console.log(`${result.palette.written ? "Wrote" : "Unchanged"} ${path.relative(process.cwd(), result.palette.file) || result.palette.file}.`);
|
|
193
|
+
}
|
|
161
194
|
else if (command === "lint-config") console.log(`Generated ${result.file}\nUse this optional configuration only in the project linter you choose to run.`);
|
|
162
195
|
else if (command === "behaviors") console.log(JSON.stringify(result, null, 2));
|
|
196
|
+
else if (command === "audit") { const { findingCounts } = await import("./finding-rules.mjs"); console.log(`ADS accessibility audit (${result.engine}): ${findingCounts(result.diagnostics.length, result.findings.length)} across ${result.scenarios} scenarios × ${result.themes.length} themes (${result.themes.join(", ")})${result.brands ? ` × ${result.brands.length} brands (${result.brands.join(", ")})` : ""}.`); for (const finding of result.findings) console.error(`${finding.file}:${finding.line}:${finding.column} [${finding.severity}:${finding.rule}] ${finding.message}`); }
|
|
163
197
|
else if (command === "verify") { for (const item of result.results) console.log(`${item.unit}#${item.check}: ${item.status} (${item.profile})`); }
|
|
164
198
|
else if (command === "validate") {console.log(`ADS ${result.policy} ${result.ok?"passed":"failed"}: ${result.scope}${result.fallback?` (${result.fallback})`:""}`);for(const check of result.checks)console.log(`${check.name}: ${check.skipped?"skipped":check.passed?"passed":"failed"}${check.reason?` (${check.reason})`:""}`);}
|
|
165
199
|
else if (command === "tokens") {
|
|
166
|
-
for (const token of result.tokens) console.log(`${token.name}${token.type ? ` (${token.type})` : ""}: ${token.definitions.map((entry) => `${entry.scope}: ${entry.value}`).join("; ")}`);
|
|
167
|
-
} else if (
|
|
200
|
+
for (const token of result.tokens) console.log(`${token.name}${token.type ? ` (${token.type})` : ""}: ${token.definitions.map((entry) => `${entry.scope}${entry.theme ? ` (${entry.theme})` : ""}: ${entry.value}`).join("; ")}`);
|
|
201
|
+
} else if (command === "check") { const { findingCounts } = await import("./finding-rules.mjs"); console.log(`ADS check ${result.ok ? "passed" : "failed"}: ${target} (${findingCounts(result.diagnostics?.length ?? 0, (result.advisories ?? []).filter(advisory => advisory.severity === "review").length)})`); }
|
|
202
|
+
else if (result.ok) console.log(`ADS check passed: ${target}`);
|
|
168
203
|
if (!json && result.diagnostics?.length) {
|
|
169
|
-
for (const diagnostic of result.diagnostics) console.error(`${diagnostic.file}:${diagnostic.line}:${diagnostic.column} [
|
|
204
|
+
for (const diagnostic of result.diagnostics) console.error(`${diagnostic.file}:${diagnostic.line}:${diagnostic.column} [error:${diagnostic.rule}] ${diagnostic.message}`);
|
|
170
205
|
}
|
|
171
|
-
if (!json) for (const advisory of result.advisories ?? []) if(advisory.severity!=="info") console.error(`${advisory.file}:${advisory.line}:${advisory.column} [${advisory.severity ?? "
|
|
206
|
+
if (!json) for (const advisory of result.advisories ?? []) if(advisory.severity!=="info") console.error(`${advisory.file}:${advisory.line}:${advisory.column} [${advisory.severity ?? "review"}:${advisory.rule}] ${advisory.message}`);
|
|
172
207
|
if (result.ok === false || result.diagnostics?.length) process.exitCode = 1;
|
|
173
208
|
}
|
|
174
209
|
|
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
import valueParser from "postcss-value-parser";
|
|
2
|
+
|
|
3
|
+
// Static CSS Color 4/5 resolution for the generated renderer palette: every absolute color
|
|
4
|
+
// syntax (hex, named, rgb/hsl/hwb, lab/lch, oklab/oklch, color()), color-mix() and
|
|
5
|
+
// light-dark() parse to { space, coords, alpha }; conversions go through linear sRGB or
|
|
6
|
+
// XYZ-D65 with the CSS Color 4 matrices; srgb8 clips each channel to the sRGB gamut, as
|
|
7
|
+
// Chrome's 2D canvas does when it draws a wider color into an sRGB canvas. Contextual values
|
|
8
|
+
// (currentColor, system colors, relative color syntax, calc()) cannot be resolved without an
|
|
9
|
+
// element and return { unresolved: reason }; anything else that is not a color returns null.
|
|
10
|
+
|
|
11
|
+
const named = Object.fromEntries("aliceblue:f0f8ff antiquewhite:faebd7 aqua:00ffff aquamarine:7fffd4 azure:f0ffff beige:f5f5dc bisque:ffe4c4 black:000000 blanchedalmond:ffebcd blue:0000ff blueviolet:8a2be2 brown:a52a2a burlywood:deb887 cadetblue:5f9ea0 chartreuse:7fff00 chocolate:d2691e coral:ff7f50 cornflowerblue:6495ed cornsilk:fff8dc crimson:dc143c cyan:00ffff darkblue:00008b darkcyan:008b8b darkgoldenrod:b8860b darkgray:a9a9a9 darkgreen:006400 darkgrey:a9a9a9 darkkhaki:bdb76b darkmagenta:8b008b darkolivegreen:556b2f darkorange:ff8c00 darkorchid:9932cc darkred:8b0000 darksalmon:e9967a darkseagreen:8fbc8f darkslateblue:483d8b darkslategray:2f4f4f darkslategrey:2f4f4f darkturquoise:00ced1 darkviolet:9400d3 deeppink:ff1493 deepskyblue:00bfff dimgray:696969 dimgrey:696969 dodgerblue:1e90ff firebrick:b22222 floralwhite:fffaf0 forestgreen:228b22 fuchsia:ff00ff gainsboro:dcdcdc ghostwhite:f8f8ff gold:ffd700 goldenrod:daa520 gray:808080 green:008000 greenyellow:adff2f grey:808080 honeydew:f0fff0 hotpink:ff69b4 indianred:cd5c5c indigo:4b0082 ivory:fffff0 khaki:f0e68c lavender:e6e6fa lavenderblush:fff0f5 lawngreen:7cfc00 lemonchiffon:fffacd lightblue:add8e6 lightcoral:f08080 lightcyan:e0ffff lightgoldenrodyellow:fafad2 lightgray:d3d3d3 lightgreen:90ee90 lightgrey:d3d3d3 lightpink:ffb6c1 lightsalmon:ffa07a lightseagreen:20b2aa lightskyblue:87cefa lightslategray:778899 lightslategrey:778899 lightsteelblue:b0c4de lightyellow:ffffe0 lime:00ff00 limegreen:32cd32 linen:faf0e6 magenta:ff00ff maroon:800000 mediumaquamarine:66cdaa mediumblue:0000cd mediumorchid:ba55d3 mediumpurple:9370db mediumseagreen:3cb371 mediumslateblue:7b68ee mediumspringgreen:00fa9a mediumturquoise:48d1cc mediumvioletred:c71585 midnightblue:191970 mintcream:f5fffa mistyrose:ffe4e1 moccasin:ffe4b5 navajowhite:ffdead navy:000080 oldlace:fdf5e6 olive:808000 olivedrab:6b8e23 orange:ffa500 orangered:ff4500 orchid:da70d6 palegoldenrod:eee8aa palegreen:98fb98 paleturquoise:afeeee palevioletred:db7093 papayawhip:ffefd5 peachpuff:ffdab9 peru:cd853f pink:ffc0cb plum:dda0dd powderblue:b0e0e6 purple:800080 rebeccapurple:663399 red:ff0000 rosybrown:bc8f8f royalblue:4169e1 saddlebrown:8b4513 salmon:fa8072 sandybrown:f4a460 seagreen:2e8b57 seashell:fff5ee sienna:a0522d silver:c0c0c0 skyblue:87ceeb slateblue:6a5acd slategray:708090 slategrey:708090 snow:fffafa springgreen:00ff7f steelblue:4682b4 tan:d2b48c teal:008080 thistle:d8bfd8 tomato:ff6347 turquoise:40e0d0 violet:ee82ee wheat:f5deb3 white:ffffff whitesmoke:f5f5f5 yellow:ffff00 yellowgreen:9acd32".split(" ").map(pair => pair.split(":")));
|
|
12
|
+
const systemColors = new Set(["accentcolor", "accentcolortext", "activetext", "buttonborder", "buttonface", "buttontext", "canvas", "canvastext", "field", "fieldtext", "graytext", "highlight", "highlighttext", "linktext", "mark", "marktext", "selecteditem", "selecteditemtext", "visitedtext"]);
|
|
13
|
+
const colorFunctions = new Set(["rgb", "rgba", "hsl", "hsla", "hwb", "lab", "lch", "oklab", "oklch", "color", "color-mix", "light-dark", "contrast-color", "device-cmyk"]);
|
|
14
|
+
|
|
15
|
+
const multiply = (matrix, [a, b, c]) => matrix.map(row => row[0] * a + row[1] * b + row[2] * c);
|
|
16
|
+
const fromSrgbGamma = value => { const abs = Math.abs(value); return abs <= 0.04045 ? value / 12.92 : Math.sign(value) * ((abs + 0.055) / 1.055) ** 2.4; };
|
|
17
|
+
const toSrgbGamma = value => { const abs = Math.abs(value); return abs > 0.0031308 ? Math.sign(value) * (1.055 * abs ** (1 / 2.4) - 0.055) : 12.92 * value; };
|
|
18
|
+
|
|
19
|
+
const linearSrgbToXyz = [[506752 / 1228815, 87881 / 245763, 12673 / 70218], [87098 / 409605, 175762 / 245763, 12673 / 175545], [7918 / 409605, 87881 / 737289, 1001167 / 1053270]];
|
|
20
|
+
const xyzToLinearSrgb = [[12831 / 3959, -329 / 214, -1974 / 3959], [-851781 / 878810, 1648619 / 878810, 36519 / 878810], [705 / 12673, -2585 / 12673, 705 / 667]];
|
|
21
|
+
const d65ToD50 = [[1.0479297925449969, 0.022946870601609652, -0.05019226628920524], [0.02962780877005599, 0.9904344267538799, -0.017073799063418826], [-0.009243040646204504, 0.015055191490298152, 0.7518742814281371]];
|
|
22
|
+
const d50ToD65 = [[0.955473421488075, -0.02309845494876471, 0.06325924320057072], [-0.0283697093338637, 1.0099953980813041, 0.021041441191917323], [0.012314014864481998, -0.020507649298898964, 1.330365926242124]];
|
|
23
|
+
const xyzToLms = [[0.819022437996703, 0.3619062600528904, -0.1288737815209879], [0.0329836539323885, 0.9292868615863434, 0.0361446663506424], [0.0481771893596242, 0.2642395317527308, 0.6335478284694309]];
|
|
24
|
+
const lmsToXyz = [[1.2268798758459243, -0.5578149944602171, 0.2813910456659647], [-0.0405757452148008, 1.112286803280317, -0.0716766580655164], [-0.0763729366746601, -0.4214933324022432, 1.5869240198367816]];
|
|
25
|
+
const lmsToOklab = [[0.210454268309314, 0.7936177747023054, -0.0040720430116193], [1.9779985324311684, -2.42859224204858, 0.450593709617411], [0.0259040424655478, 0.7827717124575296, -0.8086757549230774]];
|
|
26
|
+
const oklabToLms = [[1, 0.3963377773761749, 0.2158037573099136], [1, -0.1055613458156586, -0.0638541728258133], [1, -0.0894841775298119, -1.2914855480194092]];
|
|
27
|
+
const d50White = [0.3457 / 0.3585, 1, (1 - 0.3457 - 0.3585) / 0.3585];
|
|
28
|
+
const kappa = 24389 / 27, epsilon = 216 / 24389;
|
|
29
|
+
|
|
30
|
+
// RGB spaces: transfer function to linear light and the linear-to-XYZ matrix (D65 unless noted).
|
|
31
|
+
const invert = matrix => {
|
|
32
|
+
const [[a, b, c], [d, e, f], [g, h, i]] = matrix, det = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g);
|
|
33
|
+
return [[e * i - f * h, c * h - b * i, b * f - c * e], [f * g - d * i, a * i - c * g, c * d - a * f], [d * h - e * g, b * g - a * h, a * e - b * d]].map(row => row.map(value => value / det));
|
|
34
|
+
};
|
|
35
|
+
const rgbSpace = (toLinear, fromLinear, toXyz, d50 = false) => ({ toLinear, fromLinear, toXyz, fromXyz: invert(toXyz), d50 });
|
|
36
|
+
const identity = value => value;
|
|
37
|
+
const a98 = 563 / 256;
|
|
38
|
+
const rec2020 = { alpha: 1.09929682680944, beta: 0.018053968510807 };
|
|
39
|
+
const rgbSpaces = {
|
|
40
|
+
srgb: { toLinear: fromSrgbGamma, fromLinear: toSrgbGamma, toXyz: linearSrgbToXyz, fromXyz: xyzToLinearSrgb, d50: false },
|
|
41
|
+
"srgb-linear": { toLinear: identity, fromLinear: identity, toXyz: linearSrgbToXyz, fromXyz: xyzToLinearSrgb, d50: false },
|
|
42
|
+
"display-p3": rgbSpace(fromSrgbGamma, toSrgbGamma, [[608311 / 1250200, 189793 / 714400, 198249 / 1000160], [35783 / 156275, 247089 / 357200, 198249 / 2500400], [0, 32229 / 714400, 5220557 / 5000800]]),
|
|
43
|
+
"a98-rgb": rgbSpace(value => Math.sign(value) * Math.abs(value) ** a98, value => Math.sign(value) * Math.abs(value) ** (1 / a98),
|
|
44
|
+
[[573536 / 994567, 263643 / 1420810, 187206 / 994567], [591459 / 1989134, 6239551 / 9945670, 374412 / 4972835], [53769 / 1989134, 351524 / 4972835, 4929758 / 4972835]]),
|
|
45
|
+
"prophoto-rgb": rgbSpace(value => Math.abs(value) <= 16 / 512 ? value / 16 : Math.sign(value) * Math.abs(value) ** 1.8, value => Math.abs(value) >= 1 / 512 ? Math.sign(value) * Math.abs(value) ** (1 / 1.8) : 16 * value,
|
|
46
|
+
[[0.7977666449006423, 0.13518129740053308, 0.0313477341283922], [0.2880748288194013, 0.711835234241873, 0.00008993693872564], [0, 0, 0.8251046025104602]], true),
|
|
47
|
+
rec2020: rgbSpace(value => Math.abs(value) < rec2020.beta * 4.5 ? value / 4.5 : Math.sign(value) * ((Math.abs(value) + rec2020.alpha - 1) / rec2020.alpha) ** (1 / 0.45),
|
|
48
|
+
value => Math.abs(value) > rec2020.beta ? Math.sign(value) * (rec2020.alpha * Math.abs(value) ** 0.45 - (rec2020.alpha - 1)) : 4.5 * value,
|
|
49
|
+
[[63426534 / 99577255, 20160776 / 139408157, 47086771 / 278816314], [26158966 / 99577255, 472592308 / 697040785, 8267143 / 139408157], [0, 19567812 / 697040785, 295819943 / 278816314]]),
|
|
50
|
+
};
|
|
51
|
+
const xyzSpaces = { xyz: false, "xyz-d65": false, "xyz-d50": true };
|
|
52
|
+
const polar = new Set(["hsl", "hwb", "lch", "oklch"]);
|
|
53
|
+
/** The hue index of a polar space's coordinates. */
|
|
54
|
+
const hueIndex = space => space === "hsl" || space === "hwb" ? 0 : 2;
|
|
55
|
+
|
|
56
|
+
const zero = value => Number.isNaN(value) ? 0 : value;
|
|
57
|
+
const radians = degrees => degrees * Math.PI / 180;
|
|
58
|
+
|
|
59
|
+
function hslToSrgb([h, s, l]) {
|
|
60
|
+
const k = n => (n + h / 30) % 12, a = s * Math.min(l, 1 - l);
|
|
61
|
+
return [0, 8, 4].map(n => l - a * Math.max(-1, Math.min(k(n) - 3, 9 - k(n), 1)));
|
|
62
|
+
}
|
|
63
|
+
function srgbToHsl([r, g, b]) {
|
|
64
|
+
const max = Math.max(r, g, b), min = Math.min(r, g, b), l = (max + min) / 2, d = max - min;
|
|
65
|
+
let h = Number.NaN, s = 0;
|
|
66
|
+
if (d !== 0) {
|
|
67
|
+
s = l === 0 || l === 1 ? 0 : (max - l) / Math.min(l, 1 - l);
|
|
68
|
+
h = max === r ? (g - b) / d + (g < b ? 6 : 0) : max === g ? (b - r) / d + 2 : (r - g) / d + 4;
|
|
69
|
+
h *= 60;
|
|
70
|
+
}
|
|
71
|
+
if (s < 0) { h += 180; s = Math.abs(s); }
|
|
72
|
+
if (h >= 360) h -= 360;
|
|
73
|
+
return [Math.abs(s) < 1e-5 ? Number.NaN : h, s, l];
|
|
74
|
+
}
|
|
75
|
+
function hwbToSrgb([h, w, b]) {
|
|
76
|
+
if (w + b >= 1) { const gray = w / (w + b); return [gray, gray, gray]; }
|
|
77
|
+
return hslToSrgb([h, 1, 0.5]).map(value => value * (1 - w - b) + w);
|
|
78
|
+
}
|
|
79
|
+
function srgbToHwb(rgb) {
|
|
80
|
+
const [h] = srgbToHsl(rgb), w = Math.min(...rgb), b = 1 - Math.max(...rgb);
|
|
81
|
+
return [w + b >= 1 - 1e-5 ? Number.NaN : h, w, b];
|
|
82
|
+
}
|
|
83
|
+
const labToXyzD50 = ([l, a, b]) => {
|
|
84
|
+
const f1 = (l + 16) / 116, f0 = a / 500 + f1, f2 = f1 - b / 200;
|
|
85
|
+
return [f0 ** 3 > epsilon ? f0 ** 3 : (116 * f0 - 16) / kappa, l > kappa * epsilon ? f1 ** 3 : l / kappa, f2 ** 3 > epsilon ? f2 ** 3 : (116 * f2 - 16) / kappa].map((value, index) => value * d50White[index]);
|
|
86
|
+
};
|
|
87
|
+
const xyzD50ToLab = xyz => {
|
|
88
|
+
const [f0, f1, f2] = xyz.map((value, index) => value / d50White[index]).map(value => value > epsilon ? Math.cbrt(value) : (kappa * value + 16) / 116);
|
|
89
|
+
return [116 * f1 - 16, 500 * (f0 - f1), 200 * (f1 - f2)];
|
|
90
|
+
};
|
|
91
|
+
const toPolar = ([l, a, b], threshold) => { const c = Math.hypot(a, b); let h = Math.atan2(b, a) * 180 / Math.PI; if (h < 0) h += 360; return [l, c, c < threshold ? Number.NaN : h]; };
|
|
92
|
+
const fromPolar = ([l, c, h]) => [l, zero(c) * Math.cos(radians(zero(h))), zero(c) * Math.sin(radians(zero(h)))];
|
|
93
|
+
|
|
94
|
+
/** XYZ-D65 coordinates of a parsed color. */
|
|
95
|
+
function toXyz({ space, coords }) {
|
|
96
|
+
const values = coords.map(zero);
|
|
97
|
+
if (rgbSpaces[space]) { const rgb = rgbSpaces[space], xyz = multiply(rgb.toXyz, values.map(rgb.toLinear)); return rgb.d50 ? multiply(d50ToD65, xyz) : xyz; }
|
|
98
|
+
if (space in xyzSpaces) return xyzSpaces[space] ? multiply(d50ToD65, values) : values;
|
|
99
|
+
if (space === "hsl") return toXyz({ space: "srgb", coords: hslToSrgb(values) });
|
|
100
|
+
if (space === "hwb") return toXyz({ space: "srgb", coords: hwbToSrgb(values) });
|
|
101
|
+
if (space === "lab") return multiply(d50ToD65, labToXyzD50(values));
|
|
102
|
+
if (space === "lch") return multiply(d50ToD65, labToXyzD50(fromPolar(coords)));
|
|
103
|
+
if (space === "oklab" || space === "oklch") return multiply(lmsToXyz, multiply(oklabToLms, space === "oklch" ? fromPolar(coords) : values).map(value => value ** 3));
|
|
104
|
+
throw new Error(`Unknown color space ${space}.`);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** A parsed color's coordinates in another space (polar spaces mark a powerless hue as NaN). */
|
|
108
|
+
export function convert(color, space) {
|
|
109
|
+
if (color.space === space) return color.coords;
|
|
110
|
+
const xyz = toXyz(color);
|
|
111
|
+
if (rgbSpaces[space]) { const rgb = rgbSpaces[space]; return multiply(rgb.fromXyz, rgb.d50 ? multiply(d65ToD50, xyz) : xyz).map(rgb.fromLinear); }
|
|
112
|
+
if (space in xyzSpaces) return xyzSpaces[space] ? multiply(d65ToD50, xyz) : xyz;
|
|
113
|
+
if (space === "hsl") return srgbToHsl(convert({ space: "xyz", coords: xyz }, "srgb"));
|
|
114
|
+
if (space === "hwb") return srgbToHwb(convert({ space: "xyz", coords: xyz }, "srgb"));
|
|
115
|
+
if (space === "lab") return xyzD50ToLab(multiply(d65ToD50, xyz));
|
|
116
|
+
if (space === "lch") return toPolar(xyzD50ToLab(multiply(d65ToD50, xyz)), 0.01);
|
|
117
|
+
const lab = multiply(lmsToOklab, multiply(xyzToLms, xyz).map(Math.cbrt));
|
|
118
|
+
if (space === "oklab") return lab;
|
|
119
|
+
if (space === "oklch") return toPolar(lab, 0.0004);
|
|
120
|
+
throw new Error(`Unknown color space ${space}.`);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** sRGB 0–255 integer channels and alpha 0–1 (four decimals), each channel clipped to the gamut. */
|
|
124
|
+
export function srgb8(color) {
|
|
125
|
+
// A hair above half rounds up, so exact halves (hwb(200 10% 20%) → 25.5) land where Chrome puts them.
|
|
126
|
+
const rgb = convert(color, "srgb").map(value => Math.round(Math.min(1, Math.max(0, zero(value))) * 255 + 1e-9));
|
|
127
|
+
return [...rgb, Math.round(Math.min(1, Math.max(0, zero(color.alpha))) * 10000) / 10000];
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** The canonical CSS string of sRGB channels: #rrggbb when opaque, rgba(r, g, b, a) otherwise. */
|
|
131
|
+
export function canonicalCss([r, g, b, a]) {
|
|
132
|
+
return a >= 1 ? `#${[r, g, b].map(value => value.toString(16).padStart(2, "0")).join("")}` : `rgba(${r}, ${g}, ${b}, ${a})`;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
class Unresolved extends Error {}
|
|
136
|
+
const unresolved = reason => { throw new Unresolved(reason); };
|
|
137
|
+
const meaningful = nodes => nodes.filter(node => node.type !== "space" && node.type !== "comment");
|
|
138
|
+
|
|
139
|
+
const angle = text => {
|
|
140
|
+
const match = text.match(/^([+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?)(deg|rad|grad|turn)?$/i);
|
|
141
|
+
if (!match) return null;
|
|
142
|
+
const value = Number(match[1]), unit = match[2]?.toLowerCase();
|
|
143
|
+
return unit === "rad" ? value * 180 / Math.PI : unit === "grad" ? value * 0.9 : unit === "turn" ? value * 360 : value;
|
|
144
|
+
};
|
|
145
|
+
const numeric = text => {
|
|
146
|
+
const match = text.match(/^([+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?)(%)?$/i);
|
|
147
|
+
return match ? { value: Number(match[1]), percent: !!match[2] } : null;
|
|
148
|
+
};
|
|
149
|
+
const clamp = (value, min, max) => Math.min(max, Math.max(min, value));
|
|
150
|
+
|
|
151
|
+
/** One channel: a number, a percentage scaled to `percent` (100% = percent) or none (NaN). */
|
|
152
|
+
function channel(node, percent, { hue = false, allowNumber = true, allowPercent = true } = {}) {
|
|
153
|
+
if (node.type === "function") unresolved(node.value.toLowerCase() === "calc" || /^(?:min|max|clamp|round|mod|rem|abs|sign|sin|cos|tan|exp|pow|sqrt|log|hypot)$/i.test(node.value) ? "a math function in a color channel" : `${node.value}() in a color channel`);
|
|
154
|
+
if (node.type !== "word") throw new SyntaxError("channel");
|
|
155
|
+
if (node.value.toLowerCase() === "none") return Number.NaN;
|
|
156
|
+
if (hue) { const degrees = angle(node.value); if (degrees === null) throw new SyntaxError("hue"); return degrees; }
|
|
157
|
+
const parsed = numeric(node.value);
|
|
158
|
+
if (!parsed || (parsed.percent ? !allowPercent : !allowNumber)) throw new SyntaxError("channel");
|
|
159
|
+
return parsed.percent ? parsed.value / 100 * percent : parsed.value;
|
|
160
|
+
}
|
|
161
|
+
const alphaChannel = node => node ? channel(node, 1) : 1;
|
|
162
|
+
|
|
163
|
+
/** Splits a color function's arguments into channels and alpha, in the modern (space and /)
|
|
164
|
+
* or legacy (comma) syntax. */
|
|
165
|
+
function channels(node, count, legacy) {
|
|
166
|
+
const parts = meaningful(node.nodes);
|
|
167
|
+
if (parts[0]?.type === "word" && parts[0].value.toLowerCase() === "from") unresolved("relative color syntax");
|
|
168
|
+
if (legacy && parts.some(part => part.type === "div" && part.value === ",")) {
|
|
169
|
+
const items = [];
|
|
170
|
+
for (let index = 0; index < parts.length; index += 2) {
|
|
171
|
+
items.push(parts[index]);
|
|
172
|
+
if (index + 1 < parts.length && !(parts[index + 1].type === "div" && parts[index + 1].value === ",")) throw new SyntaxError("legacy");
|
|
173
|
+
}
|
|
174
|
+
if (items.length !== count && items.length !== count + 1) throw new SyntaxError("legacy");
|
|
175
|
+
return { values: items.slice(0, count), alpha: items[count], legacy: true };
|
|
176
|
+
}
|
|
177
|
+
const slash = parts.findIndex(part => part.type === "div" && part.value === "/");
|
|
178
|
+
const values = slash < 0 ? parts : parts.slice(0, slash), alpha = slash < 0 ? undefined : parts.slice(slash + 1);
|
|
179
|
+
if (values.length !== count || values.some(part => part.type === "div") || alpha && alpha.length !== 1) throw new SyntaxError("modern");
|
|
180
|
+
return { values, alpha: alpha?.[0] };
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function parseHex(text) {
|
|
184
|
+
let hex = text.slice(1);
|
|
185
|
+
if (![3, 4, 6, 8].includes(hex.length) || !/^[\da-f]+$/i.test(hex)) return null;
|
|
186
|
+
if (hex.length < 6) hex = [...hex].map(digit => digit + digit).join("");
|
|
187
|
+
const values = [0, 2, 4, 6].map(index => parseInt(hex.slice(index, index + 2) || "ff", 16) / 255);
|
|
188
|
+
return { space: "srgb", coords: values.slice(0, 3), alpha: values[3] };
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function parseFunction(node, options) {
|
|
192
|
+
const name = node.value.toLowerCase();
|
|
193
|
+
if (name === "color-mix") return parseMix(node, options);
|
|
194
|
+
if (name === "light-dark") {
|
|
195
|
+
const parts = meaningful(node.nodes), comma = parts.findIndex(part => part.type === "div" && part.value === ",");
|
|
196
|
+
if (comma !== 1 || parts.length !== 3) throw new SyntaxError("light-dark");
|
|
197
|
+
if (!options.scheme) unresolved("light-dark() needs the color scheme");
|
|
198
|
+
return parseNode(parts[options.scheme === "dark" ? 2 : 0], options);
|
|
199
|
+
}
|
|
200
|
+
if (name === "rgb" || name === "rgba") {
|
|
201
|
+
const { values, alpha, legacy } = channels(node, 3, true);
|
|
202
|
+
const parsed = values.map(part => channel(part, 255));
|
|
203
|
+
if (legacy && values.some(part => numeric(part.value)?.percent) !== values.every(part => numeric(part.value)?.percent)) throw new SyntaxError("rgb");
|
|
204
|
+
return { space: "srgb", coords: parsed.map(value => Number.isNaN(value) ? value : clamp(value, 0, 255) / 255), alpha: clamp(alphaChannel(alpha), 0, 1) };
|
|
205
|
+
}
|
|
206
|
+
if (name === "hsl" || name === "hsla" || name === "hwb") {
|
|
207
|
+
const { values, alpha, legacy } = channels(node, 3, name !== "hwb");
|
|
208
|
+
const h = channel(values[0], 0, { hue: true }), [a, b] = values.slice(1).map(part => channel(part, 100, { allowNumber: !legacy }) / 100);
|
|
209
|
+
const hue = Number.isNaN(h) ? h : ((h % 360) + 360) % 360;
|
|
210
|
+
return { space: name === "hwb" ? "hwb" : "hsl", coords: [hue, Number.isNaN(a) ? a : name === "hwb" ? a : clamp(a, 0, 1), Number.isNaN(b) ? b : name === "hwb" ? b : clamp(b, 0, 1)], alpha: clamp(alphaChannel(alpha), 0, 1) };
|
|
211
|
+
}
|
|
212
|
+
if (name === "lab" || name === "oklab") {
|
|
213
|
+
const { values, alpha } = channels(node, 3, false), ok = name === "oklab";
|
|
214
|
+
const l = channel(values[0], ok ? 1 : 100), [a, b] = values.slice(1).map(part => channel(part, ok ? 0.4 : 125));
|
|
215
|
+
return { space: name, coords: [Number.isNaN(l) ? l : clamp(l, 0, ok ? 1 : 100), a, b], alpha: clamp(alphaChannel(alpha), 0, 1) };
|
|
216
|
+
}
|
|
217
|
+
if (name === "lch" || name === "oklch") {
|
|
218
|
+
const { values, alpha } = channels(node, 3, false), ok = name === "oklch";
|
|
219
|
+
const l = channel(values[0], ok ? 1 : 100), c = channel(values[1], ok ? 0.4 : 150), h = channel(values[2], 0, { hue: true });
|
|
220
|
+
return { space: name, coords: [Number.isNaN(l) ? l : clamp(l, 0, ok ? 1 : 100), Number.isNaN(c) ? c : Math.max(0, c), Number.isNaN(h) ? h : ((h % 360) + 360) % 360], alpha: clamp(alphaChannel(alpha), 0, 1) };
|
|
221
|
+
}
|
|
222
|
+
if (name === "color") {
|
|
223
|
+
const parts = meaningful(node.nodes);
|
|
224
|
+
if (parts[0]?.type === "word" && parts[0].value.toLowerCase() === "from") unresolved("relative color syntax");
|
|
225
|
+
const space = parts[0]?.type === "word" ? parts[0].value.toLowerCase() : "";
|
|
226
|
+
if (!rgbSpaces[space] && !(space in xyzSpaces)) { if (space.startsWith("--")) unresolved(`custom color space ${space}`); throw new SyntaxError("color"); }
|
|
227
|
+
const { values, alpha } = channels({ nodes: parts.slice(1) }, 3, false);
|
|
228
|
+
return { space, coords: values.map(part => channel(part, 1)), alpha: clamp(alphaChannel(alpha), 0, 1) };
|
|
229
|
+
}
|
|
230
|
+
unresolved(`${node.value}() is not resolved statically`);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
const mixSpaces = new Set([...Object.keys(rgbSpaces), ...Object.keys(xyzSpaces), "lab", "oklab", "hsl", "hwb", "lch", "oklch"]);
|
|
234
|
+
|
|
235
|
+
/** color-mix(in <space> [<method> hue], <color> [<p>], <color> [<p>]) per CSS Color 5:
|
|
236
|
+
* premultiplied interpolation, percentages normalized, and an alpha multiplier when they sum
|
|
237
|
+
* under 100%. Missing (none or powerless) components take the other color's value. */
|
|
238
|
+
function parseMix(node, options) {
|
|
239
|
+
const groups = [[]];
|
|
240
|
+
for (const part of meaningful(node.nodes)) if (part.type === "div" && part.value === ",") groups.push([]); else groups.at(-1).push(part);
|
|
241
|
+
let space = "oklab", method = "shorter";
|
|
242
|
+
if (groups[0][0]?.type === "word" && groups[0][0].value.toLowerCase() === "in") {
|
|
243
|
+
const words = groups.shift().map(part => part.type === "word" ? part.value.toLowerCase() : "");
|
|
244
|
+
space = words[1];
|
|
245
|
+
if (!mixSpaces.has(space)) { if (space?.startsWith("--")) unresolved(`custom color space ${space}`); throw new SyntaxError("color-mix space"); }
|
|
246
|
+
if (words.length === 4 && words[3] === "hue" && polar.has(space) && ["shorter", "longer", "increasing", "decreasing"].includes(words[2])) method = words[2];
|
|
247
|
+
else if (words.length !== 2) throw new SyntaxError("color-mix method");
|
|
248
|
+
}
|
|
249
|
+
if (space === "xyz") space = "xyz-d65";
|
|
250
|
+
if (groups.length !== 2) { if (groups.length > 2) unresolved("color-mix() with more than two colors"); throw new SyntaxError("color-mix colors"); }
|
|
251
|
+
const items = groups.map(group => {
|
|
252
|
+
const percentNode = group.find(part => part.type === "word" && part.value.endsWith("%")), rest = group.filter(part => part !== percentNode);
|
|
253
|
+
if (rest.length !== 1 || group.length > 2) throw new SyntaxError("color-mix item");
|
|
254
|
+
const percent = percentNode ? numeric(percentNode.value) : null;
|
|
255
|
+
if (percentNode && (!percent?.percent || percent.value < 0 || percent.value > 100)) throw new SyntaxError("color-mix percentage");
|
|
256
|
+
return { color: parseNode(rest[0], options), percent: percent?.value ?? null };
|
|
257
|
+
});
|
|
258
|
+
let [p1, p2] = items.map(item => item.percent);
|
|
259
|
+
if (p1 === null && p2 === null) [p1, p2] = [50, 50];
|
|
260
|
+
else if (p1 === null) p1 = 100 - p2;
|
|
261
|
+
else if (p2 === null) p2 = 100 - p1;
|
|
262
|
+
const sum = p1 + p2;
|
|
263
|
+
if (sum === 0) throw new SyntaxError("color-mix percentages sum to zero");
|
|
264
|
+
const multiplier = Math.min(1, sum / 100), t = p2 / sum;
|
|
265
|
+
const [a, b] = items.map(({ color }) => ({ coords: [...convert(color, space)], alpha: color.alpha }));
|
|
266
|
+
// A component missing in one color takes the other's.
|
|
267
|
+
for (let index = 0; index < 3; index++) {
|
|
268
|
+
if (Number.isNaN(a.coords[index])) a.coords[index] = b.coords[index];
|
|
269
|
+
else if (Number.isNaN(b.coords[index])) b.coords[index] = a.coords[index];
|
|
270
|
+
}
|
|
271
|
+
if (Number.isNaN(a.alpha)) a.alpha = b.alpha; else if (Number.isNaN(b.alpha)) b.alpha = a.alpha;
|
|
272
|
+
const alpha1 = zero(a.alpha), alpha2 = zero(b.alpha), alpha = alpha1 * (1 - t) + alpha2 * t;
|
|
273
|
+
const hue = polar.has(space) ? hueIndex(space) : -1;
|
|
274
|
+
const coords = [0, 1, 2].map(index => {
|
|
275
|
+
let [c1, c2] = [a.coords[index], b.coords[index]];
|
|
276
|
+
if (Number.isNaN(c1)) return Number.NaN;
|
|
277
|
+
if (index === hue) {
|
|
278
|
+
const delta = c2 - c1;
|
|
279
|
+
if (method === "shorter") { if (delta > 180) c1 += 360; else if (delta < -180) c2 += 360; }
|
|
280
|
+
else if (method === "longer") { if (delta > 0 && delta < 180) c1 += 360; else if (delta > -180 && delta <= 0) c2 += 360; }
|
|
281
|
+
else if (method === "increasing") { if (delta < 0) c2 += 360; }
|
|
282
|
+
else if (delta > 0) c1 += 360;
|
|
283
|
+
return ((c1 * (1 - t) + c2 * t) % 360 + 360) % 360;
|
|
284
|
+
}
|
|
285
|
+
const mixed = c1 * alpha1 * (1 - t) + c2 * alpha2 * t;
|
|
286
|
+
return alpha === 0 ? mixed : mixed / alpha;
|
|
287
|
+
});
|
|
288
|
+
return { space, coords, alpha: alpha * multiplier };
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function parseNode(node, options) {
|
|
292
|
+
if (node.type === "word") {
|
|
293
|
+
const text = node.value.toLowerCase();
|
|
294
|
+
if (text.startsWith("#")) { const color = parseHex(text); if (!color) throw new SyntaxError("hex"); return color; }
|
|
295
|
+
if (text === "transparent") return { space: "srgb", coords: [0, 0, 0], alpha: 0 };
|
|
296
|
+
if (named[text]) return parseHex(`#${named[text]}`);
|
|
297
|
+
if (text === "currentcolor") unresolved("currentColor depends on the element");
|
|
298
|
+
if (systemColors.has(text)) unresolved(`system color ${node.value}`);
|
|
299
|
+
throw new SyntaxError("word");
|
|
300
|
+
}
|
|
301
|
+
if (node.type === "function" && colorFunctions.has(node.value.toLowerCase())) return parseFunction(node, options);
|
|
302
|
+
if (node.type === "function") unresolved(`${node.value}() is not resolved statically`);
|
|
303
|
+
throw new SyntaxError("node");
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/** A CSS value as a color: { color: { space, coords, alpha } }, { unresolved: reason } for a color
|
|
307
|
+
* that depends on its element or uses syntax ADS does not evaluate, or null when the value is
|
|
308
|
+
* not a single color. `scheme` ("light" | "dark") selects light-dark() branches. */
|
|
309
|
+
export function parseCssColor(value, { scheme } = {}) {
|
|
310
|
+
const nodes = meaningful(valueParser(String(value).trim()).nodes);
|
|
311
|
+
if (nodes.length !== 1) return null;
|
|
312
|
+
const [node] = nodes;
|
|
313
|
+
const colorish = node.type === "function" ? colorFunctions.has(node.value.toLowerCase()) : node.type === "word" && (node.value.startsWith("#") || node.value.toLowerCase() in named || ["transparent", "currentcolor"].includes(node.value.toLowerCase()) || systemColors.has(node.value.toLowerCase()));
|
|
314
|
+
if (!colorish) return null;
|
|
315
|
+
try { return { color: parseNode(node, { scheme }) }; }
|
|
316
|
+
catch (error) {
|
|
317
|
+
if (error instanceof Unresolved) return { unresolved: error.message };
|
|
318
|
+
if (error instanceof SyntaxError) return { unresolved: "invalid color syntax" };
|
|
319
|
+
throw error;
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/** Whether a value names something ADS treats as a color even when it cannot resolve it: a single
|
|
324
|
+
* function call (an unknown or contextual function). */
|
|
325
|
+
export const singleFunction = value => { const nodes = meaningful(valueParser(String(value).trim()).nodes); return nodes.length === 1 && nodes[0].type === "function" ? nodes[0].value : null; };
|