@designtools/tokens 0.8.0 → 0.10.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/index.d.ts CHANGED
@@ -218,6 +218,35 @@ type SemanticShadeOverrides = Record<string, {
218
218
  light?: Partial<VariantShadeOverrides>;
219
219
  dark?: Partial<VariantShadeOverrides>;
220
220
  }>;
221
+ /**
222
+ * How colourful each step of a ramp is. `follow` (the default) eases from pale tints to the seed's
223
+ * chroma; `constant` holds the seed's chroma at every step, as far as the screen allows (Material's
224
+ * tonal palettes); `relative` keeps the seed's share of the most each step's lightness can hold;
225
+ * `peak` peaks at `peakAt` and falls away either side (Tailwind's shape).
226
+ */
227
+ type ChromaProfile = "follow" | "constant" | "relative" | "peak";
228
+ /** Colourfulness: the profile, how strong (1 is the seed's own; it eases in beside the seed, which never moves), and where `peak` peaks. */
229
+ interface ChromaShape {
230
+ profile?: ChromaProfile;
231
+ strength?: number;
232
+ peakAt?: ShadeNumber;
233
+ }
234
+ /**
235
+ * How the hue turns in the steps darker than the seed. `none` (the default) holds it; `natural` turns
236
+ * yellows towards amber and blues towards indigo, as Tailwind's darks do, and leaves other hues; a number
237
+ * is degrees at the deepest step, positive counter-clockwise.
238
+ */
239
+ type HueDrift = "none" | "natural" | number;
240
+ /** One colour family leaning away from the system: each field replaces the system's for that family only. Lightness 0 to 1. */
241
+ interface FamilyShape {
242
+ lightnessRange?: {
243
+ light?: number;
244
+ dark?: number;
245
+ };
246
+ tintFloor?: number;
247
+ chroma?: ChromaShape;
248
+ hueDrift?: HueDrift;
249
+ }
221
250
  /** Per-surface-token shade overrides */
