@eluan/theme-generator 0.3.1 → 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,80 +1,68 @@
1
1
  import { wcagContrast } from 'culori';
2
+ import { contrastGrounds, modeRef } from './semanticMap.js';
3
+ import { parseRef, resolveRef as resolveTokenRef } from './refs.js';
2
4
  const ORDERED_STEPS = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950];
3
5
  export function checkContrast(fgHex, bgHex) {
4
6
  return wcagContrast(fgHex, bgHex);
5
7
  }
6
- function resolveTokenRef(ref, primitives) {
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) };
8
+ /** Contrast against the hardest of several grounds. */
9
+ function worstContrast(fgHex, bgHexes) {
10
+ return Math.min(...bgHexes.map((bgHex) => checkContrast(fgHex, bgHex)));
26
11
  }
27
- function shiftFgTowardsContrast(originalRef, bgHex, primitives, minContrast, mode) {
12
+ /**
13
+ * Walks the fg's ramp one step at a time from `originalRef` in `direction`
14
+ * ('light' toward the dark steps, for text on a light ground; 'dark' toward
15
+ * the light steps) and takes the first step that passes: the smallest change
16
+ * that fixes the pair, so brand-coloured text stays as close to its brand
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.
21
+ */
22
+ function shiftFgTowardsContrast(originalRef, bgHexes, primitives, minContrast, direction) {
28
23
  const parsed = parseRef(originalRef);
29
- if (!parsed)
24
+ const scale = parsed ? primitives[parsed.scaleName] : undefined;
25
+ if (parsed && !scale)
30
26
  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
- };
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
+ }
52
48
  }
53
- attempts++;
54
49
  }
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;
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.
67
58
  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 };
59
+ const ratio = worstContrast(fb.hex, bgHexes);
60
+ if (ratio >= minContrast) {
61
+ return { ref: fb.ref, contrast: ratio, kind: 'hard-fallback' };
71
62
  }
72
63
  }
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);
64
+ const whiteRatio = worstContrast('#ffffff', bgHexes);
65
+ const blackRatio = worstContrast('#000000', bgHexes);
78
66
  const best = whiteRatio >= blackRatio ? { ref: 'white', contrast: whiteRatio } : { ref: 'black', contrast: blackRatio };
79
67
  return { ref: best.ref, contrast: best.contrast, kind: 'hard-fallback' };
80
68
  }
@@ -86,35 +74,31 @@ export function autoCorrect(map, primitives, mode, defaultMinContrast) {
86
74
  continue;
87
75
  if (entry.role !== 'fg' && entry.role !== 'border')
88
76
  continue;
89
- if (!entry.contrastAgainst)
77
+ const bgHexes = contrastGrounds(entry)
78
+ .flatMap((ground) => (map[ground] ? [resolveTokenRef(modeRef(map[ground], mode), primitives)] : []))
79
+ .filter((hex) => hex !== null);
80
+ if (bgHexes.length === 0)
90
81
  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);
82
+ const fgRef = modeRef(entry, mode);
97
83
  const fgHex = resolveTokenRef(fgRef, primitives);
98
- if (!bgHex || !fgHex)
84
+ if (!fgHex)
99
85
  continue;
100
86
  // The config-wide minimum is a floor: per-entry values can raise it but
101
87
  // not lower it, except for entries that opt into a lower WCAG tier.
102
88
  const minContrast = entry.allowBelowDefault && entry.minContrast !== undefined
103
89
  ? entry.minContrast
104
90
  : Math.max(entry.minContrast ?? 0, defaultMinContrast);
105
- const ratio = checkContrast(fgHex, bgHex);
91
+ const ratio = worstContrast(fgHex, bgHexes);
106
92
  if (ratio >= minContrast)
107
93
  continue;
