@designtools/tokens 0.7.1 → 0.9.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/CHANGELOG.md CHANGED
@@ -2,6 +2,34 @@
2
2
 
3
3
  Notable changes to `@designtools/tokens`. Dates are release dates; versions follow semver, with breaking changes in the minor slot while the package is pre-1.0.
4
4
 
5
+ ## 0.9.0
6
+
7
+ ### Minor Changes
8
+
9
+ - 3a8e79f: `ColourGenerator` in `@designtools/tokens/studio`: the generator's inputs as a tool in the widgets dock. Primary and neutral first, colours to add, then contrast, target, lightness, labels on fills and the primary's step, with the score in both modes. It re-themes the page and every artboard live, and Copy prompt hands back the seed and the command to regenerate. The studio's hand-back prompt reads more clearly, and asks for `--report`.
10
+
11
+ ### Patch Changes
12
+
13
+ - Updated dependencies [3a8e79f]
14
+ - @designtools/widgets@0.1.3
15
+
16
+ ## 0.8.0
17
+
18
+ ### Minor Changes
19
+
20
+ - d4f5e45: **`@designtools/tokens/studio`: try the scales live.** A `<TokenStudio>` for the widgets dock, on the page it's put on: the hand-authored scales (a type ramp from a base and a ratio, the spacing unit, radii and shadows), live on the page and in every artboard. Copy prompt hands the changes back for `scale.css`. Colour editing isn't offered yet, while how it should work is settled; a re-theme stays a new seed and the generator. The seed helpers underneath (`parseCommand`, `optionsFromSeed`, `seedCommand`, `seedJson`, `studioCss`, and `readProjectSeed()` from `./studio/next`) are exported, and the command `seedCommand` writes regenerates a byte-identical file to the project's own.
21
+
22
+ The optional `apca-w3` import is now skipped by bundlers and treated as unavailable in a browser, so the generator runs client-side.
23
+
24
+ Widgets: tools can bring their own stylesheet and add a paragraph to the copied prompt (`useHandback`); `useSystemTokens`, `useToolsEnabled` and the store are exported.
25
+
26
+ ### Patch Changes
27
+
28
+ - Updated dependencies [0baf5e2]
29
+ - Updated dependencies [d4f5e45]
30
+ - Updated dependencies [ce32ba8]
31
+ - @designtools/widgets@0.1.0
32
+
5
33
  ## 0.7.1
6
34
 
7
35
  ### Patch Changes
package/README.md CHANGED
@@ -163,6 +163,37 @@ check: tokens.css differs — same generator and seed, so the file was edited by
163
163
  check: tokens.css differs — generated by v0.4.0, running v0.5.0. Expected after a generator upgrade.
