@designtools/tokens 0.9.0 → 0.11.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,10 +1,11 @@
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 { Plus, RotateCcw, X } 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
10
  /** The seed the studio and the colour generator apply to the page, in every frame. */
10
11
  export const STUDIO_KEY = "studio:seed";
@@ -52,7 +53,6 @@ export function useApplySeed() {
52
53
  return subscribeStored((k) => k === KEY && apply());
53
54
  }, [enabled]);
54
55
  }
55
- const SHADES = VALID_SHADES.map((s) => ({ value: String(s), label: String(s) }));
56
56
  /** What fails at the target, in each mode, worst first. */
57
57
  function failures(system, target) {
58
58
  const need = (r) => (target === "aaa" ? r.passesAAA : target === "aa-large" ? r.ratio >= 3 : r.passesAA);
@@ -85,32 +85,56 @@ function Score({ system, seed }) {
85
85
  const label = `${algorithm === "apca" ? "APCA" : "WCAG"} ${target === "aa-large" ? "AA large" : target.toUpperCase()}`;
86
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"] })] }))] }));
87
87
  }
88
- const STATUS = ["success", "destructive", "warning"];
89
- const NAME = /^[a-z][a-z0-9-]*$/;
90
88
  /**
91
- * The colour generator, as a tool in the dock: the brand colours first (primary, neutral, any added),
92
- * then how it generates, with the score. Every change re-themes the page and every artboard at once;
93
- * Copy prompt hands back the seed and the command, so the generator stays the source.
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.
94
92
  */
95
93
  function Colour({ project }) {
96
94
  useApplySeed();
97
95
  const stored = useStoredSeed();
98
96
  const seed = stored ?? project.seed;
99
97
  const set = (patch) => writeStored(KEY, { ...seed, ...patch });
100
- 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(() => {
101
101
  try {
102
- return generateFromSeed(seed);
102
+ return generateFromSeed(project.seed);
103
103
  }
104
104
  catch {
105
105
  return null;
106
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
+ }
107
115
  }, [seed]);
108
- const apca = isAPCAAvailable();
109
- useHandback("Colour generator", () => {
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 = () => {
110
133
  if (!stored)
111
134
  return null;
112
135
  return [
113
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("; ")}.`] : []),
114
138
  `1. Save this as ${project.seedPath}:`,
115
139
  "",
116
140
  "```json",
@@ -120,28 +144,10 @@ function Colour({ project }) {
120
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 })}`,
121
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.",
122
146
  ].join("\n");
123
- });
124
- const colours = seed.additionalColors ?? [];
125
- const setColours = (next) => set({ additionalColors: next.length ? next : undefined });
126
- const addColour = () => {
127
- const taken = new Set(["primary", "neutral", ...STATUS, ...colours.map((c) => c.name)]);
128
- const name = ["accent", "info", "highlight", "brand", "extra"].find((n) => !taken.has(n)) ?? `colour-${colours.length + 1}`;
129
- setColours([...colours, { name, color: "#8b5cf6" }]);
130
147
  };
131
- return (_jsxs(Tool, { name: "Colour generator", scope: "tokens", alone: true, onReset: () => writeStored(KEY, undefined), changes: () => (readStored(KEY, null) ? 1 : 0), styles: STYLES, children: [system ? _jsx(Score, { system: system, seed: seed }) : _jsx("p", { className: "text-[11px] text-fail", children: "That colour can't be read yet: finish typing it." }), _jsx("p", { className: "text-[10px] font-semibold tracking-wide text-ink3 uppercase", children: "Colours" }), _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.map((c, i) => (_jsxs("div", { className: "flex items-end gap-1.5", children: [_jsxs("div", { className: "min-w-0 flex-1", children: [_jsx("label", { className: "mb-1 block text-[9px] text-ink3", htmlFor: `colour-name-${i}`, children: "Name" }), _jsx("input", { id: `colour-name-${i}`, value: c.name, spellCheck: false, "aria-invalid": !NAME.test(c.name), onChange: (e) => setColours(colours.map((x, j) => (j === i ? { ...x, name: e.target.value.toLowerCase().replace(/\s+/g, "-") } : x))), className: `h-7 w-full rounded-md bg-muted px-2 font-mono text-[11px] text-ink outline-none focus-visible:ring-1 focus-visible:ring-sel ${NAME.test(c.name) ? "" : "ring-1 ring-fail"}` })] }), _jsx("div", { className: "w-[140px] shrink-0", children: _jsx(ColorInput, { label: `${c.name} colour`, value: c.color, onChange: (color) => setColours(colours.map((x, j) => (j === i ? { ...x, color } : x))) }) }), _jsx("button", { type: "button", "aria-label": `Remove ${c.name}`, onClick: () => setColours(colours.filter((_, j) => j !== i)), className: "flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-md text-ink3 hover:bg-scrim hover:text-ink", children: _jsx(X, { "aria-hidden": true, width: 13, height: 13 }) })] }, i))), _jsxs("button", { type: "button", onClick: addColour, className: "flex h-7 cursor-pointer items-center justify-center gap-1.5 rounded-md border border-dashed border-edge text-[11px] text-ink2 hover:bg-scrim hover:text-ink", children: [_jsx(Plus, { "aria-hidden": true, width: 12, height: 12 }), " Add a colour"] }), _jsx("p", { className: "text-[10px] font-semibold tracking-wide text-ink3 uppercase", children: "How it generates" }), _jsx(Field, { label: "Contrast", children: (id) => (_jsx(Segmented, { labelledBy: id, value: seed.contrastAlgorithm ?? "wcag", onChange: (v) => set({ contrastAlgorithm: v }), options: [
132
- { value: "wcag", label: "WCAG 2" },
133
- ...(apca ? [{ value: "apca", label: "APCA" }] : []),
134
- ] })) }), _jsx(Field, { label: "Target", children: (id) => (_jsx(Segmented, { labelledBy: id, value: seed.contrastTarget ?? "aa", onChange: (v) => set({ contrastTarget: v }), options: [
135
- { value: "aa-large", label: "AA large" },
136
- { value: "aa", label: "AA" },
137
- { value: "aaa", label: "AAA" },
138
- ] })) }), _jsxs(Row, { children: [_jsx(Field, { label: "Lightness", children: (id) => (_jsx(Segmented, { labelledBy: id, value: seed.lightnessStrategy ?? "fixed", onChange: (v) => set({ lightnessStrategy: v }), options: [
139
- { value: "fixed", label: "Fixed" },
140
- { value: "perceptual", label: "Even" },
141
- ] })) }), _jsx(Field, { label: "Labels on fills", children: (id) => (_jsx(Segmented, { labelledBy: id, value: seed.foreground ?? "balanced", onChange: (v) => set({ foreground: v }), options: [
142
- { value: "balanced", label: "Balanced" },
143
- { value: "max", label: "Strongest" },
144
- ] })) })] }), _jsx(Field, { label: "Primary lands on step", children: (id) => _jsx(Select, { labelledBy: id, value: String(seed.seedShade ?? 500), options: SHADES, onChange: (v) => set({ seedShade: Number(v) }) }) }), _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"] }))] })] }));
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." }) }));
145
151
  }
146
152
  const RATIOS = [
147
153
  { value: "1.067", label: "Minor second, 1.067" },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@designtools/tokens",
3
- "version": "0.9.0",
3
+ "version": "0.11.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",
@@ -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.3"
89
+ "@designtools/widgets": "0.1.5"
90
90
  },
91
91
  "keywords": [
92
92
  "design-tokens",