222
251
  interface SurfaceShadeOverrides {
223
252
  canvas?: ShadeNumber | "white" | "black";
@@ -256,6 +285,44 @@ interface GenerationOptions {
256
285
  * An alias pair (`destructive`/`red`) is one ramp, so naming either anchors both.
257
286
  */
258
287
  seedShades?: Record<string, ShadeNumber>;
288
+ /**
289
+ * Where the colour ramps end, as OKLCH lightness from 0 to 1: `light` for the palest step (25),
290
+ * `dark` for the deepest (950). Default 0.98 and 0.15. A brand that only uses soft deep tones
291
+ * raises `dark`; the steps between are spread over the new range. The neutral keeps its own,
292
+ * because both modes' backgrounds are made from it. Adjacent dark steps keep a gap however high
293
+ * `dark` goes, so the ramp never collapses.
294
+ */
295
+ lightnessRange?: {
296
+ light?: number;
297
+ dark?: number;
298
+ };
299
+ /**
300
+ * How much of the seed's colourfulness the pale steps keep, from 0 to 1. By default the steps
301
+ * above the seed fade towards grey; a tint floor of 0.6 keeps at least 60% of the seed's chroma
302
+ * in each, as far as a screen can show it. The neutral is left alone.
303
+ */
304
+ tintFloor?: number;
305
+ /** How colourful the colour ramps are, step to step. The neutral is left alone. */
306
+ chroma?: ChromaShape;
307
+ /** How the colour ramps' hue turns in their darks. The neutral is left alone. */
308
+ hueDrift?: HueDrift;
309
+ /**
310
+ * A family leaning away from the system, by name (or its alias): `{ twilight: { chroma: { strength: 1.5 } } }`.
311
+ * The neutral takes the system's shape only from here.
312
+ */
313
+ families?: Record<string, FamilyShape>;
314
+ /**
315
+ * Exact colours on given steps, by family: `{ camel: { 300: "#B7B7A3" } }`. The steps between the
316
+ * pin and the seed are refitted to pass through it. A pin that would put the ramp out of order, or that
317
+ * a screen can't show, is refused with the reason. A pin can't sit on the seed's own step.
318
+ */
319
+ pins?: Record<string, Partial<Record<ShadeNumber, string>>>;
320
+ /**
321
+ * Whether the status ramps also get their everyday names: `green`, `red` and `yellow` as the same
322
+ * ramps as `success`, `destructive` and `warning`, so `bg-red-500` matches. Default true; false
323
+ * emits each ramp once, under its semantic name.
324
+ */
325
+ aliases?: boolean;
259
326
  /**
260
327
  * Additional colours that get their ramp and nothing else: no `--<name>`,
261
328
  * no `-foreground`, no `bg-<name>` semantic. An accent that may never be text
@@ -334,6 +401,21 @@ interface SavedConfig {
334
401
  seedShade?: ShadeNumber;
335
402
  /** Where the neutral seed lands. Default: 500 */
336
403
  neutralSeedShade?: ShadeNumber;
404
+ /** Where the colour ramps end, as OKLCH lightness in percent: `{ "light": 97, "dark": 34 }`. */
405
+ lightnessRange?: {
406
+ light?: number;
407
+ dark?: number;
408
+ };
409
+ /** How much of the seed's colourfulness the pale steps keep, 0 to 1. */
410
+ tintFloor?: number;
411
+ chroma?: ChromaShape;
412
+ hueDrift?: HueDrift;
413
+ /** Families leaning away from the system; their lightness in percent, as above. */
414
+ families?: Record<string, FamilyShape>;
415
+ /** Exact colours on given steps, by family. */
416
+ pins?: Record<string, Partial<Record<ShadeNumber, string>>>;
417
+ /** false: no green, red and yellow beside success, destructive and warning. */
418
+ aliases?: boolean;
337
419
  shades?: ShadeNumber[];
338
420
  /** `seedShade` anchors that colour's own ramp. Default: 500 */
339
421
  additionalColors: {
@@ -394,6 +476,18 @@ interface ScaleOptions {
394
476
  shades?: readonly ShadeNumber[];
395
477
  /** Which display gamut every step must fit. Default: srgb */
396
478
  gamut?: Gamut;
479
+ /** Lightness of the palest step's ceiling, 0 to 1. Default: 0.98 */
480
+ lightEnd?: number;
481
+ /** Lightness of the deepest step's floor, 0 to 1. Default: 0.15 */
482
+ darkEnd?: number;
483
+ /** Share of the seed's chroma every step above the seed keeps, 0 to 1. Default: none */
484
+ tintFloor?: number;
485
+ /** How colourful each step is. Default: follow */
486
+ chroma?: ChromaShape;
487
+ /** How the hue turns below the seed. Default: none */
488
+ hueDrift?: HueDrift;
489
+ /** Exact colours on given steps; the ramp is refitted through them. */
490
+ pins?: Partial<Record<ShadeNumber, string>>;
397
491
  }
398
492
  /**
399
493
  * Print an OKLCH colour that a display of `gamut` shows exactly as written.
@@ -524,6 +618,12 @@ declare function familySeedShade(name: string, seedShade: ShadeNumber | undefine
524
618
  */
525
619
  interface PaletteOptions extends ScaleOptions {
526
620
  seedShades?: Record<string, ShadeNumber>;
621
+ /** Families leaning away from the system's shape, by name or alias. */
622
+ families?: Record<string, FamilyShape>;
623
+ /** Exact colours on given steps, by family name or alias. */
624
+ familyPins?: Record<string, Partial<Record<ShadeNumber, string>>>;
625
+ /** false: each status ramp once, under its semantic name only. */
626
+ aliases?: boolean;
527
627
  }
528
628
  declare function generatePrimitivePalette(brandColors: BrandColors, lightnessStrategy?: LightnessStrategy, options?: PaletteOptions): PrimitivePalette;
529
629
  /**
@@ -916,6 +1016,13 @@ declare function provenanceComment(p: Provenance): string;
916
1016
  declare function parseProvenance(text: string): Provenance | null;
917
1017
  /** Attach provenance to a JSON document as a `$designtools` key */
918
1018
  declare function withJsonProvenance(json: string, p: Provenance): string;
1019
+ /** A seed's lightness range (percent, as people write it) as the generator takes it (0 to 1), or nothing when unset. */
1020
+ declare function rangeOf(seed: SeedFile): {
1021
+ light?: number;
1022
+ dark?: number;
1023
+ } | undefined;
1024
+ /** A seed's families (lightness in percent) as the generator takes them (0 to 1), or nothing when none lean away. */
1025
+ declare function familiesOf(seed: SeedFile): GenerationOptions["families"] | undefined;
919
1026
 
920
1027
  declare class APCAUnavailableError extends Error {
921
1028
  constructor();
@@ -954,4 +1061,28 @@ declare function usageReport(tokens: TokenSystem, target?: ContrastTarget): Usag
954
1061
  /** Two-space JSON with a trailing newline, keys in the order built (already sorted) */
955
1062
  declare function serialiseUsage(report: UsageReport): string;
956
1063
 
957
- export { ALIAS_PAIRS, type APCAContrastResult, APCAUnavailableError, type BrandColors, type CVDType, type ColorFormat, type ColorScale, type ContrastAlgorithm, type ContrastTarget, DEFAULT_NEUTRAL_COLOR, DEFAULT_SEED_SHADE, type Declaration, type ExportFormat, type ExportOptions, type ExtendedSemanticColor, type ForegroundRef, GENERATOR_NAME, type Gamut, type GamutTokens, type GenerationOptions, type LightnessStrategy, type MergeResult, type NamedBackground, type PageContrast, type PaletteOptions, type PrimitivePalette, type Provenance, SECTIONED_FORMATS, SHADE_PRESETS, type SavedConfig, type ScaleOptions, type SeedFile, type SelectedTokens, type SemanticColorPair, type SemanticGamuts, type SemanticShadeOverrides, type SemanticTokens, type ShadeNumber, type SliceDiff, type SurfaceRef, type SurfaceShadeOverrides, type SurfaceTokens, TAILWIND_SHADES, TOKEN_SECTIONS, type TokenSection, type TokenSystem, type UsageReport, type UsageVerdict, type UtilityShadeOverrides, type UtilityTokens, VALID_SHADES, type VariantShadeOverrides, type WCAGContrastResult, WIDE_GAMUT_QUERY, adjustChroma, adjustLightness, aliasOf, checkRampChroma, checkSemanticContrast, checkSemanticContrastAPCA, checkSurfaceContrast, chromaShadeFor, classifyAPCALevel, computeAccessibilityScore, diffSlice, exportToCss, exportToDtcg, exportToTailwindV3, exportToTailwindV4, exportTokens, externalReferences, familySeedShade, findContrastingColorAPCA, fingerprint, formatColorAs, formatColorShort, formatOklchInGamut, generateColorScale, generateColorScaleAPCA, generatePrimitivePalette, generateSemanticTokens, generateSurfaceTokens, generateTokens, generateUtilityTokens, getAPCAContrast, getContrastRatio, getOklchString, getRelativeLuminance, getShade, isAPCAAvailable, isInGamut, meetsWCAG_AA, meetsWCAG_AAA, mergeSlice, oklchToHex, parseProvenance, parseToOklch, provenanceComment, readDeclarations, reanchorFactors, resolveShades, seedFingerprint, selectTokenSections, serialiseUsage, simulateCVD, snapShade, stableStringify, tokenFamilies, usageReport, withJsonProvenance };
1064
+ /**
1065
+ * The step contract: a step number means the same in every colour. If 700 carries text on white in
1066
+ * one family, it should in all of them, so a designer can reach for "the 700" without checking. Lyft
1067
+ * built its colour system on this; hand-made ramps are where it breaks.
1068
+ *
1069
+ * This measures it rather than enforcing it: for each step, which colours carry text on white, and
1070
+ * on black (4.5:1), and which disagree with the rest. The neutral and the alias names (green for
1071
+ * success) are left out: one is grey by design, the others are the same ramp twice.
1072
+ */
1073
+
1074
+ interface ContractBreak {
1075
+ step: ShadeNumber;
1076
+ /** What the step should promise: text on a white page, or on a black one. */
1077
+ role: "text on white" | "text on black";
1078
+ /** The colours where it holds. */
1079
+ holds: string[];
1080
+ /** The colours where it doesn't. */
1081
+ fails: string[];
1082
+ /** The odd ones out: whichever side has fewer colours (the failing side on a tie). */
1083
+ odd: string[];
1084
+ }
1085
+ /** Every step whose promise differs between colours, light to dark. Empty when every step means the same everywhere. */
1086
+ declare function stepContract(palette: PrimitivePalette): ContractBreak[];
1087
+
1088
+ export { ALIAS_PAIRS, type APCAContrastResult, APCAUnavailableError, type BrandColors, type CVDType, type ChromaProfile, type ChromaShape, type ColorFormat, type ColorScale, type ContractBreak, type ContrastAlgorithm, type ContrastTarget, DEFAULT_NEUTRAL_COLOR, DEFAULT_SEED_SHADE, type Declaration, type ExportFormat, type ExportOptions, type ExtendedSemanticColor, type FamilyShape, type ForegroundRef, GENERATOR_NAME, type Gamut, type GamutTokens, type GenerationOptions, type HueDrift, type LightnessStrategy, type MergeResult, type NamedBackground, type PageContrast, type PaletteOptions, type PrimitivePalette, type Provenance, SECTIONED_FORMATS, SHADE_PRESETS, type SavedConfig, type ScaleOptions, type SeedFile, type SelectedTokens, type SemanticColorPair, type SemanticGamuts, type SemanticShadeOverrides, type SemanticTokens, type ShadeNumber, type SliceDiff, type SurfaceRef, type SurfaceShadeOverrides, type SurfaceTokens, TAILWIND_SHADES, TOKEN_SECTIONS, type TokenSection, type TokenSystem, type UsageReport, type UsageVerdict, type UtilityShadeOverrides, type UtilityTokens, VALID_SHADES, type VariantShadeOverrides, type WCAGContrastResult, WIDE_GAMUT_QUERY, adjustChroma, adjustLightness, aliasOf, checkRampChroma, checkSemanticContrast, checkSemanticContrastAPCA, checkSurfaceContrast, chromaShadeFor, classifyAPCALevel, computeAccessibilityScore, diffSlice, exportToCss, exportToDtcg, exportToTailwindV3, exportToTailwindV4, exportTokens, externalReferences, familiesOf, familySeedShade, findContrastingColorAPCA, fingerprint, formatColorAs, formatColorShort, formatOklchInGamut, generateColorScale, generateColorScaleAPCA, generatePrimitivePalette, generateSemanticTokens, generateSurfaceTokens, generateTokens, generateUtilityTokens, getAPCAContrast, getContrastRatio, getOklchString, getRelativeLuminance, getShade, isAPCAAvailable, isInGamut, meetsWCAG_AA, meetsWCAG_AAA, mergeSlice, oklchToHex, parseProvenance, parseToOklch, provenanceComment, rangeOf, readDeclarations, reanchorFactors, resolveShades, seedFingerprint, selectTokenSections, serialiseUsage, simulateCVD, snapShade, stableStringify, stepContract, tokenFamilies, usageReport, withJsonProvenance };
package/dist/index.js CHANGED
@@ -27,6 +27,7 @@ import {
27
27
  exportToTailwindV4,
28
28
  exportTokens,
29
29
  externalReferences,
30
+ familiesOf,
30
31
  familySeedShade,
31
32
  findContrastingColorAPCA,
32
33
  fingerprint,
@@ -54,6 +55,7 @@ import {
54
55
  parseProvenance,
55
56
  parseToOklch,
56
57
  provenanceComment,
58
+ rangeOf,
57
59
  readDeclarations,
58
60
  reanchorFactors,
59
61
  resolveShades,
@@ -63,10 +65,11 @@ import {
63
65
  simulateCVD,
64
66
  snapShade,
65
67
  stableStringify,
68
+ stepContract,
66
69
  tokenFamilies,
67
70
  usageReport,
68
71
  withJsonProvenance
69
- } from "./chunk-P562LKFL.js";
72
+ } from "./chunk-YOUMF42P.js";
70
73
  export {
71
74
  ALIAS_PAIRS,
72
75
  APCAUnavailableError,
@@ -96,6 +99,7 @@ export {
96
99
  exportToTailwindV4,
97
100
  exportTokens,
98
101
  externalReferences,
102
+ familiesOf,
99
103
  familySeedShade,
100
104
  findContrastingColorAPCA,
101
105
  fingerprint,
@@ -123,6 +127,7 @@ export {
123
127
  parseProvenance,
124
128
  parseToOklch,
125
129
  provenanceComment,
130
+ rangeOf,
126
131
  readDeclarations,
127
132
  reanchorFactors,
128
133
  resolveShades,
@@ -132,6 +137,7 @@ export {
132
137
  simulateCVD,
133
138
  snapShade,
134
139
  stableStringify,
140
+ stepContract,
135
141
  tokenFamilies,
136
142
  usageReport,
137
143
  withJsonProvenance
@@ -0,0 +1,12 @@
1
+ /**
2
+ * What a seed changes from the project's, in words, and a seed carried in a link. Plain functions,
3
+ * shared by the colour editor and the hand-back, and tested without a page.
4
+ */
5
+ import type { SeedFile } from "@designtools/tokens";
6
+ /** What the seed changes from the project's, in words: "darkest 15% → 34%", "twilight colourfulness ×1.50". */
7
+ export declare function describeChanges(before: SeedFile, now: SeedFile): string[];
8
+ /** Where a link carries a seed: the page's hash, so nothing reaches the server. */
9
+ export declare const LINK_HASH = "designtools-colours";
10
+ export declare function seedFromHash(hash: string): SeedFile | null;
11
+ /** This page's address carrying a seed. */
12
+ export declare function linkFor(seed: SeedFile): string;
@@ -0,0 +1,98 @@
1
+ const LIGHT_END = 98;
2
+ const DARK_END = 15;
3
+ /** What the seed changes from the project's, in words: "darkest 15% → 34%", "twilight colourfulness ×1.50". */
4
+ export function describeChanges(before, now) {
5
+ const out = [];
6
+ const pct = (v, d) => `${v ?? d}%`;
7
+ const same = (a, b) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
8
+ if (!same(before.primaryColor, now.primaryColor))
9
+ out.push(`primary ${before.primaryColor} → ${now.primaryColor}`);
10
+ if (!same(before.neutralColor, now.neutralColor))
11
+ out.push(`neutral ${before.neutralColor} → ${now.neutralColor}`);
12
+ if (!same(before.seedShade, now.seedShade))
13
+ out.push(`primary lands on ${now.seedShade ?? 500}`);
14
+ if (!same(before.neutralSeedShade, now.neutralSeedShade))
15
+ out.push(`neutral lands on ${now.neutralSeedShade ?? 500}`);
16
+ const was = new Map((before.additionalColors ?? []).map((c) => [c.name, c]));
17
+ const is = new Map((now.additionalColors ?? []).map((c) => [c.name, c]));
18
+ for (const [name, c] of is) {
19
+ const old = was.get(name);
20
+ if (!old)
21
+ out.push(`${name} ${c.color} added`);
22
+ else if (!same(old, c))
23
+ out.push(`${name} ${old.color === c.color ? `lands on ${c.seedShade ?? 500}` : `${old.color} → ${c.color}`}`);
24
+ }
25
+ for (const name of was.keys())
26
+ if (!is.has(name))
27
+ out.push(`${name} removed`);
28
+ for (const k of ["contrastAlgorithm", "contrastTarget", "lightnessStrategy", "foreground"]) {
29
+ if (!same(before[k], now[k]))
30
+ out.push(`${k.replace(/([A-Z])/g, " $1").toLowerCase()} ${now[k] ?? "default"}`);
31
+ }
32
+ if (!same(before.lightnessRange?.light, now.lightnessRange?.light))
33
+ out.push(`lightest ${pct(before.lightnessRange?.light, LIGHT_END)} → ${pct(now.lightnessRange?.light, LIGHT_END)}`);
34
+ if (!same(before.lightnessRange?.dark, now.lightnessRange?.dark))
35
+ out.push(`darkest ${pct(before.lightnessRange?.dark, DARK_END)} → ${pct(now.lightnessRange?.dark, DARK_END)}`);
36
+ if (!same(before.tintFloor, now.tintFloor))
37
+ out.push(`tint floor ${Math.round((now.tintFloor ?? 0) * 100)}%`);
38
+ if (!same(before.chroma, now.chroma))
39
+ out.push(`colourfulness ${now.chroma?.profile ?? "follow"}${now.chroma?.strength && now.chroma.strength !== 1 ? ` ×${now.chroma.strength.toFixed(2)}` : ""}`);
40
+ if (!same(before.hueDrift, now.hueDrift))
41
+ out.push(`hue in the darks ${typeof now.hueDrift === "number" ? `turns ${now.hueDrift}°` : (now.hueDrift ?? "holds")}`);
42
+ const names = new Set([...Object.keys(before.families ?? {}), ...Object.keys(now.families ?? {})]);
43
+ const WORDS = { lightnessRange: "range", tintFloor: "tint floor", chroma: "colourfulness", hueDrift: "hue in the darks" };
44
+ for (const name of names) {
45
+ if (same(before.families?.[name], now.families?.[name]))
46
+ continue;
47
+ const own = now.families?.[name];
48
+ out.push(own ? `${name} ramp's own ${Object.keys(own).map((k) => WORDS[k] ?? k).join(", ")}` : `${name} ramp matches all ramps again`);
49
+ }
50
+ const pinned = new Set([...Object.keys(before.pins ?? {}), ...Object.keys(now.pins ?? {})]);
51
+ for (const name of pinned) {
52
+ const a = before.pins?.[name] ?? {};
53
+ const b = now.pins?.[name] ?? {};
54
+ for (const step of new Set([...Object.keys(a), ...Object.keys(b)])) {
55
+ const x = a[step];
56
+ const y = b[step];
57
+ if (x !== y)
58
+ out.push(y ? `${name} ${step} set to ${y}` : `${name} ${step} back to the generated colour`);
59
+ }
60
+ }
61
+ const roles = new Set([...Object.keys(before.shadeOverrides ?? {}), ...Object.keys(now.shadeOverrides ?? {})]);
62
+ for (const name of roles) {
63
+ for (const mode of ["light", "dark"]) {
64
+ const a = before.shadeOverrides?.[name]?.[mode] ?? {};
65
+ const b = now.shadeOverrides?.[name]?.[mode] ?? {};
66
+ for (const role of new Set([...Object.keys(a), ...Object.keys(b)])) {
67
+ const x = a[role];
68
+ const y = b[role];
69
+ const what = role === "DEFAULT" ? "fill" : role;
70
+ if (x !== y)
71
+ out.push(y !== undefined ? `${name} ${what} on ${y} in ${mode}` : `${name} ${what} back to the generator's choice in ${mode}`);
72
+ }
73
+ }
74
+ }
75
+ return out;
76
+ }
77
+ /** Where a link carries a seed: the page's hash, so nothing reaches the server. */
78
+ export const LINK_HASH = "designtools-colours";
79
+ export function seedFromHash(hash) {
80
+ const m = new RegExp(`${LINK_HASH}=([^&]+)`).exec(hash);
81
+ if (!m)
82
+ return null;
83
+ try {
84
+ const bytes = Uint8Array.from(atob(m[1].replace(/-/g, "+").replace(/_/g, "/")), (c) => c.charCodeAt(0));
85
+ const json = new TextDecoder().decode(bytes);
86
+ const seed = JSON.parse(json);
87
+ return seed && typeof seed === "object" ? seed : null;
88
+ }
89
+ catch {
90
+ return null;
91
+ }
92
+ }
93
+ /** This page's address carrying a seed. */
94
+ export function linkFor(seed) {
95
+ const bytes = new TextEncoder().encode(JSON.stringify(seed));
96
+ const packed = btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
97
+ return `${location.origin}${location.pathname}#${LINK_HASH}=${packed}`;
98
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Copy text from a click. The clipboard API exists only on secure pages (https, localhost), so a
3
+ * dev server opened by its network address on a phone has none; there, and wherever the API
4
+ * refuses, copy the old way, from a hidden selection. Start it in the click itself: browsers only
5
+ * copy inside the gesture, and iOS only from an editable selection.
6
+ */
7
+ export declare function copyText(text: string): Promise<void>;
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Copy text from a click. The clipboard API exists only on secure pages (https, localhost), so a
3
+ * dev server opened by its network address on a phone has none; there, and wherever the API
4
+ * refuses, copy the old way, from a hidden selection. Start it in the click itself: browsers only
5
+ * copy inside the gesture, and iOS only from an editable selection.
6
+ */
7
+ export async function copyText(text) {
8
+ if (typeof navigator !== "undefined" && navigator.clipboard && window.isSecureContext) {
9
+ try {
10
+ await navigator.clipboard.writeText(text);
11
+ return;
12
+ }
13
+ catch {
14
+ // refused: try the old way below
15
+ }
16
+ }
17
+ const area = document.createElement("textarea");
18
+ area.value = text;
19
+ area.contentEditable = "true";
20
+ area.style.cssText = "position:fixed;top:0;left:0;width:1px;height:1px;opacity:0;pointer-events:none;font-size:16px";
21
+ document.body.appendChild(area);
22
+ const range = document.createRange();
23
+ range.selectNodeContents(area);
24
+ const selection = window.getSelection();
25
+ selection?.removeAllRanges();
26
+ selection?.addRange(range);
27
+ area.setSelectionRange(0, text.length);
28
+ const copied = document.execCommand("copy");
29
+ area.remove();
30
+ selection?.removeAllRanges();
31
+ if (!copied)
32
+ throw new Error("The browser refused to copy");
33
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * The colour editor's controls, each an input to the generator, never a colour written by hand
3
+ * (pins aside, the one control that takes a colour): the shape of the ramps for the whole system and
4
+ * for one family, pins, the step contract, a ramp before and after, what changed, a link carrying the
5
+ * settings, and saved versions.
6
+ */
7
+ import { type SeedFile, type ShadeNumber, type TokenSystem } from "@designtools/tokens";
8
+ export type Edit = {
9
+ seed: SeedFile;
10
+ set: (patch: Partial<SeedFile>) => void;
11
+ system: TokenSystem | null;
12
+ /** The project's own system, from its seed: what "before" means. */
13
+ base: TokenSystem | null;
14
+ baseSeed: SeedFile;
15
+ /** Why the current settings can't be generated (a refused pin), if they can't. */
16
+ error: string | null;
17
+ };
18
+ /** A full-width action in a popover: big enough to hit on a phone. */
19
+ export declare const ACTION = "inline-flex h-8 shrink-0 cursor-pointer items-center justify-center gap-1.5 self-start rounded-md bg-muted px-3 text-[12px] font-medium text-ink transition-colors hover:bg-scrim disabled:cursor-not-allowed disabled:opacity-40 outline-none focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-sel";
20
+ /** What a control means, on hover or focus, instead of a paragraph under it. */
21
+ export declare function Hint({ text }: {
22
+ text: string;
23
+ }): import("react").JSX.Element;
24
+ declare const title: (s: string) => string;
25
+ /** Every colour ramp's shape, for the whole system. */
26
+ export declare function SystemShape({ edit }: {
27
+ edit: Edit;
28
+ }): import("react").JSX.Element;
29
+ /** One family's shape: the system's, until it leans away; every difference is listed in the settings. */
30
+ export declare function FamilyShapeControls({ family, edit }: {
31
+ family: string;
32
+ edit: Edit;
33
+ }): import("react").JSX.Element;
34
+ /** Exact colours on given steps of one family; the ramp bends through them. */
35
+ export declare function Pins({ family, anchor, edit }: {
36
+ family: string;
37
+ anchor: ShadeNumber;
38
+ edit: Edit;
39
+ }): import("react").JSX.Element;
40
+ /** One family's ramp now, over the project's own, to see what moved. */
41
+ export declare function Compare({ family, edit }: {
42
+ family: string;
43
+ edit: Edit;
44
+ }): import("react").JSX.Element | null;
45
+ /** The changes, listed, so drift is visible: every family that leans away shows here. */
46
+ export declare function Changes({ edit }: {
47
+ edit: Edit;
48
+ }): import("react").JSX.Element | null;
49
+ /** Named versions of the settings, kept in this browser, to compare before handing one back. */
50
+ export declare function Versions({ edit }: {
51
+ edit: Edit;
52
+ }): import("react").JSX.Element;
53
+ export { title };
54
+ export { describeChanges, seedFromHash } from "./changes.js";
@@ -0,0 +1,199 @@
1
+ "use client";
2
+ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
3
+ /**
4
+ * The colour editor's controls, each an input to the generator, never a colour written by hand
5
+ * (pins aside, the one control that takes a colour): the shape of the ramps for the whole system and
6
+ * for one family, pins, the step contract, a ramp before and after, what changed, a link carrying the
7
+ * settings, and saved versions.
8
+ */
9
+ import { VALID_SHADES, } from "@designtools/tokens";
10
+ import { ColorInput, Field, readStored, Segmented, Select, Slider, subscribeStored, Tip, writeStored } from "@designtools/widgets";
11
+ import { Check, CircleHelp, Link2, Pin, Plus, Trash2 } from "lucide-react";
12
+ import { useCallback, useState, useSyncExternalStore } from "react";
13
+ import { describeChanges, linkFor } from "./changes.js";
14
+ import { copyText } from "./clipboard.js";
15
+ const LIGHT_END = 98;
16
+ const DARK_END = 15;
17
+ /** The command line refuses ends closer than this, so the steps can be told apart. */
18
+ const MIN_SPAN = 30;
19
+ const SHADE_OPTIONS = VALID_SHADES.map((s) => ({ value: String(s), label: String(s) }));
20
+ const LABEL = "text-[10px] font-semibold tracking-wide text-ink3 uppercase";
21
+ /** A full-width action in a popover: big enough to hit on a phone. */
22
+ export const ACTION = "inline-flex h-8 shrink-0 cursor-pointer items-center justify-center gap-1.5 self-start rounded-md bg-muted px-3 text-[12px] font-medium text-ink transition-colors hover:bg-scrim disabled:cursor-not-allowed disabled:opacity-40 outline-none focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-sel";
23
+ /** What a control means, on hover or focus, instead of a paragraph under it. */
24
+ export function Hint({ text }) {
25
+ return (_jsx(Tip, { content: text, children: _jsx("span", { tabIndex: 0, "aria-label": text, className: "inline-flex cursor-help rounded-full text-ink3 outline-none hover:text-ink focus-visible:outline-2 focus-visible:outline-sel", children: _jsx(CircleHelp, { "aria-hidden": true, width: 11, height: 11 }) }) }));
26
+ }
27
+ const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
28
+ const title = (s) => s.charAt(0).toUpperCase() + s.slice(1);
29
+ const systemShape = (seed) => ({
30
+ light: seed.lightnessRange?.light ?? LIGHT_END,
31
+ dark: seed.lightnessRange?.dark ?? DARK_END,
32
+ tintFloor: seed.tintFloor ?? 0,
33
+ profile: seed.chroma?.profile ?? "follow",
34
+ strength: seed.chroma?.strength ?? 1,
35
+ peakAt: seed.chroma?.peakAt,
36
+ hueDrift: seed.hueDrift ?? "none",
37
+ });
38
+ /** The system's shape as seed fields: anything at its default left out, so the hand-back carries only what changed. */
39
+ function systemPatch(s) {
40
+ const range = {};
41
+ if (s.light !== LIGHT_END)
42
+ range.light = s.light;
43
+ if (s.dark !== DARK_END)
44
+ range.dark = s.dark;
45
+ const chroma = {};
46
+ if (s.profile !== "follow")
47
+ chroma.profile = s.profile;
48
+ if (s.strength !== 1)
49
+ chroma.strength = s.strength;
50
+ if (s.profile === "peak" && s.peakAt !== undefined)
51
+ chroma.peakAt = s.peakAt;
52
+ return {
53
+ lightnessRange: Object.keys(range).length ? range : undefined,
54
+ tintFloor: s.tintFloor ? s.tintFloor : undefined,
55
+ chroma: Object.keys(chroma).length ? chroma : undefined,
56
+ hueDrift: s.hueDrift === "none" ? undefined : s.hueDrift,
57
+ };
58
+ }
59
+ /** The controls for a ramp's shape: the range, the tint floor, colourfulness and hue drift. */
60
+ function ShapeFields({ shape, change }) {
61
+ const drift = typeof shape.hueDrift === "number" ? "degrees" : shape.hueDrift;
62
+ return (_jsxs(_Fragment, { children: [_jsx(Field, { label: "Lightest", actions: _jsx(Hint, { text: "How light the palest step is, as OKLCH lightness." }), children: (id) => _jsx(Slider, { labelledBy: id, value: shape.light, min: 80, max: 100, step: 0.5, unit: "%", onChange: (v) => change({ ...shape, light: v, dark: Math.min(shape.dark, v - MIN_SPAN) }) }) }), _jsx(Field, { label: "Darkest", actions: _jsx(Hint, { text: "How deep the darkest step goes. Raise it for soft deep tones; the steps keep a gap." }), children: (id) => _jsx(Slider, { labelledBy: id, value: shape.dark, min: 0, max: 60, step: 1, unit: "%", onChange: (v) => change({ ...shape, dark: v, light: Math.max(shape.light, v + MIN_SPAN) }) }) }), _jsx(Field, { label: "Tint floor", actions: _jsx(Hint, { text: "How much colour the pale steps keep, as far as a screen can show it. Matters most for muted colours." }), children: (id) => (_jsx(Slider, { labelledBy: id, value: Math.round(shape.tintFloor * 100), min: 0, max: 100, step: 5, format: (v) => (v === 0 ? "None" : `${v}%`), onChange: (v) => change({ ...shape, tintFloor: v / 100 }) })) }), _jsx(Field, { label: "Colourfulness", actions: _jsx(Hint, { text: "Follow eases from pale tints to the seed's colour. Constant holds it throughout. Relative keeps the seed's share of what each step can hold. Peak is strongest at one step." }), children: (id) => (_jsx(Segmented, { labelledBy: id, value: shape.profile, onChange: (v) => change({ ...shape, profile: v }), options: [
63
+ { value: "follow", label: "Follow" },
64
+ { value: "constant", label: "Constant" },
65
+ { value: "relative", label: "Relative" },
66
+ { value: "peak", label: "Peak" },
67
+ ] })) }), shape.profile === "peak" && (_jsx(Field, { label: "Peaks at", children: (id) => _jsx(Select, { labelledBy: id, value: String(shape.peakAt ?? 500), options: SHADE_OPTIONS, onChange: (v) => change({ ...shape, peakAt: Number(v) }) }) })), _jsx(Field, { label: "Strength", actions: _jsx(Hint, { text: "More or less colour than the seed's. The seed's own step never moves." }), children: (id) => _jsx(Slider, { labelledBy: id, value: Math.round(shape.strength * 100), min: 25, max: 300, step: 5, format: (v) => `×${(v / 100).toFixed(2)}`, onChange: (v) => change({ ...shape, strength: v / 100 }) }) }), _jsx(Field, { label: "Hue in the darks", actions: _jsx(Hint, { text: "Natural turns yellows towards amber and blues towards indigo as they darken, as hand-tuned ramps do." }), children: (id) => (_jsx(Segmented, { labelledBy: id, value: drift, onChange: (v) => change({ ...shape, hueDrift: v === "degrees" ? 10 : v }), options: [
68
+ { value: "none", label: "Holds" },
69
+ { value: "natural", label: "Natural" },
70
+ { value: "degrees", label: "Turn" },
71
+ ] })) }), typeof shape.hueDrift === "number" && (_jsx(Field, { label: "Turns by", children: (id) => _jsx(Slider, { labelledBy: id, value: shape.hueDrift, min: -45, max: 45, step: 1, unit: "\u00B0", onChange: (v) => change({ ...shape, hueDrift: v }) }) }))] }));
72
+ }
73
+ /** Every colour ramp's shape, for the whole system. */
74
+ export function SystemShape({ edit }) {
75
+ return (_jsxs(_Fragment, { children: [_jsxs("p", { className: `flex items-center gap-1.5 pt-1 ${LABEL}`, children: ["All ramps ", _jsx(Hint, { text: "Settings every colour ramp shares. The neutral isn't included, since both modes' backgrounds are made from it; change it on its own ramp." })] }), _jsx(ShapeFields, { shape: systemShape(edit.seed), change: (next) => edit.set(systemPatch(next)) })] }));
76
+ }
77
+ /** One family's shape: the system's, until it leans away; every difference is listed in the settings. */
78
+ export function FamilyShapeControls({ family, edit }) {
79
+ const { seed, set } = edit;
80
+ const own = seed.families?.[family];
81
+ const sys = family === "neutral" ? systemShape({}) : systemShape(seed);
82
+ const shape = {
83
+ light: own?.lightnessRange?.light ?? sys.light,
84
+ dark: own?.lightnessRange?.dark ?? sys.dark,
85
+ tintFloor: own?.tintFloor ?? sys.tintFloor,
86
+ profile: own?.chroma?.profile ?? sys.profile,
87
+ strength: own?.chroma?.strength ?? sys.strength,
88
+ peakAt: own?.chroma?.peakAt ?? sys.peakAt,
89
+ hueDrift: own?.hueDrift ?? sys.hueDrift,
90
+ };
91
+ const change = (next) => {
92
+ // keep only what differs from the system's shape
93
+ const diff = {};
94
+ const range = {};
95
+ if (next.light !== sys.light)
96
+ range.light = next.light;
97
+ if (next.dark !== sys.dark)
98
+ range.dark = next.dark;
99
+ if (Object.keys(range).length)
100
+ diff.lightnessRange = range;
101
+ if (next.tintFloor !== sys.tintFloor)
102
+ diff.tintFloor = next.tintFloor;
103
+ const chroma = {};
104
+ if (next.profile !== sys.profile)
105
+ chroma.profile = next.profile;
106
+ if (next.strength !== sys.strength)
107
+ chroma.strength = next.strength;
108
+ if (next.profile === "peak" && next.peakAt !== sys.peakAt)
109
+ chroma.peakAt = next.peakAt;
110
+ if (Object.keys(chroma).length)
111
+ diff.chroma = chroma;
112
+ if (next.hueDrift !== sys.hueDrift)
113
+ diff.hueDrift = next.hueDrift;
114
+ const families = { ...seed.families };
115
+ if (Object.keys(diff).length)
116
+ families[family] = diff;
117
+ else
118
+ delete families[family];
119
+ set({ families: Object.keys(families).length ? families : undefined });
120
+ };
121
+ return (_jsxs(_Fragment, { children: [_jsxs("div", { className: "flex items-center justify-between", children: [_jsxs("p", { className: `flex items-center gap-1.5 ${LABEL}`, children: ["This ramp ", _jsx(Hint, { text: "Starts from the settings for all ramps. Change one here and it applies to this ramp only." })] }), own && (_jsx("button", { type: "button", onClick: () => change(sys), className: "cursor-pointer rounded-sm px-1 text-[10px] text-ink3 hover:text-ink", children: "Match all ramps" }))] }), _jsx(ShapeFields, { shape: shape, change: change })] }));
122
+ }
123
+ /* ---------------------------------------------------------------------------------------------- */
124
+ /* Pins */
125
+ /** Exact colours on given steps of one family; the ramp bends through them. */
126
+ export function Pins({ family, anchor, edit }) {
127
+ const { seed, set, system } = edit;
128
+ const pins = seed.pins?.[family] ?? {};
129
+ const steps = Object.keys(pins).map(Number);
130
+ const scale = system?.primitives[family];
131
+ const write = (next) => {
132
+ const all = { ...seed.pins };
133
+ if (Object.keys(next).length)
134
+ all[family] = next;
135
+ else
136
+ delete all[family];
137
+ set({ pins: Object.keys(all).length ? all : undefined });
138
+ };
139
+ const free = VALID_SHADES.filter((s) => s !== anchor && !steps.includes(s));
140
+ const add = () => {
141
+ const step = free.find((s) => s > anchor) ?? free[0];
142
+ if (step !== undefined)
143
+ write({ ...pins, [step]: scale?.[String(step)] ?? "#808080" });
144
+ };
145
+ return (_jsxs(_Fragment, { children: [_jsxs("p", { className: `flex items-center gap-1.5 ${LABEL}`, children: ["Exact colours", " ", _jsx(Hint, { text: "Use an exact colour for one step instead of the generated one, a print match say. The steps around it adjust so the ramp still runs light to dark; a colour that can't fit, or can't be shown on screen, is refused with the reason." })] }), steps.map((step) => (_jsxs("div", { className: "flex items-end gap-1.5", children: [_jsx("div", { className: "w-[84px] shrink-0", children: _jsx(Select, { label: "Step", value: String(step), options: SHADE_OPTIONS.filter((o) => Number(o.value) === step || free.includes(Number(o.value))), onChange: (v) => {
146
+ const { [step]: colour, ...rest } = pins;
147
+ write({ ...rest, [Number(v)]: colour });
148
+ } }) }), _jsx("div", { className: "min-w-0 flex-1", children: _jsx(ColorInput, { label: `${family} ${step}`, value: pins[step] ?? "", onChange: (c) => write({ ...pins, [step]: c }) }) }), _jsx("button", { type: "button", "aria-label": `Back to the generated colour on ${step}`, onClick: () => {
149
+ const { [step]: _, ...rest } = pins;
150
+ write(rest);
151
+ }, className: "flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-md text-ink3 hover:bg-scrim hover:text-ink", children: _jsx(Trash2, { "aria-hidden": true, width: 14, height: 14 }) })] }, step))), _jsxs("button", { type: "button", onClick: add, disabled: !free.length, className: ACTION, children: [_jsx(Pin, { "aria-hidden": true, width: 13, height: 13 }), " Use an exact colour for a step"] })] }));
152
+ }
153
+ /* ---------------------------------------------------------------------------------------------- */
154
+ /* A ramp before and after, the step contract, what changed */
155
+ /** One family's ramp now, over the project's own, to see what moved. */
156
+ export function Compare({ family, edit }) {
157
+ const now = edit.system?.primitives[family];
158
+ const before = edit.base?.primitives[family];
159
+ if (!now)
160
+ return null;
161
+ const row = (scale, label) => (_jsxs("div", { className: "flex items-center gap-2", children: [_jsx("span", { className: "w-10 shrink-0 text-[9px] text-ink3", children: label }), _jsx("span", { className: "grid flex-1 grid-cols-12", children: VALID_SHADES.map((s) => (_jsx("span", { title: scale ? `${s}: ${scale[String(s)]}` : undefined, className: "h-4", style: { background: scale?.[String(s)] ?? "transparent" } }, s))) })] }));
162
+ return (_jsxs("div", { className: "flex flex-col gap-1", children: [row(now, "Now"), before ? row(before, "Before") : _jsx("p", { className: "text-[10px] text-ink3", children: "New: not in the project yet." })] }));
163
+ }
164
+ /** The changes, listed, so drift is visible: every family that leans away shows here. */
165
+ export function Changes({ edit }) {
166
+ const list = describeChanges(edit.baseSeed, edit.seed);
167
+ if (!list.length)
168
+ return null;
169
+ return (_jsxs("div", { className: "flex flex-col gap-1", children: [_jsx("p", { className: LABEL, children: "Changed" }), _jsx("ul", { className: "flex flex-col gap-0.5 text-[10px] leading-snug text-ink2", children: list.map((c) => (_jsx("li", { children: c }, c))) })] }));
170
+ }
171
+ /* ---------------------------------------------------------------------------------------------- */
172
+ /* Sharing and versions */
173
+ const VERSIONS_KEY = "studio:versions";
174
+ const NONE = [];
175
+ /** Named versions of the settings, kept in this browser, to compare before handing one back. */
176
+ export function Versions({ edit }) {
177
+ const versions = useSyncExternalStore(useCallback((cb) => subscribeStored((k) => k === VERSIONS_KEY && cb()), []), () => readStored(VERSIONS_KEY, NONE), () => NONE);
178
+ const save = () => writeStored(VERSIONS_KEY, [...versions, { name: `Version ${versions.length + 1}`, seed: edit.seed, at: Date.now() }]);
179
+ // a version's link: copied, or shown to copy by hand when the clipboard refuses
180
+ const [linked, setLinked] = useState(null);
181
+ const copyLink = async (v) => {
182
+ const url = linkFor(v.seed);
183
+ try {
184
+ await copyText(url);
185
+ setLinked({ at: v.at });
186
+ setTimeout(() => setLinked((l) => (l?.at === v.at && !l.url ? null : l)), 1500);
187
+ }
188
+ catch {
189
+ setLinked({ at: v.at, url });
190
+ }
191
+ };
192
+ const drop = (i) => {
193
+ const next = versions.filter((_, j) => j !== i);
194
+ writeStored(VERSIONS_KEY, next.length ? next : undefined);
195
+ };
196
+ return (_jsxs("div", { className: "flex flex-col gap-1.5", children: [_jsxs("p", { className: `flex items-center gap-1.5 ${LABEL}`, children: ["Versions ", _jsx(Hint, { text: "Kept in this browser, to compare before handing one back. Each has a link that opens this page with it, for someone else to see." })] }), versions.map((v, i) => (_jsxs("div", { className: "flex flex-col gap-1", children: [_jsxs("div", { className: "flex items-center gap-1.5 text-[11px]", children: [_jsx("span", { className: "min-w-0 flex-1 truncate text-ink", children: v.name }), _jsx("span", { className: "text-[10px] text-ink3", children: plural(describeChanges(edit.baseSeed, v.seed).length, "change") }), _jsx("button", { type: "button", onClick: () => edit.set({ ...v.seed }), className: "flex h-7 cursor-pointer items-center rounded-md px-2 text-[11px] text-ink2 hover:bg-scrim hover:text-ink", children: "Show" }), _jsx(Tip, { content: linked?.at === v.at && !linked.url ? "Link copied" : `Copy a link that opens this page with ${v.name}`, children: _jsx("button", { type: "button", "aria-label": `Copy a link to ${v.name}`, onClick: () => copyLink(v), className: "flex size-7 cursor-pointer items-center justify-center rounded-md text-ink3 hover:bg-scrim hover:text-ink", children: linked?.at === v.at && !linked.url ? _jsx(Check, { "aria-hidden": true, width: 13, height: 13 }) : _jsx(Link2, { "aria-hidden": true, width: 13, height: 13 }) }) }), _jsx("button", { type: "button", "aria-label": `Delete ${v.name}`, onClick: () => drop(i), className: "flex size-7 cursor-pointer items-center justify-center rounded-md text-ink3 hover:bg-scrim hover:text-ink", children: _jsx(Trash2, { "aria-hidden": true, width: 13, height: 13 }) })] }), linked?.at === v.at && linked.url && (_jsx("textarea", { readOnly: true, value: linked.url, onFocus: (e) => e.currentTarget.select(), className: "h-14 w-full resize-none rounded-md bg-muted p-2 font-mono text-[10px] text-ink2" }))] }, v.at))), _jsxs("button", { type: "button", onClick: save, className: ACTION, children: [_jsx(Plus, { "aria-hidden": true, width: 13, height: 13 }), " Save as a version"] })] }));
197
+ }
198
+ export { title };
199
+ export { describeChanges, seedFromHash } from "./changes.js";