krz/brand-bench

A dynamic brand documentation generator with Ollama integration. branding documentation generator ollama

Commit f43a3c29ad

f43a3c29ad3cd2b52c57b761d410e71184d6d123

parent: 89caccc0f4

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-22 21:10 UTC

Add Qlty config; split generator data, sanitizer, hooks, and components

Palettes use sixTone, and visual directions move to directions.json.
sanitizeOutputs maps each list with mapList; usePackages applies pure
store changes through update; useWorkspace keeps its undo stack in
useEditHistory. ColorSwatchCard uses EditableField, PackageSwitcher
renders PackageTab and TabMenu, and the generate label drops a branch
that returned the same string either way. Generator output for 240
inputs, sanitizer output for 7,570, a 21-step hook run, and a 13-step
UI run in jsdom are unchanged.

Layout: unified · split

.qlty/.gitignore added +7
@@ -0,0 +1,7 @@
1*
2!configs
3!configs/**
4!hooks
5!hooks/**
6!qlty.toml
7!.gitignore
.qlty/qlty.toml added +44
@@ -0,0 +1,44 @@
1config_version = "0"
2
3exclude_patterns = [
4 "**/vendor/**",
5 "**/node_modules/**",
6 "**/testdata/**",
7 "**/dist/**",
8 "**/.build/**",
9 "**/build/**",
10 "**/*.min.*",
11 "**/generated/**",
12 ".claude/**",
13 "**/Pods/**",
14]
15
16test_patterns = [
17 "**/test/**",
18 "**/tests/**",
19 "**/Tests/**",
20 "**/*_test.*",
21 "**/test_*.*",
22 "**/*.test.*",
23 "**/*Tests.swift",
24 "e2e/**",
25]
26
27[[source]]
28name = "default"
29default = true
30
31[[plugin]]
32name = "osv-scanner"
33
34[[plugin]]
35name = "trufflehog"
36
37# Early returns are guard clauses, which keep the happy path unindented.
38[smells.return_statements]
39enabled = false
40
41# Total file complexity is the sum of its functions, which function_complexity
42# already checks.
43[smells.file_complexity]
44enabled = false
src/App.tsx +22 −17
@@ -22,6 +22,26 @@ interface WorkspaceShellProps {
22 aiEnabled: boolean; 22 aiEnabled: boolean;
23} 23}
24 24
25/** ⌘Z / Ctrl+Z undoes, with Shift redoes. */
26function useUndoShortcuts(undo: () => void, redo: () => void) {
27 useEffect(() => {
28 const handler = (e: KeyboardEvent) => {
29 if (!(e.metaKey || e.ctrlKey) || e.key !== 'z') return;
30 e.preventDefault();
31 if (e.shiftKey) redo();
32 else undo();
33 };
34 window.addEventListener('keydown', handler);
35 return () => window.removeEventListener('keydown', handler);
36 }, [undo, redo]);
37}
38
39function generateLabel(isGenerating: boolean, hasOutputs: boolean, aiEnabled: boolean): string {
40 if (isGenerating) return 'Cancel';
41 if (hasOutputs) return 'Regenerate';
42 return aiEnabled ? 'Generate with AI' : 'Generate';
43}
44
25function WorkspaceShell({ 45function WorkspaceShell({
26 storageKey, slots, activeId, 46 storageKey, slots, activeId,
27 onSwitch, onCreate, onRemove, onRename, onDuplicate, 47 onSwitch, onCreate, onRemove, onRename, onDuplicate,
@@ -33,26 +53,11 @@ function WorkspaceShell({
33 undo, redo, canUndo, canRedo, 53 undo, redo, canUndo, canRedo,
34 } = useWorkspace(storageKey); 54 } = useWorkspace(storageKey);
35 55
36 useEffect(() => { 56 useUndoShortcuts(undo, redo);
37 const handler = (e: KeyboardEvent) => {
38 if (!(e.metaKey || e.ctrlKey) || e.key !== 'z') return;
39 e.preventDefault();
40 if (e.shiftKey) redo();
41 else undo();
42 };
43 window.addEventListener('keydown', handler);
44 return () => window.removeEventListener('keydown', handler);
45 }, [undo, redo]);
46 57
47 const handleEdit = <K extends keyof BrandOutputs>(key: K, value: BrandOutputs[K]) => 58 const handleEdit = <K extends keyof BrandOutputs>(key: K, value: BrandOutputs[K]) =>
48 updateEdit(key, value); 59 updateEdit(key, value);
49 60
50 const generateLabel = isGenerating
51 ? 'Cancel'
52 : outputs
53 ? (aiEnabled ? `Regenerate` : 'Regenerate')
54 : (aiEnabled ? 'Generate with AI' : 'Generate');
55
56 return ( 61 return (
57 <> 62 <>
58 <header className="app-header"> 63 <header className="app-header">
@@ -84,7 +89,7 @@ function WorkspaceShell({
84 onChange={setInputs} 89 onChange={setInputs}
85 onGenerate={isGenerating ? cancelGenerate : runGenerate} 90 onGenerate={isGenerating ? cancelGenerate : runGenerate}
86 isGenerating={isGenerating} 91 isGenerating={isGenerating}
87 generateLabel={generateLabel} 92 generateLabel={generateLabel(isGenerating, outputs !== null, aiEnabled)}
88 /> 93 />
89 <PreviewPanel 94 <PreviewPanel
90 inputs={inputs} 95 inputs={inputs}
src/components/BrandDoc.tsx +56 −50
@@ -220,27 +220,55 @@ interface ColorSwatchCardProps {
220 onRemove: () => void; 220 onRemove: () => void;
221} 221}
222 222
223interface EditableFieldProps {
224 value: string;
225 className: string;
226 inputClassName: string;
227 onCommit: (draft: string) => void;
228}
229
230/** Text that turns into an input on click; Enter or blur commits, Escape cancels. */
231function EditableField({ value, className, inputClassName, onCommit }: EditableFieldProps) {
232 const [editing, setEditing] = useState(false);
233 const [draft, setDraft] = useState(value);
234
235 const commit = () => {
236 setEditing(false);
237 onCommit(draft);
238 };
239
240 if (editing) {
241 return (
242 <input
243 autoFocus
244 className={inputClassName}
245 value={draft}
246 onChange={e => setDraft(e.target.value)}
247 onBlur={commit}
248 onKeyDown={e => {
249 if (e.key === 'Enter') commit();
250 if (e.key === 'Escape') { setEditing(false); setDraft(value); }
251 }}
252 />
253 );
254 }
255 return (
256 <div className={className} onClick={() => { setDraft(value); setEditing(true); }} title="Click to edit">
257 {value}
258 </div>
259 );
260}
261
223function ColorSwatchCard({ swatch, onChange, onRemove }: ColorSwatchCardProps) { 262function ColorSwatchCard({ swatch, onChange, onRemove }: ColorSwatchCardProps) {
224 const [nameEditing, setNameEditing] = useState(false); 263 const commitName = (draft: string) => {
225 const [nameDraft, setNameDraft] = useState(swatch.name); 264 const v = draft.trim();
226 const [hexEditing, setHexEditing] = useState(false);
227 const [hexDraft, setHexDraft] = useState(swatch.hex);
228
229 const commitName = () => {
230 setNameEditing(false);
231 const v = nameDraft.trim();
232 if (v && v !== swatch.name) onChange({ ...swatch, name: v }); 265 if (v && v !== swatch.name) onChange({ ...swatch, name: v });
233 }; 266 };
234 267
235 const commitHex = () => { 268 const commitHex = (draft: string) => {
236 setHexEditing(false); 269 const v = draft.trim().toLowerCase();
237 const v = hexDraft.trim().toLowerCase();
238 const normalized = v.startsWith('#') ? v : `#${v}`; 270 const normalized = v.startsWith('#') ? v : `#${v}`;
239 if (/^#[0-9a-f]{6}$/.test(normalized)) { 271 if (/^#[0-9a-f]{6}$/.test(normalized)) onChange({ ...swatch, hex: normalized });
240 onChange({ ...swatch, hex: normalized });
241 } else {
242 setHexDraft(swatch.hex);
243 }
244 }; 272 };
245 273
246 return ( 274 return (
@@ -256,40 +284,18 @@ function ColorSwatchCard({ swatch, onChange, onRemove }: ColorSwatchCardProps) {
256 <button className="color-swatch-remove" onClick={onRemove} title="Remove">×</button> 284 <button className="color-swatch-remove" onClick={onRemove} title="Remove">×</button>
257 </div> 285 </div>
258 <div className="color-swatch-info"> 286 <div className="color-swatch-info">
259 {nameEditing ? ( 287 <EditableField
260 <input 288 value={swatch.name}
261 autoFocus 289 className="color-swatch-name"
262 className="color-swatch-field-input" 290 inputClassName="color-swatch-field-input"
263 value={nameDraft} 291 onCommit={commitName}
264 onChange={e => setNameDraft(e.target.value)} 292 />
265 onBlur={commitName} 293 <EditableField
266 onKeyDown={e => { 294 value={swatch.hex}
267 if (e.key === 'Enter') commitName(); 295 className="color-swatch-hex"
268 if (e.key === 'Escape') { setNameEditing(false); setNameDraft(swatch.name); } 296 inputClassName="color-swatch-field-input color-swatch-hex-input"
269 }} 297 onCommit={commitHex}
270 /> 298 />
271 ) : (
272 <div className="color-swatch-name" onClick={() => { setNameDraft(swatch.name); setNameEditing(true); }} title="Click to edit">
273 {swatch.name}
274 </div>
275 )}
276 {hexEditing ? (
277 <input
278 autoFocus
279 className="color-swatch-field-input color-swatch-hex-input"
280 value={hexDraft}
281 onChange={e => setHexDraft(e.target.value)}
282 onBlur={commitHex}
283 onKeyDown={e => {
284 if (e.key === 'Enter') commitHex();
285 if (e.key === 'Escape') { setHexEditing(false); setHexDraft(swatch.hex); }
286 }}
287 />
288 ) : (
289 <div className="color-swatch-hex" onClick={() => { setHexDraft(swatch.hex); setHexEditing(true); }} title="Click to edit">
290 {swatch.hex}
291 </div>
292 )}
293 </div> 299 </div>
294 </div> 300 </div>
295 ); 301 );
src/components/PackageSwitcher.tsx +123 −66
@@ -18,6 +18,99 @@ interface MenuState {
18 left: number; 18 left: number;
19} 19}
20 20
21interface TabMenuProps {
22 menu: MenuState;
23 canDelete: boolean;
24 onRename: () => void;
25 onDuplicate: () => void;
26 onDelete: () => void;
27 onClose: () => void;
28}
29
30/** A tab's options dropdown, rendered in a portal to escape overflow clipping. */
31function TabMenu({ menu, canDelete, onRename, onDuplicate, onDelete, onClose }: TabMenuProps) {
32 return createPortal(
33 <div
34 className="pkg-tab-dropdown"
35 style={{ position: 'fixed', top: menu.top, left: menu.left }}
36 onClick={e => e.stopPropagation()}
37 >
38 <button onClick={() => { onRename(); onClose(); }}>Rename</button>
39 <button onClick={() => { onDuplicate(); onClose(); }}>Duplicate</button>
40 {canDelete && (
41 <button className="danger" onClick={() => { onDelete(); onClose(); }}>Delete</button>
42 )}
43 </div>,
44 document.body
45 );
46}
47
48interface PackageTabProps {
49 slot: PackageSlot;
50 active: boolean;
51 editing: boolean;
52 draft: string;
53 canRemove: boolean;
54 onDraft: (value: string) => void;
55 onSwitch: () => void;
56 onStartRename: () => void;
57 onCommit: () => void;
58 onCancel: () => void;
59 onMenu: (e: React.MouseEvent<HTMLButtonElement>) => void;
60 onRemove: () => void;
61}
62
63function PackageTab(props: PackageTabProps) {
64 const { slot, active, editing, draft, canRemove } = props;
65 return (
66 <div
67 className={`pkg-tab${active ? ' active' : ''}`}
68 onClick={() => !active && props.onSwitch()}
69 >
70 {editing ? (
71 <input
72 autoFocus
73 className="pkg-tab-input"
74 value={draft}
75 onChange={e => props.onDraft(e.target.value)}
76 onBlur={props.onCommit}
77 onKeyDown={e => {
78 if (e.key === 'Enter') props.onCommit();
79 if (e.key === 'Escape') props.onCancel();
80 }}
81 onClick={e => e.stopPropagation()}
82 />
83 ) : (
84 <span
85 className="pkg-tab-name"
86 onDoubleClick={e => { e.stopPropagation(); props.onStartRename(); }}
87 >
88 {slot.name}
89 </span>
90 )}
91
92 <div className="pkg-tab-actions">
93 <button
94 className="pkg-tab-menu-btn"
95 title="Options"
96 onClick={props.onMenu}
97 >
98 ···
99 </button>
100 {canRemove && (
101 <button
102 className="pkg-tab-close"
103 title="Remove"
104 onClick={e => { e.stopPropagation(); props.onRemove(); }}
105 >
106 ×
107 </button>
108 )}
109 </div>
110 </div>
111 );
112}
113
21export function PackageSwitcher({ slots, activeId, onSwitch, onCreate, onRemove, onRename, onDuplicate }: Props) { 114export function PackageSwitcher({ slots, activeId, onSwitch, onCreate, onRemove, onRename, onDuplicate }: Props) {
22 const [editingId, setEditingId] = useState<string | null>(null); 115 const [editingId, setEditingId] = useState<string | null>(null);
23 const [draft, setDraft] = useState(''); 116 const [draft, setDraft] = useState('');
@@ -38,6 +131,11 @@ export function PackageSwitcher({ slots, activeId, onSwitch, onCreate, onRemove,
38 setMenu({ id, top: rect.bottom + 4, left: rect.left }); 131 setMenu({ id, top: rect.bottom + 4, left: rect.left });
39 }; 132 };
40 133
134 const startRename = (slot: PackageSlot) => {
135 setDraft(slot.name);
136 setEditingId(slot.id);
137 };
138
41 const commitRename = (id: string) => { 139 const commitRename = (id: string) => {
42 const name = draft.trim(); 140 const name = draft.trim();
43 if (name) onRename(id, name); 141 if (name) onRename(id, name);
@@ -47,78 +145,37 @@ export function PackageSwitcher({ slots, activeId, onSwitch, onCreate, onRemove,
47 return ( 145 return (
48 <div className="pkg-switcher"> 146 <div className="pkg-switcher">
49 {slots.map(slot => ( 147 {slots.map(slot => (
50 <div 148 <PackageTab
51 key={slot.id} 149 key={slot.id}
52 className={`pkg-tab${slot.id === activeId ? ' active' : ''}`} 150 slot={slot}
53 onClick={() => slot.id !== activeId && onSwitch(slot.id)} 151 active={slot.id === activeId}
54 > 152 editing={editingId === slot.id}
55 {editingId === slot.id ? ( 153 draft={draft}
56 <input 154 canRemove={slots.length > 1}
57 autoFocus 155 onDraft={setDraft}
58 className="pkg-tab-input" 156 onSwitch={() => onSwitch(slot.id)}
59 value={draft} 157 onStartRename={() => startRename(slot)}
60 onChange={e => setDraft(e.target.value)} 158 onCommit={() => commitRename(slot.id)}
61 onBlur={() => commitRename(slot.id)} 159 onCancel={() => setEditingId(null)}
62 onKeyDown={e => { 160 onMenu={e => openMenu(slot.id, e)}
63 if (e.key === 'Enter') commitRename(slot.id); 161 onRemove={() => onRemove(slot.id)}
64 if (e.key === 'Escape') setEditingId(null); 162 />
65 }}
66 onClick={e => e.stopPropagation()}
67 />
68 ) : (
69 <span
70 className="pkg-tab-name"
71 onDoubleClick={e => {
72 e.stopPropagation();
73 setDraft(slot.name);
74 setEditingId(slot.id);
75 }}
76 >
77 {slot.name}
78 </span>
79 )}
80
81 <div className="pkg-tab-actions">
82 <button
83 className="pkg-tab-menu-btn"
84 title="Options"
85 onClick={e => openMenu(slot.id, e)}
86 >
87 ···
88 </button>
89 {slots.length > 1 && (
90 <button
91 className="pkg-tab-close"
92 title="Remove"
93 onClick={e => { e.stopPropagation(); onRemove(slot.id); }}
94 >
95 ×
96 </button>
97 )}
98 </div>
99 </div>
100 ))} 163 ))}
101 164
102 <button className="pkg-new-btn" onClick={onCreate} title="New package">+</button> 165 <button className="pkg-new-btn" onClick={onCreate} title="New package">+</button>
103 166
104 {/* Dropdown rendered in a portal to escape overflow clipping */} 167 {menu && (
105 {menu && createPortal( 168 <TabMenu
106 <div 169 menu={menu}
107 className="pkg-tab-dropdown" 170 canDelete={slots.length > 1}
108 style={{ position: 'fixed', top: menu.top, left: menu.left }} 171 onRename={() => {
109 onClick={e => e.stopPropagation()}
110 >
111 <button onClick={() => {
112 const slot = slots.find(s => s.id === menu.id); 172 const slot = slots.find(s => s.id === menu.id);
113 if (slot) { setDraft(slot.name); setEditingId(slot.id); } 173 if (slot) startRename(slot);
114 setMenu(null); 174 }}
115 }}>Rename</button> 175 onDuplicate={() => onDuplicate(menu.id)}
116 <button onClick={() => { onDuplicate(menu.id); setMenu(null); }}>Duplicate</button> 176 onDelete={() => onRemove(menu.id)}
117 {slots.length > 1 && ( 177 onClose={() => setMenu(null)}
118 <button className="danger" onClick={() => { onRemove(menu.id); setMenu(null); }}>Delete</button> 178 />
119 )}
120 </div>,
121 document.body
122 )} 179 )}
123 </div> 180 </div>
124 ); 181 );
src/engine/directions.json added +98
@@ -0,0 +1,98 @@
1{
2 "technical": [
3 {
4 "id": "terminal-minimal",
5 "name": "Terminal Minimal",
6 "description": "Dark background, monospace type throughout, no ornament. Functional and uncompromising. Every element earns its place.",
7 "palette": "Near-black ground (#0d0d0d), off-white text (#e0e0e0), single muted accent (amber or green).",
8 "typography": "Monospace primary — JetBrains Mono or Iosevka. Consistent weight. No italic.",
9 "references": "htop, k9s, the Stripe CLI, Linear issue view."
10 },
11 {
12 "id": "technical-document",
13 "name": "Technical Document",
14 "description": "Off-white ground, dense information layout, RFC/spec aesthetic. Designed for reading, not scanning. Typography does all the work.",
15 "palette": "Warm white (#f5f3ef), dark text (#1a1a1a), minimal color — one functional accent only.",
16 "typography": "Sans-serif (Inter or similar) for body, mono for code. Tight line height. Strong hierarchy through size and weight alone.",
17 "references": "Stripe docs, Oxide Computer RFCs, GNU manpages reformatted."
18 },
19 {
20 "id": "precision-interface",
21 "name": "Precision Interface",
22 "description": "Neutral mid-range palette, strong grid, engineering-tool aesthetic. Balanced between document and application. Calm but capable.",
23 "palette": "Mid-grey ground (#f0f0f0 or #1c1c1c), charcoal type, restrained use of blue or slate as action color.",
24 "typography": "Sans-serif for UI, mono for data. Clear size differentiation. No decorative weight use.",
25 "references": "Figma sidebar, Retool, Zed editor, TablePlus."
26 }
27 ],
28 "creative": [
29 {
30 "id": "editorial",
31 "name": "Editorial",
32 "description": "Strong typographic hierarchy, restrained palette, print-design influences. Work foreground, everything else background.",
33 "palette": "Off-white or cream (#f7f4ef), near-black type, accent used once — a single warm or cool tone.",
34 "typography": "A good serif for display, neutral sans for body. Generous leading. No decorative fonts.",
35 "references": "Are.na, Typewolf, Emigre back catalog, Letterform Archive."
36 },
37 {
38 "id": "quiet-studio",
39 "name": "Quiet Studio",
40 "description": "Neutral and considered. Nothing decorative. Space used to direct attention, not fill it.",
41 "palette": "Warm white (#fafaf8) or deep neutral (#141414), type-only color use. No gradients.",
42 "typography": "One typeface family, two weights. Let leading and spacing create rhythm.",
43 "references": "Pentagram case studies, Swiss International Style, Muji product design."
44 },
45 {
46 "id": "contemporary-craft",
47 "name": "Contemporary Craft",
48 "description": "Tactile references — paper, grain, texture — applied with restraint. Warmth without nostalgia.",
49 "palette": "Off-white base with a warm paper tone, subtle texture overlays, earthy accent.",
50 "typography": "Mix: display serif + utility sans. Comfortable reading size. Generous margins.",
51 "references": "Oak Studio, Analog, Offscreen Magazine, Present & Correct."
52 }
53 ],
54 "product": [
55 {
56 "id": "focused-product",
57 "name": "Focused Product",
58 "description": "Clean, professional, information-forward. Looks like it was built to be used, not to be admired. Trust through clarity.",
59 "palette": "White or light grey ground, dark neutral type, one brand color used only for primary actions.",
60 "typography": "Neutral sans-serif, systematic sizing, no personality — the product is the personality.",
61 "references": "Linear, Cron (v1), Vercel dashboard, Raycast."
62 },
63 {
64 "id": "minimal-commerce",
65 "name": "Minimal Commerce",
66 "description": "Premium restraint. No decorative elements. White space signals quality. Type-driven.",
67 "palette": "White ground, black type, one warm accent for selective emphasis.",
68 "typography": "A refined sans-serif. Large display size for key claims. Small, tracked caps for labels.",
69 "references": "Stripe marketing, Basecamp, Arc browser landing page."
70 },
71 {
72 "id": "structured-trust",
73 "name": "Structured Trust",
74 "description": "Grid-heavy, methodical, legible. Communicates that things are in order. More function, less flourish.",
75 "palette": "Light neutral ground, two text weights (body + emphasis), a contained accent color.",
76 "typography": "Professional sans-serif — GT Walsheim or Plus Jakarta or similar. Tight tracking for headings.",
77 "references": "Harvest app, FreshBooks, Notion, Loom landing page."
78 }
79 ],
80 "fallback": [
81 {
82 "id": "type-forward",
83 "name": "Type Forward",
84 "description": "Typography as the only design element. No illustration, no photography, no pattern. Words do everything.",
85 "palette": "Black and white, one optional accent. No gradients.",
86 "typography": "One great typeface. Multiple weights. Extreme size contrast. Nothing else needed.",
87 "references": "Early Bloomberg Businessweek covers, Helvetica film poster, The Economist."
88 },
89 {
90 "id": "system-neutral",
91 "name": "System Neutral",
92 "description": "Invisible design — system fonts, default spacing, no signature. The brand is in the content, not the container.",
93 "palette": "System defaults. One custom color — the brand color. Everything else inherited.",
94 "typography": "System UI stack. Optimized for the OS it runs on.",
95 "references": "HN, iA Writer, Pinboard, older Stripe."
96 }
97 ]
98}
src/engine/generator.ts +40 −255
@@ -10,6 +10,7 @@ import type {
10 Typography, 10 Typography,
11 TypographyToken, 11 TypographyToken,
12} from '../types'; 12} from '../types';
13import DIRECTIONS from './directions.json';
13 14
14type CategoryType = 'developer' | 'creative' | 'product' | 'services' | 'personal' | 'general'; 15type CategoryType = 'developer' | 'creative' | 'product' | 'services' | 'personal' | 'general';
15 16
@@ -391,122 +392,16 @@ function generateVisualDirections(ctx: GenContext): VisualDirection[] {
391 const allDirections: VisualDirection[] = []; 392 const allDirections: VisualDirection[] = [];
392 393
393 if (catType === 'developer' || hasTone('technical') || hasTone('minimal')) { 394 if (catType === 'developer' || hasTone('technical') || hasTone('minimal')) {
394 allDirections.push( 395 allDirections.push(...DIRECTIONS.technical);
395 {
396 id: 'terminal-minimal',
397 name: 'Terminal Minimal',
398 description:
399 'Dark background, monospace type throughout, no ornament. Functional and uncompromising. Every element earns its place.',
400 palette: 'Near-black ground (#0d0d0d), off-white text (#e0e0e0), single muted accent (amber or green).',
401 typography: 'Monospace primary — JetBrains Mono or Iosevka. Consistent weight. No italic.',
402 references: 'htop, k9s, the Stripe CLI, Linear issue view.',
403 },
404 {
405 id: 'technical-document',
406 name: 'Technical Document',
407 description:
408 'Off-white ground, dense information layout, RFC/spec aesthetic. Designed for reading, not scanning. Typography does all the work.',
409 palette: 'Warm white (#f5f3ef), dark text (#1a1a1a), minimal color — one functional accent only.',
410 typography: 'Sans-serif (Inter or similar) for body, mono for code. Tight line height. Strong hierarchy through size and weight alone.',
411 references: 'Stripe docs, Oxide Computer RFCs, GNU manpages reformatted.',
412 },
413 {
414 id: 'precision-interface',
415 name: 'Precision Interface',
416 description:
417 'Neutral mid-range palette, strong grid, engineering-tool aesthetic. Balanced between document and application. Calm but capable.',
418 palette: 'Mid-grey ground (#f0f0f0 or #1c1c1c), charcoal type, restrained use of blue or slate as action color.',
419 typography: 'Sans-serif for UI, mono for data. Clear size differentiation. No decorative weight use.',
420 references: 'Figma sidebar, Retool, Zed editor, TablePlus.',
421 }
422 );
423 } 396 }
424
425 if (catType === 'creative' || catType === 'personal') { 397 if (catType === 'creative' || catType === 'personal') {
426 allDirections.push( 398 allDirections.push(...DIRECTIONS.creative);
427 {
428 id: 'editorial',
429 name: 'Editorial',
430 description:
431 'Strong typographic hierarchy, restrained palette, print-design influences. Work foreground, everything else background.',
432 palette: 'Off-white or cream (#f7f4ef), near-black type, accent used once — a single warm or cool tone.',
433 typography: 'A good serif for display, neutral sans for body. Generous leading. No decorative fonts.',
434 references: 'Are.na, Typewolf, Emigre back catalog, Letterform Archive.',
435 },
436 {
437 id: 'quiet-studio',
438 name: 'Quiet Studio',
439 description:
440 'Neutral and considered. Nothing decorative. Space used to direct attention, not fill it.',
441 palette: 'Warm white (#fafaf8) or deep neutral (#141414), type-only color use. No gradients.',
442 typography: 'One typeface family, two weights. Let leading and spacing create rhythm.',
443 references: 'Pentagram case studies, Swiss International Style, Muji product design.',
444 },
445 {
446 id: 'contemporary-craft',
447 name: 'Contemporary Craft',
448 description:
449 'Tactile references — paper, grain, texture — applied with restraint. Warmth without nostalgia.',
450 palette: 'Off-white base with a warm paper tone, subtle texture overlays, earthy accent.',
451 typography: 'Mix: display serif + utility sans. Comfortable reading size. Generous margins.',
452 references: 'Oak Studio, Analog, Offscreen Magazine, Present & Correct.',
453 }
454 );
455 } 399 }
456
457 if (catType === 'product' || catType === 'services') { 400 if (catType === 'product' || catType === 'services') {
458 allDirections.push( 401 allDirections.push(...DIRECTIONS.product);
459 {
460 id: 'focused-product',
461 name: 'Focused Product',
462 description:
463 'Clean, professional, information-forward. Looks like it was built to be used, not to be admired. Trust through clarity.',
464 palette: 'White or light grey ground, dark neutral type, one brand color used only for primary actions.',
465 typography: 'Neutral sans-serif, systematic sizing, no personality — the product is the personality.',
466 references: 'Linear, Cron (v1), Vercel dashboard, Raycast.',
467 },
468 {
469 id: 'minimal-commerce',
470 name: 'Minimal Commerce',
471 description:
472 'Premium restraint. No decorative elements. White space signals quality. Type-driven.',
473 palette: 'White ground, black type, one warm accent for selective emphasis.',
474 typography: 'A refined sans-serif. Large display size for key claims. Small, tracked caps for labels.',
475 references: 'Stripe marketing, Basecamp, Arc browser landing page.',
476 },
477 {
478 id: 'structured-trust',
479 name: 'Structured Trust',
480 description:
481 'Grid-heavy, methodical, legible. Communicates that things are in order. More function, less flourish.',
482 palette: 'Light neutral ground, two text weights (body + emphasis), a contained accent color.',
483 typography: 'Professional sans-serif — GT Walsheim or Plus Jakarta or similar. Tight tracking for headings.',
484 references: 'Harvest app, FreshBooks, Notion, Loom landing page.',
485 }
486 );
487 } 402 }
488
489 if (allDirections.length === 0) { 403 if (allDirections.length === 0) {
490 allDirections.push( 404 allDirections.push(...DIRECTIONS.fallback);
491 {
492 id: 'type-forward',
493 name: 'Type Forward',
494 description:
495 'Typography as the only design element. No illustration, no photography, no pattern. Words do everything.',
496 palette: 'Black and white, one optional accent. No gradients.',
497 typography: 'One great typeface. Multiple weights. Extreme size contrast. Nothing else needed.',
498 references: 'Early Bloomberg Businessweek covers, Helvetica film poster, The Economist.',
499 },
500 {
501 id: 'system-neutral',
502 name: 'System Neutral',
503 description:
504 'Invisible design — system fonts, default spacing, no signature. The brand is in the content, not the container.',
505 palette: 'System defaults. One custom color — the brand color. Everything else inherited.',
506 typography: 'System UI stack. Optimized for the OS it runs on.',
507 references: 'HN, iA Writer, Pinboard, older Stripe.',
508 }
509 );
510 } 405 }
511 406
512 return pickN(allDirections, Math.min(3, allDirections.length)); 407 return pickN(allDirections, Math.min(3, allDirections.length));
@@ -768,166 +663,56 @@ function makeSwatches(entries: [string, string, string][]): ColorSwatch[] {
768 return entries.map(([name, hex, role], i) => ({ id: `s${i}`, name, hex, role })); 663 return entries.map(([name, hex, role], i) => ({ id: `s${i}`, name, hex, role }));
769} 664}
770 665
666type SwatchEntry = [string, string, string]; // [name, hex, role]
667
668/** A six-swatch palette: background, surface, neutral, primary, accent, text. */
669function sixTone(
670 [background, surface, neutral, primary, accent, text]: [string, string, string, string, string, string],
671 neutralName = 'Neutral',
672): SwatchEntry[] {
673 return [
674 ['Background', background, 'background'],
675 ['Surface', surface, 'neutral'],
676 [neutralName, neutral, 'neutral'],
677 ['Primary', primary, 'primary'],
678 ['Accent', accent, 'accent'],
679 ['Text', text, 'text'],
680 ];
681}
682
771function generateColorPalette(ctx: GenContext): ColorPalette { 683function generateColorPalette(ctx: GenContext): ColorPalette {
772 type SwatchEntry = [string, string, string]; // [name, hex, role]
773 type PaletteSet = SwatchEntry[][]; 684 type PaletteSet = SwatchEntry[][];
774 685
775 const palettes: Record<string, PaletteSet> = { 686 const palettes: Record<string, PaletteSet> = {
776 developer: [ 687 developer: [
777 [ 688 sixTone(['#0d1117', '#161b22', '#30363d', '#58a6ff', '#3fb950', '#f0f6fc'], 'Border'),
778 ['Background', '#0d1117', 'background'], 689 sixTone(['#0a0010', '#160025', '#2d1f3d', '#7c3aed', '#a78bfa', '#e2d9f3']),
779 ['Surface', '#161b22', 'neutral'], 690 sixTone(['#0a0a0a', '#141414', '#292929', '#e5e5e5', '#c9a96e', '#f5f5f5']),
780 ['Border', '#30363d', 'neutral'],
781 ['Primary', '#58a6ff', 'primary'],
782 ['Accent', '#3fb950', 'accent'],
783 ['Text', '#f0f6fc', 'text'],
784 ],
785 [
786 ['Background', '#0a0010', 'background'],
787 ['Surface', '#160025', 'neutral'],
788 ['Neutral', '#2d1f3d', 'neutral'],
789 ['Primary', '#7c3aed', 'primary'],
790 ['Accent', '#a78bfa', 'accent'],
791 ['Text', '#e2d9f3', 'text'],
792 ],
793 [
794 ['Background', '#0a0a0a', 'background'],
795 ['Surface', '#141414', 'neutral'],
796 ['Neutral', '#292929', 'neutral'],
797 ['Primary', '#e5e5e5', 'primary'],
798 ['Accent', '#c9a96e', 'accent'],
799 ['Text', '#f5f5f5', 'text'],
800 ],
801 ], 691 ],
802 creative: [ 692 creative: [
803 [ 693 sixTone(['#faf7f2', '#f5efe4', '#e8d9c4', '#c07850', '#4a7c5f', '#1a1410']),
804 ['Background', '#faf7f2', 'background'], 694 sixTone(['#0f0f0f', '#1a1a1a', '#2e2e2e', '#ff6b35', '#ffd700', '#f8f8f8']),
805 ['Surface', '#f5efe4', 'neutral'], 695 sixTone(['#f8f4ef', '#efe9e0', '#d4c4b0', '#8b5e3c', '#6b8f71', '#2c2018']),
806 ['Neutral', '#e8d9c4', 'neutral'],
807 ['Primary', '#c07850', 'primary'],
808 ['Accent', '#4a7c5f', 'accent'],
809 ['Text', '#1a1410', 'text'],
810 ],
811 [
812 ['Background', '#0f0f0f', 'background'],
813 ['Surface', '#1a1a1a', 'neutral'],
814 ['Neutral', '#2e2e2e', 'neutral'],
815 ['Primary', '#ff6b35', 'primary'],
816 ['Accent', '#ffd700', 'accent'],
817 ['Text', '#f8f8f8', 'text'],
818 ],
819 [
820 ['Background', '#f8f4ef', 'background'],
821 ['Surface', '#efe9e0', 'neutral'],
822 ['Neutral', '#d4c4b0', 'neutral'],
823 ['Primary', '#8b5e3c', 'primary'],
824 ['Accent', '#6b8f71', 'accent'],
825 ['Text', '#2c2018', 'text'],
826 ],
827 ], 696 ],
828 product: [ 697 product: [
829 [ 698 sixTone(['#fafbfc', '#f0f4f8', '#d1dce8', '#2563eb', '#7c3aed', '#1e293b']),
830 ['Background', '#fafbfc', 'background'], 699 sixTone(['#0f172a', '#1e293b', '#334155', '#6366f1', '#22d3ee', '#f1f5f9']),
831 ['Surface', '#f0f4f8', 'neutral'], 700 sixTone(['#f0fafa', '#e0f5f5', '#b2dede', '#0d9488', '#f59e0b', '#134e4a']),
832 ['Neutral', '#d1dce8', 'neutral'],
833 ['Primary', '#2563eb', 'primary'],
834 ['Accent', '#7c3aed', 'accent'],
835 ['Text', '#1e293b', 'text'],
836 ],
837 [
838 ['Background', '#0f172a', 'background'],
839 ['Surface', '#1e293b', 'neutral'],
840 ['Neutral', '#334155', 'neutral'],
841 ['Primary', '#6366f1', 'primary'],
842 ['Accent', '#22d3ee', 'accent'],
843 ['Text', '#f1f5f9', 'text'],
844 ],
845 [
846 ['Background', '#f0fafa', 'background'],
847 ['Surface', '#e0f5f5', 'neutral'],
848 ['Neutral', '#b2dede', 'neutral'],
849 ['Primary', '#0d9488', 'primary'],
850 ['Accent', '#f59e0b', 'accent'],
851 ['Text', '#134e4a', 'text'],
852 ],
853 ], 701 ],
854 services: [ 702 services: [
855 [ 703 sixTone(['#f8fafd', '#edf2fa', '#ccd9ee', '#1d4ed8', '#0f9e6e', '#1a2038']),
856 ['Background', '#f8fafd', 'background'], 704 sixTone(['#0c1421', '#152035', '#243450', '#3b82f6', '#34d399', '#f8fafc']),
857 ['Surface', '#edf2fa', 'neutral'], 705 sixTone(['#faf8f5', '#f0ebe0', '#d9cdb8', '#78523a', '#2d6a4f', '#1c1410']),
858 ['Neutral', '#ccd9ee', 'neutral'],
859 ['Primary', '#1d4ed8', 'primary'],
860 ['Accent', '#0f9e6e', 'accent'],
861 ['Text', '#1a2038', 'text'],
862 ],
863 [
864 ['Background', '#0c1421', 'background'],
865 ['Surface', '#152035', 'neutral'],
866 ['Neutral', '#243450', 'neutral'],
867 ['Primary', '#3b82f6', 'primary'],
868 ['Accent', '#34d399', 'accent'],
869 ['Text', '#f8fafc', 'text'],
870 ],
871 [
872 ['Background', '#faf8f5', 'background'],
873 ['Surface', '#f0ebe0', 'neutral'],
874 ['Neutral', '#d9cdb8', 'neutral'],
875 ['Primary', '#78523a', 'primary'],
876 ['Accent', '#2d6a4f', 'accent'],
877 ['Text', '#1c1410', 'text'],
878 ],
879 ], 706 ],
880 personal: [ 707 personal: [
881 [ 708 sixTone(['#fffef9', '#fdf8ee', '#f0e6cc', '#c9a96e', '#7c9e87', '#2d2d2d']),
882 ['Background', '#fffef9', 'background'], 709 sixTone(['#fafafa', '#f5f5f5', '#e5e5e5', '#171717', '#737373', '#404040']),
883 ['Surface', '#fdf8ee', 'neutral'], 710 sixTone(['#f9f8ff', '#f0eeff', '#ddd8f7', '#4f46e5', '#ec4899', '#1e1b4b']),
884 ['Neutral', '#f0e6cc', 'neutral'],
885 ['Primary', '#c9a96e', 'primary'],
886 ['Accent', '#7c9e87', 'accent'],
887 ['Text', '#2d2d2d', 'text'],
888 ],
889 [
890 ['Background', '#fafafa', 'background'],
891 ['Surface', '#f5f5f5', 'neutral'],
892 ['Neutral', '#e5e5e5', 'neutral'],
893 ['Primary', '#171717', 'primary'],
894 ['Accent', '#737373', 'accent'],
895 ['Text', '#404040', 'text'],
896 ],
897 [
898 ['Background', '#f9f8ff', 'background'],
899 ['Surface', '#f0eeff', 'neutral'],
900 ['Neutral', '#ddd8f7', 'neutral'],
901 ['Primary', '#4f46e5', 'primary'],
902 ['Accent', '#ec4899', 'accent'],
903 ['Text', '#1e1b4b', 'text'],
904 ],
905 ], 711 ],
906 general: [ 712 general: [
907 [ 713 sixTone(['#111111', '#1a1a1a', '#2e2e2e', '#c9a96e', '#6b8f71', '#dedede']),
908 ['Background', '#111111', 'background'], 714 sixTone(['#ffffff', '#f5f5f5', '#e0e0e0', '#1a1a1a', '#3b82f6', '#333333']),
909 ['Surface', '#1a1a1a', 'neutral'], 715 sixTone(['#0f0f1a', '#1a1a2e', '#252545', '#4f8ef7', '#a78bfa', '#e2e8f0']),
910 ['Neutral', '#2e2e2e', 'neutral'],
911 ['Primary', '#c9a96e', 'primary'],
912 ['Accent', '#6b8f71', 'accent'],
913 ['Text', '#dedede', 'text'],
914 ],
915 [
916 ['Background', '#ffffff', 'background'],
917 ['Surface', '#f5f5f5', 'neutral'],
918 ['Neutral', '#e0e0e0', 'neutral'],
919 ['Primary', '#1a1a1a', 'primary'],
920 ['Accent', '#3b82f6', 'accent'],
921 ['Text', '#333333', 'text'],
922 ],
923 [
924 ['Background', '#0f0f1a', 'background'],
925 ['Surface', '#1a1a2e', 'neutral'],
926 ['Neutral', '#252545', 'neutral'],
927 ['Primary', '#4f8ef7', 'primary'],
928 ['Accent', '#a78bfa', 'accent'],
929 ['Text', '#e2e8f0', 'text'],
930 ],
931 ], 716 ],
932 }; 717 };
933 718
src/hooks/usePackages.ts +45 −52
@@ -45,68 +45,61 @@ function saveStore(store: PackagesStore): void {
45 try { localStorage.setItem(STORE_KEY, JSON.stringify(store)); } catch { /* ignore */ } 45 try { localStorage.setItem(STORE_KEY, JSON.stringify(store)); } catch { /* ignore */ }
46} 46}
47 47
48export function usePackages() { 48function withActive(prev: PackagesStore, id: string): PackagesStore {
49 const [store, setStore] = useState<PackagesStore>(loadStore); 49 return prev.activeId === id ? prev : { ...prev, activeId: id };
50}
50 51
51 const activeSlot = store.slots.find(s => s.id === store.activeId) ?? store.slots[0]; 52function withNewSlot(prev: PackagesStore): PackagesStore {
53 const slot = makeSlot(`Package ${prev.slots.length + 1}`);
54 // New slot has no data in localStorage — useWorkspace will start fresh
55 return { activeId: slot.id, slots: [...prev.slots, slot] };
56}
52 57
53 // useWorkspace saves directly to each slot's storageKey on every change, 58function withoutSlot(prev: PackagesStore, id: string): PackagesStore {
54 // so switching just needs to update activeId — no snapshot/copy required. 59 if (prev.slots.length <= 1) return prev;
55 const switchTo = useCallback((id: string) => { 60 const target = prev.slots.find(s => s.id === id);
56 setStore(prev => { 61 try { if (target) localStorage.removeItem(target.storageKey); } catch { /* ignore */ }
57 if (prev.activeId === id) return prev; 62 const slots = prev.slots.filter(s => s.id !== id);
58 const next = { ...prev, activeId: id }; 63 const activeId = prev.activeId === id ? slots[0].id : prev.activeId;
59 saveStore(next); 64 return { activeId, slots };
60 return next; 65}
61 });
62 }, []);
63 66
64 const createNew = useCallback(() => { 67function withRenamed(prev: PackagesStore, id: string, name: string): PackagesStore {
65 setStore(prev => { 68 return { ...prev, slots: prev.slots.map(s => s.id === id ? { ...s, name } : s) };
66 const slot = makeSlot(`Package ${prev.slots.length + 1}`); 69}
67 // New slot has no data in localStorage — useWorkspace will start fresh
68 const next = { activeId: slot.id, slots: [...prev.slots, slot] };
69 saveStore(next);
70 return next;
71 });
72 }, []);
73 70
74 const remove = useCallback((id: string) => { 71function withDuplicate(prev: PackagesStore, id: string): PackagesStore {
75 setStore(prev => { 72 const source = prev.slots.find(s => s.id === id);
76 if (prev.slots.length <= 1) return prev; 73 if (!source) return prev;
77 const target = prev.slots.find(s => s.id === id); 74 const newSlot = makeSlot(`${source.name} copy`);
78 try { if (target) localStorage.removeItem(target.storageKey); } catch { /* ignore */ } 75 try {
79 const slots = prev.slots.filter(s => s.id !== id); 76 const data = localStorage.getItem(source.storageKey);
80 const activeId = prev.activeId === id ? slots[0].id : prev.activeId; 77 if (data) localStorage.setItem(newSlot.storageKey, data);
81 const next = { activeId, slots }; 78 } catch { /* ignore */ }
82 saveStore(next); 79 return { activeId: newSlot.id, slots: [...prev.slots, newSlot] };
83 return next; 80}
84 });
85 }, []);
86 81
87 const rename = useCallback((id: string, name: string) => { 82export function usePackages() {
88 setStore(prev => { 83 const [store, setStore] = useState<PackagesStore>(loadStore);
89 const slots = prev.slots.map(s => s.id === id ? { ...s, name } : s); 84
90 const next = { ...prev, slots }; 85 const activeSlot = store.slots.find(s => s.id === store.activeId) ?? store.slots[0];
91 saveStore(next);
92 return next;
93 });
94 }, []);
95 86
96 const duplicate = useCallback((id: string) => { 87 // Apply a change and save it; a change that returns the same store is a no-op.
88 const update = useCallback((change: (prev: PackagesStore) => PackagesStore) => {
97 setStore(prev => { 89 setStore(prev => {
98 const source = prev.slots.find(s => s.id === id); 90 const next = change(prev);
99 if (!source) return prev; 91 if (next !== prev) saveStore(next);
100 const newSlot = makeSlot(`${source.name} copy`);
101 try {
102 const data = localStorage.getItem(source.storageKey);
103 if (data) localStorage.setItem(newSlot.storageKey, data);
104 } catch { /* ignore */ }
105 const next = { activeId: newSlot.id, slots: [...prev.slots, newSlot] };
106 saveStore(next);
107 return next; 92 return next;
108 }); 93 });
109 }, []); 94 }, []);
110 95
96 // useWorkspace saves directly to each slot's storageKey on every change,
97 // so switching just needs to update activeId — no snapshot/copy required.
98 const switchTo = useCallback((id: string) => update(prev => withActive(prev, id)), [update]);
99 const createNew = useCallback(() => update(withNewSlot), [update]);
100 const remove = useCallback((id: string) => update(prev => withoutSlot(prev, id)), [update]);
101 const rename = useCallback((id: string, name: string) => update(prev => withRenamed(prev, id, name)), [update]);
102 const duplicate = useCallback((id: string) => update(prev => withDuplicate(prev, id)), [update]);
103
111 return { slots: store.slots, activeId: store.activeId, activeSlot, switchTo, createNew, remove, rename, duplicate }; 104 return { slots: store.slots, activeId: store.activeId, activeSlot, switchTo, createNew, remove, rename, duplicate };
112} 105}
src/hooks/useWorkspace.ts +77 −60
@@ -73,25 +73,25 @@ function applyLocks(
73 return merged; 73 return merged;
74} 74}
75 75
76export function useWorkspace(storageKey = 'bw:workspace') { 76/** The template or AI outputs for `inputs`, or null if aborted while waiting. */
77 const saved = loadState(storageKey); 77async function produceOutputs(
78 inputs: BrandInputs,
79 settings: ReturnType<typeof readSettings>,
80 signal: AbortSignal,
81): Promise<BrandOutputs | null> {
82 if (settings.enabled) return generateWithAI(inputs, settings, signal);
83 await new Promise(r => setTimeout(r, 120));
84 if (signal.aborted) return null;
85 return generate(inputs);
86}
78 87
79 const [inputs, setInputsRaw] = useState<BrandInputs>(saved.inputs ?? DEFAULT_INPUTS); 88/** Section edits with an undo/redo stack. */
80 const [outputs, setOutputs] = useState<BrandOutputs | null>(saved.outputs ?? null); 89function useEditHistory(initial: Partial<BrandOutputs>) {
81 const [edits, setEditsRaw] = useState<Partial<BrandOutputs>>(saved.edits ?? {}); 90 const [edits, setEditsRaw] = useState<Partial<BrandOutputs>>(initial);
82 const [locked, setLocked] = useState<LockedSections>(saved.locked ?? DEFAULT_LOCKED);
83 const [isGenerating, setIsGenerating] = useState(false);
84 const [generateMode, setGenerateMode] = useState<'template' | string>('template');
85 const [generateError, setGenerateError] = useState<string | null>(null);
86 const [canUndo, setCanUndo] = useState(false); 91 const [canUndo, setCanUndo] = useState(false);
87 const [canRedo, setCanRedo] = useState(false); 92 const [canRedo, setCanRedo] = useState(false);
88 93 const editStack = useRef<Array<Partial<BrandOutputs>>>([initial]);
89 const editStack = useRef<Array<Partial<BrandOutputs>>>([saved.edits ?? {}]);
90 const stackIdx = useRef(0); 94 const stackIdx = useRef(0);
91 const abortRef = useRef<AbortController | null>(null);
92
93 const stateRef = useRef({ inputs, outputs, edits, locked });
94 stateRef.current = { inputs, outputs, edits, locked };
95 95
96 const syncUndoRedo = () => { 96 const syncUndoRedo = () => {
97 setCanUndo(stackIdx.current > 0); 97 setCanUndo(stackIdx.current > 0);
@@ -108,11 +108,52 @@ export function useWorkspace(storageKey = 'bw:workspace') {
108 syncUndoRedo(); 108 syncUndoRedo();
109 }, []); 109 }, []);
110 110
111 const persistInputs = useCallback((value: BrandInputs) => { 111 const reset = useCallback(() => {
112 const { outputs, edits, locked } = stateRef.current; 112 editStack.current = [{}];
113 saveState(storageKey, { inputs: value, outputs, edits, locked }); 113 stackIdx.current = 0;
114 setEditsRaw({});
115 syncUndoRedo();
116 }, []);
117
118 // Move `delta` steps through the history; returns the edits stepped to, or
119 // null if that step does not exist.
120 const step = useCallback((delta: number): Partial<BrandOutputs> | null => {
121 const index = stackIdx.current + delta;
122 if (index < 0 || index >= editStack.current.length) return null;
123 stackIdx.current = index;
124 const next = editStack.current[index];
125 setEdits(next, false);
126 return next;
127 }, [setEdits]);
128
129 return { edits, canUndo, canRedo, setEdits, reset, step };
130}
131
132export function useWorkspace(storageKey = 'bw:workspace') {
133 const saved = loadState(storageKey);
134
135 const [inputs, setInputsRaw] = useState<BrandInputs>(saved.inputs ?? DEFAULT_INPUTS);
136 const [outputs, setOutputs] = useState<BrandOutputs | null>(saved.outputs ?? null);
137 const [locked, setLocked] = useState<LockedSections>(saved.locked ?? DEFAULT_LOCKED);
138 const [isGenerating, setIsGenerating] = useState(false);
139 const [generateMode, setGenerateMode] = useState<'template' | string>('template');
140 const [generateError, setGenerateError] = useState<string | null>(null);
141 const history = useEditHistory(saved.edits ?? {});
142 const { edits, setEdits } = history;
143 const abortRef = useRef<AbortController | null>(null);
144
145 const stateRef = useRef({ inputs, outputs, edits, locked });
146 stateRef.current = { inputs, outputs, edits, locked };
147
148 // Save the current state with `patch` applied.
149 const persist = useCallback((patch: Partial<WorkspaceState>) => {
150 saveState(storageKey, { ...stateRef.current, ...patch });
114 }, [storageKey]); 151 }, [storageKey]);
115 152
153 const persistInputs = useCallback((value: BrandInputs) => {
154 persist({ inputs: value });
155 }, [persist]);
156
116 const setInputs = useCallback((next: BrandInputs | ((prev: BrandInputs) => BrandInputs)) => { 157 const setInputs = useCallback((next: BrandInputs | ((prev: BrandInputs) => BrandInputs)) => {
117 setInputsRaw(prev => { 158 setInputsRaw(prev => {
118 const value = typeof next === 'function' ? next(prev) : next; 159 const value = typeof next === 'function' ? next(prev) : next;
@@ -135,24 +176,12 @@ export function useWorkspace(storageKey = 'bw:workspace') {
135 setGenerateMode(settings.enabled ? settings.model : 'template'); 176 setGenerateMode(settings.enabled ? settings.model : 'template');
136 177
137 try { 178 try {
138 let newOutputs: BrandOutputs; 179 const newOutputs = await produceOutputs(inputs, settings, abort.signal);
139 180 if (!newOutputs || abort.signal.aborted) return;
140 if (settings.enabled) {
141 newOutputs = await generateWithAI(inputs, settings, abort.signal);
142 } else {
143 await new Promise(r => setTimeout(r, 120));
144 if (abort.signal.aborted) return;
145 newOutputs = generate(inputs);
146 }
147
148 if (abort.signal.aborted) return;
149 181
150 const merged = applyLocks({ ...newOutputs }, locked, outputs, edits); 182 const merged = applyLocks({ ...newOutputs }, locked, outputs, edits);
151 setOutputs(merged); 183 setOutputs(merged);
152 editStack.current = [{}]; 184 history.reset();
153 stackIdx.current = 0;
154 setEditsRaw({});
155 syncUndoRedo();
156 saveState(storageKey, { inputs, outputs: merged, edits: {}, locked }); 185 saveState(storageKey, { inputs, outputs: merged, edits: {}, locked });
157 } catch (err) { 186 } catch (err) {
158 if ((err as Error).name === 'AbortError') return; 187 if ((err as Error).name === 'AbortError') return;
@@ -160,7 +189,7 @@ export function useWorkspace(storageKey = 'bw:workspace') {
160 } finally { 189 } finally {
161 setIsGenerating(false); 190 setIsGenerating(false);
162 } 191 }
163 }, [storageKey]); 192 }, [storageKey, history.reset]);
164 193
165 const cancelGenerate = useCallback(() => { 194 const cancelGenerate = useCallback(() => {
166 abortRef.current?.abort(); 195 abortRef.current?.abort();
@@ -169,38 +198,26 @@ export function useWorkspace(storageKey = 'bw:workspace') {
169 }, []); 198 }, []);
170 199
171 const updateEdit = useCallback(<K extends keyof BrandOutputs>(key: K, value: BrandOutputs[K]) => { 200 const updateEdit = useCallback(<K extends keyof BrandOutputs>(key: K, value: BrandOutputs[K]) => {
172 const { inputs, outputs, locked } = stateRef.current;
173 const next = { ...stateRef.current.edits, [key]: value }; 201 const next = { ...stateRef.current.edits, [key]: value };
174 setEdits(next, true); 202 setEdits(next, true);
175 saveState(storageKey, { inputs, outputs, edits: next, locked }); 203 persist({ edits: next });
176 }, [storageKey, setEdits]); 204 }, [persist, setEdits]);
177 205
178 const undo = useCallback(() => { 206 const stepHistory = useCallback((delta: number) => {
179 if (stackIdx.current <= 0) return; 207 const edits = history.step(delta);
180 stackIdx.current -= 1; 208 if (edits) persist({ edits });
181 const prev = editStack.current[stackIdx.current]; 209 }, [persist, history.step]);
182 const { inputs, outputs, locked } = stateRef.current; 210
183 setEdits(prev, false); 211 const undo = useCallback(() => stepHistory(-1), [stepHistory]);
184 saveState(storageKey, { inputs, outputs, edits: prev, locked }); 212 const redo = useCallback(() => stepHistory(1), [stepHistory]);
185 }, [storageKey, setEdits]);
186
187 const redo = useCallback(() => {
188 if (stackIdx.current >= editStack.current.length - 1) return;
189 stackIdx.current += 1;
190 const next = editStack.current[stackIdx.current];
191 const { inputs, outputs, locked } = stateRef.current;
192 setEdits(next, false);
193 saveState(storageKey, { inputs, outputs, edits: next, locked });
194 }, [storageKey, setEdits]);
195 213
196 const toggleLock = useCallback((section: keyof LockedSections) => { 214 const toggleLock = useCallback((section: keyof LockedSections) => {
197 setLocked(prev => { 215 setLocked(prev => {
198 const next = { ...prev, [section]: !prev[section] }; 216 const next = { ...prev, [section]: !prev[section] };
199 const { inputs, outputs, edits } = stateRef.current; 217 persist({ locked: next });
200 saveState(storageKey, { inputs, outputs, edits, locked: next });
201 return next; 218 return next;
202 }); 219 });
203 }, [storageKey]); 220 }, [persist]);
204 221
205 const effectiveOutputs: BrandOutputs | null = outputs ? { ...outputs, ...edits } : null; 222 const effectiveOutputs: BrandOutputs | null = outputs ? { ...outputs, ...edits } : null;
206 223
@@ -218,8 +235,8 @@ export function useWorkspace(storageKey = 'bw:workspace') {
218 toggleLock, 235 toggleLock,
219 undo, 236 undo,
220 redo, 237 redo,
221 canUndo, 238 canUndo: history.canUndo,
222 canRedo, 239 canRedo: history.canRedo,
223 hasOutput: outputs !== null, 240 hasOutput: outputs !== null,
224 }; 241 };
225} 242}
src/lib/sanitize.ts +53 −58
@@ -56,76 +56,71 @@ const DEFAULT_SWATCHES = [
56 { id: 's4', name: 'Text', hex: '#111111', role: 'text' }, 56 { id: 's4', name: 'Text', hex: '#111111', role: 'text' },
57]; 57];
58 58
59export function sanitizeOutputs(raw: unknown): BrandOutputs | null { 59/** The value as a plain record, or an empty one if it is not an object. */
60 if (!raw || typeof raw !== 'object') return null; 60function record(v: unknown): Record<string, unknown> {
61 let r = raw as Record<string, unknown>; 61 return (v && typeof v === 'object' ? v : {}) as Record<string, unknown>;
62}
62 63
63 // Unwrap single-key envelopes: {"brand_package": {...}} → {...} 64/** Unwrap single-key envelopes: {"brand_package": {...}} → {...} */
65function unwrapEnvelope(r: Record<string, unknown>): Record<string, unknown> {
64 const keys = Object.keys(r); 66 const keys = Object.keys(r);
65 if (keys.length === 1 && r[keys[0]] && typeof r[keys[0]] === 'object') { 67 if (keys.length === 1 && r[keys[0]] && typeof r[keys[0]] === 'object') {
66 r = r[keys[0]] as Record<string, unknown>; 68 return r[keys[0]] as Record<string, unknown>;
67 } 69 }
70 return r;
71}
68 72
69 // Must have at least one recognisable content field 73/** Must have at least one recognisable content field. */
70 if (!r.overview && !r.positioning && !r.tone && !r.titles && !r.palette) return null; 74const CONTENT_FIELDS = ['overview', 'positioning', 'tone', 'titles', 'palette'];
71 75
72 const tone = (r.tone && typeof r.tone === 'object' ? r.tone : {}) as Record<string, unknown>; 76function mapList<T>(v: unknown, map: (item: Record<string, unknown>, i: number) => T): T[] {
73 const typo = (r.typography && typeof r.typography === 'object' ? r.typography : {}) as Record<string, unknown>; 77 return Array.isArray(v) ? v.map((item: unknown, i: number) => map(record(item), i)) : [];
74 const palette = (r.palette && typeof r.palette === 'object' ? r.palette : {}) as Record<string, unknown>; 78}
75 79
80function sanitizeSwatches(palette: Record<string, unknown>) {
76 // Accept swatches under palette.swatches or palette.colors 81 // Accept swatches under palette.swatches or palette.colors
77 const rawSwatches = Array.isArray(palette.swatches) ? palette.swatches 82 const rawSwatches = Array.isArray(palette.swatches) ? palette.swatches
78 : Array.isArray(palette.colors) ? palette.colors 83 : Array.isArray(palette.colors) ? palette.colors
79 : []; 84 : [];
85 if (!rawSwatches.length) return DEFAULT_SWATCHES;
86 return mapList(rawSwatches, (sw, i) => ({
87 id: str(sw.id, `s${i}`),
88 name: str(sw.name, 'Color'),
89 hex: normalizeHex(str(sw.hex ?? sw.color ?? sw.value, '#888888')),
90 role: str(sw.role ?? sw.type, 'accent'),
91 }));
92}
80 93
81 const swatches = rawSwatches.length 94export function sanitizeOutputs(raw: unknown): BrandOutputs | null {
82 ? rawSwatches.map((s: unknown, i: number) => { 95 if (!raw || typeof raw !== 'object') return null;
83 const sw = (s && typeof s === 'object' ? s : {}) as Record<string, unknown>; 96 const r = unwrapEnvelope(raw as Record<string, unknown>);
84 return { 97 if (!CONTENT_FIELDS.some(k => r[k])) return null;
85 id: str(sw.id, `s${i}`), 98
86 name: str(sw.name, 'Color'), 99 const tone = record(r.tone);
87 hex: normalizeHex(str(sw.hex ?? sw.color ?? sw.value, '#888888')), 100 const typo = record(r.typography);
88 role: str(sw.role ?? sw.type, 'accent'), 101 const swatches = sanitizeSwatches(record(r.palette));
89 }; 102
90 }) 103 const visualDirections = mapList(r.visualDirections, (d, i) => ({
91 : DEFAULT_SWATCHES; 104 id: str(d.id, `v${i + 1}`),
92 105 name: str(d.name, `Direction ${i + 1}`),
93 const visualDirections = Array.isArray(r.visualDirections) 106 description: str(d.description, ''),
94 ? r.visualDirections.map((v: unknown, i: number) => { 107 palette: str(d.palette, ''),
95 const d = (v && typeof v === 'object' ? v : {}) as Record<string, unknown>; 108 typography: str(d.typography, ''),
96 return { 109 references: str(d.references, ''),
97 id: str(d.id, `v${i + 1}`), 110 }));
98 name: str(d.name, `Direction ${i + 1}`), 111
99 description: str(d.description, ''), 112 const logoConcepts = mapList(r.logoConcepts, (c, i) => ({
100 palette: str(d.palette, ''), 113 id: str(c.id, `l${i + 1}`),
101 typography: str(d.typography, ''), 114 title: str(c.title, `Concept ${i + 1}`),
102 references: str(d.references, ''), 115 concept: str(c.concept, ''),
103 }; 116 mark: str(c.mark, ''),
104 }) 117 execution: str(c.execution, ''),
105 : []; 118 }));
106 119
107 const logoConcepts = Array.isArray(r.logoConcepts) 120 const usageExamples = mapList(r.usageExamples, (e) => ({
108 ? r.logoConcepts.map((v: unknown, i: number) => { 121 context: str(e.context, 'Example'),
109 const c = (v && typeof v === 'object' ? v : {}) as Record<string, unknown>; 122 text: str(e.text, ''),
110 return { 123 }));
111 id: str(c.id, `l${i + 1}`),
112 title: str(c.title, `Concept ${i + 1}`),
113 concept: str(c.concept, ''),
114 mark: str(c.mark, ''),
115 execution: str(c.execution, ''),
116 };
117 })
118 : [];
119
120 const usageExamples = Array.isArray(r.usageExamples)
121 ? r.usageExamples.map((v: unknown) => {
122 const e = (v && typeof v === 'object' ? v : {}) as Record<string, unknown>;
123 return {
124 context: str(e.context, 'Example'),
125 text: str(e.text, ''),
126 };
127 })
128 : [];
129 124
130 // Preserve an existing valid scale (already-saved data) or fall back to default 125 // Preserve an existing valid scale (already-saved data) or fall back to default
131 const existingScale = Array.isArray(typo.scale) ? typo.scale : TYPE_SCALE; 126 const existingScale = Array.isArray(typo.scale) ? typo.scale : TYPE_SCALE;
tsconfig.json +1
@@ -6,6 +6,7 @@
6 "module": "ESNext", 6 "module": "ESNext",
7 "skipLibCheck": true, 7 "skipLibCheck": true,
8 "moduleResolution": "bundler", 8 "moduleResolution": "bundler",
9 "resolveJsonModule": true,
9 "allowImportingTsExtensions": true, 10 "allowImportingTsExtensions": true,
10 "isolatedModules": true, 11 "isolatedModules": true,
11 "moduleDetection": "force", 12 "moduleDetection": "force",