164
164
  ```
165
165
 
166
+ ## Trying scales live: the studio
167
+
168
+ Once the tokens exist, `@designtools/tokens/studio` lets you try the hand-authored scales on the running app before writing them: a type ramp from a base and a ratio, the spacing unit, radii and shadows. It draws in the [`@designtools/widgets`](../widgets) dock, on the page you put it on, and changes the page and every [artboard](../artboards) as you go. It never writes a file: Copy prompt hands the changes back for `scale.css`.
169
+
170
+ ```bash
171
+ pnpm add -D @designtools/widgets react react-dom @base-ui/react lucide-react
172
+ ```
173
+
174
+ ```tsx
175
+ "use client"; // on the page where it was asked for, inside the app's <Widgets>
176
+ import { TokenStudio } from "@designtools/tokens/studio";
177
+
178
+ export function ScalesTool() {
179
+ return <TokenStudio />;
180
+ }
181
+ ```
182
+
183
+ ## Trying new colours: the colour generator
184
+
185
+ `ColourGenerator` is the generator's own inputs as a tool in the dock: the primary and neutral first, any colours to add (named, removable), then how it generates (contrast method and target, lightness, labels on fills, the step the primary lands on), with the score in both modes. It starts from the project's seed, re-themes the page and every artboard as you change it, and the docs' colour page follows, added colours included. Copy prompt hands back the seed and the exact command, so the generator stays the source; reset puts the project's colours back.
186
+
187
+ ```tsx
188
+ // a server component on the page it was asked for (the docs' colour page, say), inside the app's <Widgets>
189
+ import { ColourGenerator } from "@designtools/tokens/studio";
190
+ import { readProjectSeed } from "@designtools/tokens/studio/next";
191
+
192
+ <ColourGenerator project={readProjectSeed()} />
193
+ ```
194
+
195
+ On the docs, put it on the colour page with `extras: { colour: <ColourGenerator project={readProjectSeed()} /> }`.
196
+
166
197
  ## Regenerating part of a token file
167
198
 
168
199
  The problem this solves: an agent asked to "change the reds" regenerates the whole file and wipes out every hand-edit someone made to the primary.
@@ -14,9 +14,14 @@ function isMissing(error) {
14
14
  }
15
15
  var apca = null;
16
16
  try {
17
- apca = await import("apca-w3");
17
+ apca = await import(
18
+ /* webpackIgnore: true */
19
+ /* turbopackIgnore: true */
20
+ /* @vite-ignore */
21
+ APCA_PACKAGE
22
+ );
18
23
  } catch (error) {
19
- if (!isMissing(error)) throw error;
24
+ if (!isMissing(error) && typeof window === "undefined") throw error;
20
25
  }
21
26
  function isAPCAAvailable() {
22
27
  return apca !== null;
package/dist/cli.js CHANGED
@@ -33,7 +33,7 @@ import {
33
33
  tokenFamilies,
34
34
  usageReport,
35
35
  withJsonProvenance
36
- } from "./chunk-L73RTEAG.js";
36
+ } from "./chunk-P562LKFL.js";
37
37
 
38
38
  // src/cli.ts
39
39
  import { parseArgs } from "util";
package/dist/index.js CHANGED
@@ -66,7 +66,7 @@ import {
66
66
  tokenFamilies,
67
67
  usageReport,
68
68
  withJsonProvenance
69
- } from "./chunk-L73RTEAG.js";
69
+ } from "./chunk-P562LKFL.js";
70
70
  export {
71
71
  ALIAS_PAIRS,
72
72
  APCAUnavailableError,
@@ -0,0 +1,2 @@
1
+ export declare const css = "";
2
+ export declare const properties = "";
@@ -0,0 +1,2 @@
1
+ export const css = "/*! tailwindcss v4.3.3 | MIT License | https://tailwindcss.com */\n@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-border-style:solid;--tw-font-weight:initial;--tw-tracking:initial;--tw-ordinal:initial;--tw-slashed-zero:initial;--tw-numeric-figure:initial;--tw-numeric-spacing:initial;--tw-numeric-fraction:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000}}}@layer theme{:root,:host{--font-sans:ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif;--spacing:4px;--font-weight-semibold:600;--tracking-wide:.025em}}@layer utilities{.fixed{position:fixed}.mb-1{margin-bottom:4px}.block{display:block}.flex{display:flex}.hidden{display:none}.inline{display:inline}.size-7{width:28px;height:28px}.h-7{height:28px}.w-\\[140px\\]{width:140px}.w-full{width:100%}.min-w-0{min-width:0}.flex-1{flex:1}.shrink-0{flex-shrink:0}.-rotate-90{rotate:-90deg}.cursor-pointer{cursor:pointer}.flex-col{flex-direction:column}.items-center{align-items:center}.items-end{align-items:flex-end}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.gap-0\\.5{gap:2px}.gap-1{gap:4px}.gap-1\\.5{gap:6px}.gap-2{gap:8px}.gap-3{gap:12px}.truncate{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.rounded-md{border-radius:6px}.rounded-sm{border-radius:4px}.border{border-style:var(--tw-border-style);border-width:1px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-dashed{--tw-border-style:dashed;border-style:dashed}.border-edge{border-color:var(--dt-edge)}.bg-muted{background-color:var(--dt-muted)}.p-2\\.5{padding:10px}.px-1{padding-inline:4px}.px-2{padding-inline:8px}.pt-2{padding-top:8px}.font-mono{font-family:ui-monospace,SF Mono,SFMono-Regular,Menlo,Consolas,monospace}.text-\\[9px\\]{font-size:9px}.text-\\[10px\\]{font-size:10px}.text-\\[11px\\]{font-size:11px}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.tracking-wide{--tw-tracking:var(--tracking-wide);letter-spacing:var(--tracking-wide)}.text-fail{color:var(--dt-fail)}.text-ink{color:var(--dt-ink)}.text-ink2{color:var(--dt-ink2)}.text-ink3{color:var(--dt-ink3)}.text-ok{color:var(--dt-ok)}.text-warn{color:var(--dt-warn)}.capitalize{text-transform:capitalize}.uppercase{text-transform:uppercase}.tabular-nums{--tw-numeric-spacing:tabular-nums;font-variant-numeric:var(--tw-ordinal,) var(--tw-slashed-zero,) var(--tw-numeric-figure,) var(--tw-numeric-spacing,) var(--tw-numeric-fraction,)}.shadow{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a), 0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.ring,.ring-1{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.ring-fail{--tw-ring-color:var(--dt-fail)}.outline-none{--tw-outline-style:none;outline-style:none}@media (hover:hover){.hover\\:bg-scrim:hover{background-color:var(--dt-scrim)}.hover\\:text-ink:hover{color:var(--dt-ink)}}.focus-visible\\:ring-1:focus-visible{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.focus-visible\\:ring-sel:focus-visible{--tw-ring-color:var(--dt-sel)}}:host{all:initial}.dt-base{all:initial;--dt-page:#fff;--dt-raised:#f8f8f9;--dt-muted:#f0f0f2;--dt-edge:#e4e4e7;--dt-ink:#09090b;--dt-ink2:#71717a;--dt-ink3:#a1a1aa;--dt-sel:#3b82f6;--dt-scrim:#0000000f;--dt-ok:#16a34a;--dt-warn:#d97706;--dt-fail:#dc2626;--dt-icon:oklch(55% 0 0);color-scheme:light;font-family:var(--font-sans);letter-spacing:normal;text-align:left;cursor:auto;color:var(--dt-ink);-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-size:11px;font-weight:400;line-height:1.4;display:contents}.dt-base[data-theme=dark]{--dt-page:#161618;--dt-raised:#18181b;--dt-muted:#27272a;--dt-edge:#2e2e33;--dt-ink:#fafafa;--dt-ink2:#b5b5be;--dt-ink3:#9494a0;--dt-scrim:#ffffff14;--dt-ok:#4ade80;--dt-warn:#fbbf24;--dt-fail:#f87171;color-scheme:dark}@media (prefers-color-scheme:dark){.dt-base:not([data-theme=light]){--dt-page:#161618;--dt-raised:#18181b;--dt-muted:#27272a;--dt-edge:#2e2e33;--dt-ink:#fafafa;--dt-ink2:#b5b5be;--dt-ink3:#9494a0;--dt-scrim:#ffffff14;--dt-ok:#4ade80;--dt-warn:#fbbf24;--dt-fail:#f87171;color-scheme:dark}}input[type=number]::-webkit-inner-spin-button{appearance:none;margin:0}input[type=number]::-webkit-outer-spin-button{appearance:none;margin:0}\n";
2
+ export const properties = "@property --tw-border-style{syntax:\"*\";inherits:false;initial-value:solid}\n@property --tw-font-weight{syntax:\"*\";inherits:false}\n@property --tw-tracking{syntax:\"*\";inherits:false}\n@property --tw-ordinal{syntax:\"*\";inherits:false}\n@property --tw-slashed-zero{syntax:\"*\";inherits:false}\n@property --tw-numeric-figure{syntax:\"*\";inherits:false}\n@property --tw-numeric-spacing{syntax:\"*\";inherits:false}\n@property --tw-numeric-fraction{syntax:\"*\";inherits:false}\n@property --tw-shadow{syntax:\"*\";inherits:false;initial-value:0 0 #0000}\n@property --tw-shadow-color{syntax:\"*\";inherits:false}\n@property --tw-shadow-alpha{syntax:\"<percentage>\";inherits:false;initial-value:100%}\n@property --tw-inset-shadow{syntax:\"*\";inherits:false;initial-value:0 0 #0000}\n@property --tw-inset-shadow-color{syntax:\"*\";inherits:false}\n@property --tw-inset-shadow-alpha{syntax:\"<percentage>\";inherits:false;initial-value:100%}\n@property --tw-ring-color{syntax:\"*\";inherits:false}\n@property --tw-ring-shadow{syntax:\"*\";inherits:false;initial-value:0 0 #0000}\n@property --tw-inset-ring-color{syntax:\"*\";inherits:false}\n@property --tw-inset-ring-shadow{syntax:\"*\";inherits:false;initial-value:0 0 #0000}\n@property --tw-ring-inset{syntax:\"*\";inherits:false}\n@property --tw-ring-offset-width{syntax:\"<length>\";inherits:false;initial-value:0}\n@property --tw-ring-offset-color{syntax:\"*\";inherits:false;initial-value:#fff}\n@property --tw-ring-offset-shadow{syntax:\"*\";inherits:false;initial-value:0 0 #0000}";
@@ -0,0 +1,4 @@
1
+ export type { ProjectSeed } from "./next.js";
2
+ export { generateFromSeed, mergeSeed, type OutputFlags, optionsFromSeed, type ParsedCommand, parseCommand, seedCommand, seedJson, splitCommand, studioCss } from "./seed.js";
3
+ export { ColourGenerator } from "./studio.js";
4
+ export { TokenStudio } from "./studio.js";
@@ -0,0 +1,3 @@
1
+ export { generateFromSeed, mergeSeed, optionsFromSeed, parseCommand, seedCommand, seedJson, splitCommand, studioCss } from "./seed.js";
2
+ export { ColourGenerator } from "./studio.js";
3
+ export { TokenStudio } from "./studio.js";
@@ -0,0 +1,21 @@
1
+ import type { SeedFile } from "@designtools/tokens";
2
+ import { type OutputFlags } from "./seed.js";
3
+ export interface ProjectSeed {
4
+ /** The seed the project's tokens were generated from. */
5
+ seed: SeedFile;
6
+ /** The package.json script that generates them, and its command as written. */
7
+ script?: string;
8
+ command?: string;
9
+ /** How and where the output is written, kept in the command the studio hands back. */
10
+ output: OutputFlags;
11
+ /** Where a seed file is, or should go. */
12
+ seedPath: string;
13
+ /** The installed generator's version, so the hand-back pins the same one. */
14
+ version?: string;
15
+ }
16
+ /**
17
+ * Read the seed a project's tokens were made from: the package.json script that runs the generator
18
+ * (any script whose command runs `generate-tokens` or `@designtools/tokens`), with any `--seed` or
19
+ * `--overrides` file it names folded in. Server only; pass the result to `<TokenStudio>`.
20
+ */
21
+ export declare function readProjectSeed(root?: string): ProjectSeed | null;
@@ -0,0 +1,39 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { mergeSeed, parseCommand } from "./seed.js";
4
+ const readJson = (path) => {
5
+ try {
6
+ return JSON.parse(readFileSync(path, "utf8"));
7
+ }
8
+ catch {
9
+ return undefined;
10
+ }
11
+ };
12
+ /**
13
+ * Read the seed a project's tokens were made from: the package.json script that runs the generator
14
+ * (any script whose command runs `generate-tokens` or `@designtools/tokens`), with any `--seed` or
15
+ * `--overrides` file it names folded in. Server only; pass the result to `<TokenStudio>`.
16
+ */
17
+ export function readProjectSeed(root = process.cwd()) {
18
+ const pkg = readJson(join(root, "package.json"));
19
+ if (!pkg)
20
+ return null;
21
+ const entry = Object.entries(pkg.scripts ?? {}).find(([, cmd]) => /generate-tokens|@designtools\/tokens/.test(cmd) && /--(primary|seed)\b/.test(cmd));
22
+ if (!entry)
23
+ return null;
24
+ const [script, command] = entry;
25
+ const parsed = parseCommand(command);
26
+ let seed = parsed.seed;
27
+ if (parsed.files.seed)
28
+ seed = mergeSeed(readJson(join(root, parsed.files.seed)) ?? {}, seed);
29
+ if (parsed.files.overrides) {
30
+ const o = readJson(join(root, parsed.files.overrides));
31
+ if (o)
32
+ seed = { ...seed, ...o };
33
+ }
34
+ const installed = readJson(join(root, "node_modules/@designtools/tokens/package.json"))?.version;
35
+ const declared = (pkg.devDependencies ?? {})["@designtools/tokens"] ?? (pkg.dependencies ?? {})["@designtools/tokens"];
36
+ const version = installed ?? declared?.replace(/^[\^~]/, "");
37
+ const seedPath = parsed.files.seed ?? (parsed.output.out ? parsed.output.out.replace(/[^/]+$/, "tokens.seed.json") : "tokens.seed.json");
38
+ return { seed, script, command, output: parsed.output, seedPath, version };
39
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * The studio's plain logic, browser-safe: a project's generate-tokens command read into a seed, a
3
+ * seed turned into the generator's inputs, and the command that regenerates from a seed.
4
+ */
5
+ import { type BrandColors, type GenerationOptions, type SeedFile, type TokenSystem } from "@designtools/tokens";
6
+ /** Flags that say where and how the output is written, kept when the colour moves into a seed. */
7
+ export interface OutputFlags {
8
+ format?: string;
9
+ out?: string;
10
+ usage?: string;
11
+ colorFormat?: string;
12
+ /** Anything else, as written: `--merge`, `--only semantic`. */
13
+ rest: string[];
14
+ }
15
+ export interface ParsedCommand {
16
+ seed: SeedFile;
17
+ /** Files the command reads, which the caller reads and folds in. */
18
+ files: {
19
+ seed?: string;
20
+ overrides?: string;
21
+ };
22
+ output: OutputFlags;
23
+ }
24
+ /** Split a command line on spaces outside quotes, unquoting as a shell would. */
25
+ export declare function splitCommand(command: string): string[];
26
+ /**
27
+ * Read a generate-tokens command (as in a package.json script) into a seed, as the CLI would.
28
+ * Anything before the generator (`npx`, `pnpm exec`) is ignored. A `--seed` or `--overrides` file is
29
+ * named in `files` for the caller to read; flags win over the seed file, as in the CLI.
30
+ */
31
+ export declare function parseCommand(command: string): ParsedCommand;
32
+ /** Fold a seed file under the flags, as the CLI does: a flag wins over the file. */
33
+ export declare function mergeSeed(file: SeedFile, flags: SeedFile): SeedFile;
34
+ /** A seed as the generator's inputs, with the CLI's defaults. */
35
+ export declare function optionsFromSeed(seed: SeedFile): {
36
+ brand: BrandColors;
37
+ options: Partial<GenerationOptions> & Pick<GenerationOptions, "shadeOverrides">;
38
+ };
39
+ /** Generate the token system a seed describes. */
40
+ export declare function generateFromSeed(seed: SeedFile): TokenSystem;
41
+ /**
42
+ * The CSS a seed generates, as plain custom properties on the same selectors a project's own
43
+ * tokens file uses, so added after it, it re-themes the page.
44
+ */
45
+ export declare function studioCss(seed: SeedFile, tokens?: TokenSystem): string;
46
+ /** The command that regenerates from a seed file, keeping how and where the output is written. */
47
+ export declare function seedCommand({ seedPath, output, version }: {
48
+ seedPath: string;
49
+ output: OutputFlags;
50
+ version?: string;
51
+ }): string;
52
+ /** A seed as the JSON a --seed file holds, keys sorted and empty parts left out. */
53
+ export declare function seedJson(seed: SeedFile): string;
@@ -0,0 +1,242 @@
1
+ /**
2
+ * The studio's plain logic, browser-safe: a project's generate-tokens command read into a seed, a
3
+ * seed turned into the generator's inputs, and the command that regenerates from a seed.
4
+ */
5
+ import { exportTokens, generateTokens, } from "@designtools/tokens";
6
+ /** Split a command line on spaces outside quotes, unquoting as a shell would. */
7
+ export function splitCommand(command) {
8
+ const out = [];
9
+ let current = "";
10
+ let quote = null;
11
+ let has = false;
12
+ for (const c of command) {
13
+ if (quote) {
14
+ if (c === quote)
15
+ quote = null;
16
+ else
17
+ current += c;
18
+ }
19
+ else if (c === '"' || c === "'") {
20
+ quote = c;
21
+ has = true;
22
+ }
23
+ else if (/\s/.test(c)) {
24
+ if (has || current)
25
+ out.push(current);
26
+ current = "";
27
+ has = false;
28
+ }
29
+ else
30
+ current += c;
31
+ }
32
+ if (has || current)
33
+ out.push(current);
34
+ return out;
35
+ }
36
+ /** `#F2F2F0` or `#F2F2F0/#12171D`: a light colour, and maybe a dark one. */
37
+ function lightDark(raw) {
38
+ const [light, dark] = raw.split("/").map((s) => s.trim());
39
+ return dark ? { light, dark } : { light };
40
+ }
41
+ /**
42
+ * Read a generate-tokens command (as in a package.json script) into a seed, as the CLI would.
43
+ * Anything before the generator (`npx`, `pnpm exec`) is ignored. A `--seed` or `--overrides` file is
44
+ * named in `files` for the caller to read; flags win over the seed file, as in the CLI.
45
+ */
46
+ export function parseCommand(command) {
47
+ const args = splitCommand(command);
48
+ const start = args.findIndex((a) => /generate-tokens$|@designtools\/tokens(@[\w.-]+)?$/.test(a));
49
+ const flags = start === -1 ? args : args.slice(start + 1);
50
+ const seed = {};
51
+ const files = {};
52
+ const output = { rest: [] };
53
+ const colours = [];
54
+ const decorative = new Set();
55
+ const surfaces = { light: {}, dark: {} };
56
+ const backgrounds = {};
57
+ for (let i = 0; i < flags.length; i++) {
58
+ const flag = flags[i];
59
+ const eq = flag.indexOf("=");
60
+ const [name, inline] = flag.startsWith("--") && eq > 2 ? [flag.slice(0, eq), flag.slice(eq + 1)] : [flag, undefined];
61
+ const value = () => inline ?? flags[++i] ?? "";
62
+ switch (name) {
63
+ case "--primary":
64
+ seed.primaryColor = value();
65
+ break;
66
+ case "--neutral":
67
+ seed.neutralColor = value();
68
+ break;
69
+ case "--color": {
70
+ const entry = value();
71
+ const at = entry.indexOf("=");
72
+ const colour = entry.slice(at + 1);
73
+ const anchored = /^(.*)@(\d+)$/.exec(colour);
74
+ colours.push({ name: entry.slice(0, at), color: anchored ? anchored[1] : colour, ...(anchored ? { seedShade: Number(anchored[2]) } : {}) });
75
+ break;
76
+ }
77
+ case "--decorative":
78
+ decorative.add(value());
79
+ break;
80
+ case "--canvas":
81
+ case "--surface":
82
+ case "--overlay": {
83
+ const key = name.slice(2);
84
+ const { light, dark } = lightDark(value());
85
+ (surfaces.light ??= {})[key] = light;
86
+ if (dark)
87
+ (surfaces.dark ??= {})[key] = dark;
88
+ break;
89
+ }
90
+ case "--background": {
91
+ const entry = value();
92
+ const at = entry.indexOf("=");
93
+ backgrounds[entry.slice(0, at)] = lightDark(entry.slice(at + 1));
94
+ break;
95
+ }
96
+ case "--contrast":
97
+ seed.contrastAlgorithm = value();
98
+ break;
99
+ case "--target":
100
+ seed.contrastTarget = value();
101
+ break;
102
+ case "--lightness":
103
+ seed.lightnessStrategy = value();
104
+ break;
105
+ case "--foreground":
106
+ seed.foreground = value();
107
+ break;
108
+ case "--no-wcag-floor":
109
+ seed.wcagFloor = false;
110
+ break;
111
+ case "--gamut":
112
+ seed.gamut = value();
113
+ break;
114
+ case "--seed-shade":
115
+ seed.seedShade = Number(value());
116
+ break;
117
+ case "--neutral-seed-shade":
118
+ seed.neutralSeedShade = Number(value());
119
+ break;
120
+ case "--shades":
121
+ seed.shades = value()
122
+ .split(",")
123
+ .map((n) => Number(n));
124
+ break;
125
+ case "--color-format":
126
+ output.colorFormat = value();
127
+ seed.colorFormat = output.colorFormat;
128
+ break;
129
+ case "--seed":
130
+ files.seed = value();
131
+ break;
132
+ case "--overrides":
133
+ files.overrides = value();
134
+ break;
135
+ case "--format":
136
+ output.format = value();
137
+ break;
138
+ case "--out":
139
+ output.out = value();
140
+ break;
141
+ case "--usage":
142
+ output.usage = value();
143
+ break;
144
+ default:
145
+ output.rest.push(flag);
146
+ // a value-taking flag we don't model keeps its value
147
+ if (inline === undefined && flags[i + 1] && !flags[i + 1].startsWith("--") && ["--only", "--ramps"].includes(name))
148
+ output.rest.push(flags[++i]);
149
+ }
150
+ }
151
+ if (colours.length)
152
+ seed.additionalColors = colours.map((c) => (decorative.has(c.name) ? { ...c, decorative: true } : c));
153
+ if (Object.keys(surfaces.light ?? {}).length || Object.keys(surfaces.dark ?? {}).length)
154
+ seed.surfaceColors = surfaces;
155
+ if (Object.keys(backgrounds).length)
156
+ seed.backgrounds = backgrounds;
157
+ return { seed, files, output };
158
+ }
159
+ /** Fold a seed file under the flags, as the CLI does: a flag wins over the file. */
160
+ export function mergeSeed(file, flags) {
161
+ return {
162
+ ...file,
163
+ ...flags,
164
+ additionalColors: flags.additionalColors ?? file.additionalColors,
165
+ surfaceColors: flags.surfaceColors
166
+ ? { light: { ...file.surfaceColors?.light, ...flags.surfaceColors.light }, dark: { ...file.surfaceColors?.dark, ...flags.surfaceColors.dark } }
167
+ : file.surfaceColors,
168
+ backgrounds: flags.backgrounds ? { ...file.backgrounds, ...flags.backgrounds } : file.backgrounds,
169
+ };
170
+ }
171
+ /** A seed as the generator's inputs, with the CLI's defaults. */
172
+ export function optionsFromSeed(seed) {
173
+ const additional = Object.fromEntries((seed.additionalColors ?? []).map((c) => [c.name, c.color]));
174
+ const seedShades = {};
175
+ if (seed.neutralSeedShade)
176
+ seedShades.neutral = seed.neutralSeedShade;
177
+ for (const c of seed.additionalColors ?? [])
178
+ if (c.seedShade)
179
+ seedShades[c.name] = c.seedShade;
180
+ const decorative = (seed.additionalColors ?? []).filter((c) => c.decorative).map((c) => c.name);
181
+ return {
182
+ brand: { primary: seed.primaryColor ?? "#3b82f6", neutral: seed.neutralColor ?? "#737373", ...(Object.keys(additional).length ? { additionalColors: additional } : {}) },
183
+ options: {
184
+ contrastAlgorithm: seed.contrastAlgorithm ?? "wcag",
185
+ contrastTarget: seed.contrastTarget ?? "aa",
186
+ lightnessStrategy: seed.lightnessStrategy ?? "fixed",
187
+ ...(seed.foreground && seed.foreground !== "balanced" ? { foreground: seed.foreground } : {}),
188
+ ...(seed.wcagFloor === false ? { wcagFloor: false } : {}),
189
+ ...(seed.surfaceColors ? { surfaceColors: seed.surfaceColors } : {}),
190
+ ...(seed.backgrounds ? { backgrounds: seed.backgrounds } : {}),
191
+ seedShade: seed.seedShade,
192
+ ...(Object.keys(seedShades).length ? { seedShades } : {}),
193
+ ...(decorative.length ? { decorative: decorative.sort() } : {}),
194
+ shades: seed.shades,
195
+ shadeOverrides: seed.shadeOverrides ?? {},
196
+ surfaceShadeOverrides: seed.surfaceShadeOverrides,
197
+ utilityShadeOverrides: seed.utilityShadeOverrides,
198
+ gamut: seed.gamut ?? "srgb",
199
+ },
200
+ };
201
+ }
202
+ /** Generate the token system a seed describes. */
203
+ export function generateFromSeed(seed) {
204
+ const { brand, options } = optionsFromSeed(seed);
205
+ return generateTokens(brand, options);
206
+ }
207
+ /**
208
+ * The CSS a seed generates, as plain custom properties on the same selectors a project's own
209
+ * tokens file uses, so added after it, it re-themes the page.
210
+ */
211
+ export function studioCss(seed, tokens = generateFromSeed(seed)) {
212
+ const { options } = optionsFromSeed(seed);
213
+ return exportTokens(tokens, "css", { colorFormat: seed.colorFormat ?? "oklch", shadeOverrides: options.shadeOverrides, seedShade: options.seedShade, seedShades: options.seedShades });
214
+ }
215
+ /** The command that regenerates from a seed file, keeping how and where the output is written. */
216
+ export function seedCommand({ seedPath, output, version }) {
217
+ const parts = [`npx @designtools/tokens${version ? `@${version}` : ""}`, `--seed ${seedPath}`];
218
+ if (output.format)
219
+ parts.push(`--format ${output.format}`);
220
+ if (output.out)
221
+ parts.push(`--out ${output.out}`);
222
+ if (output.usage)
223
+ parts.push(`--usage ${output.usage}`);
224
+ parts.push(...output.rest);
225
+ return parts.join(" ");
226
+ }
227
+ /** A seed as the JSON a --seed file holds, keys sorted and empty parts left out. */
228
+ export function seedJson(seed) {
229
+ const clean = (v) => {
230
+ if (Array.isArray(v))
231
+ return v.map(clean);
232
+ if (v && typeof v === "object") {
233
+ const entries = Object.entries(v)
234
+ .map(([k, x]) => [k, clean(x)])
235
+ .filter(([, x]) => x !== undefined && !(x && typeof x === "object" && !Array.isArray(x) && Object.keys(x).length === 0))
236
+ .sort(([a], [b]) => a.localeCompare(b));
237
+ return Object.fromEntries(entries);
238
+ }
239
+ return v;
240
+ };
241
+ return JSON.stringify(clean(seed), null, 2);
242
+ }
@@ -0,0 +1,20 @@
1
+ import type { ProjectSeed } from "./next.js";
2
+ /** The seed the studio and the colour generator apply to the page, in every frame. */
3
+ export declare const STUDIO_KEY = "studio:seed";
4
+ /**
5
+ * The seed set in the studio, applied to this frame's page as the generator's own CSS, added after
6
+ * the app's so it wins. It runs in every frame, the dock's and each artboard's, so they all re-theme.
7
+ */
8
+ export declare function useApplySeed(): void;
9
+ /**
10
+ * The colour generator in the dock, where it's asked for: the project's seed to start from, changed by
11
+ * hand, live on the page, handed back as the seed and the command.
12
+ *
13
+ * <Widgets tokens={manifest}><ColourGenerator project={readProjectSeed()} /></Widgets>
14
+ */
15
+ export declare function ColourGenerator({ project }: {
16
+ project: ProjectSeed | null;
17
+ }): import("react").JSX.Element | null;
18
+ export declare function TokenStudio({ project }: {
19
+ project?: ProjectSeed | null;
20
+ }): import("react").JSX.Element;
@@ -0,0 +1,212 @@
1
+ "use client";
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";
7
+ import { css, properties } from "./css.js";
8
+ import { generateFromSeed, seedCommand, seedJson, studioCss } from "./seed.js";
9
+ /** The seed the studio and the colour generator apply to the page, in every frame. */
10
+ export const STUDIO_KEY = "studio:seed";
11
+ const KEY = STUDIO_KEY;
12
+ const NONE = {};
13
+ const STYLES = [{ id: "tokens-studio", css, properties }];
14
+ function useStoredSeed() {
15
+ return useSyncExternalStore(useCallback((cb) => subscribeStored((k) => k === KEY && cb()), []), () => readStored(KEY, null), () => null);
16
+ }
17
+ /**
18
+ * The seed set in the studio, applied to this frame's page as the generator's own CSS, added after
19
+ * the app's so it wins. It runs in every frame, the dock's and each artboard's, so they all re-theme.
20
+ */
21
+ export function useApplySeed() {
22
+ const enabled = useToolsEnabled();
23
+ useEffect(() => {
24
+ if (!enabled)
25
+ return;
26
+ const apply = () => {
27
+ const seed = readStored(KEY, null);
28
+ let tag = document.head.querySelector("style[data-designtools-studio]");
29
+ if (!seed) {
30
+ if (tag) {
31
+ tag.remove();
32
+ window.dispatchEvent(new Event("designtools:retheme"));
33
+ }
34
+ return;
35
+ }
36
+ try {
37
+ const text = studioCss(seed);
38
+ if (!tag) {
39
+ tag = document.createElement("style");
40
+ tag.setAttribute("data-designtools-studio", "");
41
+ }
42
+ tag.textContent = text;
43
+ document.head.appendChild(tag); // last, so it follows the app's own tokens
44
+ }
45
+ catch {
46
+ // a half-typed colour: keep what was applied
47
+ }
48
+ // anything measuring colours on the page (the docs' contrast) measures again
49
+ window.dispatchEvent(new Event("designtools:retheme"));
50
+ };
51
+ apply();
52
+ return subscribeStored((k) => k === KEY && apply());
53
+ }, [enabled]);
54
+ }
55
+ const SHADES = VALID_SHADES.map((s) => ({ value: String(s), label: String(s) }));
56
+ /** What fails at the target, in each mode, worst first. */
57
+ function failures(system, target) {
58
+ const need = (r) => (target === "aaa" ? r.passesAAA : target === "aa-large" ? r.ratio >= 3 : r.passesAA);
59
+ return ["light", "dark"]
60
+ .flatMap((mode) => Object.entries(checkSemanticContrast(system.semantic[mode])).filter(([, r]) => !need(r)).map(([pair, r]) => ({ mode, pair, ratio: r.ratio })))
61
+ .sort((a, b) => a.ratio - b.ratio);
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
+ }
71
+ function Score({ system, seed }) {
72
+ const algorithm = seed.contrastAlgorithm ?? "wcag";
73
+ const target = seed.contrastTarget ?? "aa";
74
+ const scores = ["light", "dark"].map((m) => {
75
+ try {
76
+ return { mode: m, ...computeAccessibilityScore(system.semantic[m], algorithm, target) };
77
+ }
78
+ catch {
79
+ return { mode: m, score: Number.NaN, passed: 0, total: 0 };
80
+ }
81
+ });
82
+ const failing = failures(system, target);
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"] })] }))] }));
87
+ }
88
+ const STATUS = ["success", "destructive", "warning"];
89
+ const NAME = /^[a-z][a-z0-9-]*$/;
90
+ /**
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.
94
+ */
95
+ function Colour({ project }) {
96
+ useApplySeed();
97
+ const stored = useStoredSeed();
98
+ const seed = stored ?? project.seed;
99
+ const set = (patch) => writeStored(KEY, { ...seed, ...patch });
100
+ const system = useMemo(() => {
101
+ try {
102
+ return generateFromSeed(seed);
103
+ }
104
+ catch {
105
+ return null;
106
+ }
107
+ }, [seed]);
108
+ const apca = isAPCAAvailable();
109
+ useHandback("Colour generator", () => {
110
+ if (!stored)
111
+ return null;
112
+ return [
113
+ "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.",
114
+ `1. Save this as ${project.seedPath}:`,
115
+ "",
116
+ "```json",
117
+ seedJson(stored),
118
+ "```",
119
+ "",
120
+ `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
+ "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
+ ].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
+ };
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"] }))] })] }));
145
+ }
146
+ const RATIOS = [
147
+ { value: "1.067", label: "Minor second, 1.067" },
148
+ { value: "1.125", label: "Major second, 1.125" },
149
+ { value: "1.2", label: "Minor third, 1.2" },
150
+ { value: "1.25", label: "Major third, 1.25" },
151
+ { value: "1.333", label: "Perfect fourth, 1.333" },
152
+ { value: "1.414", label: "Augmented fourth, 1.414" },
153
+ { value: "1.5", label: "Perfect fifth, 1.5" },
154
+ ];
155
+ const rem = (v) => (v.endsWith("px") ? Number.parseFloat(v) / 16 : Number.parseFloat(v));
156
+ /** The type ramp from a base and a ratio, written as the system's own `--text-*` steps. */
157
+ function TypeRamp() {
158
+ const tokens = useSystemTokens();
159
+ const steps = stepsFor(tokens, "text");
160
+ const baseIndex = Math.max(0, steps.findIndex((s) => s.name === "base"));
161
+ const overrides = useSyncExternalStore(useCallback((cb) => subscribeStored((k) => k === TOKENS_KEY && cb()), []), () => readStored(TOKENS_KEY, NONE), () => NONE);
162
+ const current = (i) => overrides[steps[i].token] ?? steps[i].value;
163
+ const base = steps.length ? rem(current(baseIndex)) : 1;
164
+ const above = steps[baseIndex + 1];
165
+ const ratio = above ? rem(current(baseIndex + 1)) / base : 1.25;
166
+ const write = (nextBase, nextRatio) => {
167
+ const next = { ...readStored(TOKENS_KEY, {}) };
168
+ steps.forEach((s, i) => {
169
+ const v = `${Number.parseFloat((nextBase * nextRatio ** (i - baseIndex)).toFixed(4))}rem`;
170
+ if (v === s.value)
171
+ delete next[s.token];
172
+ else
173
+ next[s.token] = v;
174
+ });
175
+ writeStored(TOKENS_KEY, Object.keys(next).length ? next : undefined);
176
+ };
177
+ if (!steps.length)
178
+ return _jsx("p", { className: "text-[11px] text-ink2", children: "The manifest has no type scale to work from." });
179
+ const nearest = RATIOS.reduce((a, r) => (Math.abs(Number(r.value) - ratio) < Math.abs(Number(a.value) - ratio) ? r : a));
180
+ return (_jsxs(_Fragment, { children: [_jsxs(Row, { children: [_jsx(Field, { label: "Base size", children: (id) => _jsx(NumberScrub, { label: "Base size", labelledBy: id, handle: "B", value: `${Number.parseFloat(base.toFixed(4))}rem`, min: 0.5, step: 0.0625, onChange: (v) => write(rem(v), ratio) }) }), _jsx(Field, { label: "Ratio", children: (id) => _jsx(NumberScrub, { label: "Ratio", labelledBy: id, handle: "R", value: `${Number.parseFloat(ratio.toFixed(3))}`, min: 1, max: 2, step: 0.005, onChange: (v) => write(base, Number.parseFloat(v)) }) })] }), _jsx(Field, { label: "Named ratios", children: (id) => _jsx(Select, { labelledBy: id, value: nearest.value, options: RATIOS, onChange: (v) => write(base, Number(v)) }) }), _jsx("ul", { className: "flex flex-col gap-0.5 rounded-md bg-muted p-2.5 text-[10px] text-ink2", children: steps.map((s, i) => (_jsxs("li", { className: "flex justify-between font-mono", children: [_jsx("span", { children: s.name }), _jsx("span", { className: overrides[s.token] ? "text-ink" : "", children: current(i) })] }, s.token))) })] }));
181
+ }
182
+ /** The hand-authored scales: type, spacing, radius and shadow, as the system's own tokens. */
183
+ function Scales() {
184
+ const tokens = useSystemTokens();
185
+ const radii = stepsFor(tokens, "radius").filter((s) => s.name !== "full");
186
+ const shadows = stepsFor(tokens, "shadow");
187
+ return (_jsxs(Tool, { name: "Theme scales", scope: "tokens", styles: STYLES, children: [_jsx(TypeRamp, {}), _jsx(TokenControl, { token: "--spacing", label: "Spacing unit" }), _jsx(Row, { children: radii.map((r) => (_jsx(TokenControl, { token: r.token, label: `Radius ${r.name}` }, r.token))) }), shadows.map((s) => (_jsx(TokenControl, { token: s.token, label: `Shadow ${s.name}` }, s.token)))] }));
188
+ }
189
+ /**
190
+ * Re-theme after the tokens are generated: the generator's colour inputs and the hand-authored
191
+ * scales, live on the page and in every artboard, inside the widgets dock. Keep hands back the seed
192
+ * and the command to regenerate, and the scale tokens to change, for the agent.
193
+ *
194
+ * <Widgets tokens={manifest}><TokenStudio project={readProjectSeed()} /></Widgets>
195
+ */
196
+ /**
197
+ * Colour editing is hidden until how it should work is settled (a token, the generator's seed, or
198
+ * both): the studio offers the scales only. The colour tool stays here, off, for when it is.
199
+ */
200
+ const COLOUR_EDITING = false;
201
+ /**
202
+ * The colour generator in the dock, where it's asked for: the project's seed to start from, changed by
203
+ * hand, live on the page, handed back as the seed and the command.
204
+ *
205
+ * <Widgets tokens={manifest}><ColourGenerator project={readProjectSeed()} /></Widgets>
206
+ */
207
+ export function ColourGenerator({ project }) {
208
+ return project ? _jsx(Colour, { project: project }) : null;
209
+ }
210
+ export function TokenStudio({ project = null }) {
211
+ return (_jsxs(_Fragment, { children: [COLOUR_EDITING && project ? _jsx(Colour, { project: project }) : null, _jsx(Scales, {})] }));
212
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@designtools/tokens",
3
- "version": "0.7.1",
3
+ "version": "0.9.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",
@@ -16,6 +16,14 @@
16
16
  ".": {
17
17
  "import": "./dist/index.js",
18
18
  "types": "./dist/index.d.ts"
19
+ },
20
+ "./studio": {
21
+ "types": "./dist/studio/index.d.ts",
22
+ "import": "./dist/studio/index.js"
23
+ },
24
+ "./studio/next": {
25
+ "types": "./dist/studio/next.d.ts",
26
+ "import": "./dist/studio/next.js"
19
27
  }
20
28
  },
21
29
  "bin": {
@@ -34,21 +42,51 @@
34
42
  "culori": "^4.0.2"
35
43
  },
36
44
  "peerDependencies": {
37
- "apca-w3": "^0.1.9"
45
+ "@base-ui/react": "^1.6.0",
46
+ "@designtools/widgets": "^0.1.3",
47
+ "apca-w3": "^0.1.9",
48
+ "lucide-react": "^1.23.0",
49
+ "react": ">=19",
50
+ "react-dom": ">=19"
38
51
  },
39
52
  "peerDependenciesMeta": {
53
+ "@base-ui/react": {
54
+ "optional": true
55
+ },
56
+ "@designtools/widgets": {
57
+ "optional": true
58
+ },
40
59
  "apca-w3": {
41
60
  "optional": true
61
+ },
62
+ "lucide-react": {
63
+ "optional": true
64
+ },
65
+ "react": {
66
+ "optional": true
67
+ },
68
+ "react-dom": {
69
+ "optional": true
42
70
  }
43
71
  },
44
72
  "devDependencies": {
73
+ "@base-ui/react": "1.6.0",
74
+ "@tailwindcss/postcss": "4.3.3",
45
75
  "@types/culori": "^4.0.1",
46
76
  "@types/node": "^24.13.3",
77
+ "@types/react": "^19.3.0",
78
+ "@types/react-dom": "^19.3.0",
47
79
  "apca-w3": "^0.1.9",
80
+ "lucide-react": "1.23.0",
81
+ "postcss": "8.5.29",
82
+ "react": "19.2.7",
83
+ "react-dom": "19.2.7",
84
+ "tailwindcss": "4.3.3",
48
85
  "tsup": "^8.0.0",
49
86
  "tsx": "^4.19.0",
50
87
  "typescript": "^5.9.3",
51
- "vitest": "^4.1.11"
88
+ "vitest": "^4.1.11",
89
+ "@designtools/widgets": "0.1.3"
52
90
  },
53
91
  "keywords": [
54
92
  "design-tokens",
@@ -84,8 +122,8 @@
84
122
  "url": "https://github.com/madebymany/designtools/issues"
85
123
  },
86
124
  "scripts": {
87
- "build": "tsup src/index.ts src/cli.ts --format esm --dts --clean",
88
- "typecheck": "tsc --noEmit",
125
+ "build": "tsup src/index.ts src/cli.ts --format esm --dts --clean && tsc -p tsconfig.studio.json && node scripts/fix-extensions.mjs && node ../widgets/scripts/build-css.mjs src/studio/styles.css dist/studio/css.js",
126
+ "typecheck": "tsc --noEmit && tsc -p tsconfig.studio.json --noEmit",
89
127
  "cli": "tsx src/cli.ts",
90
128
  "fixtures": "tsx test/generate-fixtures.ts",
91
129
  "test": "vitest run"