@designtools/tokens 0.7.1 → 0.8.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,23 @@
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.8.0
6
+
7
+ ### Minor Changes
8
+
9
+ - 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.
10
+
11
+ The optional `apca-w3` import is now skipped by bundlers and treated as unavailable in a browser, so the generator runs client-side.
12
+
13
+ Widgets: tools can bring their own stylesheet and add a paragraph to the copied prompt (`useHandback`); `useSystemTokens`, `useToolsEnabled` and the store are exported.
14
+
15
+ ### Patch Changes
16
+
17
+ - Updated dependencies [0baf5e2]
18
+ - Updated dependencies [d4f5e45]
19
+ - Updated dependencies [ce32ba8]
20
+ - @designtools/widgets@0.1.0
21
+
5
22
  ## 0.7.1
6
23
 
7
24
  ### Patch Changes
package/README.md CHANGED
@@ -163,6 +163,23 @@ 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`. Colour isn't offered yet; a re-theme is a new seed and the generator, as above.
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
+
166
183
  ## Regenerating part of a token file
167
184
 
168
185
  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-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}}@layer utilities{.fixed{position:fixed}.ml-auto{margin-left:auto}.flex{display:flex}.hidden{display:none}.inline{display:inline}.shrink-0{flex-shrink:0}.cursor-pointer{cursor:pointer}.flex-col{flex-direction:column}.items-baseline{align-items:baseline}.items-center{align-items:center}.justify-between{justify-content:space-between}.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-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-edge{border-color:var(--dt-edge)}.bg-muted{background-color:var(--dt-muted)}.p-2\\.5{padding:10px}.px-1{padding-inline:4px}.pt-2{padding-top:8px}.font-mono{font-family:ui-monospace,SF Mono,SFMono-Regular,Menlo,Consolas,monospace}.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)}.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}.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)}@media (hover:hover){.hover\\:text-ink:hover{color:var(--dt-ink)}}}: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-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,3 @@
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 { TokenStudio } from "./studio.js";
@@ -0,0 +1,2 @@
1
+ export { generateFromSeed, mergeSeed, optionsFromSeed, parseCommand, seedCommand, seedJson, splitCommand, studioCss } from "./seed.js";
2
+ 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,4 @@
1
+ import type { ProjectSeed } from "./next.js";
2
+ export declare function TokenStudio({ project }: {
3
+ project?: ProjectSeed | null;
4
+ }): import("react").JSX.Element;
@@ -0,0 +1,174 @@
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 { Palette, RotateCcw } 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
+ const KEY = "studio:seed";
10
+ const NONE = {};
11
+ const STYLES = [{ id: "tokens-studio", css, properties }];
12
+ function useStoredSeed() {
13
+ return useSyncExternalStore(useCallback((cb) => subscribeStored((k) => k === KEY && cb()), []), () => readStored(KEY, null), () => null);
14
+ }
15
+ /**
16
+ * The seed set in the studio, applied to this frame's page as the generator's own CSS, added after
17
+ * the app's so it wins. It runs in every frame, the dock's and each artboard's, so they all re-theme.
18
+ */
19
+ function useApplySeed() {
20
+ const enabled = useToolsEnabled();
21
+ useEffect(() => {
22
+ if (!enabled)
23
+ return;
24
+ const apply = () => {
25
+ const seed = readStored(KEY, null);
26
+ let tag = document.head.querySelector("style[data-designtools-studio]");
27
+ if (!seed) {
28
+ tag?.remove();
29
+ return;
30
+ }
31
+ try {
32
+ const text = studioCss(seed);
33
+ if (!tag) {
34
+ tag = document.createElement("style");
35
+ tag.setAttribute("data-designtools-studio", "");
36
+ }
37
+ tag.textContent = text;
38
+ document.head.appendChild(tag); // last, so it follows the app's own tokens
39
+ }
40
+ catch {
41
+ // a half-typed colour: keep what was applied
42
+ }
43
+ };
44
+ apply();
45
+ return subscribeStored((k) => k === KEY && apply());
46
+ }, [enabled]);
47
+ }
48
+ const SHADES = VALID_SHADES.map((s) => ({ value: String(s), label: String(s) }));
49
+ /** What fails at the target, in each mode, worst first. */
50
+ function failures(system, target) {
51
+ const need = (r) => (target === "aaa" ? r.passesAAA : target === "aa-large" ? r.ratio >= 3 : r.passesAA);
52
+ return ["light", "dark"]
53
+ .flatMap((mode) => Object.entries(checkSemanticContrast(system.semantic[mode])).filter(([, r]) => !need(r)).map(([pair, r]) => ({ mode, pair, ratio: r.ratio })))
54
+ .sort((a, b) => a.ratio - b.ratio);
55
+ }
56
+ function Score({ system, seed }) {
57
+ const algorithm = seed.contrastAlgorithm ?? "wcag";
58
+ const target = seed.contrastTarget ?? "aa";
59
+ const scores = ["light", "dark"].map((m) => {
60
+ try {
61
+ return { mode: m, ...computeAccessibilityScore(system.semantic[m], algorithm, target) };
62
+ }
63
+ catch {
64
+ return { mode: m, score: Number.NaN, passed: 0, total: 0 };
65
+ }
66
+ });
67
+ 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"] })] }))] }));
69
+ }
70
+ /** The colour half: the generator's inputs, live on the page and in every artboard. */
71
+ function Colour({ project }) {
72
+ useApplySeed();
73
+ const stored = useStoredSeed();
74
+ const seed = stored ?? project.seed;
75
+ const set = (patch) => writeStored(KEY, { ...seed, ...patch });
76
+ const system = useMemo(() => {
77
+ try {
78
+ return generateFromSeed(seed);
79
+ }
80
+ catch {
81
+ return null;
82
+ }
83
+ }, [seed]);
84
+ const apca = isAPCAAvailable();
85
+ useHandback("Theme colour", () => {
86
+ if (!stored)
87
+ return null;
88
+ return [
89
+ "Colour: the tokens are generated, so regenerate them from this seed rather than editing the generated file.",
90
+ `1. Save this as ${project.seedPath}:`,
91
+ "",
92
+ "```json",
93
+ seedJson(stored),
94
+ "```",
95
+ "",
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.",
98
+ ].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." })] }));
116
+ }
117
+ const RATIOS = [
118
+ { value: "1.067", label: "Minor second, 1.067" },
119
+ { value: "1.125", label: "Major second, 1.125" },
120
+ { value: "1.2", label: "Minor third, 1.2" },
121
+ { value: "1.25", label: "Major third, 1.25" },
122
+ { value: "1.333", label: "Perfect fourth, 1.333" },
123
+ { value: "1.414", label: "Augmented fourth, 1.414" },
124
+ { value: "1.5", label: "Perfect fifth, 1.5" },
125
+ ];
126
+ const rem = (v) => (v.endsWith("px") ? Number.parseFloat(v) / 16 : Number.parseFloat(v));
127
+ /** The type ramp from a base and a ratio, written as the system's own `--text-*` steps. */
128
+ function TypeRamp() {
129
+ const tokens = useSystemTokens();
130
+ const steps = stepsFor(tokens, "text");
131
+ const baseIndex = Math.max(0, steps.findIndex((s) => s.name === "base"));
132
+ const overrides = useSyncExternalStore(useCallback((cb) => subscribeStored((k) => k === TOKENS_KEY && cb()), []), () => readStored(TOKENS_KEY, NONE), () => NONE);
133
+ const current = (i) => overrides[steps[i].token] ?? steps[i].value;
134
+ const base = steps.length ? rem(current(baseIndex)) : 1;
135
+ const above = steps[baseIndex + 1];
136
+ const ratio = above ? rem(current(baseIndex + 1)) / base : 1.25;
137
+ const write = (nextBase, nextRatio) => {
138
+ const next = { ...readStored(TOKENS_KEY, {}) };
139
+ steps.forEach((s, i) => {
140
+ const v = `${Number.parseFloat((nextBase * nextRatio ** (i - baseIndex)).toFixed(4))}rem`;
141
+ if (v === s.value)
142
+ delete next[s.token];
143
+ else
144
+ next[s.token] = v;
145
+ });
146
+ writeStored(TOKENS_KEY, Object.keys(next).length ? next : undefined);
147
+ };
148
+ if (!steps.length)
149
+ return _jsx("p", { className: "text-[11px] text-ink2", children: "The manifest has no type scale to work from." });
150
+ const nearest = RATIOS.reduce((a, r) => (Math.abs(Number(r.value) - ratio) < Math.abs(Number(a.value) - ratio) ? r : a));
151
+ 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))) })] }));
152
+ }
153
+ /** The hand-authored scales: type, spacing, radius and shadow, as the system's own tokens. */
154
+ function Scales() {
155
+ const tokens = useSystemTokens();
156
+ const radii = stepsFor(tokens, "radius").filter((s) => s.name !== "full");
157
+ const shadows = stepsFor(tokens, "shadow");
158
+ 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)))] }));
159
+ }
160
+ /**
161
+ * Re-theme after the tokens are generated: the generator's colour inputs and the hand-authored
162
+ * scales, live on the page and in every artboard, inside the widgets dock. Keep hands back the seed
163
+ * and the command to regenerate, and the scale tokens to change, for the agent.
164
+ *
165
+ * <Widgets tokens={manifest}><TokenStudio project={readProjectSeed()} /></Widgets>
166
+ */
167
+ /**
168
+ * Colour editing is hidden until how it should work is settled (a token, the generator's seed, or
169
+ * both): the studio offers the scales only. The colour tool stays here, off, for when it is.
170
+ */
171
+ const COLOUR_EDITING = false;
172
+ export function TokenStudio({ project = null }) {
173
+ return (_jsxs(_Fragment, { children: [COLOUR_EDITING && project ? _jsx(Colour, { project: project }) : null, _jsx(Scales, {})] }));
174
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@designtools/tokens",
3
- "version": "0.7.1",
3
+ "version": "0.8.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.0",
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.0"
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"