@behavioral-agentic-design-system/core 0.3.0 → 0.3.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@behavioral-agentic-design-system/core",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "description": "BADS core — tokens, shadcn/ui components, and the BADS template shell (app routes, customize tab, theme hooks). Forks consume this and re-export, keeping client repos to ~30 lines of glue.",
5
5
  "license": "ISC",
6
6
  "type": "module",
@@ -46,7 +46,12 @@
46
46
  "./app/preview/dashboard/page": "./src/app/preview/dashboard/page.tsx",
47
47
  "./app/preview/mail/page": "./src/app/preview/mail/page.tsx",
48
48
  "./app/preview/pricing/page": "./src/app/preview/pricing/page.tsx",
49
- "./app/preview/typography/page": "./src/app/preview/typography/page.tsx"
49
+ "./app/preview/typography/page": "./src/app/preview/typography/page.tsx",
50
+ "./api/bads-update-check": "./src/api/bads-update-check.ts",
51
+ "./api/layers": "./src/api/layers.ts",
52
+ "./api/layers/file": "./src/api/layers/file.ts",
53
+ "./api/save-tokens": "./src/api/save-tokens.ts",
54
+ "./api/brand-colors": "./src/api/brand-colors.ts"
50
55
  },
51
56
  "publishConfig": {
52
57
  "access": "public"
@@ -70,6 +70,20 @@ const fontSerif = tokens.fontFamily.serif.$value;
70
70
  const radius = tokens.borderRadius?.lg?.$value ?? '0.625rem';
71
71
  const spacing = tokens.theme?.light?.spacing?.$value ?? '0.25rem';
72
72
 
73
+ // Animation token layer. Components use `transition-[var(--duration-base)]`
74
+ // and `ease-[var(--ease-out)]` (or motion-* utility names — see @theme
75
+ // inline below). Sourced from tokens.json so designer / token edits
76
+ // propagate without code change.
77
+ const dur = (k, fallback) => tokens.duration?.[k]?.$value ?? fallback;
78
+ const easing = (k, fallback) => tokens.easing?.[k]?.$value ?? fallback;
79
+ const durationFast = dur('fast', '150ms');
80
+ const durationBase = dur('base', '200ms');
81
+ const durationSlow = dur('slow', '300ms');
82
+ const easeIn = easing('ease-in', 'cubic-bezier(0.4, 0, 1, 1)');
83
+ const easeOut = easing('ease-out', 'cubic-bezier(0, 0, 0.2, 1)');
84
+ const easeInOut = easing('ease-in-out', 'cubic-bezier(0.4, 0, 0.2, 1)');
85
+ const easeSpring = easing('ease-spring', 'cubic-bezier(0.34, 1.56, 0.64, 1)');
86
+
73
87
  const fontSize = (key, fallback) => tokens.fontSize?.[key]?.$value ?? fallback;
74
88
  const textXs = fontSize('xs', '14px');
75
89
  const textSm = fontSize('sm', '16px');
@@ -90,21 +104,43 @@ const text8xl = fontSize('8xl', '96px');
90
104
  const banner = `/* GENERATED FROM tokens.json — DO NOT EDIT BY HAND.
91
105
  * Run \`pnpm build:tokens\` after changing tokens.json. */`;
92
106
 
93
- // Shadow tokens, all keyed off a single --shadow-opacity variable so the
94
- // Customize tab's Shadow Opacity slider (use-global-design-controls →
95
- // documentElement.style --shadow-opacity) actually retunes every elevation.
96
- // Default 0.10 matches shadcn's classic alpha. The 2xs/xs are 0.5× base
97
- // (subtler edges) and 2xl is 2.5× base (deeper drop) so the proportional
98
- // rhythm holds while one slider drives them all.
99
- const shadowBlock = ` --shadow-opacity: 0.10;
100
- --shadow-2xs: 0 1px 3px 0px hsl(0 0% 0% / calc(var(--shadow-opacity) * 0.5));
101
- --shadow-xs: 0 1px 3px 0px hsl(0 0% 0% / calc(var(--shadow-opacity) * 0.5));
102
- --shadow-sm: 0 1px 3px 0px hsl(0 0% 0% / var(--shadow-opacity)), 0 1px 2px -1px hsl(0 0% 0% / var(--shadow-opacity));
103
- --shadow: 0 1px 3px 0px hsl(0 0% 0% / var(--shadow-opacity)), 0 1px 2px -1px hsl(0 0% 0% / var(--shadow-opacity));
104
- --shadow-md: 0 1px 3px 0px hsl(0 0% 0% / var(--shadow-opacity)), 0 2px 4px -1px hsl(0 0% 0% / var(--shadow-opacity));
105
- --shadow-lg: 0 1px 3px 0px hsl(0 0% 0% / var(--shadow-opacity)), 0 4px 6px -1px hsl(0 0% 0% / var(--shadow-opacity));
106
- --shadow-xl: 0 1px 3px 0px hsl(0 0% 0% / var(--shadow-opacity)), 0 8px 10px -1px hsl(0 0% 0% / var(--shadow-opacity));
107
- --shadow-2xl: 0 1px 3px 0px hsl(0 0% 0% / calc(var(--shadow-opacity) * 2.5));`;
107
+ // Shadow tokens, fully sourced from tokens.json so Sir's edits to the base
108
+ // opacity or per-level multipliers propagate without touching this script.
109
+ // - shadow.opacity: the base alpha (also overridable at runtime
110
+ // via documentElement.style.--shadow-opacity from
111
+ // the Customize tab's slider)
112
+ // - shadow.opacityMultiplier.{level}: per-level scaling on top of base,
113
+ // so 2xs/xs sit at 0.5× and 2xl sits at 2.5×
114
+ // for the elevation rhythm.
115
+ const shadowOpacity = tokens.shadow?.opacity?.$value ?? '0.10';
116
+ const shadowMul = (lvl, fallback) =>
117
+ tokens.shadow?.opacityMultiplier?.[lvl]?.$value ?? fallback;
118
+ const shadowAlpha = (lvl) =>
119
+ shadowMul(lvl, '1') === '1.0' || shadowMul(lvl, '1') === '1'
120
+ ? `var(--shadow-opacity)`
121
+ : `calc(var(--shadow-opacity) * ${shadowMul(lvl, '1')})`;
122
+ const shadowBlock = ` --shadow-opacity: ${shadowOpacity};
123
+ --shadow-2xs: 0 1px 3px 0px hsl(0 0% 0% / ${shadowAlpha('2xs')});
124
+ --shadow-xs: 0 1px 3px 0px hsl(0 0% 0% / ${shadowAlpha('xs')});
125
+ --shadow-sm: 0 1px 3px 0px hsl(0 0% 0% / ${shadowAlpha('sm')}), 0 1px 2px -1px hsl(0 0% 0% / ${shadowAlpha('sm')});
126
+ --shadow: 0 1px 3px 0px hsl(0 0% 0% / ${shadowAlpha('md')}), 0 1px 2px -1px hsl(0 0% 0% / ${shadowAlpha('md')});
127
+ --shadow-md: 0 1px 3px 0px hsl(0 0% 0% / ${shadowAlpha('md')}), 0 2px 4px -1px hsl(0 0% 0% / ${shadowAlpha('md')});
128
+ --shadow-lg: 0 1px 3px 0px hsl(0 0% 0% / ${shadowAlpha('lg')}), 0 4px 6px -1px hsl(0 0% 0% / ${shadowAlpha('lg')});
129
+ --shadow-xl: 0 1px 3px 0px hsl(0 0% 0% / ${shadowAlpha('xl')}), 0 8px 10px -1px hsl(0 0% 0% / ${shadowAlpha('xl')});
130
+ --shadow-2xl: 0 1px 3px 0px hsl(0 0% 0% / ${shadowAlpha('2xl')});`;
131
+
132
+ // Animation tokens emitted into :root from tokens.json. Components reference
133
+ // var(--duration-*) and var(--ease-*) so Sir's edits in tokens.json (or any
134
+ // future runtime override on documentElement) propagate without touching
135
+ // component source. The @theme inline block below maps these onto Tailwind's
136
+ // duration-* and ease-* utility names so classnames work too.
137
+ const motionBlock = ` --duration-fast: ${durationFast};
138
+ --duration-base: ${durationBase};
139
+ --duration-slow: ${durationSlow};
140
+ --ease-in: ${easeIn};
141
+ --ease-out: ${easeOut};
142
+ --ease-in-out: ${easeInOut};
143
+ --ease-spring: ${easeSpring};`;
108
144
 
109
145
  // Chart palette derives from --primary by default so all data viz tracks the
110
146
  // brand color picker. Each chart-N reads --primary's hue and rotates around
@@ -120,17 +156,24 @@ const shadowBlock = ` --shadow-opacity: 0.10;
120
156
  // or any client code) — wins because inline styles beat :root.
121
157
  //
122
158
  // Uses CSS Color 5 relative-color syntax: Chrome 119+, Safari 18+, Firefox 128+.
159
+ // Lightness, hue rotations, and chroma damping all sourced from
160
+ // tokens.json's chart section so they're tunable without code change.
161
+ const chartLightnessLight = tokens.chart?.lightness?.light?.$value ?? '0.58';
162
+ const chartLightnessDark = tokens.chart?.lightness?.dark?.$value ?? '0.78';
163
+ const chartHue = (n, fallback) =>
164
+ tokens.chart?.hueRotation?.[`step${n}`]?.$value ?? fallback;
165
+ const chartChroma2 = tokens.chart?.chroma2Damping?.$value ?? '0.65';
123
166
  const chartDerivationLight = ` /* Chart palette — derives from --primary so brand changes propagate.
124
167
  Override individual --chart-N inline (documentElement.style) to opt out. */
125
- --chart-lightness: 0.58;
126
- --chart-1: oklch(from var(--primary) var(--chart-lightness) c h);
127
- --chart-2: oklch(from var(--primary) var(--chart-lightness) calc(c * 0.65) calc(h + 35));
128
- --chart-3: oklch(from var(--primary) var(--chart-lightness) c calc(h + 70));
129
- --chart-4: oklch(from var(--primary) var(--chart-lightness) c calc(h + 105));
130
- --chart-5: oklch(from var(--primary) var(--chart-lightness) c calc(h + 140));`;
168
+ --chart-lightness: ${chartLightnessLight};
169
+ --chart-1: oklch(from var(--primary) var(--chart-lightness) c calc(h + ${chartHue(1, '0')}));
170
+ --chart-2: oklch(from var(--primary) var(--chart-lightness) calc(c * ${chartChroma2}) calc(h + ${chartHue(2, '35')}));
171
+ --chart-3: oklch(from var(--primary) var(--chart-lightness) c calc(h + ${chartHue(3, '70')}));
172
+ --chart-4: oklch(from var(--primary) var(--chart-lightness) c calc(h + ${chartHue(4, '105')}));
173
+ --chart-5: oklch(from var(--primary) var(--chart-lightness) c calc(h + ${chartHue(5, '140')}));`;
131
174
 
132
175
  const chartDerivationDark = ` /* Lift lightness on dark backgrounds so charts stay readable. */
133
- --chart-lightness: 0.78;`;
176
+ --chart-lightness: ${chartLightnessDark};`;
134
177
 
135
178
  const themeInline = `@theme inline {
136
179
  --color-background: var(--background);
@@ -188,6 +231,18 @@ const themeInline = `@theme inline {
188
231
  --shadow-xl: var(--shadow-xl);
189
232
  --shadow-2xl: var(--shadow-2xl);
190
233
 
234
+ /* Animation token layer. Sourced from tokens.json (duration / easing).
235
+ Components use these via Tailwind utilities — duration-base,
236
+ ease-spring, etc. — or the raw var(--duration-base) / var(--ease-out)
237
+ when classnames don't fit. Single source of truth for motion. */
238
+ --duration-fast: var(--duration-fast);
239
+ --duration-base: var(--duration-base);
240
+ --duration-slow: var(--duration-slow);
241
+ --ease-in: var(--ease-in);
242
+ --ease-out: var(--ease-out);
243
+ --ease-in-out: var(--ease-in-out);
244
+ --ease-spring: var(--ease-spring);
245
+
191
246
  /* Accessibility floor — minimum 14px for text-xs (vs Tailwind's 12px default).
192
247
  Font sizes are dynamically computed by useGlobalTypeScale hook and set as
193
248
  --text-xs-size, --text-sm-size, etc. These are then scaled by --font-size-scale
@@ -358,6 +413,7 @@ ${lightVars}
358
413
 
359
414
  --radius: ${radius};
360
415
  ${shadowBlock}
416
+ ${motionBlock}
361
417
  --spacing: ${spacing};
362
418
 
363
419
  ${chartDerivationLight}
@@ -405,6 +461,7 @@ ${lightVars}
405
461
 
406
462
  --radius: ${radius};
407
463
  ${shadowBlock}
464
+ ${motionBlock}
408
465
  --spacing: ${spacing};
409
466
 
410
467
  ${chartDerivationLight}
@@ -0,0 +1,151 @@
1
+ import { exec } from "node:child_process";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { promisify } from "node:util";
5
+ import { NextResponse } from "next/server";
6
+
7
+ const execAsync = promisify(exec);
8
+
9
+ // Where upstream BADS lives. Hardcoded — clients consuming this template
10
+ // inherit it. Change here if BADS ever moves repos.
11
+ const UPSTREAM = "matthewlarn/behavioral-agentic-design-system";
12
+ const UPSTREAM_BRANCH = "main";
13
+ const UPSTREAM_API = `https://api.github.com/repos/${UPSTREAM}/commits/${UPSTREAM_BRANCH}`;
14
+ const UPSTREAM_COMPARE = (from: string, to: string) =>
15
+ `https://github.com/${UPSTREAM}/compare/${from}...${to}`;
16
+
17
+ type IdentityFile = {
18
+ name?: string;
19
+ slug?: string;
20
+ upstream?: string;
21
+ };
22
+
23
+ async function readIdentity(): Promise<IdentityFile | null> {
24
+ try {
25
+ const raw = await fs.readFile(
26
+ path.join(process.cwd(), ".client-identity.json"),
27
+ "utf8",
28
+ );
29
+ return JSON.parse(raw) as IdentityFile;
30
+ } catch {
31
+ return null;
32
+ }
33
+ }
34
+
35
+ async function readSyncState(): Promise<string | null> {
36
+ try {
37
+ const raw = await fs.readFile(
38
+ path.join(process.cwd(), ".bads-sync-state.json"),
39
+ "utf8",
40
+ );
41
+ const parsed = JSON.parse(raw) as { upstreamCommit?: string };
42
+ return parsed.upstreamCommit ?? null;
43
+ } catch {
44
+ return null;
45
+ }
46
+ }
47
+
48
+ async function readLocalCommit(): Promise<string | null> {
49
+ // Prefer the recorded sync-state (last commit pulled FROM upstream); fall
50
+ // back to the local HEAD commit. The fallback is meaningful for forks that
51
+ // haven't run `pnpm bads:sync` yet — they're still at upstream HEAD as of
52
+ // their last clone.
53
+ const synced = await readSyncState();
54
+ if (synced) return synced;
55
+ try {
56
+ const { stdout } = await execAsync("git rev-parse HEAD", {
57
+ cwd: process.cwd(),
58
+ });
59
+ return stdout.trim() || null;
60
+ } catch {
61
+ return null;
62
+ }
63
+ }
64
+
65
+ export async function GET() {
66
+ const identity = await readIdentity();
67
+
68
+ // Upstream BADS itself doesn't need an update banner — it IS the upstream.
69
+ // Skip the check when we recognize this is upstream (no client-identity
70
+ // marker AND root package name matches the canonical upstream slug).
71
+ if (!identity) {
72
+ try {
73
+ const pkg = JSON.parse(
74
+ await fs.readFile(path.join(process.cwd(), "package.json"), "utf8"),
75
+ ) as { name?: string };
76
+ if (pkg.name === "behavioral-agentic-design-system") {
77
+ return NextResponse.json({ ok: true, upstream: true, skip: "is-upstream" });
78
+ }
79
+ } catch {}
80
+ }
81
+
82
+ const local = await readLocalCommit();
83
+ if (!local) {
84
+ return NextResponse.json({ ok: true, error: "no-local-commit" });
85
+ }
86
+
87
+ let remoteSha: string | null = null;
88
+ let remoteShortMessage: string | null = null;
89
+ let remoteDate: string | null = null;
90
+ try {
91
+ const res = await fetch(UPSTREAM_API, {
92
+ headers: { Accept: "application/vnd.github.v3+json" },
93
+ // 5-minute cache so opening the showcase doesn't hammer the API.
94
+ next: { revalidate: 300 },
95
+ });
96
+ if (!res.ok) {
97
+ return NextResponse.json({ ok: true, error: `github-${res.status}` });
98
+ }
99
+ const data = (await res.json()) as {
100
+ sha?: string;
101
+ commit?: { message?: string; author?: { date?: string } };
102
+ };
103
+ remoteSha = data.sha ?? null;
104
+ remoteShortMessage = data.commit?.message?.split("\n")[0] ?? null;
105
+ remoteDate = data.commit?.author?.date ?? null;
106
+ } catch {
107
+ return NextResponse.json({ ok: true, error: "github-unreachable" });
108
+ }
109
+
110
+ if (!remoteSha) {
111
+ return NextResponse.json({ ok: true, error: "no-remote-sha" });
112
+ }
113
+
114
+ // If local matches remote, no update.
115
+ if (remoteSha === local) {
116
+ return NextResponse.json({
117
+ ok: true,
118
+ upToDate: true,
119
+ local,
120
+ remote: remoteSha,
121
+ });
122
+ }
123
+
124
+ // Behind. Get the commits-behind count by counting GitHub's compare API.
125
+ let behind: number | null = null;
126
+ try {
127
+ const res = await fetch(
128
+ `https://api.github.com/repos/${UPSTREAM}/compare/${local}...${remoteSha}`,
129
+ {
130
+ headers: { Accept: "application/vnd.github.v3+json" },
131
+ next: { revalidate: 300 },
132
+ },
133
+ );
134
+ if (res.ok) {
135
+ const data = (await res.json()) as { ahead_by?: number; behind_by?: number };
136
+ behind = data.ahead_by ?? null;
137
+ }
138
+ } catch {}
139
+
140
+ return NextResponse.json({
141
+ ok: true,
142
+ upToDate: false,
143
+ local,
144
+ remote: remoteSha,
145
+ behind,
146
+ remoteMessage: remoteShortMessage,
147
+ remoteDate,
148
+ compareUrl: UPSTREAM_COMPARE(local, remoteSha),
149
+ releasesUrl: `https://github.com/${UPSTREAM}/releases`,
150
+ });
151
+ }
@@ -0,0 +1,180 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { NextResponse } from "next/server";
4
+
5
+ const COLORS_PATH = path.join(process.cwd(), "brand-colors.json");
6
+
7
+ type BrandColorEntry = {
8
+ id: string;
9
+ label: string;
10
+ primary: string;
11
+ primaryForeground?: string;
12
+ note?: string | null;
13
+ };
14
+
15
+ type ColorsFile = {
16
+ $comment?: string;
17
+ colors: BrandColorEntry[];
18
+ };
19
+
20
+ type Op =
21
+ | { action: "pin"; entry: BrandColorEntry }
22
+ | { action: "rename"; id: string; label: string }
23
+ | { action: "remove"; id: string }
24
+ | { action: "reorder"; ids: string[] };
25
+
26
+ async function readFile(): Promise<ColorsFile> {
27
+ const raw = await fs.readFile(COLORS_PATH, "utf8");
28
+ const parsed = JSON.parse(raw) as ColorsFile;
29
+ if (!Array.isArray(parsed.colors)) {
30
+ throw new Error("brand-colors.json missing colors array");
31
+ }
32
+ return parsed;
33
+ }
34
+
35
+ async function writeFile(file: ColorsFile) {
36
+ await fs.writeFile(COLORS_PATH, JSON.stringify(file, null, 2) + "\n", "utf8");
37
+ }
38
+
39
+ function isValidHex(hex: string) {
40
+ return /^#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})$/.test(hex.trim());
41
+ }
42
+
43
+ function isValidId(id: string) {
44
+ return /^[a-z][a-z0-9-]{0,63}$/.test(id);
45
+ }
46
+
47
+ export async function GET() {
48
+ if (process.env.NODE_ENV !== "development") {
49
+ return NextResponse.json({ ok: false, error: "dev-only" }, { status: 403 });
50
+ }
51
+ try {
52
+ const file = await readFile();
53
+ return NextResponse.json({ ok: true, colors: file.colors });
54
+ } catch (err) {
55
+ return NextResponse.json(
56
+ { ok: false, error: (err as Error).message },
57
+ { status: 500 },
58
+ );
59
+ }
60
+ }
61
+
62
+ export async function POST(request: Request) {
63
+ if (process.env.NODE_ENV !== "development") {
64
+ return NextResponse.json({ ok: false, error: "dev-only" }, { status: 403 });
65
+ }
66
+
67
+ let op: Op;
68
+ try {
69
+ op = (await request.json()) as Op;
70
+ } catch {
71
+ return NextResponse.json({ ok: false, error: "Invalid JSON" }, { status: 400 });
72
+ }
73
+
74
+ let file: ColorsFile;
75
+ try {
76
+ file = await readFile();
77
+ } catch (err) {
78
+ return NextResponse.json(
79
+ { ok: false, error: `Could not read brand-colors.json: ${(err as Error).message}` },
80
+ { status: 500 },
81
+ );
82
+ }
83
+
84
+ // ─── pin: append a new entry (or replace if id collides) ─────────────────
85
+ if (op.action === "pin") {
86
+ const e = op.entry;
87
+ if (!e || !isValidId(e.id) || !isValidHex(e.primary) || !e.label?.trim()) {
88
+ return NextResponse.json(
89
+ { ok: false, error: "Invalid entry — need id, label, valid primary hex" },
90
+ { status: 400 },
91
+ );
92
+ }
93
+ if (e.primaryForeground && !isValidHex(e.primaryForeground)) {
94
+ return NextResponse.json(
95
+ { ok: false, error: "Invalid primaryForeground hex" },
96
+ { status: 400 },
97
+ );
98
+ }
99
+ const cleaned: BrandColorEntry = {
100
+ id: e.id,
101
+ label: e.label.trim(),
102
+ primary: e.primary,
103
+ ...(e.primaryForeground ? { primaryForeground: e.primaryForeground } : {}),
104
+ ...(e.note ? { note: e.note } : {}),
105
+ };
106
+ const existing = file.colors.findIndex((c) => c.id === cleaned.id);
107
+ if (existing >= 0) {
108
+ file.colors[existing] = cleaned;
109
+ } else {
110
+ file.colors.push(cleaned);
111
+ }
112
+ await writeFile(file);
113
+ return NextResponse.json({ ok: true, colors: file.colors, action: "pin" });
114
+ }
115
+
116
+ // ─── rename: change label of an existing entry ──────────────────────────
117
+ if (op.action === "rename") {
118
+ if (!op.id || !op.label?.trim()) {
119
+ return NextResponse.json(
120
+ { ok: false, error: "Need id and non-empty label" },
121
+ { status: 400 },
122
+ );
123
+ }
124
+ const target = file.colors.find((c) => c.id === op.id);
125
+ if (!target) {
126
+ return NextResponse.json(
127
+ { ok: false, error: `No brand color with id ${op.id}` },
128
+ { status: 404 },
129
+ );
130
+ }
131
+ target.label = op.label.trim();
132
+ await writeFile(file);
133
+ return NextResponse.json({ ok: true, colors: file.colors, action: "rename" });
134
+ }
135
+
136
+ // ─── remove: drop an entry ──────────────────────────────────────────────
137
+ if (op.action === "remove") {
138
+ if (!op.id) {
139
+ return NextResponse.json(
140
+ { ok: false, error: "Need id" },
141
+ { status: 400 },
142
+ );
143
+ }
144
+ const before = file.colors.length;
145
+ file.colors = file.colors.filter((c) => c.id !== op.id);
146
+ if (file.colors.length === before) {
147
+ return NextResponse.json(
148
+ { ok: false, error: `No brand color with id ${op.id}` },
149
+ { status: 404 },
150
+ );
151
+ }
152
+ await writeFile(file);
153
+ return NextResponse.json({ ok: true, colors: file.colors, action: "remove" });
154
+ }
155
+
156
+ // ─── reorder: full id-list replacement preserving entries ───────────────
157
+ if (op.action === "reorder") {
158
+ if (!Array.isArray(op.ids)) {
159
+ return NextResponse.json({ ok: false, error: "Need ids array" }, { status: 400 });
160
+ }
161
+ const byId = new Map(file.colors.map((c) => [c.id, c]));
162
+ const next: BrandColorEntry[] = [];
163
+ for (const id of op.ids) {
164
+ const entry = byId.get(id);
165
+ if (entry) next.push(entry);
166
+ }
167
+ // Preserve any entries the client didn't include (defensive — shouldn't happen).
168
+ for (const c of file.colors) {
169
+ if (!op.ids.includes(c.id)) next.push(c);
170
+ }
171
+ file.colors = next;
172
+ await writeFile(file);
173
+ return NextResponse.json({ ok: true, colors: file.colors, action: "reorder" });
174
+ }
175
+
176
+ return NextResponse.json(
177
+ { ok: false, error: `Unknown action: ${(op as { action?: string }).action}` },
178
+ { status: 400 },
179
+ );
180
+ }
@@ -0,0 +1,71 @@
1
+ import { exec } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { promisify } from "node:util";
5
+
6
+ const execAsync = promisify(exec);
7
+ const ROOT = process.cwd();
8
+
9
+ function isAllowed(rel: string) {
10
+ // Only allow paths inside layer-*/ to prevent traversal abuse.
11
+ const norm = path.normalize(rel);
12
+ if (norm.startsWith("..") || path.isAbsolute(norm)) return false;
13
+ return /^layer-[\w-]+\//.test(norm) && /\.(md|json)$/.test(norm);
14
+ }
15
+
16
+ export async function GET(request: Request) {
17
+ if (process.env.NODE_ENV !== "development") {
18
+ return Response.json({ error: "dev-only" }, { status: 403 });
19
+ }
20
+ const url = new URL(request.url);
21
+ const rel = url.searchParams.get("path") ?? "";
22
+ if (!isAllowed(rel)) {
23
+ return Response.json({ error: "invalid path" }, { status: 400 });
24
+ }
25
+ const full = path.join(ROOT, rel);
26
+ if (!fs.existsSync(full)) {
27
+ return Response.json({ error: "not found" }, { status: 404 });
28
+ }
29
+ return Response.json({ path: rel, content: fs.readFileSync(full, "utf8") });
30
+ }
31
+
32
+ export async function POST(request: Request) {
33
+ if (process.env.NODE_ENV !== "development") {
34
+ return Response.json({ error: "dev-only" }, { status: 403 });
35
+ }
36
+ try {
37
+ const body = (await request.json()) as {
38
+ path: string;
39
+ content: string;
40
+ message?: string;
41
+ commit?: boolean;
42
+ };
43
+ if (!isAllowed(body.path)) {
44
+ return Response.json({ error: "invalid path" }, { status: 400 });
45
+ }
46
+ const full = path.join(ROOT, body.path);
47
+ fs.writeFileSync(full, body.content);
48
+
49
+ if (body.commit !== false) {
50
+ const message = body.message?.trim() || `docs: edit ${body.path}`;
51
+ await execAsync(`git add ${JSON.stringify(body.path)}`, { cwd: ROOT });
52
+ // --allow-empty so saves with no diff don't error; precommit hook still runs.
53
+ try {
54
+ await execAsync(`git commit -m ${JSON.stringify(message)}`, { cwd: ROOT });
55
+ } catch (e) {
56
+ // No diff is fine. Anything else surfaces as an error.
57
+ const msg = e instanceof Error ? e.message : String(e);
58
+ if (!/nothing to commit/i.test(msg)) {
59
+ return Response.json({ error: "commit failed", details: msg }, { status: 500 });
60
+ }
61
+ }
62
+ }
63
+
64
+ return Response.json({ success: true, path: body.path });
65
+ } catch (error) {
66
+ return Response.json(
67
+ { error: "save failed", details: error instanceof Error ? error.message : String(error) },
68
+ { status: 500 }
69
+ );
70
+ }
71
+ }
@@ -0,0 +1,49 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+
4
+ const ROOT = process.cwd();
5
+
6
+ function listLayers() {
7
+ return fs
8
+ .readdirSync(ROOT)
9
+ .filter((name) => name.startsWith("layer-"))
10
+ .filter((name) => fs.statSync(path.join(ROOT, name)).isDirectory())
11
+ .sort((a, b) => {
12
+ const na = parseInt(a.split("-")[1], 10) || 0;
13
+ const nb = parseInt(b.split("-")[1], 10) || 0;
14
+ return na - nb;
15
+ });
16
+ }
17
+
18
+ function listFiles(dir: string): string[] {
19
+ const out: string[] = [];
20
+ for (const entry of fs.readdirSync(dir)) {
21
+ const full = path.join(dir, entry);
22
+ const stat = fs.statSync(full);
23
+ if (stat.isDirectory()) {
24
+ out.push(...listFiles(full));
25
+ } else if (/\.(md|json)$/.test(entry)) {
26
+ out.push(path.relative(ROOT, full));
27
+ }
28
+ }
29
+ return out;
30
+ }
31
+
32
+ function prettifyLayerName(slug: string) {
33
+ // "layer-2-ethics-responsibility" → "2 · Ethics & Responsibility"
34
+ const [, num, ...rest] = slug.split("-");
35
+ const label = rest.map((w) => w[0].toUpperCase() + w.slice(1)).join(" ");
36
+ return `${num} · ${label.replace(/\bAnd\b/g, "&")}`;
37
+ }
38
+
39
+ export async function GET() {
40
+ if (process.env.NODE_ENV !== "development") {
41
+ return Response.json({ error: "dev-only" }, { status: 403 });
42
+ }
43
+ const layers = listLayers().map((slug) => ({
44
+ slug,
45
+ label: prettifyLayerName(slug),
46
+ files: listFiles(path.join(ROOT, slug)).sort(),
47
+ }));
48
+ return Response.json({ layers });
49
+ }
@@ -0,0 +1,280 @@
1
+ import { exec } from "node:child_process";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { promisify } from "node:util";
5
+ import { NextResponse } from "next/server";
6
+
7
+ const execAsync = promisify(exec);
8
+ const TOKENS_PATH = path.join(process.cwd(), "packages/core/src/tokens.json");
9
+ const BRAND_COLORS_PATH = path.join(process.cwd(), "brand-colors.json");
10
+
11
+ type SavePayload = {
12
+ brandColor?: {
13
+ primary: string;
14
+ primaryHover?: string;
15
+ primaryForeground: string;
16
+ } | null;
17
+ /**
18
+ * When the active color is a localStorage custom, the Save Bar piggybacks
19
+ * a pinAsBuiltin entry so we promote the swatch to brand-colors.json in
20
+ * the same write. Keeps the chain to "one click = full persistence":
21
+ *
22
+ * active custom → tokens.json (system primary) AND brand-colors.json
23
+ * (picker option for every future clone).
24
+ */
25
+ pinAsBuiltin?: {
26
+ id: string;
27
+ label: string;
28
+ primary: string;
29
+ primaryForeground?: string;
30
+ note?: string | null;
31
+ replaceCustomId?: string;
32
+ } | null;
33
+ fonts?: {
34
+ sans?: string;
35
+ serif?: string;
36
+ mono?: string;
37
+ } | null;
38
+ fontSizes?: Record<string, number> | null;
39
+ radius?: number | null;
40
+ reset?: boolean;
41
+ };
42
+
43
+ type BrandColorEntry = {
44
+ id: string;
45
+ label: string;
46
+ primary: string;
47
+ primaryForeground?: string;
48
+ note?: string | null;
49
+ };
50
+
51
+ type BrandColorsFile = {
52
+ $comment?: string;
53
+ colors: BrandColorEntry[];
54
+ };
55
+
56
+ function isValidId(id: string) {
57
+ return /^[a-z][a-z0-9-]{0,63}$/.test(id);
58
+ }
59
+
60
+ function isValidHex(hex: string) {
61
+ return /^#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})$/.test(hex.trim());
62
+ }
63
+
64
+ function setLeaf(
65
+ node: Record<string, unknown>,
66
+ dotPath: string,
67
+ mutator: (leaf: Record<string, unknown>) => void,
68
+ ) {
69
+ const parts = dotPath.split(".");
70
+ let current: Record<string, unknown> = node;
71
+ for (let i = 0; i < parts.length; i++) {
72
+ const key = parts[i];
73
+ const next = current[key];
74
+ if (i === parts.length - 1) {
75
+ if (next && typeof next === "object") {
76
+ mutator(next as Record<string, unknown>);
77
+ }
78
+ return;
79
+ }
80
+ if (!next || typeof next !== "object") return;
81
+ current = next as Record<string, unknown>;
82
+ }
83
+ }
84
+
85
+ export async function POST(request: Request) {
86
+ if (process.env.NODE_ENV !== "development") {
87
+ return NextResponse.json(
88
+ { ok: false, error: "Saving requires a local dev environment." },
89
+ { status: 403 },
90
+ );
91
+ }
92
+
93
+ let payload: SavePayload;
94
+ try {
95
+ payload = await request.json();
96
+ } catch {
97
+ return NextResponse.json({ ok: false, error: "Invalid JSON" }, { status: 400 });
98
+ }
99
+
100
+ if (payload.reset) {
101
+ const defaultPath = path.join(process.cwd(), "packages/core/src/tokens.default.json");
102
+ try {
103
+ await fs.access(defaultPath);
104
+ } catch {
105
+ return NextResponse.json(
106
+ { ok: false, error: "tokens.default.json missing" },
107
+ { status: 500 },
108
+ );
109
+ }
110
+ await fs.copyFile(defaultPath, TOKENS_PATH);
111
+ await execAsync("pnpm build:tokens", { cwd: process.cwd() });
112
+ return NextResponse.json({ ok: true, updates: ["reset"], note: "Reset to baseline" });
113
+ }
114
+
115
+ let raw: string;
116
+ try {
117
+ raw = await fs.readFile(TOKENS_PATH, "utf8");
118
+ } catch (err) {
119
+ return NextResponse.json(
120
+ { ok: false, error: `Could not read tokens.json: ${(err as Error).message}` },
121
+ { status: 500 },
122
+ );
123
+ }
124
+
125
+ let tokens: Record<string, unknown>;
126
+ try {
127
+ tokens = JSON.parse(raw);
128
+ } catch (err) {
129
+ return NextResponse.json(
130
+ { ok: false, error: `tokens.json is malformed: ${(err as Error).message}` },
131
+ { status: 500 },
132
+ );
133
+ }
134
+
135
+ const updates: string[] = [];
136
+
137
+ if (payload.brandColor) {
138
+ // Only write the primary to the LIGHT theme. Writing both to the same hex
139
+ // breaks dark-mode contrast — a near-black primary on a near-black page
140
+ // background fails WCAG 1.4.11 (3:1 non-text). Dark mode keeps its own
141
+ // inverted primary (near-white surface, near-black text). If a designer
142
+ // wants to override dark too, they can edit tokens.json directly or send
143
+ // a separate payload (future: { brandColorDark: { ... } }).
144
+ const { primary, primaryForeground } = payload.brandColor;
145
+ setLeaf(tokens, "theme.light.primary", (leaf) => {
146
+ leaf.$value = primary;
147
+ updates.push("theme.light.primary");
148
+ });
149
+ setLeaf(tokens, "theme.light.primary-foreground", (leaf) => {
150
+ leaf.$value = primaryForeground;
151
+ updates.push("theme.light.primary-foreground");
152
+ });
153
+ }
154
+
155
+ // Promote the active custom color to a built-in entry in brand-colors.json
156
+ // alongside the tokens.json write, so a Save fully persists the swatch
157
+ // (everyone on the repo sees it as a picker option) and the system primary
158
+ // in one round-trip. Validation matches /api/brand-colors so a malformed
159
+ // entry is rejected without corrupting the file.
160
+ let pinnedBuiltinId: string | null = null;
161
+ if (payload.pinAsBuiltin) {
162
+ const e = payload.pinAsBuiltin;
163
+ if (!isValidId(e.id) || !isValidHex(e.primary) || !e.label?.trim()) {
164
+ return NextResponse.json(
165
+ { ok: false, error: "pinAsBuiltin: need valid id, label, primary hex" },
166
+ { status: 400 },
167
+ );
168
+ }
169
+ if (e.primaryForeground && !isValidHex(e.primaryForeground)) {
170
+ return NextResponse.json(
171
+ { ok: false, error: "pinAsBuiltin: invalid primaryForeground hex" },
172
+ { status: 400 },
173
+ );
174
+ }
175
+ try {
176
+ const raw = await fs.readFile(BRAND_COLORS_PATH, "utf8");
177
+ const file = JSON.parse(raw) as BrandColorsFile;
178
+ if (!Array.isArray(file.colors)) file.colors = [];
179
+ const cleaned: BrandColorEntry = {
180
+ id: e.id,
181
+ label: e.label.trim(),
182
+ primary: e.primary,
183
+ ...(e.primaryForeground ? { primaryForeground: e.primaryForeground } : {}),
184
+ ...(e.note ? { note: e.note } : {}),
185
+ };
186
+ const existing = file.colors.findIndex((c) => c.id === cleaned.id);
187
+ if (existing >= 0) file.colors[existing] = cleaned;
188
+ else file.colors.push(cleaned);
189
+ await fs.writeFile(BRAND_COLORS_PATH, JSON.stringify(file, null, 2) + "\n", "utf8");
190
+ pinnedBuiltinId = cleaned.id;
191
+ updates.push(`brand-colors.json:${cleaned.id}`);
192
+ } catch (err) {
193
+ return NextResponse.json(
194
+ { ok: false, error: `Failed to write brand-colors.json: ${(err as Error).message}` },
195
+ { status: 500 },
196
+ );
197
+ }
198
+ }
199
+
200
+ if (payload.fonts) {
201
+ if (payload.fonts.sans) {
202
+ setLeaf(tokens, "fontFamily.sans", (leaf) => {
203
+ leaf.$value = payload.fonts!.sans;
204
+ updates.push("fontFamily.sans");
205
+ });
206
+ }
207
+ if (payload.fonts.serif) {
208
+ setLeaf(tokens, "fontFamily.serif", (leaf) => {
209
+ leaf.$value = payload.fonts!.serif;
210
+ updates.push("fontFamily.serif");
211
+ });
212
+ }
213
+ if (payload.fonts.mono) {
214
+ setLeaf(tokens, "fontFamily.mono", (leaf) => {
215
+ leaf.$value = payload.fonts!.mono;
216
+ updates.push("fontFamily.mono");
217
+ });
218
+ }
219
+ }
220
+
221
+ if (payload.fontSizes) {
222
+ // Floor-clamp every step so the type-scale slider can't drift below the
223
+ // 14px AAA accessibility floor (SC 1.4.4). The Customize tab can show
224
+ // smaller previews live if the user really wants, but persisting them
225
+ // to tokens.json would break the system's a11y guarantee for everyone
226
+ // pulling the repo.
227
+ const FONT_SIZE_FLOOR_PX = 14;
228
+ const stepKeys = ["xs", "sm", "base", "lg", "xl", "2xl", "3xl"];
229
+ for (const step of stepKeys) {
230
+ const px = payload.fontSizes[`text-${step}`];
231
+ if (typeof px === "number") {
232
+ const clamped = Math.max(FONT_SIZE_FLOOR_PX, px);
233
+ setLeaf(tokens, `fontSize.${step}`, (leaf) => {
234
+ leaf.$value = `${Math.round(clamped * 100) / 100}px`;
235
+ updates.push(`fontSize.${step}${clamped !== px ? " (clamped to floor)" : ""}`);
236
+ });
237
+ }
238
+ }
239
+ }
240
+
241
+ if (typeof payload.radius === "number") {
242
+ setLeaf(tokens, "borderRadius.lg", (leaf) => {
243
+ leaf.$value = `${payload.radius}rem`;
244
+ updates.push("borderRadius.lg");
245
+ });
246
+ }
247
+
248
+ if (updates.length === 0) {
249
+ return NextResponse.json({ ok: true, updates: [], note: "No changes to save." });
250
+ }
251
+
252
+ try {
253
+ const output = JSON.stringify(tokens, null, 2) + "\n";
254
+ await fs.writeFile(TOKENS_PATH, output, "utf8");
255
+ } catch (err) {
256
+ return NextResponse.json(
257
+ { ok: false, error: `Failed to write tokens.json: ${(err as Error).message}` },
258
+ { status: 500 },
259
+ );
260
+ }
261
+
262
+ try {
263
+ await execAsync("pnpm build:tokens", { cwd: process.cwd() });
264
+ } catch (err) {
265
+ return NextResponse.json({
266
+ ok: true,
267
+ updates,
268
+ warning: `Saved tokens.json but build:tokens failed: ${(err as Error).message}`,
269
+ pinnedBuiltinId,
270
+ replaceCustomId: payload.pinAsBuiltin?.replaceCustomId ?? null,
271
+ });
272
+ }
273
+
274
+ return NextResponse.json({
275
+ ok: true,
276
+ updates,
277
+ pinnedBuiltinId,
278
+ replaceCustomId: payload.pinAsBuiltin?.replaceCustomId ?? null,
279
+ });
280
+ }
package/src/styles.css CHANGED
@@ -77,12 +77,19 @@
77
77
  --shadow-lg: 0 1px 3px 0px hsl(0 0% 0% / var(--shadow-opacity)), 0 4px 6px -1px hsl(0 0% 0% / var(--shadow-opacity));
78
78
  --shadow-xl: 0 1px 3px 0px hsl(0 0% 0% / var(--shadow-opacity)), 0 8px 10px -1px hsl(0 0% 0% / var(--shadow-opacity));
79
79
  --shadow-2xl: 0 1px 3px 0px hsl(0 0% 0% / calc(var(--shadow-opacity) * 2.5));
80
+ --duration-fast: 150ms;
81
+ --duration-base: 200ms;
82
+ --duration-slow: 300ms;
83
+ --ease-in: cubic-bezier(0.4, 0, 1, 1);
84
+ --ease-out: cubic-bezier(0, 0, 0.2, 1);
85
+ --ease-in-out: cubic-bezier(0.4, 0, 0.2, 1);
86
+ --ease-spring: cubic-bezier(0.34, 1.56, 0.64, 1);
80
87
  --spacing: 0.25rem;
81
88
 
82
89
  /* Chart palette — derives from --primary so brand changes propagate.
83
90
  Override individual --chart-N inline (documentElement.style) to opt out. */
84
91
  --chart-lightness: 0.58;
85
- --chart-1: oklch(from var(--primary) var(--chart-lightness) c h);
92
+ --chart-1: oklch(from var(--primary) var(--chart-lightness) c calc(h + 0));
86
93
  --chart-2: oklch(from var(--primary) var(--chart-lightness) calc(c * 0.65) calc(h + 35));
87
94
  --chart-3: oklch(from var(--primary) var(--chart-lightness) c calc(h + 70));
88
95
  --chart-4: oklch(from var(--primary) var(--chart-lightness) c calc(h + 105));
@@ -183,6 +190,18 @@
183
190
  --shadow-xl: var(--shadow-xl);
184
191
  --shadow-2xl: var(--shadow-2xl);
185
192
 
193
+ /* Animation token layer. Sourced from tokens.json (duration / easing).
194
+ Components use these via Tailwind utilities — duration-base,
195
+ ease-spring, etc. — or the raw var(--duration-base) / var(--ease-out)
196
+ when classnames don't fit. Single source of truth for motion. */
197
+ --duration-fast: var(--duration-fast);
198
+ --duration-base: var(--duration-base);
199
+ --duration-slow: var(--duration-slow);
200
+ --ease-in: var(--ease-in);
201
+ --ease-out: var(--ease-out);
202
+ --ease-in-out: var(--ease-in-out);
203
+ --ease-spring: var(--ease-spring);
204
+
186
205
  /* Accessibility floor — minimum 14px for text-xs (vs Tailwind's 12px default).
187
206
  Font sizes are dynamically computed by useGlobalTypeScale hook and set as
188
207
  --text-xs-size, --text-sm-size, etc. These are then scaled by --font-size-scale
package/src/tokens.json CHANGED
@@ -356,6 +356,43 @@
356
356
  "xl": {
357
357
  "$value": "0 1px 3px 0px hsl(0 0% 0% / 0.10), 0 8px 10px -1px hsl(0 0% 0% / 0.10)",
358
358
  "$type": "shadow"
359
+ },
360
+ "opacity": {
361
+ "$value": "0.10",
362
+ "$type": "number",
363
+ "$description": "Base alpha for hsl-driven shadows. Customize tab Shadow Opacity slider overrides at runtime via documentElement.style.--shadow-opacity. Each shadow level (2xs, xs, sm, md, lg, xl, 2xl) scales this base by its opacityMultiplier."
364
+ },
365
+ "opacityMultiplier": {
366
+ "2xs": {
367
+ "$value": "0.5",
368
+ "$type": "number",
369
+ "$description": "Soft edge — subtle UI accents."
370
+ },
371
+ "xs": {
372
+ "$value": "0.5",
373
+ "$type": "number"
374
+ },
375
+ "sm": {
376
+ "$value": "1.0",
377
+ "$type": "number"
378
+ },
379
+ "md": {
380
+ "$value": "1.0",
381
+ "$type": "number"
382
+ },
383
+ "lg": {
384
+ "$value": "1.0",
385
+ "$type": "number"
386
+ },
387
+ "xl": {
388
+ "$value": "1.0",
389
+ "$type": "number"
390
+ },
391
+ "2xl": {
392
+ "$value": "2.5",
393
+ "$type": "number",
394
+ "$description": "Deep drop — modal / overlay surfaces."
395
+ }
359
396
  }
360
397
  },
361
398
  "breakpoint": {
@@ -1030,5 +1067,49 @@
1030
1067
  "$description": "AAA non-text 3:1 on dark sidebar."
1031
1068
  }
1032
1069
  }
1070
+ },
1071
+ "chart": {
1072
+ "lightness": {
1073
+ "light": {
1074
+ "$value": "0.58",
1075
+ "$type": "number",
1076
+ "$description": "Absolute L for chart series in light mode (oklch). Tuned so all five series sit at readable contrast on white card surfaces."
1077
+ },
1078
+ "dark": {
1079
+ "$value": "0.78",
1080
+ "$type": "number",
1081
+ "$description": "Absolute L for chart series in dark mode. Lifted from light so charts stay legible on near-black backgrounds."
1082
+ }
1083
+ },
1084
+ "hueRotation": {
1085
+ "step1": {
1086
+ "$value": "0",
1087
+ "$type": "number",
1088
+ "$description": "Series 1 — hue inherited from --primary as-is."
1089
+ },
1090
+ "step2": {
1091
+ "$value": "35",
1092
+ "$type": "number",
1093
+ "$description": "Series 2 — primary hue + 35deg, chroma damped to 0.65× for pairing."
1094
+ },
1095
+ "step3": {
1096
+ "$value": "70",
1097
+ "$type": "number"
1098
+ },
1099
+ "step4": {
1100
+ "$value": "105",
1101
+ "$type": "number"
1102
+ },
1103
+ "step5": {
1104
+ "$value": "140",
1105
+ "$type": "number",
1106
+ "$description": "Series 5 — final hue rotation, max separation from primary."
1107
+ }
1108
+ },
1109
+ "chroma2Damping": {
1110
+ "$value": "0.65",
1111
+ "$type": "number",
1112
+ "$description": "Chroma multiplier on series 2 only (others inherit primary chroma)."
1113
+ }
1033
1114
  }
1034
1115
  }