@eluan/theme-generator 0.4.0 → 0.5.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.
@@ -1,21 +1,35 @@
1
- import { modeRef } from '../tokens/semanticMap.js';
1
+ import { buildSemanticMap, modeRef } from '../tokens/semanticMap.js';
2
+ import { resolveHex } from '../tokens/refs.js';
2
3
  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
- const scale = primitives[scaleName];
11
- if (!scale) {
12
- throw new Error(`Invalid token reference "${ref}": unknown scale "${scaleName}".`);
13
- }
14
- const entry = scale[step];
15
- if (!entry) {
16
- throw new Error(`Invalid token reference "${ref}": scale "${scaleName}" has no step ${stepStr}.`);
17
- }
18
- return entry.hex;
4
+ const MODES = ['light', 'dim', 'dark'];
5
+ /**
6
+ * The tokens a generated theme states. The base theme derives every grey
7
+ * token from the ramp, so those are left to it, except one a contrast
8
+ * correction has moved: that one is stated, and in every mode, because the
9
+ * theme's light block applies in all three.
10
+ */
11
+ export function emittedTokens(map) {
12
+ const base = buildSemanticMap();
13
+ return Object.keys(map).filter((token) => {
14
+ const entry = map[token];
15
+ if (!entry.inherit)
16
+ return true;
17
+ const original = base[token];
18
+ return !original || MODES.some((mode) => modeRef(entry, mode) !== modeRef(original, mode));
19
+ });
20
+ }
21
+ /**
22
+ * The grey ramp as `--color-neutral-*`, the one thing every mode's surfaces,
23
+ * text and borders are built from. Step 0 is white.
24
+ */
25
+ export function compileNeutralRamp(primitives) {
26
+ const neutral = primitives.neutral;
27
+ if (!neutral)
28
+ throw new Error('Neutral scale is required');
29
+ const ramp = { '--color-neutral-0': '#ffffff' };
30
+ for (const step of SCALE_STEPS)
31
+ ramp[`--color-neutral-${step}`] = neutral[step].hex;
32
+ return ramp;
19
33
  }
