material-theme-builder 2.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/dist/cli.js ADDED
@@ -0,0 +1,828 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli.ts
4
+ import * as fs from "fs";
5
+ import * as path from "path";
6
+ import { Command, Option } from "commander";
7
+
8
+ // src/lib/builder.ts
9
+ import {
10
+ argbFromHex,
11
+ Blend,
12
+ blueFromArgb,
13
+ DynamicColor,
14
+ DynamicScheme,
15
+ greenFromArgb,
16
+ Hct,
17
+ hexFromArgb,
18
+ MaterialDynamicColors,
19
+ redFromArgb,
20
+ SchemeContent,
21
+ SchemeExpressive,
22
+ SchemeFidelity,
23
+ SchemeMonochrome,
24
+ SchemeNeutral,
25
+ SchemeTonalSpot,
26
+ SchemeVibrant,
27
+ TonalPalette
28
+ } from "@material/material-color-utilities";
29
+ import { kebabCase, startCase, upperFirst } from "lodash-es";
30
+ var schemeNames = [
31
+ "tonalSpot",
32
+ "monochrome",
33
+ "neutral",
34
+ "vibrant",
35
+ "expressive",
36
+ "fidelity",
37
+ "content"
38
+ ];
39
+ var schemesMap = {
40
+ tonalSpot: SchemeTonalSpot,
41
+ monochrome: SchemeMonochrome,
42
+ neutral: SchemeNeutral,
43
+ vibrant: SchemeVibrant,
44
+ expressive: SchemeExpressive,
45
+ fidelity: SchemeFidelity,
46
+ content: SchemeContent
47
+ };
48
+ var DEFAULT_SCHEME = "tonalSpot";
49
+ var DEFAULT_CONTRAST = 0;
50
+ var DEFAULT_CUSTOM_COLORS = [];
51
+ var DEFAULT_BLEND = true;
52
+ var DEFAULT_PREFIX = "md";
53
+ var STANDARD_TONES = [
54
+ 0,
55
+ 4,
56
+ 5,
57
+ 6,
58
+ 10,
59
+ 12,
60
+ 15,
61
+ 17,
62
+ 20,
63
+ 22,
64
+ 24,
65
+ 25,
66
+ 30,
67
+ 35,
68
+ 40,
69
+ 50,
70
+ 60,
71
+ 70,
72
+ 80,
73
+ 87,
74
+ 90,
75
+ 92,
76
+ 94,
77
+ 95,
78
+ 96,
79
+ 98,
80
+ 99,
81
+ 100
82
+ ];
83
+ var MTB_TONES = [
84
+ 0,
85
+ 5,
86
+ 10,
87
+ 15,
88
+ 20,
89
+ 25,
90
+ 30,
91
+ 35,
92
+ 40,
93
+ 50,
94
+ 60,
95
+ 70,
96
+ 80,
97
+ 90,
98
+ 95,
99
+ 98,
100
+ 99,
101
+ 100
102
+ ];
103
+ var Variant = {
104
+ MONOCHROME: 0,
105
+ NEUTRAL: 1,
106
+ TONAL_SPOT: 2,
107
+ VIBRANT: 3,
108
+ EXPRESSIVE: 4,
109
+ FIDELITY: 5,
110
+ CONTENT: 6,
111
+ RAINBOW: 7,
112
+ FRUIT_SALAD: 8
113
+ };
114
+ var schemeToVariant = {
115
+ monochrome: Variant.MONOCHROME,
116
+ neutral: Variant.NEUTRAL,
117
+ tonalSpot: Variant.TONAL_SPOT,
118
+ vibrant: Variant.VIBRANT,
119
+ expressive: Variant.EXPRESSIVE,
120
+ fidelity: Variant.FIDELITY,
121
+ content: Variant.CONTENT
122
+ };
123
+ var tokenDescriptions = {
124
+ background: "Default background color for screens and large surfaces.",
125
+ error: "Color for error states, used on elements like error text and icons.",
126
+ errorContainer: "Fill color for error container elements like error banners.",
127
+ inverseOnSurface: "Color for text and icons on inverse surface backgrounds.",
128
+ inversePrimary: "Primary color used on inverse surface, e.g. buttons on snackbars.",
129
+ inverseSurface: "Background for elements that require reverse contrast, such as snackbars.",
130
+ onBackground: "Color for text and icons displayed on the background.",
131
+ onError: "Color for text and icons on error-colored elements.",
132
+ onErrorContainer: "Color for text and icons on error container elements.",
133
+ onPrimary: "Color for text and icons on primary-colored elements like filled buttons.",
134
+ onPrimaryContainer: "Color for text and icons on primary container elements like tonal buttons.",
135
+ onPrimaryFixed: "Color for text and icons on primary fixed elements, constant across themes.",
136
+ onPrimaryFixedVariant: "Lower-emphasis color for text and icons on primary fixed elements.",
137
+ onSecondary: "Color for text and icons on secondary-colored elements.",
138
+ onSecondaryContainer: "Color for text and icons on secondary container elements.",
139
+ onSecondaryFixed: "Color for text and icons on secondary fixed elements, constant across themes.",
140
+ onSecondaryFixedVariant: "Lower-emphasis color for text and icons on secondary fixed elements.",
141
+ onSurface: "High-emphasis color for text and icons on surface backgrounds.",
142
+ onSurfaceVariant: "Medium-emphasis color for text and icons on surface variant backgrounds.",
143
+ onTertiary: "Color for text and icons on tertiary-colored elements.",
144
+ onTertiaryContainer: "Color for text and icons on tertiary container elements.",
145
+ onTertiaryFixed: "Color for text and icons on tertiary fixed elements, constant across themes.",
146
+ onTertiaryFixedVariant: "Lower-emphasis color for text and icons on tertiary fixed elements.",
147
+ outline: "Subtle color for borders and dividers to create visual separation.",
148
+ outlineVariant: "Lower-emphasis border color used for decorative dividers.",
149
+ primary: "Main brand color, used for key components like filled buttons and active states.",
150
+ primaryContainer: "Fill color for large primary elements like cards and tonal buttons.",
151
+ primaryFixed: "Fixed primary color that stays the same in light and dark themes.",
152
+ primaryFixedDim: "Dimmed variant of the fixed primary color for lower emphasis.",
153
+ scrim: "Color overlay for modals and dialogs to obscure background content.",
154
+ secondary: "Accent color for less prominent elements like filter chips and selections.",
155
+ secondaryContainer: "Fill color for secondary container elements like tonal buttons and input fields.",
156
+ secondaryFixed: "Fixed secondary color that stays the same in light and dark themes.",
157
+ secondaryFixedDim: "Dimmed variant of the fixed secondary color for lower emphasis.",
158
+ shadow: "Color for elevation shadows applied to surfaces and components.",
159
+ surface: "Default surface color for cards, sheets, and dialogs.",
160
+ surfaceBright: "Brightest surface variant, used for elevated surfaces in dark themes.",
161
+ surfaceContainer: "Middle-emphasis container color for grouping related content.",
162
+ surfaceContainerHigh: "Higher-emphasis container color for elements like cards.",
163
+ surfaceContainerHighest: "Highest-emphasis container color for text fields and other input areas.",
164
+ surfaceContainerLow: "Lower-emphasis container color for subtle surface groupings.",
165
+ surfaceContainerLowest: "Lowest-emphasis container, typically the lightest surface in light theme.",
166
+ surfaceDim: "Dimmest surface variant, used for recessed areas or dark theme backgrounds.",
167
+ surfaceTint: "Tint color applied to surfaces for subtle primary color elevation overlay.",
168
+ surfaceVariant: "Alternative surface color for differentiated areas like sidebar backgrounds.",
169
+ tertiary: "Third accent color for complementary elements that balance primary and secondary.",
170
+ tertiaryContainer: "Fill color for tertiary container elements like complementary cards.",
171
+ tertiaryFixed: "Fixed tertiary color that stays the same in light and dark themes.",
172
+ tertiaryFixedDim: "Dimmed variant of the fixed tertiary color for lower emphasis."
173
+ };
174
+ var tokenNames = Object.keys(
175
+ tokenDescriptions
176
+ );
177
+ function toRecord(arr, getEntry) {
178
+ return Object.fromEntries(arr.map(getEntry));
179
+ }
180
+ function getPalette(palettes, colorName) {
181
+ const palette = palettes[colorName];
182
+ if (!palette) {
183
+ throw new Error(
184
+ `Custom color palette not found for '${colorName}'. This is likely a bug in the implementation.`
185
+ );
186
+ }
187
+ return palette;
188
+ }
189
+ function mergeBaseAndCustomColors(scheme, customColors, colorPalettes) {
190
+ const baseVars = toRecord(tokenNames, (tokenName) => {
191
+ const dynamicColor = MaterialDynamicColors[tokenName];
192
+ const argb = dynamicColor.getArgb(scheme);
193
+ return [tokenName, argb];
194
+ });
195
+ const customVars = {};
196
+ customColors.forEach((color) => {
197
+ const colorname = color.name;
198
+ const getPaletteForColor = (s) => getPalette(colorPalettes, colorname);
199
+ const getTone = (baseTone) => (_s) => {
200
+ return baseTone;
201
+ };
202
+ const colorDynamicColor = new DynamicColor(
203
+ colorname,
204
+ getPaletteForColor,
205
+ (s) => getTone(s.isDark ? 80 : 40)(s),
206
+ // Main color: lighter in dark mode, darker in light mode
207
+ true
208
+ // background
209
+ );
210
+ const onColorDynamicColor = new DynamicColor(
211
+ `on${upperFirst(colorname)}`,
212
+ getPaletteForColor,
213
+ (s) => getTone(s.isDark ? 20 : 100)(s),
214
+ // Text on main color: high contrast (dark on light, light on dark)
215
+ false
216
+ );
217
+ const containerDynamicColor = new DynamicColor(
218
+ `${colorname}Container`,
219
+ getPaletteForColor,
220
+ (s) => getTone(s.isDark ? 30 : 90)(s),
221
+ // Container: subtle variant (darker in dark mode, lighter in light mode)
222
+ true
223
+ // background
224
+ );
225
+ const onContainerDynamicColor = new DynamicColor(
226
+ `on${upperFirst(colorname)}Container`,
227
+ getPaletteForColor,
228
+ (s) => getTone(s.isDark ? 90 : 30)(s),
229
+ // Text on container: high contrast against container background
230
+ false
231
+ );
232
+ customVars[colorname] = colorDynamicColor.getArgb(scheme);
233
+ customVars[`on${upperFirst(colorname)}`] = onColorDynamicColor.getArgb(scheme);
234
+ customVars[`${colorname}Container`] = containerDynamicColor.getArgb(scheme);
235
+ customVars[`on${upperFirst(colorname)}Container`] = onContainerDynamicColor.getArgb(scheme);
236
+ });
237
+ return { ...baseVars, ...customVars };
238
+ }
239
+ function createColorPalette(colorDef, baseScheme, effectiveSourceForHarmonization) {
240
+ const colorArgb = argbFromHex(colorDef.hex);
241
+ const harmonizedArgb = colorDef.blend ? Blend.harmonize(colorArgb, effectiveSourceForHarmonization) : colorArgb;
242
+ const hct = Hct.fromInt(harmonizedArgb);
243
+ let targetChroma;
244
+ if (colorDef.core && colorDef.chromaSource) {
245
+ if (colorDef.chromaSource === "neutral") {
246
+ targetChroma = baseScheme.neutralPalette.chroma;
247
+ } else if (colorDef.chromaSource === "neutralVariant") {
248
+ targetChroma = baseScheme.neutralVariantPalette.chroma;
249
+ } else {
250
+ targetChroma = baseScheme.primaryPalette.chroma;
251
+ }
252
+ } else {
253
+ targetChroma = baseScheme.primaryPalette.chroma;
254
+ }
255
+ return TonalPalette.fromHueAndChroma(hct.hue, targetChroma);
256
+ }
257
+ function builder(hexSource, {
258
+ scheme = DEFAULT_SCHEME,
259
+ contrast = DEFAULT_CONTRAST,
260
+ primary,
261
+ secondary,
262
+ tertiary,
263
+ neutral,
264
+ neutralVariant,
265
+ error,
266
+ customColors: hexCustomColors = DEFAULT_CUSTOM_COLORS,
267
+ prefix = DEFAULT_PREFIX
268
+ } = {}) {
269
+ const sourceArgb = argbFromHex(hexSource);
270
+ const sourceHct = Hct.fromInt(sourceArgb);
271
+ const effectiveSource = primary || hexSource;
272
+ const effectiveSourceArgb = argbFromHex(effectiveSource);
273
+ const effectiveSourceForHarmonization = primary ? argbFromHex(primary) : sourceArgb;
274
+ const SchemeClass = schemesMap[scheme];
275
+ const primaryHct = Hct.fromInt(effectiveSourceArgb);
276
+ const baseScheme = new SchemeClass(primaryHct, false, contrast);
277
+ const allColors = [
278
+ // Core colors (hex may be undefined)
279
+ {
280
+ name: "primary",
281
+ hex: primary,
282
+ core: true,
283
+ chromaSource: "primary"
284
+ },
285
+ {
286
+ name: "secondary",
287
+ hex: secondary,
288
+ core: true,
289
+ chromaSource: "primary"
290
+ },
291
+ {
292
+ name: "tertiary",
293
+ hex: tertiary,
294
+ core: true,
295
+ chromaSource: "primary"
296
+ },
297
+ { name: "error", hex: error, core: true, chromaSource: "primary" },
298
+ {
299
+ name: "neutral",
300
+ hex: neutral,
301
+ core: true,
302
+ chromaSource: "neutral"
303
+ },
304
+ {
305
+ name: "neutralVariant",
306
+ hex: neutralVariant,
307
+ core: true,
308
+ chromaSource: "neutralVariant"
309
+ },
310
+ //
311
+ // Custom colors
312
+ //
313
+ ...hexCustomColors.map((c) => ({
314
+ name: c.name,
315
+ hex: c.hex,
316
+ blend: c.blend,
317
+ core: false
318
+ }))
319
+ ];
320
+ const definedColors = allColors.filter(
321
+ (c) => c.hex !== void 0
322
+ );
323
+ const colorPalettes = Object.fromEntries(
324
+ definedColors.map((colorDef) => [
325
+ colorDef.name,
326
+ createColorPalette(colorDef, baseScheme, effectiveSourceForHarmonization)
327
+ ])
328
+ );
329
+ const variant = schemeToVariant[scheme];
330
+ const schemeConfig = {
331
+ sourceColorArgb: effectiveSourceArgb,
332
+ variant,
333
+ contrastLevel: contrast,
334
+ primaryPalette: colorPalettes["primary"] || baseScheme.primaryPalette,
335
+ secondaryPalette: colorPalettes["secondary"] || baseScheme.secondaryPalette,
336
+ tertiaryPalette: colorPalettes["tertiary"] || baseScheme.tertiaryPalette,
337
+ neutralPalette: colorPalettes["neutral"] || baseScheme.neutralPalette,
338
+ neutralVariantPalette: colorPalettes["neutralVariant"] || baseScheme.neutralVariantPalette
339
+ };
340
+ const lightScheme = new DynamicScheme({ ...schemeConfig, isDark: false });
341
+ const darkScheme = new DynamicScheme({ ...schemeConfig, isDark: true });
342
+ const errorPalette = colorPalettes["error"];
343
+ if (errorPalette) {
344
+ lightScheme.errorPalette = errorPalette;
345
+ darkScheme.errorPalette = errorPalette;
346
+ }
347
+ const allPalettes = {
348
+ primary: lightScheme.primaryPalette,
349
+ secondary: lightScheme.secondaryPalette,
350
+ tertiary: lightScheme.tertiaryPalette,
351
+ error: lightScheme.errorPalette,
352
+ neutral: lightScheme.neutralPalette,
353
+ "neutral-variant": lightScheme.neutralVariantPalette,
354
+ // Add custom color palettes
355
+ ...Object.fromEntries(
356
+ definedColors.filter((c) => !c.core).map((colorDef) => [colorDef.name, colorPalettes[colorDef.name]])
357
+ )
358
+ };
359
+ const customColors = definedColors.filter((c) => !c.core).map((c) => ({
360
+ name: c.name,
361
+ blend: c.blend ?? DEFAULT_BLEND,
362
+ value: argbFromHex(c.hex)
363
+ }));
364
+ const mergedColorsLight = mergeBaseAndCustomColors(
365
+ lightScheme,
366
+ customColors,
367
+ colorPalettes
368
+ );
369
+ const mergedColorsDark = mergeBaseAndCustomColors(
370
+ darkScheme,
371
+ customColors,
372
+ colorPalettes
373
+ );
374
+ const schemePalettes = [
375
+ ["primary", lightScheme.primaryPalette],
376
+ ["secondary", lightScheme.secondaryPalette],
377
+ ["tertiary", lightScheme.tertiaryPalette],
378
+ ["error", lightScheme.errorPalette],
379
+ ["neutral", lightScheme.neutralPalette],
380
+ ["neutral-variant", lightScheme.neutralVariantPalette]
381
+ ];
382
+ function buildTokenToPaletteMap(schemePalettes2, scheme2) {
383
+ const result = {};
384
+ for (const propName of Object.getOwnPropertyNames(MaterialDynamicColors)) {
385
+ const dc = MaterialDynamicColors[propName];
386
+ if (!(dc instanceof DynamicColor)) continue;
387
+ const palette = dc.palette(scheme2);
388
+ for (const [palName, pal] of schemePalettes2) {
389
+ if (palette === pal) {
390
+ result[propName] = palName;
391
+ break;
392
+ }
393
+ }
394
+ }
395
+ return result;
396
+ }
397
+ const tokenToPalette = buildTokenToPaletteMap(schemePalettes, lightScheme);
398
+ const allPaletteNamesKebab = new Set(Object.keys(allPalettes).map(kebabCase));
399
+ function deriveCustomPaletteName(tokenName) {
400
+ let baseName = tokenName;
401
+ if (/^on[A-Z]/.test(baseName) && baseName.length > 2) {
402
+ baseName = baseName.charAt(2).toLowerCase() + baseName.slice(3);
403
+ }
404
+ if (baseName.endsWith("Container")) {
405
+ baseName = baseName.slice(0, -"Container".length);
406
+ }
407
+ const kebab = kebabCase(baseName);
408
+ return allPaletteNamesKebab.has(kebab) ? kebab : void 0;
409
+ }
410
+ return {
411
+ //
412
+ // ██████ ███████ ███████
413
+ // ██ ██ ██
414
+ // ██ ███████ ███████
415
+ // ██ ██ ██
416
+ // ██████ ███████ ███████
417
+ //
418
+ toCss() {
419
+ function buildRefPaletteLookup() {
420
+ const lookup = {};
421
+ for (const [name, palette] of Object.entries(allPalettes)) {
422
+ const paletteName = kebabCase(name);
423
+ for (const tone of STANDARD_TONES) {
424
+ const hex = hexFromArgb(palette.tone(tone));
425
+ if (!lookup[hex]) lookup[hex] = [];
426
+ lookup[hex].push({ paletteName, tone });
427
+ }
428
+ }
429
+ return lookup;
430
+ }
431
+ function sysColorVar(colorName, colorValue, lookup) {
432
+ const name = `--${prefix}-sys-color-${kebabCase(colorName)}`;
433
+ const hex = hexFromArgb(colorValue);
434
+ const matches = lookup[hex];
435
+ if (matches && matches.length > 0) {
436
+ const preferred = tokenToPalette[colorName] ?? deriveCustomPaletteName(colorName);
437
+ const match = (preferred ? matches.find((m) => m.paletteName === preferred) : void 0) ?? matches[0];
438
+ return `${name}:var(--${prefix}-ref-palette-${match.paletteName}-${match.tone});`;
439
+ }
440
+ return `${name}:${hex};`;
441
+ }
442
+ function toCssVars(mergedColors, lookup) {
443
+ return Object.entries(mergedColors).map(([name, value]) => sysColorVar(name, value, lookup)).join(" ");
444
+ }
445
+ function refPaletteVar(paletteName, tone, colorValue) {
446
+ const name = `--${prefix}-ref-palette-${paletteName}-${tone}`;
447
+ const value = hexFromArgb(colorValue);
448
+ return `${name}:${value};`;
449
+ }
450
+ function generateTonalPaletteVars(paletteName, palette) {
451
+ return STANDARD_TONES.map((tone) => {
452
+ const color = palette.tone(tone);
453
+ return refPaletteVar(paletteName, tone, color);
454
+ }).join(" ");
455
+ }
456
+ function generateTonalVars() {
457
+ return Object.entries(allPalettes).map(
458
+ ([name, palette]) => generateTonalPaletteVars(kebabCase(name), palette)
459
+ ).join(" ");
460
+ }
461
+ const refPaletteLookup = buildRefPaletteLookup();
462
+ const lightVars = toCssVars(mergedColorsLight, refPaletteLookup);
463
+ const darkVars = toCssVars(mergedColorsDark, refPaletteLookup);
464
+ const tonalVars = generateTonalVars();
465
+ return `
466
+ :root { ${lightVars} ${tonalVars} }
467
+ .dark { ${darkVars} ${tonalVars} }
468
+ `;
469
+ },
470
+ //
471
+ // ██ ███████ ██████ ███ ██
472
+ // ██ ██ ██ ██ ████ ██
473
+ // ██ ███████ ██ ██ ██ ██ ██
474
+ // ██ ██ ██ ██ ██ ██ ██ ██
475
+ // █████ ███████ ██████ ██ ████
476
+ //
477
+ toJson() {
478
+ const fixtureTokenOrder = [
479
+ "primary",
480
+ "surfaceTint",
481
+ "onPrimary",
482
+ "primaryContainer",
483
+ "onPrimaryContainer",
484
+ "secondary",
485
+ "onSecondary",
486
+ "secondaryContainer",
487
+ "onSecondaryContainer",
488
+ "tertiary",
489
+ "onTertiary",
490
+ "tertiaryContainer",
491
+ "onTertiaryContainer",
492
+ "error",
493
+ "onError",
494
+ "errorContainer",
495
+ "onErrorContainer",
496
+ "background",
497
+ "onBackground",
498
+ "surface",
499
+ "onSurface",
500
+ "surfaceVariant",
501
+ "onSurfaceVariant",
502
+ "outline",
503
+ "outlineVariant",
504
+ "shadow",
505
+ "scrim",
506
+ "inverseSurface",
507
+ "inverseOnSurface",
508
+ "inversePrimary",
509
+ "primaryFixed",
510
+ "onPrimaryFixed",
511
+ "primaryFixedDim",
512
+ "onPrimaryFixedVariant",
513
+ "secondaryFixed",
514
+ "onSecondaryFixed",
515
+ "secondaryFixedDim",
516
+ "onSecondaryFixedVariant",
517
+ "tertiaryFixed",
518
+ "onTertiaryFixed",
519
+ "tertiaryFixedDim",
520
+ "onTertiaryFixedVariant",
521
+ "surfaceDim",
522
+ "surfaceBright",
523
+ "surfaceContainerLowest",
524
+ "surfaceContainerLow",
525
+ "surfaceContainer",
526
+ "surfaceContainerHigh",
527
+ "surfaceContainerHighest"
528
+ ];
529
+ const neuHct = neutral ? Hct.fromInt(argbFromHex(neutral)) : sourceHct;
530
+ const nvHct = neutralVariant ? Hct.fromInt(argbFromHex(neutralVariant)) : sourceHct;
531
+ const rawPalettes = {
532
+ primary: TonalPalette.fromInt(effectiveSourceArgb),
533
+ secondary: secondary ? TonalPalette.fromInt(argbFromHex(secondary)) : TonalPalette.fromHueAndChroma(sourceHct.hue, sourceHct.chroma / 3),
534
+ tertiary: tertiary ? TonalPalette.fromInt(argbFromHex(tertiary)) : TonalPalette.fromHueAndChroma(
535
+ (sourceHct.hue + 60) % 360,
536
+ sourceHct.chroma / 2
537
+ ),
538
+ neutral: TonalPalette.fromHueAndChroma(
539
+ neuHct.hue,
540
+ Math.min(neuHct.chroma / 12, 4)
541
+ ),
542
+ "neutral-variant": TonalPalette.fromHueAndChroma(
543
+ nvHct.hue,
544
+ Math.min(nvHct.chroma / 6, 8)
545
+ )
546
+ };
547
+ function buildJsonSchemes() {
548
+ function extractSchemeColors(scheme2, backgroundScheme) {
549
+ const colors = {};
550
+ for (const tokenName of fixtureTokenOrder) {
551
+ const dynamicColor = MaterialDynamicColors[tokenName];
552
+ const useScheme = backgroundScheme && (tokenName === "background" || tokenName === "onBackground") ? backgroundScheme : scheme2;
553
+ colors[tokenName] = hexFromArgb(
554
+ dynamicColor.getArgb(useScheme)
555
+ ).toUpperCase();
556
+ }
557
+ return colors;
558
+ }
559
+ function resolveOverridePalette(hex, role) {
560
+ if (!hex) return null;
561
+ return new SchemeClass(Hct.fromInt(argbFromHex(hex)), false, 0)[role];
562
+ }
563
+ const secPalette = resolveOverridePalette(secondary, "primaryPalette");
564
+ const terPalette = resolveOverridePalette(tertiary, "primaryPalette");
565
+ const errPalette = resolveOverridePalette(error, "primaryPalette");
566
+ const neuPalette = resolveOverridePalette(neutral, "neutralPalette");
567
+ const nvPalette = resolveOverridePalette(
568
+ neutralVariant,
569
+ "neutralVariantPalette"
570
+ );
571
+ const jsonSchemes = {};
572
+ const jsonContrastLevels = [
573
+ { name: "light", isDark: false, contrast: 0 },
574
+ { name: "light-medium-contrast", isDark: false, contrast: 0.5 },
575
+ { name: "light-high-contrast", isDark: false, contrast: 1 },
576
+ { name: "dark", isDark: true, contrast: 0 },
577
+ { name: "dark-medium-contrast", isDark: true, contrast: 0.5 },
578
+ { name: "dark-high-contrast", isDark: true, contrast: 1 }
579
+ ];
580
+ for (const { name, isDark, contrast: contrast2 } of jsonContrastLevels) {
581
+ const baseScheme2 = new SchemeClass(primaryHct, isDark, contrast2);
582
+ const composedScheme = new DynamicScheme({
583
+ sourceColorArgb: effectiveSourceArgb,
584
+ variant: schemeToVariant[scheme],
585
+ contrastLevel: contrast2,
586
+ isDark,
587
+ primaryPalette: baseScheme2.primaryPalette,
588
+ secondaryPalette: secPalette || baseScheme2.secondaryPalette,
589
+ tertiaryPalette: terPalette || baseScheme2.tertiaryPalette,
590
+ neutralPalette: neuPalette || baseScheme2.neutralPalette,
591
+ neutralVariantPalette: nvPalette || baseScheme2.neutralVariantPalette
592
+ });
593
+ if (errPalette) composedScheme.errorPalette = errPalette;
594
+ jsonSchemes[name] = extractSchemeColors(composedScheme, baseScheme2);
595
+ }
596
+ return jsonSchemes;
597
+ }
598
+ function rawPalettesToJson() {
599
+ const jsonPalettes = {};
600
+ const RAW_PALETTE_NAMES = [
601
+ "primary",
602
+ "secondary",
603
+ "tertiary",
604
+ "neutral",
605
+ "neutral-variant"
606
+ ];
607
+ for (const name of RAW_PALETTE_NAMES) {
608
+ const palette = rawPalettes[name];
609
+ const tones = {};
610
+ for (const tone of MTB_TONES) {
611
+ tones[tone.toString()] = hexFromArgb(
612
+ palette.tone(tone)
613
+ ).toUpperCase();
614
+ }
615
+ jsonPalettes[name] = tones;
616
+ }
617
+ return jsonPalettes;
618
+ }
619
+ function buildCoreColors(opts) {
620
+ const colors = { primary: opts.primary };
621
+ if (opts.secondary) colors.secondary = opts.secondary.toUpperCase();
622
+ if (opts.tertiary) colors.tertiary = opts.tertiary.toUpperCase();
623
+ if (opts.error) colors.error = opts.error.toUpperCase();
624
+ if (opts.neutral) colors.neutral = opts.neutral.toUpperCase();
625
+ if (opts.neutralVariant)
626
+ colors.neutralVariant = opts.neutralVariant.toUpperCase();
627
+ return colors;
628
+ }
629
+ const seed = hexSource.toUpperCase();
630
+ const coreColors = buildCoreColors({
631
+ primary: (primary || hexSource).toUpperCase(),
632
+ secondary,
633
+ tertiary,
634
+ error,
635
+ neutral,
636
+ neutralVariant
637
+ });
638
+ const extendedColors = hexCustomColors.map((c) => ({
639
+ name: c.name,
640
+ color: c.hex.toUpperCase(),
641
+ description: "",
642
+ harmonized: c.blend ?? DEFAULT_BLEND
643
+ }));
644
+ return {
645
+ seed,
646
+ coreColors,
647
+ extendedColors,
648
+ schemes: buildJsonSchemes(),
649
+ palettes: rawPalettesToJson()
650
+ };
651
+ },
652
+ //
653
+ // ███████ ██ ██████ ███ ███ █████
654
+ // ██ ██ ██ ████ ████ ██ ██
655
+ // █████ ██ ██ ███ ██ ████ ██ ███████
656
+ // ██ ██ ██ ██ ██ ██ ██ ██ ██
657
+ // ██ ██ ██████ ██ ██ ██ ██
658
+ //
659
+ toFigmaTokens() {
660
+ function argbToFigmaColorValue(argb) {
661
+ return {
662
+ colorSpace: "srgb",
663
+ components: [
664
+ redFromArgb(argb) / 255,
665
+ greenFromArgb(argb) / 255,
666
+ blueFromArgb(argb) / 255
667
+ ],
668
+ alpha: 1,
669
+ hex: hexFromArgb(argb).toUpperCase()
670
+ };
671
+ }
672
+ function figmaToken(argb) {
673
+ return {
674
+ $type: "color",
675
+ $value: argbToFigmaColorValue(argb),
676
+ $extensions: {
677
+ "com.figma.scopes": ["ALL_SCOPES"],
678
+ "com.figma.isOverride": true
679
+ }
680
+ };
681
+ }
682
+ function buildRefPaletteTokens() {
683
+ const palettes = {};
684
+ for (const [name, palette] of Object.entries(allPalettes)) {
685
+ const tones = {};
686
+ for (const tone of STANDARD_TONES) {
687
+ const argb = palette.tone(tone);
688
+ tones[tone.toString()] = figmaToken(argb);
689
+ }
690
+ palettes[startCase(name)] = tones;
691
+ }
692
+ return palettes;
693
+ }
694
+ function findToneInPalette(hex, paletteName, tones) {
695
+ for (const [tone, token] of Object.entries(tones)) {
696
+ if (token.$value.hex === hex) {
697
+ return `{ref.palette.${paletteName}.${tone}}`;
698
+ }
699
+ }
700
+ return null;
701
+ }
702
+ function findAlias(hex, tokenName, refPalettes2) {
703
+ const preferredPaletteKebab = tokenToPalette[tokenName] ?? deriveCustomPaletteName(tokenName);
704
+ const preferredPalette = preferredPaletteKebab ? startCase(preferredPaletteKebab) : void 0;
705
+ if (preferredPalette && refPalettes2[preferredPalette]) {
706
+ const match = findToneInPalette(
707
+ hex,
708
+ preferredPalette,
709
+ refPalettes2[preferredPalette]
710
+ );
711
+ if (match) return match;
712
+ }
713
+ for (const [palName, tones] of Object.entries(refPalettes2)) {
714
+ const match = findToneInPalette(hex, palName, tones);
715
+ if (match) return match;
716
+ }
717
+ return null;
718
+ }
719
+ function resolveModeValue(argb, tokenName, refPalettes2) {
720
+ const hex = hexFromArgb(argb).toUpperCase();
721
+ return findAlias(hex, tokenName, refPalettes2) ?? argbToFigmaColorValue(argb);
722
+ }
723
+ function buildSysColorTokens(mergedColors, refPalettes2) {
724
+ const tokens = {};
725
+ for (const [name, argb] of Object.entries(mergedColors)) {
726
+ const description = tokenDescriptions[name];
727
+ const cssVar = `--${prefix}-sys-color-${kebabCase(name)}`;
728
+ const value = resolveModeValue(argb, name, refPalettes2);
729
+ tokens[startCase(name)] = {
730
+ $type: "color",
731
+ $value: value,
732
+ ...description ? { $description: description } : {},
733
+ $extensions: {
734
+ "com.figma.scopes": ["ALL_SCOPES"],
735
+ "css.variable": cssVar
736
+ }
737
+ };
738
+ }
739
+ return tokens;
740
+ }
741
+ const refPalettes = buildRefPaletteTokens();
742
+ function buildModeFile(modeName, mergedColors) {
743
+ return {
744
+ ref: {
745
+ palette: refPalettes
746
+ },
747
+ sys: {
748
+ color: buildSysColorTokens(mergedColors, refPalettes)
749
+ },
750
+ $extensions: {
751
+ "com.figma.modeName": modeName
752
+ }
753
+ };
754
+ }
755
+ return {
756
+ "Light.tokens.json": buildModeFile("Light", mergedColorsLight),
757
+ "Dark.tokens.json": buildModeFile("Dark", mergedColorsDark)
758
+ };
759
+ },
760
+ //
761
+ // API
762
+ //
763
+ mergedColorsLight,
764
+ mergedColorsDark,
765
+ allPalettes
766
+ };
767
+ }
768
+
769
+ // src/cli.ts
770
+ var program = new Command();
771
+ program.name("material-theme-builder").description("m3 color system");
772
+ program.command("builder").description("Generate a color theme from a source color").argument("<source>", "Source color in hex format (e.g. #6750A4)").addOption(
773
+ new Option("--scheme <name>", "Color scheme variant").choices(schemeNames).default(DEFAULT_SCHEME)
774
+ ).option(
775
+ "--contrast <number>",
776
+ "Contrast level from -1.0 to 1.0",
777
+ parseFloat,
778
+ DEFAULT_CONTRAST
779
+ ).option("--primary <hex>", "Primary color override").option("--secondary <hex>", "Secondary color override").option("--tertiary <hex>", "Tertiary color override").option("--error <hex>", "Error color override").option("--neutral <hex>", "Neutral color override").option("--neutral-variant <hex>", "Neutral variant color override").option(
780
+ "--custom-colors <json>",
781
+ `Custom colors as JSON array (e.g. '[{"name":"brand","hex":"#FF5733","blend":true}]')`
782
+ ).option("--format <type>", "Output format: json, css, or figma", "figma").option("--output <dir>", "Output directory (required for figma format)").option(
783
+ "--prefix <string>",
784
+ "CSS variable prefix (e.g. md \u2192 --md-sys-color-*, --md-ref-palette-*)",
785
+ DEFAULT_PREFIX
786
+ ).action((source, opts) => {
787
+ let customColors = [];
788
+ if (opts.customColors) {
789
+ try {
790
+ const parsed = JSON.parse(opts.customColors);
791
+ customColors = parsed.map((c) => ({
792
+ name: c.name,
793
+ hex: c.hex,
794
+ blend: c.blend ?? DEFAULT_BLEND
795
+ }));
796
+ } catch {
797
+ console.error("Error: --custom-colors must be valid JSON");
798
+ process.exit(1);
799
+ }
800
+ }
801
+ const result = builder(source, {
802
+ scheme: opts.scheme,
803
+ contrast: opts.contrast,
804
+ primary: opts.primary,
805
+ secondary: opts.secondary,
806
+ tertiary: opts.tertiary,
807
+ error: opts.error,
808
+ neutral: opts.neutral,
809
+ neutralVariant: opts.neutralVariant,
810
+ customColors,
811
+ prefix: opts.prefix
812
+ });
813
+ if (opts.format === "css") {
814
+ process.stdout.write(result.toCss());
815
+ } else if (opts.format === "figma") {
816
+ const outputDir = opts.output ?? "material-theme";
817
+ fs.mkdirSync(outputDir, { recursive: true });
818
+ const files = result.toFigmaTokens();
819
+ for (const [filename, content] of Object.entries(files)) {
820
+ const filePath = path.join(outputDir, filename);
821
+ fs.writeFileSync(filePath, JSON.stringify(content, null, 2) + "\n");
822
+ console.error(`wrote ${filePath}`);
823
+ }
824
+ } else {
825
+ process.stdout.write(JSON.stringify(result.toJson(), null, 2) + "\n");
826
+ }
827
+ });
828
+ program.parse();