@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,20 +1,35 @@
1
+ import { buildSemanticMap, modeRef } from '../tokens/semanticMap.js';
2
+ import { resolveHex } from '../tokens/refs.js';
1
3
  const SCALE_STEPS = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950];
2
- function resolveHex(ref, primitives) {
3
- if (ref === 'white')
4
- return '#ffffff';
5
- if (ref === 'black')
6
- return '#000000';
7
- const [scaleName, stepStr] = ref.split('.');
8
- const step = Number(stepStr);
9
- const scale = primitives[scaleName];
10
- if (!scale) {
11
- throw new Error(`Invalid token reference "${ref}": unknown scale "${scaleName}".`);
12
- }
13
- const entry = scale[step];
14
- if (!entry) {
15
- throw new Error(`Invalid token reference "${ref}": scale "${scaleName}" has no step ${stepStr}.`);
16
- }
17
- 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;
18
33
  }
19
34
  function scaleToW3C(name, scale) {
20
35
  const group = {};
@@ -41,20 +56,26 @@ export function compilePrimitivesJSON(primitives) {
41
56
  }
42
57
  return JSON.stringify(doc, null, 2);
43
58
  }
44
- export function compileSemanticJSON(map, primitives) {
59
+ export function compileSemanticJSON(map, primitives, darkPrimitives = primitives, dimPrimitives = primitives) {
45
60
  const doc = {};
46
61
  for (const [token, entry] of Object.entries(map)) {
62
+ const dim = modeRef(entry, 'dim');
47
63
  doc[token] = {
48
64
  $type: 'color',
49
65
  light: {
50
66
  $value: resolveHex(entry.light, primitives),
51
67
  $ref: entry.light,
52
68
  },
69
+ dim: {
70
+ $value: resolveHex(dim, dimPrimitives),
71
+ $ref: dim,
72
+ },
53
73
  dark: {
54
- $value: resolveHex(entry.dark, primitives),
74
+ $value: resolveHex(entry.dark, darkPrimitives),
55
75
  $ref: entry.dark,
56
76
  },
57
77
  role: entry.role,
78
+ ...(entry.inherit ? { inherit: true } : {}),
58
79
  ...(entry.contrastAgainst ? { contrastAgainst: entry.contrastAgainst } : {}),
59
80
  ...(entry.minContrast ? { minContrast: entry.minContrast } : {}),
60
81
  ...(entry.allowBelowDefault ? { allowBelowDefault: true } : {}),
@@ -76,46 +97,46 @@ export function compilePrimitivesCSS(primitives, themeName) {
76
97
  if (!scale)
77
98
  continue;
78
99
  blocks.push(`\n /* ${name} */`);
100
+ if (name === 'neutral')
101
+ blocks.push(` --color-neutral-0: #ffffff;`);
79
102
  blocks.push(compilePrimitiveCSSBlock(name, scale, name));
80
103
  }
81
104
  return `/* Generated by eluan-theme-generator — ${themeName} primitives */\n\n[data-theme="${themeName}"] {\n${blocks.join('\n')}\n}`;
82
105
  }
106
+ // Dim is light one step deeper throughout, matching dimRef()
107
+ const PALETTE_STEPS = {
108
+ light: { main: 500, background: 50, tint: 100, foreground: 700, shade: 800 },
109
+ dim: { main: 600, background: 100, tint: 200, foreground: 800, shade: 900 },
110
+ dark: { main: 400, background: 950, tint: 900, foreground: 200, shade: 300 },
111
+ };
112
+ const MODE_LABELS = { light: 'Light', dim: 'Dim', dark: 'Dark' };
83
113
  function compileModeCSSBlock(map, primitives, mode, scaleName, cssPrefix) {
84
114
  const scale = primitives[scaleName];
85
115
  if (!scale)
86
116
  return '';
87
117
  const lines = [];
88
- const mainStep = mode === 'light' ? 500 : 400;
89
- const bgStep = mode === 'light' ? 50 : 950;
90
- const tintStep = mode === 'light' ? 100 : 900;
91
- const fgStep = mode === 'light' ? 700 : 200;
92
- const shadeStep = mode === 'light' ? 800 : 300;
93
- lines.push(` --${cssPrefix}-main: ${scale[mainStep].hex};`);
94
- lines.push(` --${cssPrefix}-background: ${scale[bgStep].hex};`);
95
- lines.push(` --${cssPrefix}-tint: ${scale[tintStep].hex};`);
96
- lines.push(` --${cssPrefix}-foreground: ${scale[fgStep].hex};`);
97
- lines.push(` --${cssPrefix}-shade: ${scale[shadeStep].hex};`);
118
+ for (const [role, step] of Object.entries(PALETTE_STEPS[mode])) {
119
+ lines.push(` --${cssPrefix}-${role}: ${scale[step].hex};`);
120
+ }
98
121
  return lines.join('\n');
99
122
  }
100
123
  export function compileModeCSS(map, primitives, mode, themeName) {
101
124
  const lines = [];
102
- const neutral = primitives.neutral;
103
- if (!neutral)
125
+ if (!primitives.neutral)
104
126
  throw new Error('Neutral scale is required');
105
- const bgSteps = mode === 'light'
106
- ? { primary: 50, secondary: 100, tertiary: 200, quaternary: 300, quinary: 400 }
107
- : { primary: 800, secondary: 900, tertiary: 950, quaternary: 700, quinary: 600 };
108
- const fgSteps = mode === 'light'
109
- ? { primary: 950, secondary: 800, tertiary: 600, quaternary: 500, quinary: 400 }
110
- : { primary: 50, secondary: 100, tertiary: 200, quaternary: 300, quinary: 400 };
111
- lines.push(` /* Backgrounds */`);
112
- for (const [level, step] of Object.entries(bgSteps)) {
113
- lines.push(` --backgrounds-${level}: ${neutral[step].hex};`);
114
- }
115
- lines.push(`\n /* Foregrounds */`);
116
- for (const [level, step] of Object.entries(fgSteps)) {
117
- lines.push(` --foregrounds-${level}: ${neutral[step].hex};`);
118
- }
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-');
119
140
  const paletteScales = [
120
141
  ['primary', 'accent'],
121
142
  ['error', 'error'],
@@ -130,39 +151,80 @@ export function compileModeCSS(map, primitives, mode, themeName) {
130
151
  lines.push(block);
131
152
  }
132
153
  }
133
- const modeLabel = mode === 'light' ? 'Light' : 'Dark';
134
- return `/* Generated by eluan-theme-generator — ${themeName} ${mode} mode */\n\n[data-theme="${themeName}"][data-mode="${mode}"],\n[data-theme="${themeName}"][data-mode="${modeLabel}"] {\n${lines.join('\n')}\n}`;
154
+ return `/* Generated by eluan-theme-generator — ${themeName} ${mode} mode */\n\n[data-theme="${themeName}"][data-mode="${mode}"],\n[data-theme="${themeName}"][data-mode="${MODE_LABELS[mode]}"] {\n${lines.join('\n')}\n}`;
135
155
  }
136
- export function compileThemeCSS(map, primitives, themeName, inputHash) {
156
+ export function compileThemeCSS(map, primitives, themeName, inputHash, darkPrimitives = primitives, dimPrimitives = primitives) {
137
157
  const lines = [];
138
158
  lines.push(`/* Generated by eluan-theme-generator v0.1.0 */`);
139
159
  lines.push(`/* Input hash: ${inputHash} */`);
140
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.
141
163
  lines.push('');
142
- const lightLines = [];
143
- const darkLines = [];
144
- for (const [token, entry] of Object.entries(map)) {
145
- const lightHex = resolveHex(entry.light, primitives);
146
- const darkHex = resolveHex(entry.dark, primitives);
147
- lightLines.push(` --${token}: ${lightHex}; /* ${entry.light} */`);
148
- darkLines.push(` --${token}: ${darkHex}; /* ${entry.dark} */`);
149
- }
150
- lines.push(`[data-theme="${themeName}"][data-mode="light"],`);
151
- lines.push(`[data-theme="${themeName}"][data-mode="Light"] {`);
152
- lines.push(lightLines.join('\n'));
153
- lines.push('}');
154
- lines.push('');
155
- lines.push(`[data-theme="${themeName}"][data-mode="dark"],`);
156
- lines.push(`[data-theme="${themeName}"][data-mode="Dark"] {`);
157
- lines.push(darkLines.join('\n'));
164
+ lines.push(`[data-theme="${themeName}"][data-mode] {`);
165
+ lines.push(Object.entries(compileNeutralRamp(primitives))
166
+ .map(([prop, value]) => ` ${prop}: ${value};`)
167
+ .join('\n'));
158
168
  lines.push('}');
169
+ const emitted = emittedTokens(map);
170
+ const sources = { light: primitives, dim: dimPrimitives, dark: darkPrimitives };
171
+ for (const mode of MODES) {
172
+ const tokenLines = [];
173
+ for (const token of emitted) {
174
+ const ref = modeRef(map[token], mode);
175
+ tokenLines.push(` --${token}: ${resolveHex(ref, sources[mode])}; /* ${ref} */`);
176
+ }
177
+ lines.push('');
178
+ lines.push(`[data-theme="${themeName}"][data-mode="${mode}"],`);
179
+ lines.push(`[data-theme="${themeName}"][data-mode="${MODE_LABELS[mode]}"] {`);
180
+ lines.push(tokenLines.join('\n'));
181
+ lines.push('}');
182
+ }
159
183
  return lines.join('\n');
160
184
  }
161
- 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) {
162
191
  const tokens = {};
163
192
  for (const [token, entry] of Object.entries(map)) {
164
- const ref = mode === 'light' ? entry.light : entry.dark;
165
- tokens[`--${token}`] = resolveHex(ref, primitives);
193
+ tokens[`--${token}`] = resolveHex(modeRef(entry, mode), primitives);
194
+ }
195
+ return tokens;
196
+ }
197
+ /**
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);
166
208
  }
167
209
  return tokens;
168
210
  }
211
+ /**
212
+ * CSS for a custom theme layered on `eluan`, in the same shape `createTheme()`
213
+ * from @eluan/core emits: the light tokens on `[data-theme-custom="<name>"]`
214
+ * and the dim and dark tokens on that plus `[data-mode]`. Because the theme
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.
218
+ */
219
+ export function compileCustomThemeCSS(themeName, light, dark, dim) {
220
+ const name = themeName.replace(/["\\]/g, '\\$&');
221
+ const body = (tokens) => Object.entries(tokens)
222
+ .map(([prop, value]) => ` ${prop}: ${value};`)
223
+ .join('\n');
224
+ const modeBlock = (mode, tokens) => `[data-theme-custom="${name}"][data-mode="${mode}"],\n[data-theme-custom="${name}"][data-mode="${MODE_LABELS[mode]}"] {\n${body(tokens)}\n}`;
225
+ return [
226
+ `[data-theme-custom="${name}"] {\n${body(light)}\n}`,
227
+ ...(dim ? [modeBlock('dim', dim)] : []),
228
+ modeBlock('dark', dark),
229
+ ].join('\n\n');
230
+ }
package/dist/generate.js CHANGED
@@ -1,8 +1,11 @@
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';
5
- import { compilePrimitivesCSS, compileModeCSS, compileThemeCSS, compileCreateThemeTokens, } from './compile/css.js';
4
+ import { autoCorrect, checkContrast } from './tokens/contrast.js';
5
+ import { resolveRef } from './tokens/refs.js';
6
+ import { buildDarkPrimitives, DEFAULT_DARK_LIFT, MAX_DARK_LIFT } from './color/darkLift.js';
7
+ import { buildDimPrimitives, DEFAULT_DIM_CHROMA, MIN_DIM_CHROMA } from './color/dim.js';
8
+ import { compilePrimitivesCSS, compileModeCSS, compileThemeCSS, compileCreateThemeTokens, compileCustomThemeCSS, } from './compile/css.js';
6
9
  /*
7
10
  * FNV-1a (64-bit) constants.
8
11
  *
@@ -45,12 +48,29 @@ export function computeInputHash(config) {
45
48
  neutralTintRatio: config.neutralTintRatio,
46
49
  systemHues: config.systemHues,
47
50
  curve: config.curve,
51
+ // Only when set, so configs that predate these options keep their fingerprint
52
+ neutral: config.neutral,
53
+ neutralTint: config.neutralTint,
54
+ darkLift: config.darkLift,
55
+ dimChroma: config.dimChroma,
48
56
  });
49
57
  // Take the high 48 bits: FNV-1a mixes upward through the multiply, so the high
50
58
  // nibbles are the better-distributed end of the digest.
51
59
  return fnv1a64(input).toString(16).padStart(16, '0').slice(0, 12);
52
60
  }
53
- 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) {
54
74
  const lines = [];
55
75
  lines.push(`# Theme Generation Report`);
56
76
  lines.push('');
@@ -58,7 +78,15 @@ function buildReport(config, warnings, corrections, primitives, inputHash) {
58
78
  lines.push(`**Input hash:** ${inputHash}`);
59
79
  lines.push(`**Accents:** ${config.accents.join(', ')}`);
60
80
  lines.push(`**Min contrast:** ${config.minContrast}:1`);
61
- 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
+ }
88
+ lines.push(`**Dark lift:** ${config.darkLift ?? DEFAULT_DARK_LIFT}`);
89
+ lines.push(`**Dim chroma:** ${config.dimChroma ?? DEFAULT_DIM_CHROMA}`);
62
90
  lines.push('');
63
91
  if (warnings.length > 0) {
64
92
  lines.push(`## Warnings`);
@@ -84,6 +112,14 @@ function buildReport(config, warnings, corrections, primitives, inputHash) {
84
112
  lines.push('All fg/border pairings meet the configured minimum contrast ratio. No corrections needed.');
85
113
  lines.push('');
86
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
+ }
87
123
  const chromaClampedSteps = [];
88
124
  for (const [scaleName, scale] of Object.entries(primitives)) {
89
125
  if (!scale)
@@ -107,7 +143,7 @@ function buildReport(config, warnings, corrections, primitives, inputHash) {
107
143
  lines.push(`## Output Files`);
108
144
  lines.push('');
109
145
  lines.push(`- \`primitives.json\` — W3C Design Tokens format`);
110
- lines.push(`- \`semantic.json\` — Semantic map with light/dark refs`);
146
+ lines.push(`- \`semantic.json\` — Semantic map with light/dim/dark refs`);
111
147
  lines.push(`- \`theme.css\` — Drop-in CSS for Eluan`);
112
148
  lines.push(`- \`preview.html\` — Visual smoke test`);
113
149
  return lines.join('\n');
@@ -116,35 +152,62 @@ export function generateTheme(config) {
116
152
  const { accents: accentInputs, warnings } = validateAccents(config.accents);
117
153
  const inputHash = computeInputHash(config);
118
154
  const primitives = buildPrimitives(accentInputs, config);
155
+ const darkLift = config.darkLift ?? DEFAULT_DARK_LIFT;
156
+ if (!Number.isFinite(darkLift) || darkLift < 0 || darkLift > MAX_DARK_LIFT) {
157
+ throw new Error(`darkLift must be between 0 and ${MAX_DARK_LIFT}, got ${config.darkLift}.`);
158
+ }
159
+ const primitivesDark = buildDarkPrimitives(primitives, darkLift);
160
+ const dimChroma = config.dimChroma ?? DEFAULT_DIM_CHROMA;
161
+ if (!Number.isFinite(dimChroma) || dimChroma < MIN_DIM_CHROMA || dimChroma > 1) {
162
+ throw new Error(`dimChroma must be between ${MIN_DIM_CHROMA} and 1, got ${config.dimChroma}.`);
163
+ }
164
+ const primitivesDim = buildDimPrimitives(primitives, dimChroma);
119
165
  let semanticMap = buildSemanticMap();
120
166
  const lightResult = autoCorrect(semanticMap, primitives, 'light', config.minContrast);
121
167
  semanticMap = lightResult.correctedMap;
122
168
  const lightCorrections = lightResult.corrections;
123
- const darkResult = autoCorrect(semanticMap, primitives, 'dark', config.minContrast);
169
+ const dimResult = autoCorrect(semanticMap, primitivesDim, 'dim', config.minContrast);
170
+ semanticMap = dimResult.correctedMap;
171
+ const dimCorrections = dimResult.corrections;
172
+ const darkResult = autoCorrect(semanticMap, primitivesDark, 'dark', config.minContrast);
124
173
  semanticMap = darkResult.correctedMap;
125
174
  const darkCorrections = darkResult.corrections;
126
- const allCorrections = [...lightCorrections, ...darkCorrections];
175
+ const allCorrections = [...lightCorrections, ...dimCorrections, ...darkCorrections];
127
176
  const primitivesCSS = compilePrimitivesCSS(primitives, config.themeName);
128
177
  const lightModeCSS = compileModeCSS(semanticMap, primitives, 'light', config.themeName);
129
- const darkModeCSS = compileModeCSS(semanticMap, primitives, 'dark', config.themeName);
130
- const themeCSS = compileThemeCSS(semanticMap, primitives, config.themeName, inputHash);
178
+ const dimModeCSS = compileModeCSS(semanticMap, primitivesDim, 'dim', config.themeName);
179
+ const darkModeCSS = compileModeCSS(semanticMap, primitivesDark, 'dark', config.themeName);
180
+ const themeCSS = compileThemeCSS(semanticMap, primitives, config.themeName, inputHash, primitivesDark, primitivesDim);
131
181
  const createThemeTokens = {};
132
182
  const lightTokens = compileCreateThemeTokens(semanticMap, primitives, 'light');
133
183
  for (const [k, v] of Object.entries(lightTokens)) {
134
184
  createThemeTokens[k] = v;
135
185
  }
136
- const report = buildReport(config, warnings, allCorrections, primitives, inputHash);
186
+ const dimTokens = compileCreateThemeTokens(semanticMap, primitivesDim, 'dim');
187
+ const darkTokens = compileCreateThemeTokens(semanticMap, primitivesDark, 'dark');
188
+ const createThemeOptions = { tokens: createThemeTokens, modes: { dim: dimTokens, dark: darkTokens } };
189
+ const customTheme = {
190
+ name: config.themeName,
191
+ extends: 'eluan',
192
+ css: compileCustomThemeCSS(config.themeName, createThemeTokens, darkTokens, dimTokens),
193
+ };
194
+ const report = buildReport(config, warnings, allCorrections, primitives, inputHash, semanticMap);
137
195
  return {
138
196
  primitives,
197
+ primitivesDark,
198
+ primitivesDim,
139
199
  semanticMap,
140
200
  corrections: allCorrections,
141
201
  css: {
142
202
  primitives: primitivesCSS,
143
203
  lightMode: lightModeCSS,
204
+ dimMode: dimModeCSS,
144
205
  darkMode: darkModeCSS,
145
206
  theme: themeCSS,
146
207
  },
147
208
  createThemeTokens,
209
+ createThemeOptions,
210
+ customTheme,
148
211
  report,
149
212
  };
150
213
  }
package/dist/index.d.ts CHANGED
@@ -1,13 +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, 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';
6
8
  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 { generateNeutralScale, generateTintedNeutralScale, MAX_NEUTRAL_CHROMA } from './color/neutral.js';
10
+ export { buildSemanticMap, contrastGrounds, dimRef, modeRef, withDimRefs } from './tokens/semanticMap.js';
9
11
  export { buildPrimitives } from './tokens/primitives.js';
10
12
  export { checkContrast, autoCorrect } from './tokens/contrast.js';
11
- export { compilePrimitivesJSON, compileSemanticJSON, compilePrimitivesCSS, compileModeCSS, compileThemeCSS, compileCreateThemeTokens, } 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';
12
15
  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';
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,12 +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, 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';
6
8
  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 { generateNeutralScale, generateTintedNeutralScale, MAX_NEUTRAL_CHROMA } from './color/neutral.js';
10
+ export { buildSemanticMap, contrastGrounds, dimRef, modeRef, withDimRefs } from './tokens/semanticMap.js';
9
11
  export { buildPrimitives } from './tokens/primitives.js';
10
12
  export { checkContrast, autoCorrect } from './tokens/contrast.js';
11
- export { compilePrimitivesJSON, compileSemanticJSON, compilePrimitivesCSS, compileModeCSS, compileThemeCSS, compileCreateThemeTokens, } 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';
12
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,2 +1,2 @@
1
1
  import type { PrimitiveTokens, SemanticMap } from '../types.js';
2
- export declare function generateSmokeHTML(primitives: PrimitiveTokens, semanticMap: SemanticMap, themeName: string): string;
2
+ export declare function generateSmokeHTML(primitives: PrimitiveTokens, semanticMap: SemanticMap, themeName: string, darkPrimitives?: PrimitiveTokens, dimPrimitives?: PrimitiveTokens): string;
@@ -1,22 +1,7 @@
1
1
  import { checkContrast } from '../tokens/contrast.js';
2
+ import { contrastGrounds, modeRef } from '../tokens/semanticMap.js';
3
+ import { resolveHex } from '../tokens/refs.js';
2
4
  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;
19
- }
20
5
  function textColor(hex) {
21
6
  const r = parseInt(hex.slice(1, 3), 16);
22
7
  const g = parseInt(hex.slice(3, 5), 16);
@@ -35,31 +20,37 @@ function scaleSwatchesHTML(name, primitives) {
35
20
  }).join('');
36
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>`;
37
22
  }
38
- function semanticPairingHTML(token, fgHex, bgHex, fgRef, bgRef, mode) {
23
+ function semanticPairingHTML(token, fgHex, bgHex, fgRef, bgRef, mode, floor = 4.5) {
39
24
  const ratio = checkContrast(fgHex, bgHex);
40
- const pass = ratio >= 4.5;
25
+ const pass = ratio >= floor;
41
26
  const badge = pass
42
27
  ? `<span style="color:#16a34a;font-weight:bold">PASS</span>`
43
28
  : `<span style="color:#dc2626;font-weight:bold">FAIL</span>`;
44
29
  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>`;
45
30
  }
46
- export function generateSmokeHTML(primitives, semanticMap, themeName) {
31
+ export function generateSmokeHTML(primitives, semanticMap, themeName, darkPrimitives = primitives, dimPrimitives = primitives) {
47
32
  const scaleNames = Object.keys(primitives);
48
33
  const scaleSection = scaleNames
49
34
  .map((name) => scaleSwatchesHTML(name, primitives))
50
35
  .join('');
51
36
  const fgTokens = Object.entries(semanticMap).filter(([, entry]) => entry.role === 'fg' && entry.contrastAgainst);
52
37
  const pairingRows = [];
38
+ const sources = { light: primitives, dim: dimPrimitives, dark: darkPrimitives };
53
39
  for (const [token, entry] of fgTokens) {
54
- const bgEntry = semanticMap[entry.contrastAgainst];
55
- if (!bgEntry)
56
- continue;
57
- for (const mode of ['light', 'dark']) {
58
- const fgRef = entry[mode];
59
- const bgRef = bgEntry[mode];
60
- const fgHex = resolveHex(fgRef, primitives);
61
- const bgHex = resolveHex(bgRef, primitives);
62
- pairingRows.push(semanticPairingHTML(token, fgHex, bgHex, fgRef, bgRef, mode));
40
+ const grounds = contrastGrounds(entry);
41
+ for (const ground of grounds) {
42
+ const bgEntry = semanticMap[ground];
43
+ if (!bgEntry)
44
+ continue;
45
+ const label = grounds.length > 1 ? `${token} on ${ground}` : token;
46
+ for (const mode of ['light', 'dim', 'dark']) {
47
+ const fgRef = modeRef(entry, mode);
48
+ const bgRef = modeRef(bgEntry, mode);
49
+ const source = sources[mode];
50
+ const fgHex = resolveHex(fgRef, source);
51
+ const bgHex = resolveHex(bgRef, source);
52
+ pairingRows.push(semanticPairingHTML(label, fgHex, bgHex, fgRef, bgRef, mode, entry.minContrast));
53
+ }
63
54
  }
64
55
  }
65
56
  return `<!DOCTYPE html>
@@ -1,6 +1,6 @@
1
- import type { ContrastCorrection, PrimitiveTokens, SemanticMap } from '../types.js';
1
+ import type { ContrastCorrection, Mode, PrimitiveTokens, SemanticMap } from '../types.js';
2
2
  export declare function checkContrast(fgHex: string, bgHex: string): number;
3
- export declare function autoCorrect(map: SemanticMap, primitives: PrimitiveTokens, mode: 'light' | 'dark', defaultMinContrast: number): {
3
+ export declare function autoCorrect(map: SemanticMap, primitives: PrimitiveTokens, mode: Mode, defaultMinContrast: number): {
4
4
  correctedMap: SemanticMap;
5
5
  corrections: ContrastCorrection[];
6
6
  };