@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.
@@ -1,12 +1,15 @@
1
1
  "use client";
2
2
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
- import { computeAccessibilityScore, checkSemanticContrast, isAPCAAvailable, VALID_SHADES, } from "@designtools/tokens";
4
- import { ColorInput, Field, NumberScrub, readStored, Row, Segmented, Select, stepsFor, subscribeStored, TOKENS_KEY, Tool, TokenControl, useHandback, useSystemTokens, useToolsEnabled, writeStored, } from "@designtools/widgets";
5
- import { Palette, RotateCcw } from "lucide-react";
6
- import { useCallback, useEffect, useMemo, useSyncExternalStore } from "react";
3
+ import { computeAccessibilityScore, checkSemanticContrast, } from "@designtools/tokens";
4
+ import { Field, NumberScrub, readStored, Row, Select, stepsFor, subscribeStored, TOKENS_KEY, Tool, TokenControl, useHandback, useSystemTokens, useToolsEnabled, writeStored, } from "@designtools/widgets";
5
+ import { useCallback, useEffect, useMemo, useRef, useSyncExternalStore } from "react";
7
6
  import { css, properties } from "./css.js";
7
+ import { describeChanges, seedFromHash } from "./colour-controls.js";
8
+ import { InPlaceEditor } from "./colour-editor.js";
8
9
  import { generateFromSeed, seedCommand, seedJson, studioCss } from "./seed.js";
9
- const KEY = "studio:seed";
10
+ /** The seed the studio and the colour generator apply to the page, in every frame. */
11
+ export const STUDIO_KEY = "studio:seed";
12
+ const KEY = STUDIO_KEY;
10
13
  const NONE = {};
11
14
  const STYLES = [{ id: "tokens-studio", css, properties }];