20
34
  function scaleToW3C(name, scale) {
21
35
  const group = {};
@@ -61,6 +75,7 @@ export function compileSemanticJSON(map, primitives, darkPrimitives = primitives
61
75
  $ref: entry.dark,
62
76
  },
63
77
  role: entry.role,
78
+ ...(entry.inherit ? { inherit: true } : {}),
64
79
  ...(entry.contrastAgainst ? { contrastAgainst: entry.contrastAgainst } : {}),
65
80
  ...(entry.minContrast ? { minContrast: entry.minContrast } : {}),
66
81
  ...(entry.allowBelowDefault ? { allowBelowDefault: true } : {}),
@@ -82,6 +97,8 @@ export function compilePrimitivesCSS(primitives, themeName) {
82
97
  if (!scale)
83
98
  continue;
84
99
  blocks.push(`\n /* ${name} */`);
100
+ if (name === 'neutral')
101
+ blocks.push(` --color-neutral-0: #ffffff;`);
85
102
  blocks.push(compilePrimitiveCSSBlock(name, scale, name));
86
103
  }
87
104
  return `/* Generated by eluan-theme-generator — ${themeName} primitives */\n\n[data-theme="${themeName}"] {\n${blocks.join('\n')}\n}`;
@@ -92,20 +109,6 @@ const PALETTE_STEPS = {
92
109
  dim: { main: 600, background: 100, tint: 200, foreground: 800, shade: 900 },
93
110
  dark: { main: 400, background: 950, tint: 900, foreground: 200, shade: 300 },
94
111
  };
95
- const NEUTRAL_STEPS = {
96
- light: {
97
- bg: { primary: 50, secondary: 100, tertiary: 200, quaternary: 300, quinary: 400 },
98
- fg: { primary: 950, secondary: 800, tertiary: 600, quaternary: 500, quinary: 400 },
99
- },
100
- dim: {
101
- bg: { primary: 100, secondary: 200, tertiary: 300, quaternary: 400, quinary: 500 },
102
- fg: { primary: 950, secondary: 900, tertiary: 700, quaternary: 600, quinary: 500 },
103
- },
104
- dark: {
105
- bg: { primary: 800, secondary: 900, tertiary: 950, quaternary: 700, quinary: 600 },
106
- fg: { primary: 50, secondary: 100, tertiary: 200, quaternary: 300, quinary: 400 },
107
- },
108
- };
109
112
  const MODE_LABELS = { light: 'Light', dim: 'Dim', dark: 'Dark' };
110
113
  function compileModeCSSBlock(map, primitives, mode, scaleName, cssPrefix) {
111
114
  const scale = primitives[scaleName];
@@ -119,21 +122,21 @@ function compileModeCSSBlock(map, primitives, mode, scaleName, cssPrefix) {
119
122
  }
120
123
  export function compileModeCSS(map, primitives, mode, themeName) {
121
124
  const lines = [];
122
- const neutral = primitives.neutral;
123
- if (!neutral)
125
+ if (!primitives.neutral)
124
126
  throw new Error('Neutral scale is required');
125
- const { bg: bgSteps, fg: fgSteps } = NEUTRAL_STEPS[mode];
126
- // The semantic map's entries win when present, so this matches css.theme
127
- // and the custom theme even after a contrast correction moves one.
128
- const ramp = (token, step) => map[token] ? resolveHex(modeRef(map[token], mode), primitives) : neutral[step].hex;
129
- lines.push(` /* Backgrounds */`);
130
- for (const [level, step] of Object.entries(bgSteps)) {
131
- lines.push(` --backgrounds-${level}: ${ramp(`backgrounds-${level}`, step)};`);
132
- }
133
- lines.push(`\n /* Foregrounds */`);
134
- for (const [level, step] of Object.entries(fgSteps)) {
135
- lines.push(` --foregrounds-${level}: ${ramp(`foregrounds-${level}`, step)};`);
136
- }
127
+ // Resolved from the semantic map, so the values match css.theme and the
128
+ // custom theme even after a contrast correction moves one.
129
+ const group = (title, prefix) => {
130
+ lines.push(`${lines.length ? '\n' : ''} /* ${title} */`);
131
+ for (const [token, entry] of Object.entries(map)) {
132
+ if (!token.startsWith(prefix))
133
+ continue;
134
+ lines.push(` --${token}: ${resolveHex(modeRef(entry, mode), primitives)};`);
135
+ }
136
+ };
137
+ group('Backgrounds', 'backgrounds-');
138
+ group('Foregrounds', 'foregrounds-');
139
+ group('Borders', 'borders-');
137
140
  const paletteScales = [
138
141
  ['primary', 'accent'],
139
142
  ['error', 'error'],
@@ -155,11 +158,20 @@ export function compileThemeCSS(map, primitives, themeName, inputHash, darkPrimi
155
158
  lines.push(`/* Generated by eluan-theme-generator v0.1.0 */`);
156
159
  lines.push(`/* Input hash: ${inputHash} */`);
157
160
  lines.push(`/* Theme: ${themeName} */`);
161
+ // The ramp, on a selector that outranks the base theme's, so every mode's
162
+ // surfaces, text and borders are built from this theme's greys.
163
+ lines.push('');
164
+ lines.push(`[data-theme="${themeName}"][data-mode] {`);
165
+ lines.push(Object.entries(compileNeutralRamp(primitives))
166
+ .map(([prop, value]) => ` ${prop}: ${value};`)
167
+ .join('\n'));
168
+ lines.push('}');
169
+ const emitted = emittedTokens(map);
158
170
  const sources = { light: primitives, dim: dimPrimitives, dark: darkPrimitives };
159
- for (const mode of ['light', 'dim', 'dark']) {
171
+ for (const mode of MODES) {
160
172
  const tokenLines = [];
161
- for (const [token, entry] of Object.entries(map)) {
162
- const ref = modeRef(entry, mode);
173
+ for (const token of emitted) {
174
+ const ref = modeRef(map[token], mode);
163
175
  tokenLines.push(` --${token}: ${resolveHex(ref, sources[mode])}; /* ${ref} */`);
164
176
  }
165
177
  lines.push('');
@@ -170,7 +182,12 @@ export function compileThemeCSS(map, primitives, themeName, inputHash, darkPrimi
170
182
  }
171
183
  return lines.join('\n');
172
184
  }
173
- export function compileCreateThemeTokens(map, primitives, mode) {
185
+ /**
186
+ * Every token in the map resolved for `mode`, whether or not the theme states
187
+ * it. For contrast checks, previews and swatches; a theme itself needs only
188
+ * `compileCreateThemeTokens`.
189
+ */
190
+ export function compileResolvedTokens(map, primitives, mode) {
174
191
  const tokens = {};
175
192
  for (const [token, entry] of Object.entries(map)) {
176
193
  tokens[`--${token}`] = resolveHex(modeRef(entry, mode), primitives);
@@ -178,11 +195,26 @@ export function compileCreateThemeTokens(map, primitives, mode) {
178
195
  return tokens;
179
196
  }
180
197
  /**
181
- * CSS for a custom theme layered on `minimal`, in the same shape `createTheme()`
198
+ * The tokens a theme states for `mode`, as `createTheme()` from @eluan/core
199
+ * takes them: the grey ramp (light only), the accent and status colours, and
200
+ * any grey token a contrast correction moved.
201
+ */
202
+ export function compileCreateThemeTokens(map, primitives, mode) {
203
+ // Light carries the ramp: createTheme() puts the light tokens on a selector
204
+ // that applies in every mode, and the ramp is the same in all of them.
205
+ const tokens = mode === 'light' ? compileNeutralRamp(primitives) : {};
206
+ for (const token of emittedTokens(map)) {
207
+ tokens[`--${token}`] = resolveHex(modeRef(map[token], mode), primitives);
208
+ }
209
+ return tokens;
210
+ }
211
+ /**
212
+ * CSS for a custom theme layered on `eluan`, in the same shape `createTheme()`
182
213
  * from @eluan/core emits: the light tokens on `[data-theme-custom="<name>"]`
183
214
  * and the dim and dark tokens on that plus `[data-mode]`. Because the theme
184
- * sits on top of `minimal` instead of replacing it, `minimal`'s fonts stay in
185
- * place. Without `dim`, dim mode uses the light tokens.
215
+ * sits on top of `eluan` instead of replacing it, the base theme's fonts and
216
+ * its surface logic stay in place. Without `dim`, dim mode uses the light
217
+ * tokens.
186
218
  */
187
219
  export function compileCustomThemeCSS(themeName, light, dark, dim) {
188
220
  const name = themeName.replace(/["\\]/g, '\\$&');
package/dist/generate.js CHANGED
@@ -1,9 +1,10 @@
1
1
  import { validateAccents } from './input/validate.js';
2
2
  import { buildPrimitives } from './tokens/primitives.js';
3
3
  import { buildSemanticMap } from './tokens/semanticMap.js';
4
- import { autoCorrect } from './tokens/contrast.js';
4
+ import { autoCorrect, checkContrast } from './tokens/contrast.js';
5
+ import { resolveRef } from './tokens/refs.js';
5
6
  import { buildDarkPrimitives, DEFAULT_DARK_LIFT, MAX_DARK_LIFT } from './color/darkLift.js';
6
- import { buildDimPrimitives, DEFAULT_DIM_CHROMA, DEFAULT_DIM_WARMTH, MIN_DIM_CHROMA } from './color/dim.js';
7
+ import { buildDimPrimitives, DEFAULT_DIM_CHROMA, MIN_DIM_CHROMA } from './color/dim.js';
7
8
  import { compilePrimitivesCSS, compileModeCSS, compileThemeCSS, compileCreateThemeTokens, compileCustomThemeCSS, } from './compile/css.js';
8
9
  /*
9
10
  * FNV-1a (64-bit) constants.
@@ -48,15 +49,28 @@ export function computeInputHash(config) {
48
49
  systemHues: config.systemHues,
49
50
  curve: config.curve,
50
51
  // Only when set, so configs that predate these options keep their fingerprint
52
+ neutral: config.neutral,
53
+ neutralTint: config.neutralTint,
51
54
  darkLift: config.darkLift,
52
55
  dimChroma: config.dimChroma,
53
- dimWarmth: config.dimWarmth,
54
56
  });
55
57
  // Take the high 48 bits: FNV-1a mixes upward through the multiply, so the high
56
58
  // nibbles are the better-distributed end of the digest.
57
59
  return fnv1a64(input).toString(16).padStart(16, '0').slice(0, 12);
58
60
  }
59
- function buildReport(config, warnings, corrections, primitives, inputHash) {
61
+ /** Contrast of the primary action's text on its fill, in light mode. */
62
+ function primaryTextContrast(map, primitives) {
63
+ const fg = map['action-primary-fg'];
64
+ const bg = map['action-primary-bg'];
65
+ if (!fg || !bg)
66
+ return null;
67
+ const fgHex = resolveRef(fg.light, primitives);
68
+ const bgHex = resolveRef(bg.light, primitives);
69
+ if (!fgHex || !bgHex)
70
+ return null;
71
+ return { ref: fg.light, contrast: checkContrast(fgHex, bgHex) };
72
+ }
73
+ function buildReport(config, warnings, corrections, primitives, inputHash, semanticMap) {
60
74
  const lines = [];
61
75
  lines.push(`# Theme Generation Report`);
62
76
  lines.push('');
@@ -64,10 +78,15 @@ function buildReport(config, warnings, corrections, primitives, inputHash) {
64
78
  lines.push(`**Input hash:** ${inputHash}`);
65
79
  lines.push(`**Accents:** ${config.accents.join(', ')}`);
66
80
  lines.push(`**Min contrast:** ${config.minContrast}:1`);
67
- lines.push(`**Neutral tint ratio:** ${config.neutralTintRatio}`);
81
+ if (config.neutral === undefined && config.neutralTint === undefined) {
82
+ lines.push(`**Neutral tint ratio:** ${config.neutralTintRatio}`);
83
+ }
84
+ else {
85
+ lines.push(`**Neutral:** ${config.neutral ?? 'from the first accent'}`);
86
+ lines.push(`**Neutral tint:** ${config.neutralTint ?? "the neutral colour's own"}`);
87
+ }
68
88
  lines.push(`**Dark lift:** ${config.darkLift ?? DEFAULT_DARK_LIFT}`);
69
89
  lines.push(`**Dim chroma:** ${config.dimChroma ?? DEFAULT_DIM_CHROMA}`);
70
- lines.push(`**Dim warmth:** ${config.dimWarmth ?? DEFAULT_DIM_WARMTH}`);
71
90
  lines.push('');
72
91
  if (warnings.length > 0) {
73
92
  lines.push(`## Warnings`);
@@ -93,6 +112,14 @@ function buildReport(config, warnings, corrections, primitives, inputHash) {
93
112
  lines.push('All fg/border pairings meet the configured minimum contrast ratio. No corrections needed.');
94
113
  lines.push('');
95
114
  }
115
+ const onAccent = primaryTextContrast(semanticMap, primitives);
116
+ if (onAccent !== null && onAccent.contrast < config.minContrast) {
117
+ lines.push(`## Primary action text`);
118
+ lines.push('');
119
+ lines.push(`${onAccent.ref === 'white' ? 'White' : onAccent.ref} on the accent is ${onAccent.contrast.toFixed(2)}:1, under the ${config.minContrast}:1 minimum. ` +
120
+ `The look keeps white on the accent down to 3:1. For full-contrast button text, pick a darker accent or override \`--action-primary-fg\`.`);
121
+ lines.push('');
122
+ }
96
123
  const chromaClampedSteps = [];
97
124
  for (const [scaleName, scale] of Object.entries(primitives)) {
98
125
  if (!scale)
@@ -134,11 +161,7 @@ export function generateTheme(config) {
134
161
  if (!Number.isFinite(dimChroma) || dimChroma < MIN_DIM_CHROMA || dimChroma > 1) {
135
162
  throw new Error(`dimChroma must be between ${MIN_DIM_CHROMA} and 1, got ${config.dimChroma}.`);
136
163
  }
137
- const dimWarmth = config.dimWarmth ?? DEFAULT_DIM_WARMTH;
138
- if (!Number.isFinite(dimWarmth) || dimWarmth < 0 || dimWarmth > 1) {
139
- throw new Error(`dimWarmth must be between 0 and 1, got ${config.dimWarmth}.`);
140
- }
141
- const primitivesDim = buildDimPrimitives(primitives, dimChroma, dimWarmth);
164
+ const primitivesDim = buildDimPrimitives(primitives, dimChroma);
142
165
  let semanticMap = buildSemanticMap();
143
166
  const lightResult = autoCorrect(semanticMap, primitives, 'light', config.minContrast);
144
167
  semanticMap = lightResult.correctedMap;
@@ -165,10 +188,10 @@ export function generateTheme(config) {
165
188
  const createThemeOptions = { tokens: createThemeTokens, modes: { dim: dimTokens, dark: darkTokens } };
166
189
  const customTheme = {
167
190
  name: config.themeName,
168
- extends: 'minimal',
191
+ extends: 'eluan',
169
192
  css: compileCustomThemeCSS(config.themeName, createThemeTokens, darkTokens, dimTokens),
170
193
  };
171
- const report = buildReport(config, warnings, allCorrections, primitives, inputHash);
194
+ const report = buildReport(config, warnings, allCorrections, primitives, inputHash, semanticMap);
172
195
  return {
173
196
  primitives,
174
197
  primitivesDark,
package/dist/index.d.ts CHANGED
@@ -1,15 +1,16 @@
1
1
  export { generateTheme, computeInputHash } from './generate.js';
2
- export { validateAccents, normalizeHex, classifyAccent } from './input/validate.js';
2
+ export { validateAccents, validateNeutral, normalizeHex, classifyAccent } from './input/validate.js';
3
3
  export { hexToOklch, oklchToHex, gamutMap } from './color/convert.js';
4
- export { DEFAULT_CURVE, validateCurve } from './color/curves.js';
4
+ export { DEFAULT_CURVE, NEUTRAL_CURVE, ANCHOR_LIGHTNESS_RANGE, anchorCurve, validateCurve } from './color/curves.js';
5
5
  export { generateScale } from './color/scale.js';
6
- export { buildDarkPrimitives, liftScale, DEFAULT_DARK_LIFT, MAX_DARK_LIFT, DARK_LIFT_WEIGHTS } from './color/darkLift.js';
7
- export { buildDimPrimitives, toneDownScale, warmScale, DEFAULT_DIM_CHROMA, MIN_DIM_CHROMA, DEFAULT_DIM_WARMTH, TEAK_HUE_CHROMA, } from './color/dim.js';
6
+ export { buildDarkPrimitives, liftScale, pinAccentSteps, ACCENT_PINNED_STEPS, DEFAULT_DARK_LIFT, MAX_DARK_LIFT, DARK_LIFT_WEIGHTS, } from './color/darkLift.js';
7
+ export { buildDimPrimitives, toneDownScale, DEFAULT_DIM_CHROMA, MIN_DIM_CHROMA } from './color/dim.js';
8
8
  export { generateSystemScales, DEFAULT_SYSTEM_HUES } from './color/systemHues.js';
9
- export { generateNeutralScale } from './color/neutral.js';
9
+ export { generateNeutralScale, generateTintedNeutralScale, MAX_NEUTRAL_CHROMA } from './color/neutral.js';
10
10
  export { buildSemanticMap, contrastGrounds, dimRef, modeRef, withDimRefs } from './tokens/semanticMap.js';
11
11
  export { buildPrimitives } from './tokens/primitives.js';
12
12
  export { checkContrast, autoCorrect } from './tokens/contrast.js';
13
- export { compilePrimitivesJSON, compileSemanticJSON, compilePrimitivesCSS, compileModeCSS, compileThemeCSS, compileCreateThemeTokens, compileCustomThemeCSS, } from './compile/css.js';
13
+ export { parseRef, resolveRef } from './tokens/refs.js';
14
+ export { compilePrimitivesJSON, compileSemanticJSON, compilePrimitivesCSS, compileModeCSS, compileThemeCSS, compileCreateThemeTokens, compileCustomThemeCSS, compileNeutralRamp, compileResolvedTokens, emittedTokens, } from './compile/css.js';
14
15
  export { generateSmokeHTML } from './preview/smoke.js';
15
- export type { Oklch, ScaleStep, ScaleEntry, Scale, ScaleName, SystemHueName, PrimitiveTokens, TokenRef, SemanticRole, Mode, SemanticEntry, SemanticMap, GeneratorConfig, AccentClassification, ValidatedAccent, ContrastCorrection, GeneratorResult, GeneratedCustomTheme, } from './types.js';
16
+ export type { Oklch, ScaleStep, ScaleEntry, Scale, ScaleName, SystemHueName, PrimitiveTokens, StepRef, MixRef, TokenRef, SemanticRole, Mode, SemanticEntry, SemanticMap, GeneratorConfig, AccentClassification, ValidatedAccent, ContrastCorrection, GeneratorResult, GeneratedCustomTheme, } from './types.js';
package/dist/index.js CHANGED
@@ -1,14 +1,15 @@
1
1
  export { generateTheme, computeInputHash } from './generate.js';
2
- export { validateAccents, normalizeHex, classifyAccent } from './input/validate.js';
2
+ export { validateAccents, validateNeutral, normalizeHex, classifyAccent } from './input/validate.js';
3
3
  export { hexToOklch, oklchToHex, gamutMap } from './color/convert.js';
4
- export { DEFAULT_CURVE, validateCurve } from './color/curves.js';
4
+ export { DEFAULT_CURVE, NEUTRAL_CURVE, ANCHOR_LIGHTNESS_RANGE, anchorCurve, validateCurve } from './color/curves.js';
5
5
  export { generateScale } from './color/scale.js';
6
- export { buildDarkPrimitives, liftScale, DEFAULT_DARK_LIFT, MAX_DARK_LIFT, DARK_LIFT_WEIGHTS } from './color/darkLift.js';
7
- export { buildDimPrimitives, toneDownScale, warmScale, DEFAULT_DIM_CHROMA, MIN_DIM_CHROMA, DEFAULT_DIM_WARMTH, TEAK_HUE_CHROMA, } from './color/dim.js';
6
+ export { buildDarkPrimitives, liftScale, pinAccentSteps, ACCENT_PINNED_STEPS, DEFAULT_DARK_LIFT, MAX_DARK_LIFT, DARK_LIFT_WEIGHTS, } from './color/darkLift.js';
7
+ export { buildDimPrimitives, toneDownScale, DEFAULT_DIM_CHROMA, MIN_DIM_CHROMA } from './color/dim.js';
8
8
  export { generateSystemScales, DEFAULT_SYSTEM_HUES } from './color/systemHues.js';
9
- export { generateNeutralScale } from './color/neutral.js';
9
+ export { generateNeutralScale, generateTintedNeutralScale, MAX_NEUTRAL_CHROMA } from './color/neutral.js';
10
10
  export { buildSemanticMap, contrastGrounds, dimRef, modeRef, withDimRefs } from './tokens/semanticMap.js';
11
11
  export { buildPrimitives } from './tokens/primitives.js';
12
12
  export { checkContrast, autoCorrect } from './tokens/contrast.js';
13
- export { compilePrimitivesJSON, compileSemanticJSON, compilePrimitivesCSS, compileModeCSS, compileThemeCSS, compileCreateThemeTokens, compileCustomThemeCSS, } from './compile/css.js';
13
+ export { parseRef, resolveRef } from './tokens/refs.js';
14
+ export { compilePrimitivesJSON, compileSemanticJSON, compilePrimitivesCSS, compileModeCSS, compileThemeCSS, compileCreateThemeTokens, compileCustomThemeCSS, compileNeutralRamp, compileResolvedTokens, emittedTokens, } from './compile/css.js';
14
15
  export { generateSmokeHTML } from './preview/smoke.js';
@@ -14,3 +14,5 @@ export declare function normalizeHex(input: string): {
14
14
  };
15
15
  export declare function detectNearDuplicates(accents: ValidatedAccent[]): ValidationWarning[];
16
16
  export declare function validateAccents(inputs: string[]): ValidationResult;
17
+ /** Parses the colour the greys are tinted toward. Its lightness is not used. */
18
+ export declare function validateNeutral(input: string): Oklch;
@@ -1,4 +1,5 @@
1
1
  import { converter } from 'culori';
2
+ import { ANCHOR_LIGHTNESS_RANGE } from '../color/curves.js';
2
3
  const toOklch = converter('oklch');
3
4
  const HEX3 = /^#[0-9a-fA-F]{3}$/;
4
5
  const HEX6 = /^#[0-9a-fA-F]{6}$/;
@@ -83,7 +84,15 @@ export function validateAccents(inputs) {
83
84
  if (classification === 'extreme-lightness') {
84
85
  warnings.push({
85
86
  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
+ message: `"${hex}" has extreme lightness (L=${oklch.l.toFixed(3)}). Only hue and chroma will be used; the ramp is centred on the nearest usable lightness.`,
88
+ });
89
+ }
90
+ if (classification === 'normal' && (oklch.l < ANCHOR_LIGHTNESS_RANGE.min || oklch.l > ANCHOR_LIGHTNESS_RANGE.max)) {
91
+ const which = oklch.l > ANCHOR_LIGHTNESS_RANGE.max ? 'lighter' : 'darker';
92
+ const limit = oklch.l > ANCHOR_LIGHTNESS_RANGE.max ? ANCHOR_LIGHTNESS_RANGE.max : ANCHOR_LIGHTNESS_RANGE.min;
93
+ warnings.push({
94
+ value: hex,
95
+ message: `"${hex}" is ${which} (L=${oklch.l.toFixed(3)}) than a ramp can centre on. Step 500, the primary action's fill, uses its hue and chroma at L=${limit}.`,
87
96
  });
88
97
  }
89
98
  accents.push({ hex, oklch, classification });
@@ -91,3 +100,13 @@ export function validateAccents(inputs) {
91
100
  warnings.push(...detectNearDuplicates(accents));
92
101
  return { accents, warnings };
93
102
  }
103
+ /** Parses the colour the greys are tinted toward. Its lightness is not used. */
104
+ export function validateNeutral(input) {
105
+ const { hex } = normalizeHex(input);
106
+ const parsed = toOklch(hex);
107
+ if (!parsed) {
108
+ throw new Error(`Failed to parse neutral color "${hex}" to OKLCH.`);
109
+ }
110
+ // A grey has no hue of its own; 0 is harmless at zero chroma
111
+ return { mode: 'oklch', l: parsed.l, c: parsed.c, h: parsed.h ?? 0 };
112
+ }
@@ -1,23 +1,7 @@
1
1
  import { checkContrast } from '../tokens/contrast.js';
2
2
  import { contrastGrounds, modeRef } from '../tokens/semanticMap.js';
3
+ import { resolveHex } from '../tokens/refs.js';
3
4
  const SCALE_STEPS = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950];
4
- function resolveHex(ref, primitives) {
5
- if (ref === 'white')
6
- return '#ffffff';
7
- if (ref === 'black')
8
- return '#000000';
9
- const [scaleName, stepStr] = ref.split('.');
10
- const step = Number(stepStr);
11
- const scale = primitives[scaleName];
12
- if (!scale) {
13
- throw new Error(`Invalid token reference "${ref}": unknown scale "${scaleName}".`);
14
- }
15
- const entry = scale[step];
16
- if (!entry) {
17
- throw new Error(`Invalid token reference "${ref}": scale "${scaleName}" has no step ${stepStr}.`);
18
- }
19
- return entry.hex;
20
- }
21
5
  function textColor(hex) {
22
6
  const r = parseInt(hex.slice(1, 3), 16);
23
7
  const g = parseInt(hex.slice(3, 5), 16);
@@ -36,9 +20,9 @@ function scaleSwatchesHTML(name, primitives) {
36
20
  }).join('');
37
21
  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>`;
38
22
  }
39
- function semanticPairingHTML(token, fgHex, bgHex, fgRef, bgRef, mode) {
23
+ function semanticPairingHTML(token, fgHex, bgHex, fgRef, bgRef, mode, floor = 4.5) {
40
24
  const ratio = checkContrast(fgHex, bgHex);
41
- const pass = ratio >= 4.5;
25
+ const pass = ratio >= floor;
42
26
  const badge = pass
43
27
  ? `<span style="color:#16a34a;font-weight:bold">PASS</span>`
44
28
  : `<span style="color:#dc2626;font-weight:bold">FAIL</span>`;
@@ -65,7 +49,7 @@ export function generateSmokeHTML(primitives, semanticMap, themeName, darkPrimit
65
49
  const source = sources[mode];
66
50
  const fgHex = resolveHex(fgRef, source);
67
51
  const bgHex = resolveHex(bgRef, source);
68
- pairingRows.push(semanticPairingHTML(label, fgHex, bgHex, fgRef, bgRef, mode));
52
+ pairingRows.push(semanticPairingHTML(label, fgHex, bgHex, fgRef, bgRef, mode, entry.minContrast));
69
53
  }
70
54
  }
71
55
  }
@@ -1,5 +1,6 @@
1
1
  import { wcagContrast } from 'culori';
2
2
  import { contrastGrounds, modeRef } from './semanticMap.js';
3
+ import { parseRef, resolveRef as resolveTokenRef } from './refs.js';
3
4
  const ORDERED_STEPS = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950];
4
5
  export function checkContrast(fgHex, bgHex) {
5
6
  return wcagContrast(fgHex, bgHex);
@@ -8,81 +9,58 @@ export function checkContrast(fgHex, bgHex) {
8
9
  function worstContrast(fgHex, bgHexes) {
9
10
  return Math.min(...bgHexes.map((bgHex) => checkContrast(fgHex, bgHex)));
10
11
  }
11
- function resolveTokenRef(ref, primitives) {
12
- if (ref === 'white')
13
- return '#ffffff';
14
- if (ref === 'black')
15
- return '#000000';
16
- const [scaleName, stepStr] = ref.split('.');
17
- const step = Number(stepStr);
18
- const scale = primitives[scaleName];
19
- if (!scale)
20
- return null;
21
- const entry = scale[step];
22
- if (!entry)
23
- return null;
24
- return entry.hex;
25
- }
26
- function parseRef(ref) {
27
- if (ref === 'white' || ref === 'black')
28
- return null;
29
- const [scaleName, stepStr] = ref.split('.');
30
- return { scaleName, step: Number(stepStr) };
31
- }
32
12
  /**
33
13
  * Walks the fg's ramp one step at a time from `originalRef` in `direction`
34
14
  * ('light' toward the dark steps, for text on a light ground; 'dark' toward
35
15
  * the light steps) and takes the first step that passes: the smallest change
36
16
  * that fixes the pair, so brand-coloured text stays as close to its brand
37
- * step as contrast allows. Falls back to neutral, white or black when no step
38
- * on the ramp passes.
17
+ * step as contrast allows. A mix starts from whichever of its two steps is
18
+ * further that way. Falls back to ink (the darkest or lightest grey), then
19
+ * white or black, when no step on the ramp passes or when the ref is white or
20
+ * black and has no ramp to walk.
39
21
  */
40
22
  function shiftFgTowardsContrast(originalRef, bgHexes, primitives, minContrast, direction) {
41
23
  const parsed = parseRef(originalRef);
42
- if (!parsed)
24
+ const scale = parsed ? primitives[parsed.scaleName] : undefined;
25
+ if (parsed && !scale)
43
26
  return null;
44
- const { scaleName, step: originalStep } = parsed;
45
- const scale = primitives[scaleName];
46
- if (!scale)
47
- return null;
48
- const index = ORDERED_STEPS.indexOf(originalStep);
49
- const stepsToTry = direction === 'light'
50
- ? ORDERED_STEPS.slice(index + 1)
51
- : ORDERED_STEPS.slice(0, index).reverse();
52
- for (const step of stepsToTry) {
53
- const entry = scale[step];
54
- if (!entry)
55
- continue;
56
- const ratio = worstContrast(entry.hex, bgHexes);
57
- if (ratio >= minContrast) {
58
- return {
59
- ref: `${scaleName}.${step}`,
60
- contrast: ratio,
61
- kind: 'step-shift',
62
- };
27
+ if (parsed && scale) {
28
+ const { scaleName, steps } = parsed;
29
+ const indexes = steps.map((step) => ORDERED_STEPS.indexOf(step));
30
+ // A plain ref walks on from its own step. A mix sits between two, so its
31
+ // nearer neighbour in the search direction is the first candidate.
32
+ const mixed = steps.length > 1;
33
+ const stepsToTry = direction === 'light'
34
+ ? ORDERED_STEPS.slice(mixed ? Math.max(...indexes) : indexes[0] + 1)
35
+ : ORDERED_STEPS.slice(0, mixed ? Math.min(...indexes) + 1 : indexes[0]).reverse();
36
+ for (const step of stepsToTry) {
37
+ const entry = scale[step];
38
+ if (!entry)
39
+ continue;
40
+ const ratio = worstContrast(entry.hex, bgHexes);
41
+ if (ratio >= minContrast) {
42
+ return {
43
+ ref: `${scaleName}.${step}`,
44
+ contrast: ratio,
45
+ kind: 'step-shift',
46
+ };
47
+ }
63
48
  }
64
49
  }
65
- const hardFallbacks = direction === 'light'
66
- ? [
67
- { ref: 'neutral.950', hex: resolveTokenRef('neutral.950', primitives) ?? '#000000' },
68
- { ref: 'white', hex: '#ffffff' },
69
- { ref: 'black', hex: '#000000' },
70
- ]
71
- : [
72
- { ref: 'neutral.50', hex: resolveTokenRef('neutral.50', primitives) ?? '#ffffff' },
73
- { ref: 'white', hex: '#ffffff' },
74
- { ref: 'black', hex: '#000000' },
75
- ];
76
- let bestFallback = null;
50
+ const ink = { ref: 'neutral.950', hex: resolveTokenRef('neutral.950', primitives) ?? '#000000' };
51
+ const paper = { ref: 'neutral.50', hex: resolveTokenRef('neutral.50', primitives) ?? '#ffffff' };
52
+ const white = { ref: 'white', hex: '#ffffff' };
53
+ const black = { ref: 'black', hex: '#000000' };
54
+ // Both lists hold all four, so text on a mid-tone fill (the accent in dark
55
+ // mode, say) lands on the same ink it gets in light mode rather than black.
56
+ const hardFallbacks = direction === 'light' ? [ink, black, paper, white] : [paper, white, ink, black];
57
+ // In order of preference: the theme's own ink or paper before pure black or white.
77
58
  for (const fb of hardFallbacks) {
78
59
  const ratio = worstContrast(fb.hex, bgHexes);
79
- if (ratio >= minContrast && (!bestFallback || ratio > bestFallback.contrast)) {
80
- bestFallback = { ref: fb.ref, contrast: ratio };
60
+ if (ratio >= minContrast) {
61
+ return { ref: fb.ref, contrast: ratio, kind: 'hard-fallback' };
81
62
  }
82
63
  }
83
- if (bestFallback) {
84
- return { ref: bestFallback.ref, contrast: bestFallback.contrast, kind: 'hard-fallback' };
85
- }
86
64
  const whiteRatio = worstContrast('#ffffff', bgHexes);
87
65
  const blackRatio = worstContrast('#000000', bgHexes);
88
66
  const best = whiteRatio >= blackRatio ? { ref: 'white', contrast: whiteRatio } : { ref: 'black', contrast: blackRatio };
@@ -1,23 +1,23 @@
1
- import { DEFAULT_CURVE, validateCurve } from '../color/curves.js';
1
+ import { ANCHOR_LIGHTNESS_RANGE, DEFAULT_CURVE, NEUTRAL_CURVE, anchorCurve, validateCurve } from '../color/curves.js';
2
2
  import { generateScale } from '../color/scale.js';
3
3
  import { generateSystemScales } from '../color/systemHues.js';
4
- import { generateNeutralScale } from '../color/neutral.js';
4
+ import { generateNeutralScale, generateTintedNeutralScale } from '../color/neutral.js';
5
+ import { validateNeutral } from '../input/validate.js';
5
6
  export function buildPrimitives(accents, config) {
6
7
  const curve = config.curve ?? DEFAULT_CURVE;
7
8
  validateCurve(curve);
8
9
  const tokens = {};
9
10
  const primary = accents[0];
10
11
  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);
12
+ // A custom curve is taken as given. Otherwise each accent sits at its own
13
+ // step 500, and the greys follow the look's curve.
14
+ const accentScale = (accent) => config.curve ? generateScale(accent.oklch.h, accent.oklch.c, curve) : generateAccentScale(accent, curve);
15
+ tokens.primary = accentScale(primary);
16
+ if (accents.length >= 2)
17
+ tokens.secondary = accentScale(accents[1]);
18
+ if (accents.length >= 3)
19
+ tokens.tertiary = accentScale(accents[2]);
20
+ tokens.neutral = buildNeutral(primary, config, config.curve ?? NEUTRAL_CURVE);
21
21
  const systemScales = generateSystemScales(primary.oklch.c, isLowChroma, curve, config.systemHues);
22
22
  tokens.error = systemScales.error;
23
23
  tokens.warning = systemScales.warning;
@@ -25,3 +25,39 @@ export function buildPrimitives(accents, config) {
25
25
  tokens.info = systemScales.info;
26
26
  return tokens;
27
27
  }
28
+ /**
29
+ * An accent's ramp with the accent itself at step 500: the curve is anchored
30
+ * to its lightness, and where that lightness is inside the anchor range the
31
+ * step is the picked colour to the digit, not a round trip of it.
32
+ */
33
+ function generateAccentScale(accent, curve) {
34
+ const scale = generateScale(accent.oklch.h, accent.oklch.c, anchorCurve(curve, accent.oklch.l));
35
+ const { min, max } = ANCHOR_LIGHTNESS_RANGE;
36
+ if (accent.oklch.l >= min && accent.oklch.l <= max) {
37
+ scale[500] = { oklch: accent.oklch, hex: accent.hex };
38
+ }
39
+ return scale;
40
+ }
41
+ /**
42
+ * The grey ramp. With neither `neutral` nor `neutralTint` set it is the
43
+ * first accent's hue at `neutralTintRatio` of its chroma, as it always was.
44
+ * `neutral` picks the hue from another colour (or none), and `neutralTint`
45
+ * sets how strong the tint is on a 0 to 1 range.
46
+ */
47
+ function buildNeutral(primary, config, curve) {
48
+ const { neutral, neutralTint } = config;
49
+ if (neutralTint !== undefined && (!Number.isFinite(neutralTint) || neutralTint < 0 || neutralTint > 1)) {
50
+ throw new Error(`neutralTint must be between 0 and 1, got ${neutralTint}.`);
51
+ }
52
+ if (neutral === undefined && neutralTint === undefined) {
53
+ return generateNeutralScale(primary.oklch.h, primary.oklch.c, config.neutralTintRatio, curve);
54
+ }
55
+ if (neutral === 'none') {
56
+ return generateTintedNeutralScale({ hue: 0, chroma: 0 }, 0, curve);
57
+ }
58
+ if (neutral === undefined) {
59
+ return generateTintedNeutralScale({ hue: primary.oklch.h, chroma: primary.oklch.c }, neutralTint, curve);
60
+ }
61
+ const source = validateNeutral(neutral);
62
+ return generateTintedNeutralScale({ hue: source.h, chroma: source.c }, neutralTint, curve);
63
+ }