108
- const correction = shiftFgTowardsContrast(fgRef, bgHex, primitives, minContrast, mode);
94
+ // Dim grounds run from near-white pages to mid-tone buttons, so its search
95
+ // follows the ground: toward dark text where black reads better, else light.
96
+ const direction = mode === 'dim'
97
+ ? (worstContrast('#000000', bgHexes) >= worstContrast('#ffffff', bgHexes) ? 'light' : 'dark')
98
+ : mode;
99
+ const correction = shiftFgTowardsContrast(fgRef, bgHexes, primitives, minContrast, direction);
109
100
  if (correction) {
110
- const newEntry = { ...corrected[tokenName] };
111
- if (mode === 'light') {
112
- newEntry.light = correction.ref;
113
- }
114
- else {
115
- newEntry.dark = correction.ref;
116
- }
117
- corrected[tokenName] = newEntry;
101
+ corrected[tokenName] = { ...corrected[tokenName], [mode]: correction.ref };
118
102
  corrections.push({
119
103
  token: tokenName,
120
104
  mode,
@@ -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
+ }
@@ -0,0 +1,17 @@
1
+ import type { PrimitiveTokens, ScaleName, ScaleStepValue, TokenRef } from '../types.js';
2
+ export type ParsedRef = {
3
+ scaleName: ScaleName;
4
+ /** One step for a plain ref, two for a mix. */
5
+ steps: ScaleStepValue[];
6
+ /** Share of the first step in a mix, 0 to 1. 1 for a plain ref. */
7
+ share: number;
8
+ };
9
+ /** Splits a ref into its ramp and step(s). `white` and `black` have neither. */
10
+ export declare function parseRef(ref: TokenRef): ParsedRef | null;
11
+ /**
12
+ * The hex a ref stands for in `primitives`, or null when the ramp or step is
13
+ * not there. A mix is interpolated in OKLCH, as `color-mix(in oklch, …)` does.
14
+ */
15
+ export declare function resolveRef(ref: TokenRef, primitives: PrimitiveTokens): string | null;
16
+ /** `resolveRef`, throwing on a ref that names a ramp or step that is not there. */
17
+ export declare function resolveHex(ref: TokenRef, primitives: PrimitiveTokens): string;
@@ -0,0 +1,59 @@
1
+ import { oklchToHex } from '../color/convert.js';
2
+ /** `share` of `a` and the rest of `b`, in OKLCH, hue along the shorter arc. A grey takes the other's hue. */
3
+ function mixOklch(a, b, share) {
4
+ const t = 1 - share;
5
+ const ha = a.c < 1e-4 ? b.h : a.h;
6
+ const hb = b.c < 1e-4 ? a.h : b.h;
7
+ const delta = ((hb - ha + 540) % 360) - 180;
8
+ return {
9
+ mode: 'oklch',
10
+ l: a.l + (b.l - a.l) * t,
11
+ c: a.c + (b.c - a.c) * t,
12
+ h: (ha + delta * t + 360) % 360,
13
+ };
14
+ }
15
+ /** Splits a ref into its ramp and step(s). `white` and `black` have neither. */
16
+ export function parseRef(ref) {
17
+ if (ref === 'white' || ref === 'black')
18
+ return null;
19
+ const [scaleName, rest] = ref.split('.');
20
+ const [stepPart, sharePart] = rest.split('@');
21
+ const steps = stepPart.split('/').map((s) => Number(s));
22
+ return { scaleName, steps, share: sharePart === undefined ? 1 : Number(sharePart) / 100 };
23
+ }
24
+ /**
25
+ * The hex a ref stands for in `primitives`, or null when the ramp or step is
26
+ * not there. A mix is interpolated in OKLCH, as `color-mix(in oklch, …)` does.
27
+ */
28
+ export function resolveRef(ref, primitives) {
29
+ if (ref === 'white')
30
+ return '#ffffff';
31
+ if (ref === 'black')
32
+ return '#000000';
33
+ const parsed = parseRef(ref);
34
+ if (!parsed)
35
+ return null;
36
+ const scale = primitives[parsed.scaleName];
37
+ if (!scale)
38
+ return null;
39
+ const [first, second] = parsed.steps.map((step) => scale[step]);
40
+ if (!first)
41
+ return null;
42
+ if (parsed.steps.length === 1)
43
+ return first.hex;
44
+ if (!second)
45
+ return null;
46
+ return oklchToHex(mixOklch(first.oklch, second.oklch, parsed.share));
47
+ }
48
+ /** `resolveRef`, throwing on a ref that names a ramp or step that is not there. */
49
+ export function resolveHex(ref, primitives) {
50
+ const hex = resolveRef(ref, primitives);
51
+ if (hex === null) {
52
+ const parsed = parseRef(ref);
53
+ const scale = parsed && primitives[parsed.scaleName];
54
+ throw new Error(scale || !parsed
55
+ ? `Invalid token reference "${ref}": scale "${parsed?.scaleName}" has no step ${parsed?.steps.join('/')}.`
56
+ : `Invalid token reference "${ref}": unknown scale "${parsed.scaleName}".`);
57
+ }
58
+ return hex;
59
+ }
@@ -1,2 +1,20 @@
1
- import type { SemanticMap } from '../types.js';
1
+ import type { Mode, SemanticEntry, SemanticMap, TokenRef } from '../types.js';
2
+ /**
3
+ * The dim ref for a light ref: one step deeper on the same ramp, 950 staying
4
+ * put. It is how the base theme's own dim treats colour (a tint at 100 becomes
5
+ * 200, status text at 700 becomes 800), which keeps dim a softer light mode
6
+ * rather than a lighter dark one. Greys do not follow it: dim's surfaces are
7
+ * in-between steps, so every grey entry names its dim ref. A mix is returned
8
+ * as it is.
9
+ */
10
+ export declare function dimRef(light: TokenRef): TokenRef;
11
+ /** The ref an entry resolves to in `mode`; dim falls back to `dimRef(entry.light)`. */
12
+ export declare function modeRef(entry: SemanticEntry, mode: Mode): TokenRef;
13
+ /** The ground tokens an entry is checked against, as a list. */
14
+ export declare function contrastGrounds(entry: SemanticEntry): string[];
15
+ /**
16
+ * Pins every entry's dim ref from its light ref, so later light-mode contrast
17
+ * corrections can't move dim along with them.
18
+ */
19
+ export declare function withDimRefs(map: SemanticMap): SemanticMap;
2
20
  export declare function buildSemanticMap(): SemanticMap;