12
15
  function useStoredSeed() {
@@ -16,7 +19,7 @@ function useStoredSeed() {
16
19
  * The seed set in the studio, applied to this frame's page as the generator's own CSS, added after
17
20
  * the app's so it wins. It runs in every frame, the dock's and each artboard's, so they all re-theme.
18
21
  */
19
- function useApplySeed() {
22
+ export function useApplySeed() {
20
23
  const enabled = useToolsEnabled();
21
24
  useEffect(() => {
22
25
  if (!enabled)
@@ -25,7 +28,10 @@ function useApplySeed() {
25
28
  const seed = readStored(KEY, null);
26
29
  let tag = document.head.querySelector("style[data-designtools-studio]");
27
30
  if (!seed) {
28
- tag?.remove();
31
+ if (tag) {
32
+ tag.remove();
33
+ window.dispatchEvent(new Event("designtools:retheme"));
34
+ }
29
35
  return;
30
36
  }
31
37
  try {
@@ -40,12 +46,13 @@ function useApplySeed() {
40
46
  catch {
41
47
  // a half-typed colour: keep what was applied
42
48
  }
49
+ // anything measuring colours on the page (the docs' contrast) measures again
50
+ window.dispatchEvent(new Event("designtools:retheme"));
43
51
  };
44
52
  apply();
45
53
  return subscribeStored((k) => k === KEY && apply());
46
54
  }, [enabled]);
47
55
  }
48
- const SHADES = VALID_SHADES.map((s) => ({ value: String(s), label: String(s) }));
49
56
  /** What fails at the target, in each mode, worst first. */
50
57
  function failures(system, target) {
51
58
  const need = (r) => (target === "aaa" ? r.passesAAA : target === "aa-large" ? r.ratio >= 3 : r.passesAA);
@@ -53,6 +60,14 @@ function failures(system, target) {
53
60
  .flatMap((mode) => Object.entries(checkSemanticContrast(system.semantic[mode])).filter(([, r]) => !need(r)).map(([pair, r]) => ({ mode, pair, ratio: r.ratio })))
54
61
  .sort((a, b) => a.ratio - b.ratio);
55
62
  }
63
+ /** The score as a ring: the share of pairings that pass, coloured by how close it is to all of them. */
64
+ function Ring({ passed, total }) {
65
+ const share = total ? passed / total : 0;
66
+ const tone = share === 1 ? "text-ok" : share >= 0.8 ? "text-warn" : "text-fail";
67
+ const r = 15;
68
+ const c = 2 * Math.PI * r;
69
+ return (_jsxs("svg", { viewBox: "0 0 36 36", width: 36, height: 36, className: `shrink-0 -rotate-90 ${tone}`, "aria-hidden": true, children: [_jsx("circle", { cx: "18", cy: "18", r: r, fill: "none", stroke: "currentColor", strokeOpacity: 0.18, strokeWidth: 3 }), _jsx("circle", { cx: "18", cy: "18", r: r, fill: "none", stroke: "currentColor", strokeWidth: 3, strokeLinecap: "round", strokeDasharray: `${c * share} ${c}` })] }));
70
+ }
56
71
  function Score({ system, seed }) {
57
72
  const algorithm = seed.contrastAlgorithm ?? "wcag";
58
73
  const target = seed.contrastTarget ?? "aa";
@@ -65,54 +80,74 @@ function Score({ system, seed }) {
65
80
  }
66
81
  });
67
82
  const failing = failures(system, target);
68
- return (_jsxs("div", { className: "flex flex-col gap-2 rounded-md bg-muted p-2.5", children: [_jsxs("div", { className: "flex items-center gap-3 text-[11px]", children: [scores.map((s) => (_jsxs("span", { className: "flex items-baseline gap-1.5", children: [_jsx("span", { className: "text-ink2 capitalize", children: s.mode }), _jsxs("span", { className: `font-semibold tabular-nums ${s.passed === s.total ? "text-ok" : "text-warn"}`, children: [s.passed, "/", s.total] })] }, s.mode))), _jsxs("span", { className: "ml-auto text-[10px] text-ink3", children: ["pairs pass ", target.toUpperCase()] })] }), failing.length > 0 && (_jsxs("ul", { className: "flex flex-col gap-0.5 border-t border-edge pt-2 text-[10px]", children: [failing.slice(0, 6).map((f) => (_jsxs("li", { className: "flex justify-between gap-2 text-ink2", children: [_jsxs("span", { className: "truncate font-mono", children: [f.pair, " ", _jsxs("span", { className: "text-ink3", children: ["(", f.mode, ")"] })] }), _jsxs("span", { className: "shrink-0 tabular-nums text-fail", children: [f.ratio.toFixed(2), ":1"] })] }, `${f.mode}-${f.pair}`))), failing.length > 6 && _jsxs("li", { className: "text-ink3", children: ["and ", failing.length - 6, " more"] })] }))] }));
83
+ const passed = scores.reduce((n, s) => n + s.passed, 0);
84
+ const total = scores.reduce((n, s) => n + s.total, 0);
85
+ const label = `${algorithm === "apca" ? "APCA" : "WCAG"} ${target === "aa-large" ? "AA large" : target.toUpperCase()}`;
86
+ return (_jsxs("div", { className: "flex flex-col gap-2 rounded-md bg-muted p-2.5", children: [_jsxs("div", { className: "flex items-center gap-3", children: [_jsx(Ring, { passed: passed, total: total }), _jsxs("div", { className: "flex min-w-0 flex-1 flex-col gap-0.5", children: [_jsxs("span", { className: "text-[11px] font-semibold text-ink", children: [passed, "/", total, " pairings pass ", label] }), _jsx("span", { className: "flex gap-3 text-[10px] text-ink3", children: scores.map((s) => (_jsxs("span", { className: "capitalize tabular-nums", children: [s.mode, " ", s.passed, "/", s.total] }, s.mode))) })] })] }), failing.length > 0 && (_jsxs("ul", { className: "flex flex-col gap-0.5 border-t border-edge pt-2 text-[10px]", children: [failing.slice(0, 6).map((f) => (_jsxs("li", { className: "flex justify-between gap-2 text-ink2", children: [_jsxs("span", { className: "truncate font-mono", children: [f.pair, " ", _jsxs("span", { className: "text-ink3", children: ["(", f.mode, ")"] })] }), _jsxs("span", { className: "shrink-0 tabular-nums text-fail", children: [f.ratio.toFixed(2), ":1"] })] }, `${f.mode}-${f.pair}`))), failing.length > 6 && _jsxs("li", { className: "text-ink3", children: ["and ", failing.length - 6, " more"] })] }))] }));
69
87
  }
70
- /** The colour half: the generator's inputs, live on the page and in every artboard. */
88
+ /**
89
+ * The colour generator: edited in place on the docs' colour page (`InPlaceEditor`), applied live to
90
+ * the page and every artboard, and handed back from the dock as the seed and the command, so the
91
+ * generator stays the source.
92
+ */
71
93
  function Colour({ project }) {
72
94
  useApplySeed();
73
95
  const stored = useStoredSeed();
74
96
  const seed = stored ?? project.seed;
75
97
  const set = (patch) => writeStored(KEY, { ...seed, ...patch });
76
- const system = useMemo(() => {
98
+ const clear = () => writeStored(KEY, undefined);
99
+ // "before": the project's own colours, for the ramps' comparison and the list of changes
100
+ const base = useMemo(() => {
77
101
  try {
78
- return generateFromSeed(seed);
102
+ return generateFromSeed(project.seed);
79
103
  }
80
104
  catch {
81
105
  return null;
82
106
  }
107
+ }, [project.seed]);
108
+ const { system: generated, error } = useMemo(() => {
109
+ try {
110
+ return { system: generateFromSeed(seed), error: null };
111
+ }
112
+ catch (e) {
113
+ return { system: null, error: e.message };
114
+ }
83
115
  }, [seed]);
84
- const apca = isAPCAAvailable();
85
- useHandback("Theme colour", () => {
116
+ // while a setting is refused, the controls keep showing the last colours that could be generated, as the page does
117
+ const lastGood = useRef(generated);
118
+ if (generated)
119
+ lastGood.current = generated;
120
+ const system = generated ?? lastGood.current ?? base;
121
+ // a link carrying settings (#designtools-colours=…) opens with them, then tidies the address
122
+ useEffect(() => {
123
+ const shared = seedFromHash(location.hash);
124
+ if (!shared)
125
+ return;
126
+ writeStored(KEY, shared);
127
+ history.replaceState(null, "", location.pathname + location.search);
128
+ }, []);
129
+ // the hand-back: what changed, the seed and the command, from the main widget on the colour page
130
+ // (and in the dock's prompt too, when the dock is there for something else)
131
+ const changes = stored ? describeChanges(project.seed, stored) : [];
132
+ const handback = () => {
86
133
  if (!stored)
87
134
  return null;
88
135
  return [
89
- "Colour: the tokens are generated, so regenerate them from this seed rather than editing the generated file.",
136
+ "Colour: I tried new brand colours with the colour generator. The tokens are generated, so regenerate them from this seed rather than editing the generated file.",
137
+ ...(changes.length ? [`Changed: ${changes.join("; ")}.`] : []),
90
138
  `1. Save this as ${project.seedPath}:`,
91
139
  "",
92
140
  "```json",
93
141
  seedJson(stored),
94
142
  "```",
95
143
  "",
96
- `2. Make the${project.script ? ` "${project.script}"` : ""} script run, and run it: ${seedCommand({ seedPath: project.seedPath, output: project.output, version: project.version })}`,
97
- "3. Look at the colour page of the docs in both modes, and tell me about any pair the generator's --report flags.",
144
+ `2. ${project.script ? `Set the "${project.script}" script in package.json to this command, and run it` : "Run this"}: ${seedCommand({ seedPath: project.seedPath, output: project.output, version: project.version })}`,
145
+ "3. Run the same command with --report, tell me about any pair that misses its target, and check the colour page of the docs in both modes.",
98
146
  ].join("\n");
99
- });
100
- const colours = seed.additionalColors ?? [];
101
- const surfaces = ["canvas", "surface", "overlay"].filter((k) => seed.surfaceColors?.light?.[k] || seed.surfaceColors?.dark?.[k]);
102
- return (_jsxs(Tool, { name: "Theme colour", scope: "tokens", popover: { icon: Palette, label: "Theme colour: try new generator inputs" }, styles: STYLES, children: [_jsxs("div", { className: "flex items-center justify-between gap-2 text-[10px] text-ink3", children: [_jsx("span", { children: stored ? "Changed from the project's seed" : `From ${project.script ? `the "${project.script}" script` : "the project's seed"}` }), stored && (_jsxs("button", { type: "button", onClick: () => writeStored(KEY, undefined), className: "flex cursor-pointer items-center gap-1 rounded-sm px-1 hover:text-ink", children: [_jsx(RotateCcw, { "aria-hidden": true, width: 11, height: 11 }), " Back to the project's"] }))] }), _jsxs(Row, { children: [_jsx(Field, { label: "Primary", children: (id) => _jsx(ColorInput, { label: "Primary", labelledBy: id, value: seed.primaryColor ?? "", background: "#ffffff", onChange: (primaryColor) => set({ primaryColor }) }) }), _jsx(Field, { label: "Neutral", children: (id) => _jsx(ColorInput, { label: "Neutral", labelledBy: id, value: seed.neutralColor ?? "#737373", onChange: (neutralColor) => set({ neutralColor }) }) })] }), colours.length > 0 && (_jsx(Row, { children: colours.map((c, i) => (_jsx(Field, { label: c.decorative ? `${c.name}, decorative` : c.name, children: (id) => (_jsx(ColorInput, { label: c.name, labelledBy: id, value: c.color, onChange: (color) => set({ additionalColors: colours.map((x, j) => (j === i ? { ...x, color } : x)) }) })) }, c.name))) })), _jsx(Field, { label: "Seed lands on", children: (id) => _jsx(Select, { labelledBy: id, value: String(seed.seedShade ?? 500), options: SHADES, onChange: (v) => set({ seedShade: Number(v) }) }) }), _jsx(Field, { label: "Contrast", children: (id) => (_jsx(Segmented, { labelledBy: id, value: seed.contrastAlgorithm ?? "wcag", onChange: (v) => set({ contrastAlgorithm: v }), options: [
103
- { value: "wcag", label: "WCAG 2" },
104
- ...(apca ? [{ value: "apca", label: "APCA" }] : []),
105
- ] })) }), _jsxs(Row, { children: [_jsx(Field, { label: "Target", children: (id) => (_jsx(Segmented, { labelledBy: id, value: seed.contrastTarget ?? "aa", onChange: (v) => set({ contrastTarget: v }), options: [
106
- { value: "aa-large", label: "AA large" },
107
- { value: "aa", label: "AA" },
108
- { value: "aaa", label: "AAA" },
109
- ] })) }), _jsx(Field, { label: "Lightness", children: (id) => (_jsx(Segmented, { labelledBy: id, value: seed.lightnessStrategy ?? "fixed", onChange: (v) => set({ lightnessStrategy: v }), options: [
110
- { value: "fixed", label: "Fixed" },
111
- { value: "perceptual", label: "Even" },
112
- ] })) })] }), _jsx(Field, { label: "Labels on fills", children: (id) => (_jsx(Segmented, { labelledBy: id, value: seed.foreground ?? "balanced", onChange: (v) => set({ foreground: v }), options: [
113
- { value: "balanced", label: "Balanced" },
114
- { value: "max", label: "Strongest" },
115
- ] })) }), surfaces.map((k) => (_jsx(Row, { children: ["light", "dark"].map((mode) => (_jsx(Field, { label: `${k}, ${mode}`, children: (id) => (_jsx(ColorInput, { label: `${k}, ${mode}`, labelledBy: id, value: seed.surfaceColors?.[mode]?.[k] ?? "", onChange: (v) => set({ surfaceColors: { ...seed.surfaceColors, [mode]: { ...seed.surfaceColors?.[mode], [k]: v } } }) })) }, mode))) }, k))), Object.entries(seed.backgrounds ?? {}).map(([name, bg]) => (_jsx(Row, { children: ["light", "dark"].map((mode) => (_jsx(Field, { label: `${name}, ${mode}`, children: (id) => (_jsx(ColorInput, { label: `${name}, ${mode}`, labelledBy: id, value: (mode === "light" ? bg.light : bg.dark) ?? "", onChange: (v) => set({ backgrounds: { ...seed.backgrounds, [name]: { ...bg, [mode]: v } } }) })) }, mode))) }, name))), system ? _jsx(Score, { system: system, seed: seed }) : _jsx("p", { className: "text-[11px] text-fail", children: "That colour can't be read yet." })] }));
147
+ };
148
+ useHandback("Colour generator", handback);
149
+ // nothing in the dock: colour is edited, reset and handed back from the colour page's own widget
150
+ return (_jsx(InPlaceEditor, { edit: { seed, set, system, base, baseSeed: project.seed, error }, clear: clear, prompt: stored ? handback() : null, changes: changes.length ? changes : ["the colours"], score: system ? _jsx(Score, { system: system, seed: seed }) : _jsx("p", { className: "text-[11px] text-fail", children: "Those settings can't be generated yet." }) }));
116
151
  }
117
152
  const RATIOS = [
118
153
  { value: "1.067", label: "Minor second, 1.067" },
@@ -169,6 +204,15 @@ function Scales() {
169
204
  * both): the studio offers the scales only. The colour tool stays here, off, for when it is.
170
205
  */
171
206
  const COLOUR_EDITING = false;
207
+ /**
208
+ * The colour generator in the dock, where it's asked for: the project's seed to start from, changed by
209
+ * hand, live on the page, handed back as the seed and the command.
210
+ *
211
+ * <Widgets tokens={manifest}><ColourGenerator project={readProjectSeed()} /></Widgets>
212
+ */
213
+ export function ColourGenerator({ project }) {
214
+ return project ? _jsx(Colour, { project: project }) : null;
215
+ }
172
216
  export function TokenStudio({ project = null }) {
173
217
  return (_jsxs(_Fragment, { children: [COLOUR_EDITING && project ? _jsx(Colour, { project: project }) : null, _jsx(Scales, {})] }));
174
218
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@designtools/tokens",
3
- "version": "0.8.0",
3
+ "version": "0.10.0",
4
4
  "description": "Turn one brand colour into a complete design-token system: perceptual OKLCH ramps, contrast-checked semantic tokens (WCAG or APCA), light and dark, as CSS custom properties, Tailwind v4/v3 or DTCG. Deterministic CLI, safe for agents.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -43,7 +43,7 @@
43
43
  },
44
44
  "peerDependencies": {
45
45
  "@base-ui/react": "^1.6.0",
46
- "@designtools/widgets": "^0.1.0",
46
+ "@designtools/widgets": "^0.1.3",
47
47
  "apca-w3": "^0.1.9",
48
48
  "lucide-react": "^1.23.0",
49
49
  "react": ">=19",
@@ -86,7 +86,7 @@
86
86
  "tsx": "^4.19.0",
87
87
  "typescript": "^5.9.3",
88
88
  "vitest": "^4.1.11",
89
- "@designtools/widgets": "0.1.0"
89
+ "@designtools/widgets": "0.1.4"
90
90
  },
91
91
  "keywords": [
92
92
  "design-tokens",