@eluan/theme-generator 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +60 -0
- package/dist/cli/generate.d.ts +2 -0
- package/dist/cli/generate.js +207 -0
- package/dist/color/convert.d.ts +4 -0
- package/dist/color/convert.js +28 -0
- package/dist/color/curves.d.ts +3 -0
- package/dist/color/curves.js +29 -0
- package/dist/color/neutral.d.ts +2 -0
- package/dist/color/neutral.js +7 -0
- package/dist/color/scale.d.ts +2 -0
- package/dist/color/scale.js +19 -0
- package/dist/color/systemHues.d.ts +3 -0
- package/dist/color/systemHues.js +28 -0
- package/dist/compile/css.d.ts +7 -0
- package/dist/compile/css.js +160 -0
- package/dist/generate.d.ts +3 -0
- package/dist/generate.js +114 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +12 -0
- package/dist/input/validate.d.ts +16 -0
- package/dist/input/validate.js +93 -0
- package/dist/preview/smoke.d.ts +2 -0
- package/dist/preview/smoke.js +83 -0
- package/dist/tokens/contrast.d.ts +6 -0
- package/dist/tokens/contrast.js +126 -0
- package/dist/tokens/primitives.d.ts +2 -0
- package/dist/tokens/primitives.js +27 -0
- package/dist/tokens/semanticMap.d.ts +2 -0
- package/dist/tokens/semanticMap.js +161 -0
- package/dist/types.d.ts +68 -0
- package/dist/types.js +1 -0
- package/package.json +55 -0
package/dist/generate.js
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { validateAccents } from './input/validate.js';
|
|
3
|
+
import { buildPrimitives } from './tokens/primitives.js';
|
|
4
|
+
import { buildSemanticMap } from './tokens/semanticMap.js';
|
|
5
|
+
import { autoCorrect } from './tokens/contrast.js';
|
|
6
|
+
import { compilePrimitivesCSS, compileModeCSS, compileThemeCSS, compileCreateThemeTokens, } from './compile/css.js';
|
|
7
|
+
export function computeInputHash(config) {
|
|
8
|
+
const input = JSON.stringify({
|
|
9
|
+
accents: config.accents,
|
|
10
|
+
minContrast: config.minContrast,
|
|
11
|
+
neutralTintRatio: config.neutralTintRatio,
|
|
12
|
+
systemHues: config.systemHues,
|
|
13
|
+
curve: config.curve,
|
|
14
|
+
});
|
|
15
|
+
return createHash('sha256').update(input).digest('hex').slice(0, 12);
|
|
16
|
+
}
|
|
17
|
+
function buildReport(config, warnings, corrections, primitives, inputHash) {
|
|
18
|
+
const lines = [];
|
|
19
|
+
lines.push(`# Theme Generation Report`);
|
|
20
|
+
lines.push('');
|
|
21
|
+
lines.push(`**Theme:** ${config.themeName}`);
|
|
22
|
+
lines.push(`**Input hash:** ${inputHash}`);
|
|
23
|
+
lines.push(`**Accents:** ${config.accents.join(', ')}`);
|
|
24
|
+
lines.push(`**Min contrast:** ${config.minContrast}:1`);
|
|
25
|
+
lines.push(`**Neutral tint ratio:** ${config.neutralTintRatio}`);
|
|
26
|
+
lines.push('');
|
|
27
|
+
if (warnings.length > 0) {
|
|
28
|
+
lines.push(`## Warnings`);
|
|
29
|
+
lines.push('');
|
|
30
|
+
for (const w of warnings) {
|
|
31
|
+
lines.push(`- ${w.message}`);
|
|
32
|
+
}
|
|
33
|
+
lines.push('');
|
|
34
|
+
}
|
|
35
|
+
if (corrections.length > 0) {
|
|
36
|
+
lines.push(`## Contrast Corrections (${corrections.length})`);
|
|
37
|
+
lines.push('');
|
|
38
|
+
lines.push(`| Token | Mode | Original | Corrected | Before | After | Kind |`);
|
|
39
|
+
lines.push(`|-------|------|----------|-----------|--------|-------|------|`);
|
|
40
|
+
for (const c of corrections) {
|
|
41
|
+
lines.push(`| ${c.token} | ${c.mode} | ${c.originalRef} | ${c.correctedRef} | ${c.originalContrast.toFixed(2)} | ${c.correctedContrast.toFixed(2)} | ${c.kind} |`);
|
|
42
|
+
}
|
|
43
|
+
lines.push('');
|
|
44
|
+
}
|
|
45
|
+
else {
|
|
46
|
+
lines.push(`## Contrast`);
|
|
47
|
+
lines.push('');
|
|
48
|
+
lines.push('All fg/border pairings meet the configured minimum contrast ratio. No corrections needed.');
|
|
49
|
+
lines.push('');
|
|
50
|
+
}
|
|
51
|
+
const chromaClampedSteps = [];
|
|
52
|
+
for (const [scaleName, scale] of Object.entries(primitives)) {
|
|
53
|
+
if (!scale)
|
|
54
|
+
continue;
|
|
55
|
+
for (const [stepStr, entry] of Object.entries(scale)) {
|
|
56
|
+
const rawC = entry.oklch.c;
|
|
57
|
+
if (rawC > 0 && entry.oklch.c / rawC < 0.8) {
|
|
58
|
+
chromaClampedSteps.push(`${scaleName}.${stepStr}`);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
if (chromaClampedSteps.length > 0) {
|
|
63
|
+
lines.push(`## Gamut Mapping`);
|
|
64
|
+
lines.push('');
|
|
65
|
+
lines.push(`${chromaClampedSteps.length} steps had chroma clamped by >20%:`);
|
|
66
|
+
for (const s of chromaClampedSteps) {
|
|
67
|
+
lines.push(`- ${s}`);
|
|
68
|
+
}
|
|
69
|
+
lines.push('');
|
|
70
|
+
}
|
|
71
|
+
lines.push(`## Output Files`);
|
|
72
|
+
lines.push('');
|
|
73
|
+
lines.push(`- \`primitives.json\` — W3C Design Tokens format`);
|
|
74
|
+
lines.push(`- \`semantic.json\` — Semantic map with light/dark refs`);
|
|
75
|
+
lines.push(`- \`theme.css\` — Drop-in CSS for Eluan`);
|
|
76
|
+
lines.push(`- \`preview.html\` — Visual smoke test`);
|
|
77
|
+
return lines.join('\n');
|
|
78
|
+
}
|
|
79
|
+
export function generateTheme(config) {
|
|
80
|
+
const { accents: accentInputs, warnings } = validateAccents(config.accents);
|
|
81
|
+
const inputHash = computeInputHash(config);
|
|
82
|
+
const primitives = buildPrimitives(accentInputs, config);
|
|
83
|
+
let semanticMap = buildSemanticMap();
|
|
84
|
+
const lightResult = autoCorrect(semanticMap, primitives, 'light', config.minContrast);
|
|
85
|
+
semanticMap = lightResult.correctedMap;
|
|
86
|
+
const lightCorrections = lightResult.corrections;
|
|
87
|
+
const darkResult = autoCorrect(semanticMap, primitives, 'dark', config.minContrast);
|
|
88
|
+
semanticMap = darkResult.correctedMap;
|
|
89
|
+
const darkCorrections = darkResult.corrections;
|
|
90
|
+
const allCorrections = [...lightCorrections, ...darkCorrections];
|
|
91
|
+
const primitivesCSS = compilePrimitivesCSS(primitives, config.themeName);
|
|
92
|
+
const lightModeCSS = compileModeCSS(semanticMap, primitives, 'light', config.themeName);
|
|
93
|
+
const darkModeCSS = compileModeCSS(semanticMap, primitives, 'dark', config.themeName);
|
|
94
|
+
const themeCSS = compileThemeCSS(semanticMap, primitives, config.themeName, inputHash);
|
|
95
|
+
const createThemeTokens = {};
|
|
96
|
+
const lightTokens = compileCreateThemeTokens(semanticMap, primitives, 'light');
|
|
97
|
+
for (const [k, v] of Object.entries(lightTokens)) {
|
|
98
|
+
createThemeTokens[k] = v;
|
|
99
|
+
}
|
|
100
|
+
const report = buildReport(config, warnings, allCorrections, primitives, inputHash);
|
|
101
|
+
return {
|
|
102
|
+
primitives,
|
|
103
|
+
semanticMap,
|
|
104
|
+
corrections: allCorrections,
|
|
105
|
+
css: {
|
|
106
|
+
primitives: primitivesCSS,
|
|
107
|
+
lightMode: lightModeCSS,
|
|
108
|
+
darkMode: darkModeCSS,
|
|
109
|
+
theme: themeCSS,
|
|
110
|
+
},
|
|
111
|
+
createThemeTokens,
|
|
112
|
+
report,
|
|
113
|
+
};
|
|
114
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export { generateTheme, computeInputHash } from './generate.js';
|
|
2
|
+
export { validateAccents, normalizeHex, classifyAccent } from './input/validate.js';
|
|
3
|
+
export { hexToOklch, oklchToHex, gamutMap } from './color/convert.js';
|
|
4
|
+
export { DEFAULT_CURVE, validateCurve } from './color/curves.js';
|
|
5
|
+
export { generateScale } from './color/scale.js';
|
|
6
|
+
export { generateSystemScales, DEFAULT_SYSTEM_HUES } from './color/systemHues.js';
|
|
7
|
+
export { generateNeutralScale } from './color/neutral.js';
|
|
8
|
+
export { buildSemanticMap } from './tokens/semanticMap.js';
|
|
9
|
+
export { buildPrimitives } from './tokens/primitives.js';
|
|
10
|
+
export { checkContrast, autoCorrect } from './tokens/contrast.js';
|
|
11
|
+
export { compilePrimitivesJSON, compileSemanticJSON, compilePrimitivesCSS, compileModeCSS, compileThemeCSS, compileCreateThemeTokens, } from './compile/css.js';
|
|
12
|
+
export { generateSmokeHTML } from './preview/smoke.js';
|
|
13
|
+
export type { Oklch, ScaleStep, ScaleEntry, Scale, ScaleName, SystemHueName, PrimitiveTokens, TokenRef, SemanticRole, SemanticEntry, SemanticMap, GeneratorConfig, AccentClassification, ValidatedAccent, ContrastCorrection, GeneratorResult, } from './types.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export { generateTheme, computeInputHash } from './generate.js';
|
|
2
|
+
export { validateAccents, normalizeHex, classifyAccent } from './input/validate.js';
|
|
3
|
+
export { hexToOklch, oklchToHex, gamutMap } from './color/convert.js';
|
|
4
|
+
export { DEFAULT_CURVE, validateCurve } from './color/curves.js';
|
|
5
|
+
export { generateScale } from './color/scale.js';
|
|
6
|
+
export { generateSystemScales, DEFAULT_SYSTEM_HUES } from './color/systemHues.js';
|
|
7
|
+
export { generateNeutralScale } from './color/neutral.js';
|
|
8
|
+
export { buildSemanticMap } from './tokens/semanticMap.js';
|
|
9
|
+
export { buildPrimitives } from './tokens/primitives.js';
|
|
10
|
+
export { checkContrast, autoCorrect } from './tokens/contrast.js';
|
|
11
|
+
export { compilePrimitivesJSON, compileSemanticJSON, compilePrimitivesCSS, compileModeCSS, compileThemeCSS, compileCreateThemeTokens, } from './compile/css.js';
|
|
12
|
+
export { generateSmokeHTML } from './preview/smoke.js';
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { AccentClassification, ValidatedAccent, Oklch } from '../types.js';
|
|
2
|
+
export type ValidationWarning = {
|
|
3
|
+
value: string;
|
|
4
|
+
message: string;
|
|
5
|
+
};
|
|
6
|
+
export type ValidationResult = {
|
|
7
|
+
accents: ValidatedAccent[];
|
|
8
|
+
warnings: ValidationWarning[];
|
|
9
|
+
};
|
|
10
|
+
export declare function classifyAccent(oklch: Oklch): AccentClassification;
|
|
11
|
+
export declare function normalizeHex(input: string): {
|
|
12
|
+
hex: string;
|
|
13
|
+
warning?: string;
|
|
14
|
+
};
|
|
15
|
+
export declare function detectNearDuplicates(accents: ValidatedAccent[]): ValidationWarning[];
|
|
16
|
+
export declare function validateAccents(inputs: string[]): ValidationResult;
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { converter } from 'culori';
|
|
2
|
+
const toOklch = converter('oklch');
|
|
3
|
+
const HEX3 = /^#[0-9a-fA-F]{3}$/;
|
|
4
|
+
const HEX6 = /^#[0-9a-fA-F]{6}$/;
|
|
5
|
+
const HEX8 = /^#[0-9a-fA-F]{8}$/;
|
|
6
|
+
function expandHex3(hex) {
|
|
7
|
+
const r = hex[1], g = hex[2], b = hex[3];
|
|
8
|
+
return `#${r}${r}${g}${g}${b}${b}`;
|
|
9
|
+
}
|
|
10
|
+
function stripAlpha(hex) {
|
|
11
|
+
return hex.slice(0, 7);
|
|
12
|
+
}
|
|
13
|
+
export function classifyAccent(oklch) {
|
|
14
|
+
if (oklch.c < 0.03)
|
|
15
|
+
return 'low-chroma';
|
|
16
|
+
if (oklch.l > 0.93 || oklch.l < 0.15)
|
|
17
|
+
return 'extreme-lightness';
|
|
18
|
+
return 'normal';
|
|
19
|
+
}
|
|
20
|
+
export function normalizeHex(input) {
|
|
21
|
+
const trimmed = input.trim();
|
|
22
|
+
if (HEX3.test(trimmed)) {
|
|
23
|
+
return { hex: expandHex3(trimmed).toLowerCase() };
|
|
24
|
+
}
|
|
25
|
+
if (HEX6.test(trimmed)) {
|
|
26
|
+
return { hex: trimmed.toLowerCase() };
|
|
27
|
+
}
|
|
28
|
+
if (HEX8.test(trimmed)) {
|
|
29
|
+
return {
|
|
30
|
+
hex: stripAlpha(trimmed).toLowerCase(),
|
|
31
|
+
warning: `Alpha channel stripped from "${trimmed}" — only RGB channels used.`,
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
throw new Error(`Invalid hex color "${trimmed}". Expected #RGB, #RRGGBB, or #RRGGBBAA format.`);
|
|
35
|
+
}
|
|
36
|
+
export function detectNearDuplicates(accents) {
|
|
37
|
+
const warnings = [];
|
|
38
|
+
for (let i = 0; i < accents.length; i++) {
|
|
39
|
+
for (let j = i + 1; j < accents.length; j++) {
|
|
40
|
+
const hDiff = Math.abs(accents[i].oklch.h - accents[j].oklch.h);
|
|
41
|
+
const normalizedDiff = Math.min(hDiff, 360 - hDiff);
|
|
42
|
+
if (normalizedDiff < 10) {
|
|
43
|
+
warnings.push({
|
|
44
|
+
value: `${accents[i].hex}, ${accents[j].hex}`,
|
|
45
|
+
message: `Accents ${accents[i].hex} and ${accents[j].hex} have similar hues (ΔH = ${normalizedDiff.toFixed(1)}°). Consider using more distinct hues.`,
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return warnings;
|
|
51
|
+
}
|
|
52
|
+
export function validateAccents(inputs) {
|
|
53
|
+
if (inputs.length === 0) {
|
|
54
|
+
throw new Error('At least one accent color is required.');
|
|
55
|
+
}
|
|
56
|
+
if (inputs.length > 3) {
|
|
57
|
+
throw new Error('At most 3 accent colors are supported.');
|
|
58
|
+
}
|
|
59
|
+
const warnings = [];
|
|
60
|
+
const accents = [];
|
|
61
|
+
for (const input of inputs) {
|
|
62
|
+
const { hex, warning } = normalizeHex(input);
|
|
63
|
+
if (warning) {
|
|
64
|
+
warnings.push({ value: input, message: warning });
|
|
65
|
+
}
|
|
66
|
+
const parsed = toOklch(hex);
|
|
67
|
+
if (!parsed) {
|
|
68
|
+
throw new Error(`Failed to parse color "${hex}" to OKLCH.`);
|
|
69
|
+
}
|
|
70
|
+
const oklch = {
|
|
71
|
+
mode: 'oklch',
|
|
72
|
+
l: parsed.l,
|
|
73
|
+
c: parsed.c,
|
|
74
|
+
h: parsed.h ?? 0,
|
|
75
|
+
};
|
|
76
|
+
const classification = classifyAccent(oklch);
|
|
77
|
+
if (classification === 'low-chroma') {
|
|
78
|
+
warnings.push({
|
|
79
|
+
value: hex,
|
|
80
|
+
message: `"${hex}" is near-achromatic (chroma ${oklch.c.toFixed(4)}). Scale will have minimal color. System hues will use a fixed fallback hue.`,
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
if (classification === 'extreme-lightness') {
|
|
84
|
+
warnings.push({
|
|
85
|
+
value: hex,
|
|
86
|
+
message: `"${hex}" has extreme lightness (L=${oklch.l.toFixed(3)}). Only hue and chroma will be used; lightness follows the standard curve.`,
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
accents.push({ hex, oklch, classification });
|
|
90
|
+
}
|
|
91
|
+
warnings.push(...detectNearDuplicates(accents));
|
|
92
|
+
return { accents, warnings };
|
|
93
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { checkContrast } from '../tokens/contrast.js';
|
|
2
|
+
const SCALE_STEPS = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950];
|
|
3
|
+
function resolveHex(ref, primitives) {
|
|
4
|
+
if (ref === 'white')
|
|
5
|
+
return '#ffffff';
|
|
6
|
+
if (ref === 'black')
|
|
7
|
+
return '#000000';
|
|
8
|
+
const [scaleName, stepStr] = ref.split('.');
|
|
9
|
+
const step = Number(stepStr);
|
|
10
|
+
return primitives[scaleName][step].hex;
|
|
11
|
+
}
|
|
12
|
+
function textColor(hex) {
|
|
13
|
+
const r = parseInt(hex.slice(1, 3), 16);
|
|
14
|
+
const g = parseInt(hex.slice(3, 5), 16);
|
|
15
|
+
const b = parseInt(hex.slice(5, 7), 16);
|
|
16
|
+
const lum = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
|
|
17
|
+
return lum > 0.5 ? '#000000' : '#ffffff';
|
|
18
|
+
}
|
|
19
|
+
function scaleSwatchesHTML(name, primitives) {
|
|
20
|
+
const scale = primitives[name];
|
|
21
|
+
if (!scale)
|
|
22
|
+
return '';
|
|
23
|
+
const swatches = SCALE_STEPS.map((step) => {
|
|
24
|
+
const hex = scale[step].hex;
|
|
25
|
+
const fg = textColor(hex);
|
|
26
|
+
return `<div style="background:${hex};color:${fg};padding:8px 12px;font-size:12px;font-family:monospace;display:flex;justify-content:space-between;min-width:140px"><span>${step}</span><span>${hex}</span></div>`;
|
|
27
|
+
}).join('');
|
|
28
|
+
return `<div style="margin-bottom:16px"><h3 style="margin:0 0 4px;font-size:14px;font-family:system-ui">${name}</h3><div style="display:flex;flex-direction:column;border-radius:8px;overflow:hidden">${swatches}</div></div>`;
|
|
29
|
+
}
|
|
30
|
+
function semanticPairingHTML(token, fgHex, bgHex, fgRef, bgRef, mode) {
|
|
31
|
+
const ratio = checkContrast(fgHex, bgHex);
|
|
32
|
+
const pass = ratio >= 4.5;
|
|
33
|
+
const badge = pass
|
|
34
|
+
? `<span style="color:#16a34a;font-weight:bold">PASS</span>`
|
|
35
|
+
: `<span style="color:#dc2626;font-weight:bold">FAIL</span>`;
|
|
36
|
+
return `<div style="background:${bgHex};color:${fgHex};padding:12px 16px;border-radius:6px;margin-bottom:4px;font-family:monospace;font-size:13px;display:flex;justify-content:space-between;align-items:center"><span>${token} (${mode})</span><span>${ratio.toFixed(2)}:1 ${badge}</span></div>`;
|
|
37
|
+
}
|
|
38
|
+
export function generateSmokeHTML(primitives, semanticMap, themeName) {
|
|
39
|
+
const scaleNames = Object.keys(primitives);
|
|
40
|
+
const scaleSection = scaleNames
|
|
41
|
+
.map((name) => scaleSwatchesHTML(name, primitives))
|
|
42
|
+
.join('');
|
|
43
|
+
const fgTokens = Object.entries(semanticMap).filter(([, entry]) => entry.role === 'fg' && entry.contrastAgainst);
|
|
44
|
+
const pairingRows = [];
|
|
45
|
+
for (const [token, entry] of fgTokens) {
|
|
46
|
+
const bgEntry = semanticMap[entry.contrastAgainst];
|
|
47
|
+
if (!bgEntry)
|
|
48
|
+
continue;
|
|
49
|
+
for (const mode of ['light', 'dark']) {
|
|
50
|
+
const fgRef = entry[mode];
|
|
51
|
+
const bgRef = bgEntry[mode];
|
|
52
|
+
const fgHex = resolveHex(fgRef, primitives);
|
|
53
|
+
const bgHex = resolveHex(bgRef, primitives);
|
|
54
|
+
pairingRows.push(semanticPairingHTML(token, fgHex, bgHex, fgRef, bgRef, mode));
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return `<!DOCTYPE html>
|
|
58
|
+
<html lang="en">
|
|
59
|
+
<head>
|
|
60
|
+
<meta charset="utf-8">
|
|
61
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
62
|
+
<title>${themeName} — Theme Preview</title>
|
|
63
|
+
<style>
|
|
64
|
+
* { box-sizing: border-box; margin: 0; padding: 0; }
|
|
65
|
+
body { font-family: system-ui, sans-serif; padding: 32px; background: #f5f5f5; color: #171717; }
|
|
66
|
+
h1 { margin-bottom: 8px; }
|
|
67
|
+
h2 { margin: 32px 0 16px; border-bottom: 2px solid #e5e5e5; padding-bottom: 8px; }
|
|
68
|
+
.scales { display: flex; flex-wrap: wrap; gap: 16px; }
|
|
69
|
+
.pairings { max-width: 700px; }
|
|
70
|
+
</style>
|
|
71
|
+
</head>
|
|
72
|
+
<body>
|
|
73
|
+
<h1>${themeName}</h1>
|
|
74
|
+
<p style="color:#737373;margin-bottom:24px">Generated by eluan-theme-generator</p>
|
|
75
|
+
|
|
76
|
+
<h2>Color Scales</h2>
|
|
77
|
+
<div class="scales">${scaleSection}</div>
|
|
78
|
+
|
|
79
|
+
<h2>Semantic Pairings — Contrast Check</h2>
|
|
80
|
+
<div class="pairings">${pairingRows.join('')}</div>
|
|
81
|
+
</body>
|
|
82
|
+
</html>`;
|
|
83
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { ContrastCorrection, PrimitiveTokens, SemanticMap } from '../types.js';
|
|
2
|
+
export declare function checkContrast(fgHex: string, bgHex: string): number;
|
|
3
|
+
export declare function autoCorrect(map: SemanticMap, primitives: PrimitiveTokens, mode: 'light' | 'dark', defaultMinContrast: number): {
|
|
4
|
+
correctedMap: SemanticMap;
|
|
5
|
+
corrections: ContrastCorrection[];
|
|
6
|
+
};
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { wcagContrast } from 'culori';
|
|
2
|
+
const ORDERED_STEPS = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950];
|
|
3
|
+
export function checkContrast(fgHex, bgHex) {
|
|
4
|
+
return wcagContrast(fgHex, bgHex);
|
|
5
|
+
}
|
|
6
|
+
function resolveTokenRef(ref, primitives, neutralScale) {
|
|
7
|
+
if (ref === 'white')
|
|
8
|
+
return '#ffffff';
|
|
9
|
+
if (ref === 'black')
|
|
10
|
+
return '#000000';
|
|
11
|
+
const [scaleName, stepStr] = ref.split('.');
|
|
12
|
+
const step = Number(stepStr);
|
|
13
|
+
const scale = primitives[scaleName];
|
|
14
|
+
if (!scale)
|
|
15
|
+
return null;
|
|
16
|
+
const entry = scale[step];
|
|
17
|
+
if (!entry)
|
|
18
|
+
return null;
|
|
19
|
+
return entry.hex;
|
|
20
|
+
}
|
|
21
|
+
function parseRef(ref) {
|
|
22
|
+
if (ref === 'white' || ref === 'black')
|
|
23
|
+
return null;
|
|
24
|
+
const [scaleName, stepStr] = ref.split('.');
|
|
25
|
+
return { scaleName, step: Number(stepStr) };
|
|
26
|
+
}
|
|
27
|
+
function shiftFgTowardsContrast(originalRef, bgHex, primitives, minContrast, mode) {
|
|
28
|
+
const parsed = parseRef(originalRef);
|
|
29
|
+
if (!parsed)
|
|
30
|
+
return null;
|
|
31
|
+
const { scaleName } = parsed;
|
|
32
|
+
const scale = primitives[scaleName];
|
|
33
|
+
if (!scale)
|
|
34
|
+
return null;
|
|
35
|
+
const stepsToTry = mode === 'light'
|
|
36
|
+
? [...ORDERED_STEPS].reverse()
|
|
37
|
+
: [...ORDERED_STEPS];
|
|
38
|
+
let attempts = 0;
|
|
39
|
+
for (const step of stepsToTry) {
|
|
40
|
+
if (attempts >= 3)
|
|
41
|
+
break;
|
|
42
|
+
const entry = scale[step];
|
|
43
|
+
if (!entry)
|
|
44
|
+
continue;
|
|
45
|
+
const ratio = checkContrast(entry.hex, bgHex);
|
|
46
|
+
if (ratio >= minContrast) {
|
|
47
|
+
return {
|
|
48
|
+
ref: `${scaleName}.${step}`,
|
|
49
|
+
contrast: ratio,
|
|
50
|
+
kind: 'step-shift',
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
attempts++;
|
|
54
|
+
}
|
|
55
|
+
const hardFallbacks = mode === 'light'
|
|
56
|
+
? [
|
|
57
|
+
{ ref: 'neutral.950', hex: resolveTokenRef('neutral.950', primitives) ?? '#000000' },
|
|
58
|
+
{ ref: 'white', hex: '#ffffff' },
|
|
59
|
+
{ ref: 'black', hex: '#000000' },
|
|
60
|
+
]
|
|
61
|
+
: [
|
|
62
|
+
{ ref: 'neutral.50', hex: resolveTokenRef('neutral.50', primitives) ?? '#ffffff' },
|
|
63
|
+
{ ref: 'white', hex: '#ffffff' },
|
|
64
|
+
{ ref: 'black', hex: '#000000' },
|
|
65
|
+
];
|
|
66
|
+
let bestFallback = null;
|
|
67
|
+
for (const fb of hardFallbacks) {
|
|
68
|
+
const ratio = checkContrast(fb.hex, bgHex);
|
|
69
|
+
if (ratio >= minContrast && (!bestFallback || ratio > bestFallback.contrast)) {
|
|
70
|
+
bestFallback = { ref: fb.ref, contrast: ratio };
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
if (bestFallback) {
|
|
74
|
+
return { ref: bestFallback.ref, contrast: bestFallback.contrast, kind: 'hard-fallback' };
|
|
75
|
+
}
|
|
76
|
+
const whiteRatio = checkContrast('#ffffff', bgHex);
|
|
77
|
+
const blackRatio = checkContrast('#000000', bgHex);
|
|
78
|
+
const best = whiteRatio >= blackRatio ? { ref: 'white', contrast: whiteRatio } : { ref: 'black', contrast: blackRatio };
|
|
79
|
+
return { ref: best.ref, contrast: best.contrast, kind: 'hard-fallback' };
|
|
80
|
+
}
|
|
81
|
+
export function autoCorrect(map, primitives, mode, defaultMinContrast) {
|
|
82
|
+
const corrections = [];
|
|
83
|
+
const corrected = { ...map };
|
|
84
|
+
for (const [tokenName, entry] of Object.entries(map)) {
|
|
85
|
+
if (entry.role === 'decorative')
|
|
86
|
+
continue;
|
|
87
|
+
if (entry.role !== 'fg' && entry.role !== 'border')
|
|
88
|
+
continue;
|
|
89
|
+
if (!entry.contrastAgainst)
|
|
90
|
+
continue;
|
|
91
|
+
const bgEntry = map[entry.contrastAgainst];
|
|
92
|
+
if (!bgEntry)
|
|
93
|
+
continue;
|
|
94
|
+
const bgRef = mode === 'light' ? bgEntry.light : bgEntry.dark;
|
|
95
|
+
const fgRef = mode === 'light' ? entry.light : entry.dark;
|
|
96
|
+
const bgHex = resolveTokenRef(bgRef, primitives);
|
|
97
|
+
const fgHex = resolveTokenRef(fgRef, primitives);
|
|
98
|
+
if (!bgHex || !fgHex)
|
|
99
|
+
continue;
|
|
100
|
+
const minContrast = entry.minContrast ?? defaultMinContrast;
|
|
101
|
+
const ratio = checkContrast(fgHex, bgHex);
|
|
102
|
+
if (ratio >= minContrast)
|
|
103
|
+
continue;
|
|
104
|
+
const correction = shiftFgTowardsContrast(fgRef, bgHex, primitives, minContrast, mode);
|
|
105
|
+
if (correction) {
|
|
106
|
+
const newEntry = { ...corrected[tokenName] };
|
|
107
|
+
if (mode === 'light') {
|
|
108
|
+
newEntry.light = correction.ref;
|
|
109
|
+
}
|
|
110
|
+
else {
|
|
111
|
+
newEntry.dark = correction.ref;
|
|
112
|
+
}
|
|
113
|
+
corrected[tokenName] = newEntry;
|
|
114
|
+
corrections.push({
|
|
115
|
+
token: tokenName,
|
|
116
|
+
mode,
|
|
117
|
+
originalRef: fgRef,
|
|
118
|
+
correctedRef: correction.ref,
|
|
119
|
+
originalContrast: ratio,
|
|
120
|
+
correctedContrast: correction.contrast,
|
|
121
|
+
kind: correction.kind,
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
return { correctedMap: corrected, corrections };
|
|
126
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { DEFAULT_CURVE, validateCurve } from '../color/curves.js';
|
|
2
|
+
import { generateScale } from '../color/scale.js';
|
|
3
|
+
import { generateSystemScales } from '../color/systemHues.js';
|
|
4
|
+
import { generateNeutralScale } from '../color/neutral.js';
|
|
5
|
+
export function buildPrimitives(accents, config) {
|
|
6
|
+
const curve = config.curve ?? DEFAULT_CURVE;
|
|
7
|
+
validateCurve(curve);
|
|
8
|
+
const tokens = {};
|
|
9
|
+
const primary = accents[0];
|
|
10
|
+
const isLowChroma = primary.classification === 'low-chroma';
|
|
11
|
+
tokens.primary = generateScale(primary.oklch.h, primary.oklch.c, curve);
|
|
12
|
+
if (accents.length >= 2) {
|
|
13
|
+
const sec = accents[1];
|
|
14
|
+
tokens.secondary = generateScale(sec.oklch.h, sec.oklch.c, curve);
|
|
15
|
+
}
|
|
16
|
+
if (accents.length >= 3) {
|
|
17
|
+
const ter = accents[2];
|
|
18
|
+
tokens.tertiary = generateScale(ter.oklch.h, ter.oklch.c, curve);
|
|
19
|
+
}
|
|
20
|
+
tokens.neutral = generateNeutralScale(primary.oklch.h, primary.oklch.c, config.neutralTintRatio, curve);
|
|
21
|
+
const systemScales = generateSystemScales(primary.oklch.c, isLowChroma, curve, config.systemHues);
|
|
22
|
+
tokens.error = systemScales.error;
|
|
23
|
+
tokens.warning = systemScales.warning;
|
|
24
|
+
tokens.success = systemScales.success;
|
|
25
|
+
tokens.info = systemScales.info;
|
|
26
|
+
return tokens;
|
|
27
|
+
}
|