mirror of
https://github.com/garrytan/gstack.git
synced 2026-09-09 14:38:59 +02:00
lib/design-md.ts implements the open DESIGN.md format (google-labs-code/
design.md, Apache-2.0): YAML front matter with the five token groups (colors,
typography, rounded, spacing, components) and eight canonical `##` sections
in spec order (Overview, Colors, Typography, Layout, Elevation & Depth,
Shapes, Components, Do's and Don'ts), aliases mapped, extras preserved after
them in their original order. parseDesignMd never throws (unparsable front
matter → `unknown` with a reason); renderDesignMd re-emits the preserved front
matter bytes and only `convert` writes fresh YAML through a small block-style
emitter (Bun.YAML.stringify is flow style); upsertSection splices the body
only; tokensFlat resolves `{path}` references to primitives and reports group,
self, dangling, and cyclic refs as DESIGN_MD_TOKEN_REF_INVALID. convertLegacy
turns gstack's pre-spec DESIGN.md into the open format: Product Context and
Aesthetic Direction fold into Overview, Typography roles become
display/body/label/mono tokens (mono carries fontFeature: tnum), Color hexes
become colors (mode-qualified labels keep their qualifier; strategy lines are
not colors), the Spacing scale and Layout radii become spacing and rounded,
Motion / Grain Texture / Decisions Log survive as extras. The format marker
lives inside the file: a YAML comment on line 2 of a spec file, an HTML
comment on line 1 of a legacy file.
bin/gstack-design-md.ts: `check` (DESIGN_MD_FORMAT + marker), `convert
[--write]` (backup to DESIGN.md.legacy.bak, temp+rename, refuses ambiguous
input with DESIGN_MD_CONVERT_REFUSED), `tokens` (flat JSON), `mark
<spec|legacy-keep>`. Exit 3 + DESIGN_MD_INTERNAL_ERROR is a gstack bug.
design/src/memory.ts: updateDesignMd upserts "Extracted Design Language"
through the lib (front matter bytes untouched, canonical order kept, section
replaced on rerun) and creates a spec skeleton with tokens from the extraction
when no file exists; readDesignConstraints leads with the flat tokens and the
Overview for spec files. The design binary still bundles.
test/design-md.test.ts pins all of it against gstack's own DESIGN.md.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
235 lines
8.1 KiB
TypeScript
235 lines
8.1 KiB
TypeScript
/**
|
|
* Design Memory — extract visual language from approved mockups into DESIGN.md.
|
|
*
|
|
* After a mockup is approved, uses GPT-4o vision to extract:
|
|
* - Color palette (hex values)
|
|
* - Typography (font families, sizes, weights)
|
|
* - Spacing patterns (padding, margins, gaps)
|
|
* - Layout conventions (grid, alignment, hierarchy)
|
|
*
|
|
* If DESIGN.md exists, merges extracted patterns with existing design system.
|
|
* If no DESIGN.md, creates one from the extracted patterns.
|
|
*/
|
|
|
|
import fs from "fs";
|
|
import path from "path";
|
|
import { requireApiKey } from "./auth";
|
|
import { receiptedFetch } from "./receipted-fetch";
|
|
import { parseDesignMd, detectFormat, renderDesignMd, upsertSection, specSkeleton, tokensFlat } from "../../lib/design-md";
|
|
|
|
export interface ExtractedDesign {
|
|
colors: { name: string; hex: string; usage: string }[];
|
|
typography: { role: string; family: string; size: string; weight: string }[];
|
|
spacing: string[];
|
|
layout: string[];
|
|
mood: string;
|
|
}
|
|
|
|
/**
|
|
* Extract visual language from an approved mockup PNG.
|
|
*/
|
|
export async function extractDesignLanguage(imagePath: string): Promise<ExtractedDesign> {
|
|
const apiKey = requireApiKey();
|
|
const imageData = fs.readFileSync(imagePath).toString("base64");
|
|
|
|
const controller = new AbortController();
|
|
const timeout = setTimeout(() => controller.abort(), 60_000);
|
|
|
|
try {
|
|
const response = await receiptedFetch("memory-distill-request", "https://api.openai.com/v1/chat/completions", {
|
|
method: "POST",
|
|
headers: {
|
|
"Authorization": `Bearer ${apiKey}`,
|
|
"Content-Type": "application/json",
|
|
},
|
|
body: JSON.stringify({
|
|
model: "gpt-4o",
|
|
messages: [{
|
|
role: "user",
|
|
content: [
|
|
{
|
|
type: "image_url",
|
|
image_url: { url: `data:image/png;base64,${imageData}` },
|
|
},
|
|
{
|
|
type: "text",
|
|
text: `Analyze this UI mockup and extract the design language. Return valid JSON only, no markdown:
|
|
|
|
{
|
|
"colors": [{"name": "primary", "hex": "#...", "usage": "buttons, links"}, ...],
|
|
"typography": [{"role": "heading", "family": "...", "size": "...", "weight": "..."}, ...],
|
|
"spacing": ["8px base unit", "16px between sections", ...],
|
|
"layout": ["left-aligned content", "max-width 1200px", ...],
|
|
"mood": "one sentence describing the overall feel"
|
|
}
|
|
|
|
Extract real values from what you see. Be specific about hex colors and font sizes.`,
|
|
},
|
|
],
|
|
}],
|
|
max_tokens: 800,
|
|
response_format: { type: "json_object" },
|
|
}),
|
|
signal: controller.signal,
|
|
});
|
|
|
|
if (!response.ok) {
|
|
console.error(`Vision extraction failed (${response.status})`);
|
|
return defaultDesign();
|
|
}
|
|
|
|
const data = await response.json() as any;
|
|
const content = data.choices?.[0]?.message?.content?.trim() || "";
|
|
return JSON.parse(content) as ExtractedDesign;
|
|
} catch (err: any) {
|
|
console.error(`Design extraction error: ${err.message}`);
|
|
return defaultDesign();
|
|
} finally {
|
|
clearTimeout(timeout);
|
|
}
|
|
}
|
|
|
|
function defaultDesign(): ExtractedDesign {
|
|
return {
|
|
colors: [],
|
|
typography: [],
|
|
spacing: [],
|
|
layout: [],
|
|
mood: "Unable to extract design language",
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Write or update DESIGN.md with extracted design patterns.
|
|
*
|
|
* Existing file (spec, legacy, or anything with `##` sections): the
|
|
* "## Extracted Design Language" section is upserted through lib/design-md.ts,
|
|
* which splices the body only — front matter bytes are never re-emitted, and a
|
|
* spec file keeps its canonical section order (the extracted section is an extra
|
|
* after them). New file: a spec-format skeleton whose tokens come from the
|
|
* extraction (colors by name, typography by role) plus the extracted section.
|
|
*/
|
|
export function updateDesignMd(
|
|
repoRoot: string,
|
|
extracted: ExtractedDesign,
|
|
sourceMockup: string,
|
|
): void {
|
|
const designPath = path.join(repoRoot, "DESIGN.md");
|
|
const timestamp = new Date().toISOString().split("T")[0];
|
|
const section = formatExtractedSection(extracted, sourceMockup, timestamp);
|
|
const heading = "Extracted Design Language";
|
|
const body = section.split("\n").slice(1).join("\n"); // drop the "## Extracted Design Language" line
|
|
|
|
const write = (content: string) => {
|
|
const tmp = `${designPath}.tmp-${process.pid}`;
|
|
fs.writeFileSync(tmp, content);
|
|
fs.renameSync(tmp, designPath);
|
|
};
|
|
|
|
if (fs.existsSync(designPath)) {
|
|
const doc = parseDesignMd(fs.readFileSync(designPath, "utf-8"));
|
|
write(renderDesignMd(upsertSection(doc, heading, body)));
|
|
console.error(`Updated DESIGN.md with extracted design language`);
|
|
return;
|
|
}
|
|
|
|
const colors: Record<string, string> = {};
|
|
for (const c of extracted.colors) {
|
|
const key = c.name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
|
|
if (key && /^#[0-9a-fA-F]{3,8}$/.test(c.hex) && !(key in colors)) colors[key] = c.hex;
|
|
}
|
|
const typography: Record<string, Record<string, string>> = {};
|
|
for (const t of extracted.typography) {
|
|
const role = t.role.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
|
|
if (!role || typography[role]) continue;
|
|
const entry: Record<string, string> = { fontFamily: t.family };
|
|
if (t.size) entry.fontSize = t.size;
|
|
if (t.weight) entry.fontWeight = t.weight;
|
|
typography[role] = entry;
|
|
}
|
|
const frontmatter: Record<string, unknown> = {};
|
|
if (Object.keys(colors).length) frontmatter.colors = colors;
|
|
if (Object.keys(typography).length) frontmatter.typography = typography;
|
|
const doc = specSkeleton("Design System", frontmatter, [
|
|
{ heading: "Overview", body: `${extracted.mood}\n\nCreated by the gstack designer from an approved mockup (${path.basename(sourceMockup)}) on ${timestamp}.` },
|
|
{ heading, body },
|
|
]);
|
|
write(renderDesignMd(doc));
|
|
console.error(`Created DESIGN.md with extracted design language`);
|
|
}
|
|
|
|
function formatExtractedSection(
|
|
extracted: ExtractedDesign,
|
|
sourceMockup: string,
|
|
date: string,
|
|
): string {
|
|
const lines: string[] = [
|
|
"## Extracted Design Language",
|
|
`*Auto-extracted from approved mockup on ${date}*`,
|
|
`*Source: ${path.basename(sourceMockup)}*`,
|
|
"",
|
|
`**Mood:** ${extracted.mood}`,
|
|
"",
|
|
];
|
|
|
|
if (extracted.colors.length > 0) {
|
|
lines.push("### Colors", "");
|
|
lines.push("| Name | Hex | Usage |");
|
|
lines.push("|------|-----|-------|");
|
|
for (const c of extracted.colors) {
|
|
lines.push(`| ${c.name} | \`${c.hex}\` | ${c.usage} |`);
|
|
}
|
|
lines.push("");
|
|
}
|
|
|
|
if (extracted.typography.length > 0) {
|
|
lines.push("### Typography", "");
|
|
lines.push("| Role | Family | Size | Weight |");
|
|
lines.push("|------|--------|------|--------|");
|
|
for (const t of extracted.typography) {
|
|
lines.push(`| ${t.role} | ${t.family} | ${t.size} | ${t.weight} |`);
|
|
}
|
|
lines.push("");
|
|
}
|
|
|
|
if (extracted.spacing.length > 0) {
|
|
lines.push("### Spacing", "");
|
|
for (const s of extracted.spacing) {
|
|
lines.push(`- ${s}`);
|
|
}
|
|
lines.push("");
|
|
}
|
|
|
|
if (extracted.layout.length > 0) {
|
|
lines.push("### Layout", "");
|
|
for (const l of extracted.layout) {
|
|
lines.push(`- ${l}`);
|
|
}
|
|
lines.push("");
|
|
}
|
|
|
|
return lines.join("\n");
|
|
}
|
|
|
|
/**
|
|
* Read DESIGN.md and return it as a constraint string for brief construction.
|
|
* If no DESIGN.md exists, returns null (explore wide).
|
|
*/
|
|
export function readDesignConstraints(repoRoot: string): string | null {
|
|
const designPath = path.join(repoRoot, "DESIGN.md");
|
|
if (!fs.existsSync(designPath)) return null;
|
|
|
|
const content = fs.readFileSync(designPath, "utf-8");
|
|
const doc = parseDesignMd(content);
|
|
if (detectFormat(doc).format === "spec") {
|
|
// Spec file: the normative tokens first, then the Overview prose. Both fit
|
|
// the brief far better than the first 2000 bytes of YAML would.
|
|
const { tokens } = tokensFlat(doc.frontmatter);
|
|
const tokenLines = Object.entries(tokens).map(([k, v]) => `${k}: ${v}`).join("; ");
|
|
const overview = doc.sections.find((s) => s.canonical === "Overview")?.body ?? "";
|
|
return `Tokens: ${tokenLines}. ${overview}`.slice(0, 2000);
|
|
}
|
|
// Truncate to first 2000 chars to keep brief reasonable
|
|
return content.slice(0, 2000);
|
|
}
|