@behavioral-agentic-design-system/core 0.5.0 → 0.6.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/package.json +15 -8
- package/scripts/build-fonts.cjs +90 -0
- package/scripts/build-tokens.cjs +84 -8
- package/src/api/brand-fonts.ts +280 -0
- package/src/api/brand-mark.ts +146 -0
- package/src/api/layers/file.ts +4 -2
- package/src/api/layers.ts +23 -1
- package/src/app/font-ready.tsx +1 -1
- package/src/app/layout.tsx +3 -9
- package/src/app/preview/cards/page.tsx +1 -1
- package/src/app/preview/login/page.tsx +5 -0
- package/src/app/shell.tsx +90 -29
- package/src/components/admin-menu.stories.tsx +68 -0
- package/src/components/admin-menu.tsx +59 -0
- package/src/components/brand-mark.tsx +64 -0
- package/src/components/customize/brand-mark-section.tsx +265 -0
- package/src/components/customize/font-pickers.tsx +293 -0
- package/src/components/customize/save-bar.tsx +11 -5
- package/src/components/customize-tab.tsx +329 -24
- package/src/components/dev-identity-badge.tsx +92 -0
- package/src/components/home-tab.tsx +1022 -374
- package/src/components/layers-tab.tsx +38 -9
- package/src/components/ui/alert.tsx +10 -2
- package/src/components/ui/button.tsx +1 -1
- package/src/components/ui/calendar.tsx +1 -1
- package/src/components/ui/chart.tsx +13 -3
- package/src/components/ui/checkbox.tsx +1 -1
- package/src/components/ui/radio-group.tsx +1 -1
- package/src/components/ui/sidebar.tsx +6 -1
- package/src/components/ui/sonner.tsx +18 -0
- package/src/components/ui/switch.tsx +7 -1
- package/src/components/ui/tabs.tsx +1 -1
- package/src/hooks/use-global-brand-mark.ts +64 -0
- package/src/hooks/use-global-mono-font.ts +13 -3
- package/src/hooks/use-global-primary-color.ts +145 -8
- package/src/hooks/use-global-sans-font.ts +5 -3
- package/src/hooks/use-global-serif-font.ts +14 -4
- package/src/lib/storage.ts +31 -2
- package/src/lib/svg-sanitize.ts +272 -0
- package/src/styles.css +76 -46
- package/src/tokens.default.json +4 -4
- package/src/tokens.json +172 -78
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@behavioral-agentic-design-system/core",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.6.0",
|
|
4
|
+
"description": "Behavioral Agentic Design System core — tokens and base components.",
|
|
5
5
|
"license": "ISC",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"sideEffects": [
|
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
],
|
|
17
17
|
"bin": {
|
|
18
18
|
"bads-build-tokens": "scripts/build-tokens.cjs",
|
|
19
|
+
"bads-build-fonts": "scripts/build-fonts.cjs",
|
|
19
20
|
"bads-sync": "scripts/bads-sync.mjs"
|
|
20
21
|
},
|
|
21
22
|
"exports": {
|
|
@@ -28,10 +29,13 @@
|
|
|
28
29
|
"./hooks/*": "./src/hooks/*.ts",
|
|
29
30
|
"./components/ui": "./src/components/ui/index.ts",
|
|
30
31
|
"./components/ui/*": "./src/components/ui/*.tsx",
|
|
32
|
+
"./components/admin-menu": "./src/components/admin-menu.tsx",
|
|
31
33
|
"./components/customize-tab": "./src/components/customize-tab.tsx",
|
|
32
34
|
"./components/home-tab": "./src/components/home-tab.tsx",
|
|
33
35
|
"./components/layers-tab": "./src/components/layers-tab.tsx",
|
|
34
36
|
"./components/bads-update-banner": "./src/components/bads-update-banner.tsx",
|
|
37
|
+
"./components/brand-mark": "./src/components/brand-mark.tsx",
|
|
38
|
+
"./components/dev-identity-badge": "./src/components/dev-identity-badge.tsx",
|
|
35
39
|
"./components/customize/*": "./src/components/customize/*.tsx",
|
|
36
40
|
"./components/Foundations/*": "./src/components/Foundations/*.tsx",
|
|
37
41
|
"./app/page": "./src/app/page.tsx",
|
|
@@ -52,19 +56,20 @@
|
|
|
52
56
|
"./api/layers": "./src/api/layers.ts",
|
|
53
57
|
"./api/layers/file": "./src/api/layers/file.ts",
|
|
54
58
|
"./api/save-tokens": "./src/api/save-tokens.ts",
|
|
55
|
-
"./api/brand-colors": "./src/api/brand-colors.ts"
|
|
59
|
+
"./api/brand-colors": "./src/api/brand-colors.ts",
|
|
60
|
+
"./api/brand-fonts": "./src/api/brand-fonts.ts",
|
|
61
|
+
"./api/brand-mark": "./src/api/brand-mark.ts"
|
|
56
62
|
},
|
|
57
63
|
"publishConfig": {
|
|
58
64
|
"access": "public"
|
|
59
65
|
},
|
|
60
66
|
"dependencies": {
|
|
67
|
+
"@xmldom/xmldom": "^0.9.10",
|
|
68
|
+
"class-variance-authority": "^0.7.0",
|
|
61
69
|
"clsx": "^2.1.0",
|
|
62
|
-
"tailwind-merge": "^3.0.0"
|
|
63
|
-
"class-variance-authority": "^0.7.0"
|
|
70
|
+
"tailwind-merge": "^3.0.0"
|
|
64
71
|
},
|
|
65
72
|
"peerDependencies": {
|
|
66
|
-
"react": ">=18",
|
|
67
|
-
"react-dom": ">=18",
|
|
68
73
|
"@radix-ui/react-avatar": "*",
|
|
69
74
|
"@radix-ui/react-checkbox": "*",
|
|
70
75
|
"@radix-ui/react-collapsible": "*",
|
|
@@ -87,7 +92,9 @@
|
|
|
87
92
|
"cmdk": "*",
|
|
88
93
|
"lucide-react": "*",
|
|
89
94
|
"next-themes": "*",
|
|
95
|
+
"react": ">=18",
|
|
90
96
|
"react-day-picker": "*",
|
|
97
|
+
"react-dom": ">=18",
|
|
91
98
|
"react-resizable-panels": "*",
|
|
92
99
|
"recharts": "*",
|
|
93
100
|
"sonner": "*"
|
|
@@ -172,4 +179,4 @@
|
|
|
172
179
|
"optional": true
|
|
173
180
|
}
|
|
174
181
|
}
|
|
175
|
-
}
|
|
182
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Build brand-fonts.css from brand-fonts.json.
|
|
4
|
+
*
|
|
5
|
+
* brand-fonts.json → brand-fonts.css
|
|
6
|
+
*
|
|
7
|
+
* brand-fonts.json is the source of truth for client-uploaded fonts. The
|
|
8
|
+
* Customize tab's font-picker "+" tile uploads woff2/woff files to public/fonts/
|
|
9
|
+
* via /api/brand-fonts and appends entries to this JSON. After each upload (and
|
|
10
|
+
* during pnpm install on a fresh clone), this script regenerates brand-fonts.css
|
|
11
|
+
* so the @font-face declarations match what's on disk.
|
|
12
|
+
*
|
|
13
|
+
* The generated brand-fonts.css is imported by styles/globals.css (the import
|
|
14
|
+
* is emitted by build-tokens.cjs) so every preview surface picks up the
|
|
15
|
+
* faces automatically.
|
|
16
|
+
*
|
|
17
|
+
* Run-from-consumer model: this script is invoked from a consumer repo's CWD
|
|
18
|
+
* (via `pnpm build:fonts` → `bads-build-fonts`). Paths resolve against
|
|
19
|
+
* process.cwd() so it works the same in upstream BADS and in client forks.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
const fs = require('fs');
|
|
23
|
+
const path = require('path');
|
|
24
|
+
|
|
25
|
+
const ROOT = process.cwd();
|
|
26
|
+
const SOURCE = path.join(ROOT, 'brand-fonts.json');
|
|
27
|
+
const TARGET = path.join(ROOT, 'brand-fonts.css');
|
|
28
|
+
|
|
29
|
+
const banner = `/* GENERATED FROM brand-fonts.json — DO NOT EDIT BY HAND.
|
|
30
|
+
* Run \`pnpm build:fonts\` after changing brand-fonts.json (this happens
|
|
31
|
+
* automatically when fonts are added/removed via the Customize tab). */`;
|
|
32
|
+
|
|
33
|
+
function readSource() {
|
|
34
|
+
if (!fs.existsSync(SOURCE)) {
|
|
35
|
+
return { fonts: [] };
|
|
36
|
+
}
|
|
37
|
+
try {
|
|
38
|
+
const raw = fs.readFileSync(SOURCE, 'utf8');
|
|
39
|
+
const parsed = JSON.parse(raw);
|
|
40
|
+
return { fonts: Array.isArray(parsed.fonts) ? parsed.fonts : [] };
|
|
41
|
+
} catch (err) {
|
|
42
|
+
console.error(`build-fonts: failed to parse ${SOURCE}:`, err.message);
|
|
43
|
+
process.exit(1);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function escapeFamily(label) {
|
|
48
|
+
// Family names with spaces or punctuation must be quoted in @font-face.
|
|
49
|
+
// Single-token alphanumeric labels can be unquoted but quoting always works.
|
|
50
|
+
return `'${String(label).replace(/'/g, "\\'")}'`;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function emitFace(family, file) {
|
|
54
|
+
const format = file.format === 'woff' ? 'woff' : 'woff2';
|
|
55
|
+
const weight = file.weight ?? 400;
|
|
56
|
+
const style = file.style === 'italic' ? 'italic' : 'normal';
|
|
57
|
+
return `@font-face {
|
|
58
|
+
font-family: ${family};
|
|
59
|
+
src: url('${file.path}') format('${format}');
|
|
60
|
+
font-weight: ${weight};
|
|
61
|
+
font-style: ${style};
|
|
62
|
+
font-display: swap;
|
|
63
|
+
}`;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function emitFamily(font) {
|
|
67
|
+
const family = escapeFamily(font.label || font.id);
|
|
68
|
+
if (!Array.isArray(font.files) || font.files.length === 0) {
|
|
69
|
+
// Family registered without files — assumed to be loaded externally
|
|
70
|
+
// (the type allows this for forward-compat with hosted-font sources).
|
|
71
|
+
return `/* ${family} — registered without local files (loaded externally). */`;
|
|
72
|
+
}
|
|
73
|
+
const sectionHeader = `/* ============================================================
|
|
74
|
+
* ${family} — id: ${font.id}
|
|
75
|
+
* ============================================================ */`;
|
|
76
|
+
return [sectionHeader, ...font.files.map((f) => emitFace(family, f))].join('\n\n');
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function build() {
|
|
80
|
+
const { fonts } = readSource();
|
|
81
|
+
const blocks = fonts.map(emitFamily).join('\n\n');
|
|
82
|
+
const body = blocks.trim().length > 0
|
|
83
|
+
? blocks
|
|
84
|
+
: '/* No brand fonts registered yet. Add one via the Customize tab → font picker → "+". */';
|
|
85
|
+
const out = `${banner}\n\n${body}\n`;
|
|
86
|
+
fs.writeFileSync(TARGET, out, 'utf8');
|
|
87
|
+
console.log(`✓ wrote ${path.relative(ROOT, TARGET)} (${fonts.length} ${fonts.length === 1 ? 'family' : 'families'})`);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
build();
|
package/scripts/build-tokens.cjs
CHANGED
|
@@ -56,9 +56,26 @@ if (!tokens.theme || !tokens.theme.light || !tokens.theme.dark) {
|
|
|
56
56
|
process.exit(1);
|
|
57
57
|
}
|
|
58
58
|
|
|
59
|
+
// Resolve Tokens Studio aliases like `{color.primitive.slate.400}` to their
|
|
60
|
+
// final $value at build time. Supports nested aliases (an alias whose target
|
|
61
|
+
// is itself an alias). Non-alias values pass through unchanged.
|
|
62
|
+
function resolveAlias(value, depth = 0) {
|
|
63
|
+
if (typeof value !== 'string') return value;
|
|
64
|
+
const match = value.match(/^\{(.+)\}$/);
|
|
65
|
+
if (!match) return value;
|
|
66
|
+
if (depth > 8) {
|
|
67
|
+
throw new Error(`Token alias chain too deep — likely a cycle near "${value}"`);
|
|
68
|
+
}
|
|
69
|
+
const target = match[1].split('.').reduce((node, key) => node?.[key], tokens);
|
|
70
|
+
if (!target || target.$value === undefined) {
|
|
71
|
+
throw new Error(`Token alias "${value}" did not resolve to a token with $value`);
|
|
72
|
+
}
|
|
73
|
+
return resolveAlias(target.$value, depth + 1);
|
|
74
|
+
}
|
|
75
|
+
|
|
59
76
|
function emitVars(modeTokens) {
|
|
60
77
|
return Object.entries(modeTokens)
|
|
61
|
-
.map(([name, token]) => ` --${name}: ${token.$value};`)
|
|
78
|
+
.map(([name, token]) => ` --${name}: ${resolveAlias(token.$value)};`)
|
|
62
79
|
.join('\n');
|
|
63
80
|
}
|
|
64
81
|
|
|
@@ -163,17 +180,50 @@ const chartLightnessDark = tokens.chart?.lightness?.dark?.$value ?? '0.78';
|
|
|
163
180
|
const chartHue = (n, fallback) =>
|
|
164
181
|
tokens.chart?.hueRotation?.[`step${n}`]?.$value ?? fallback;
|
|
165
182
|
const chartChroma2 = tokens.chart?.chroma2Damping?.$value ?? '0.65';
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
183
|
+
|
|
184
|
+
// Optional per-step lightness and chroma. When defined in tokens.json the
|
|
185
|
+
// palette becomes a monochromatic ramp at --primary's hue (each step picks its
|
|
186
|
+
// own L and a chroma multiplier on --primary's c). When absent, falls back to
|
|
187
|
+
// the legacy hue-rotation behavior using a single --chart-lightness.
|
|
188
|
+
const stepL = (mode, n) =>
|
|
189
|
+
tokens.chart?.lightnessSteps?.[mode]?.[`step${n}`]?.$value;
|
|
190
|
+
const stepC = (n) => tokens.chart?.chromaSteps?.[`step${n}`]?.$value;
|
|
191
|
+
const hasLightSteps = [1, 2, 3, 4, 5].every((n) => stepL('light', n) !== undefined);
|
|
192
|
+
const hasDarkSteps = [1, 2, 3, 4, 5].every((n) => stepL('dark', n) !== undefined);
|
|
193
|
+
const hasChromaSteps = [1, 2, 3, 4, 5].every((n) => stepC(n) !== undefined);
|
|
194
|
+
|
|
195
|
+
const buildRamp = (mode, lightnessFallback) => {
|
|
196
|
+
const useSteps = mode === 'light' ? hasLightSteps : hasDarkSteps;
|
|
197
|
+
if (!useSteps) {
|
|
198
|
+
// Legacy: single L, hue rotation, chroma2 damping on series 2.
|
|
199
|
+
return ` --chart-lightness: ${lightnessFallback};
|
|
169
200
|
--chart-1: oklch(from var(--primary) var(--chart-lightness) c calc(h + ${chartHue(1, '0')}));
|
|
170
201
|
--chart-2: oklch(from var(--primary) var(--chart-lightness) calc(c * ${chartChroma2}) calc(h + ${chartHue(2, '35')}));
|
|
171
202
|
--chart-3: oklch(from var(--primary) var(--chart-lightness) c calc(h + ${chartHue(3, '70')}));
|
|
172
203
|
--chart-4: oklch(from var(--primary) var(--chart-lightness) c calc(h + ${chartHue(4, '105')}));
|
|
173
204
|
--chart-5: oklch(from var(--primary) var(--chart-lightness) c calc(h + ${chartHue(5, '140')}));`;
|
|
205
|
+
}
|
|
206
|
+
const cExpr = (n) => {
|
|
207
|
+
const m = hasChromaSteps ? stepC(n) : null;
|
|
208
|
+
return m && m !== '1.00' && m !== '1' ? `calc(c * ${m})` : 'c';
|
|
209
|
+
};
|
|
210
|
+
const hExpr = (n) => {
|
|
211
|
+
const r = chartHue(n, '0');
|
|
212
|
+
return r === '0' ? 'h' : `calc(h + ${r})`;
|
|
213
|
+
};
|
|
214
|
+
return ` --chart-1: oklch(from var(--primary) ${stepL(mode, 1)} ${cExpr(1)} ${hExpr(1)});
|
|
215
|
+
--chart-2: oklch(from var(--primary) ${stepL(mode, 2)} ${cExpr(2)} ${hExpr(2)});
|
|
216
|
+
--chart-3: oklch(from var(--primary) ${stepL(mode, 3)} ${cExpr(3)} ${hExpr(3)});
|
|
217
|
+
--chart-4: oklch(from var(--primary) ${stepL(mode, 4)} ${cExpr(4)} ${hExpr(4)});
|
|
218
|
+
--chart-5: oklch(from var(--primary) ${stepL(mode, 5)} ${cExpr(5)} ${hExpr(5)});`;
|
|
219
|
+
};
|
|
220
|
+
|
|
221
|
+
const chartDerivationLight = ` /* Chart palette — derives from --primary so brand changes propagate.
|
|
222
|
+
Override individual --chart-N inline (documentElement.style) to opt out. */
|
|
223
|
+
${buildRamp('light', chartLightnessLight)}`;
|
|
174
224
|
|
|
175
|
-
const chartDerivationDark = ` /*
|
|
176
|
-
|
|
225
|
+
const chartDerivationDark = ` /* Chart palette (dark) — same derivation, mode-specific L floor for AAA. */
|
|
226
|
+
${buildRamp('dark', chartLightnessDark)}`;
|
|
177
227
|
|
|
178
228
|
const themeInline = `@theme inline {
|
|
179
229
|
--color-background: var(--background);
|
|
@@ -184,6 +234,7 @@ const themeInline = `@theme inline {
|
|
|
184
234
|
--color-popover-foreground: var(--popover-foreground);
|
|
185
235
|
--color-primary: var(--primary);
|
|
186
236
|
--color-primary-foreground: var(--primary-foreground);
|
|
237
|
+
--color-link: var(--link);
|
|
187
238
|
--color-secondary: var(--secondary);
|
|
188
239
|
--color-secondary-foreground: var(--secondary-foreground);
|
|
189
240
|
--color-muted: var(--muted);
|
|
@@ -290,7 +341,14 @@ const themeInline = `@theme inline {
|
|
|
290
341
|
}`;
|
|
291
342
|
|
|
292
343
|
const baseLayer = `@layer base {
|
|
293
|
-
|
|
344
|
+
/* Selector is \`:root *\` rather than the more obvious \`*\` so this rule beats
|
|
345
|
+
Tailwind's preflight \`* { border: 0 solid }\` (which resets border-color to
|
|
346
|
+
currentColor = the text color) regardless of which order the consumer
|
|
347
|
+
imports stylesheets in. Both rules live in @layer base; within a layer,
|
|
348
|
+
specificity decides. \`:root *\` is (0,1,0), \`*\` is (0,0,0) — we win. Utility
|
|
349
|
+
classes in @layer utilities still beat both because later layers trump
|
|
350
|
+
specificity, so \`border-red-500\` and friends keep working normally. */
|
|
351
|
+
:root * {
|
|
294
352
|
@apply border-border outline-ring/50;
|
|
295
353
|
}
|
|
296
354
|
/* Bind html to --font-sans so the picker propagates everywhere — not just
|
|
@@ -333,10 +391,27 @@ const baseLayer = `@layer base {
|
|
|
333
391
|
}
|
|
334
392
|
/* WCAG AAA 1.4.8: paragraph spacing ≥ 1.5× line-height inside running
|
|
335
393
|
text. Scope to <p> only — UI primitives stay tight. Last-child has
|
|
336
|
-
no trailing margin so containers don't get extra padding.
|
|
394
|
+
no trailing margin so containers don't get extra padding.
|
|
395
|
+
|
|
396
|
+
The second rule bows out of flex / grid contexts because by the
|
|
397
|
+
time an author has wrapped content in display:flex or display:grid,
|
|
398
|
+
they are clearly building UI layout (rows of chips, tile metadata,
|
|
399
|
+
calendar entries, etc.) and not running prose. Without this
|
|
400
|
+
carve-out, every <p> used as a UI label inside a flex row gets
|
|
401
|
+
an extra 1.5em margin-bottom, which silently inflates its margin
|
|
402
|
+
box and breaks vertical alignment with adjacent items (a dot
|
|
403
|
+
beside an uppercase eyebrow drops below the visible text, the
|
|
404
|
+
classic symptom). The proper semantic fix is to use <span> for
|
|
405
|
+
UI labels, but the design system shouldn't punish authors who
|
|
406
|
+
reach for <p> in obvious UI contexts. Specificity 0,2,1 wins
|
|
407
|
+
over the bare 0,1,1 rule above. */
|
|
337
408
|
p:not(:last-child) {
|
|
338
409
|
margin-bottom: 1.5em;
|
|
339
410
|
}
|
|
411
|
+
:is(.flex, .inline-flex, .grid, .inline-grid, [class*="grid-cols"]) p,
|
|
412
|
+
:is(.flex, .inline-flex, .grid, .inline-grid, [class*="grid-cols"]) > * > p {
|
|
413
|
+
margin-block: 0;
|
|
414
|
+
}
|
|
340
415
|
/* WCAG AAA 2.4.13 Focus Appearance: focus indicator must be ≥ 2 CSS
|
|
341
416
|
pixels thick AND have ≥ 3:1 contrast against adjacent colors. The
|
|
342
417
|
--ring token is luminance-tuned for 3:1 against every surface in
|
|
@@ -477,6 +552,7 @@ console.log(`✓ wrote ${path.relative(ROOT, PKG_CSS)}`);
|
|
|
477
552
|
const appCss = `${banner}
|
|
478
553
|
|
|
479
554
|
@import "../fonts.css";
|
|
555
|
+
@import "../brand-fonts.css";
|
|
480
556
|
@import "tailwindcss";
|
|
481
557
|
@import "tw-animate-css";
|
|
482
558
|
|
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { spawn } from "node:child_process";
|
|
4
|
+
import { NextResponse } from "next/server";
|
|
5
|
+
|
|
6
|
+
const FONTS_PATH = path.join(process.cwd(), "brand-fonts.json");
|
|
7
|
+
const PUBLIC_FONTS = path.join(process.cwd(), "public", "fonts");
|
|
8
|
+
|
|
9
|
+
type BrandFontFile = {
|
|
10
|
+
path: string;
|
|
11
|
+
weight: number | string;
|
|
12
|
+
style: "normal" | "italic";
|
|
13
|
+
format: "woff2" | "woff";
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
type BrandFontEntry = {
|
|
17
|
+
id: string;
|
|
18
|
+
label: string;
|
|
19
|
+
stack: string;
|
|
20
|
+
kind?: "sans" | "serif" | "mono";
|
|
21
|
+
files?: BrandFontFile[];
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
type FontsFile = {
|
|
25
|
+
$comment?: string;
|
|
26
|
+
fonts: BrandFontEntry[];
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
type JsonOp =
|
|
30
|
+
| { action: "rename"; id: string; label: string }
|
|
31
|
+
| { action: "remove"; id: string }
|
|
32
|
+
| { action: "reorder"; ids: string[] };
|
|
33
|
+
|
|
34
|
+
async function readFile(): Promise<FontsFile> {
|
|
35
|
+
const raw = await fs.readFile(FONTS_PATH, "utf8");
|
|
36
|
+
const parsed = JSON.parse(raw) as FontsFile;
|
|
37
|
+
if (!Array.isArray(parsed.fonts)) {
|
|
38
|
+
throw new Error("brand-fonts.json missing fonts array");
|
|
39
|
+
}
|
|
40
|
+
return parsed;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async function writeFile(file: FontsFile) {
|
|
44
|
+
await fs.writeFile(FONTS_PATH, JSON.stringify(file, null, 2) + "\n", "utf8");
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function isValidId(id: string) {
|
|
48
|
+
return /^[a-z][a-z0-9-]{0,63}$/.test(id);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function rebuildFonts(): Promise<void> {
|
|
52
|
+
// Spawn `pnpm build:fonts` so the generated brand-fonts.css matches the
|
|
53
|
+
// updated brand-fonts.json. Non-blocking: we kick it off and resolve once
|
|
54
|
+
// it finishes so the UI's success response reflects the on-disk state.
|
|
55
|
+
return new Promise((resolve) => {
|
|
56
|
+
const child = spawn("pnpm", ["build:fonts"], { cwd: process.cwd() });
|
|
57
|
+
child.on("close", () => resolve());
|
|
58
|
+
child.on("error", () => resolve()); // log? no — just don't crash the route.
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function parseWeight(raw: FormDataEntryValue | null, fallback = 400): number | string {
|
|
63
|
+
if (raw === null) return fallback;
|
|
64
|
+
const v = String(raw).trim();
|
|
65
|
+
if (!v) return fallback;
|
|
66
|
+
// Accept variable-font ranges like "100 900" verbatim.
|
|
67
|
+
if (/^\d+\s+\d+$/.test(v)) return v;
|
|
68
|
+
const n = Number(v);
|
|
69
|
+
return Number.isFinite(n) ? n : fallback;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function parseStyle(raw: FormDataEntryValue | null): "normal" | "italic" {
|
|
73
|
+
return String(raw ?? "normal").toLowerCase() === "italic" ? "italic" : "normal";
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function fileExtFormat(name: string): "woff2" | "woff" | null {
|
|
77
|
+
const ext = name.toLowerCase().split(".").pop();
|
|
78
|
+
if (ext === "woff2") return "woff2";
|
|
79
|
+
if (ext === "woff") return "woff";
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export async function GET() {
|
|
84
|
+
if (process.env.NODE_ENV !== "development") {
|
|
85
|
+
return NextResponse.json({ ok: false, error: "dev-only" }, { status: 403 });
|
|
86
|
+
}
|
|
87
|
+
try {
|
|
88
|
+
const file = await readFile();
|
|
89
|
+
return NextResponse.json({ ok: true, fonts: file.fonts });
|
|
90
|
+
} catch (err) {
|
|
91
|
+
return NextResponse.json(
|
|
92
|
+
{ ok: false, error: (err as Error).message },
|
|
93
|
+
{ status: 500 },
|
|
94
|
+
);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export async function POST(request: Request) {
|
|
99
|
+
if (process.env.NODE_ENV !== "development") {
|
|
100
|
+
return NextResponse.json({ ok: false, error: "dev-only" }, { status: 403 });
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const contentType = request.headers.get("content-type") ?? "";
|
|
104
|
+
|
|
105
|
+
// ─── multipart upload: register a new self-hosted family ────────────────
|
|
106
|
+
if (contentType.includes("multipart/form-data")) {
|
|
107
|
+
let form: FormData;
|
|
108
|
+
try {
|
|
109
|
+
form = await request.formData();
|
|
110
|
+
} catch (err) {
|
|
111
|
+
return NextResponse.json(
|
|
112
|
+
{ ok: false, error: `Invalid multipart: ${(err as Error).message}` },
|
|
113
|
+
{ status: 400 },
|
|
114
|
+
);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const id = String(form.get("id") ?? "").trim();
|
|
118
|
+
const label = String(form.get("label") ?? "").trim();
|
|
119
|
+
const stack = String(form.get("stack") ?? "").trim();
|
|
120
|
+
const kindRaw = String(form.get("kind") ?? "sans").trim();
|
|
121
|
+
const kind: "sans" | "serif" | "mono" =
|
|
122
|
+
kindRaw === "serif" || kindRaw === "mono" ? kindRaw : "sans";
|
|
123
|
+
if (!isValidId(id) || !label || !stack) {
|
|
124
|
+
return NextResponse.json(
|
|
125
|
+
{ ok: false, error: "Need id (lowercase slug), label, and stack" },
|
|
126
|
+
{ status: 400 },
|
|
127
|
+
);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const files = form.getAll("files").filter((v): v is File => v instanceof File);
|
|
131
|
+
if (files.length === 0) {
|
|
132
|
+
return NextResponse.json(
|
|
133
|
+
{ ok: false, error: "Upload at least one font file" },
|
|
134
|
+
{ status: 400 },
|
|
135
|
+
);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// Each file's metadata comes in parallel arrays: weights[i], styles[i].
|
|
139
|
+
const weights = form.getAll("weights");
|
|
140
|
+
const styles = form.getAll("styles");
|
|
141
|
+
|
|
142
|
+
let existing: FontsFile;
|
|
143
|
+
try {
|
|
144
|
+
existing = await readFile();
|
|
145
|
+
} catch {
|
|
146
|
+
existing = { fonts: [] };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// Reject duplicate ids — UI should rename or remove first.
|
|
150
|
+
if (existing.fonts.some((f) => f.id === id)) {
|
|
151
|
+
return NextResponse.json(
|
|
152
|
+
{ ok: false, error: `Font id "${id}" already exists` },
|
|
153
|
+
{ status: 409 },
|
|
154
|
+
);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
await fs.mkdir(PUBLIC_FONTS, { recursive: true });
|
|
158
|
+
|
|
159
|
+
const written: BrandFontFile[] = [];
|
|
160
|
+
for (let i = 0; i < files.length; i++) {
|
|
161
|
+
const f = files[i];
|
|
162
|
+
const format = fileExtFormat(f.name);
|
|
163
|
+
if (!format) {
|
|
164
|
+
return NextResponse.json(
|
|
165
|
+
{ ok: false, error: `Unsupported file: ${f.name} (use woff2 or woff)` },
|
|
166
|
+
{ status: 400 },
|
|
167
|
+
);
|
|
168
|
+
}
|
|
169
|
+
const weight = parseWeight(weights[i] ?? null);
|
|
170
|
+
const style = parseStyle(styles[i] ?? null);
|
|
171
|
+
// Stable deterministic filename so re-uploads overwrite the same path.
|
|
172
|
+
const out = `${id}-${String(weight).replace(/\s+/g, "_")}-${style}.${format}`;
|
|
173
|
+
const buf = Buffer.from(await f.arrayBuffer());
|
|
174
|
+
await fs.writeFile(path.join(PUBLIC_FONTS, out), buf);
|
|
175
|
+
written.push({
|
|
176
|
+
path: `/fonts/${out}`,
|
|
177
|
+
weight,
|
|
178
|
+
style,
|
|
179
|
+
format,
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const entry: BrandFontEntry = { id, label, stack, kind, files: written };
|
|
184
|
+
existing.fonts.push(entry);
|
|
185
|
+
await writeFile(existing);
|
|
186
|
+
await rebuildFonts();
|
|
187
|
+
|
|
188
|
+
return NextResponse.json({ ok: true, font: entry, fonts: existing.fonts });
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// ─── JSON action: rename / remove / reorder ─────────────────────────────
|
|
192
|
+
let op: JsonOp;
|
|
193
|
+
try {
|
|
194
|
+
op = (await request.json()) as JsonOp;
|
|
195
|
+
} catch {
|
|
196
|
+
return NextResponse.json({ ok: false, error: "Invalid JSON" }, { status: 400 });
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
let file: FontsFile;
|
|
200
|
+
try {
|
|
201
|
+
file = await readFile();
|
|
202
|
+
} catch (err) {
|
|
203
|
+
return NextResponse.json(
|
|
204
|
+
{ ok: false, error: `Could not read brand-fonts.json: ${(err as Error).message}` },
|
|
205
|
+
{ status: 500 },
|
|
206
|
+
);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
if (op.action === "rename") {
|
|
210
|
+
if (!op.id || !op.label?.trim()) {
|
|
211
|
+
return NextResponse.json(
|
|
212
|
+
{ ok: false, error: "Need id and non-empty label" },
|
|
213
|
+
{ status: 400 },
|
|
214
|
+
);
|
|
215
|
+
}
|
|
216
|
+
const target = file.fonts.find((f) => f.id === op.id);
|
|
217
|
+
if (!target) {
|
|
218
|
+
return NextResponse.json(
|
|
219
|
+
{ ok: false, error: `No font with id ${op.id}` },
|
|
220
|
+
{ status: 404 },
|
|
221
|
+
);
|
|
222
|
+
}
|
|
223
|
+
target.label = op.label.trim();
|
|
224
|
+
await writeFile(file);
|
|
225
|
+
await rebuildFonts();
|
|
226
|
+
return NextResponse.json({ ok: true, fonts: file.fonts, action: "rename" });
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
if (op.action === "remove") {
|
|
230
|
+
if (!op.id) {
|
|
231
|
+
return NextResponse.json({ ok: false, error: "Need id" }, { status: 400 });
|
|
232
|
+
}
|
|
233
|
+
const target = file.fonts.find((f) => f.id === op.id);
|
|
234
|
+
if (!target) {
|
|
235
|
+
return NextResponse.json(
|
|
236
|
+
{ ok: false, error: `No font with id ${op.id}` },
|
|
237
|
+
{ status: 404 },
|
|
238
|
+
);
|
|
239
|
+
}
|
|
240
|
+
// Best-effort delete the actual files too — never fatal.
|
|
241
|
+
if (target.files) {
|
|
242
|
+
for (const f of target.files) {
|
|
243
|
+
const abs = path.join(process.cwd(), "public", f.path.replace(/^\//, ""));
|
|
244
|
+
try {
|
|
245
|
+
await fs.unlink(abs);
|
|
246
|
+
} catch {
|
|
247
|
+
// already gone
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
file.fonts = file.fonts.filter((f) => f.id !== op.id);
|
|
252
|
+
await writeFile(file);
|
|
253
|
+
await rebuildFonts();
|
|
254
|
+
return NextResponse.json({ ok: true, fonts: file.fonts, action: "remove" });
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
if (op.action === "reorder") {
|
|
258
|
+
if (!Array.isArray(op.ids)) {
|
|
259
|
+
return NextResponse.json({ ok: false, error: "Need ids array" }, { status: 400 });
|
|
260
|
+
}
|
|
261
|
+
const byId = new Map(file.fonts.map((f) => [f.id, f]));
|
|
262
|
+
const next: BrandFontEntry[] = [];
|
|
263
|
+
for (const id of op.ids) {
|
|
264
|
+
const entry = byId.get(id);
|
|
265
|
+
if (entry) next.push(entry);
|
|
266
|
+
}
|
|
267
|
+
for (const f of file.fonts) {
|
|
268
|
+
if (!op.ids.includes(f.id)) next.push(f);
|
|
269
|
+
}
|
|
270
|
+
file.fonts = next;
|
|
271
|
+
await writeFile(file);
|
|
272
|
+
await rebuildFonts();
|
|
273
|
+
return NextResponse.json({ ok: true, fonts: file.fonts, action: "reorder" });
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
return NextResponse.json(
|
|
277
|
+
{ ok: false, error: `Unknown action: ${(op as { action?: string }).action}` },
|
|
278
|
+
{ status: 400 },
|
|
279
|
+
);
|
|
280
|
+
}
|