Canvix — Free & open-source graphic design tool. A community-built Canva alternative with a drag-and-drop editor, templates, shapes, text, images & one-click export. Works on desktop, tablet & mobile.
TypeScript canva-alternativecanvasdesigndesign-tooldrag-and-dropeditorgraphic-designkonvanextjsopen-sourcereactself-hostedtemplatestypescript
feat: DesignSpec v2 foundation + deterministic design engine (Phase A)
Ashiq Hussain Mir0c765a40608c
diff --git a/src/lib/design-engine/compile.test.ts b/src/lib/design-engine/compile.test.tsnew file mode 100644index 0000000..0e4e4e3--- /dev/null+++ b/src/lib/design-engine/compile.test.ts@@ -0,0 +1,171 @@+// design-engine/compile.ts — the compile proof.+//+// Case 1 is the v0.29.3 failed production run (harness.test.ts line+// 441): the CANVIX poster brief that motivated the agent-correctness+// work. The pipeline must compile it end to end — brief extraction+// (zero model calls) → spec → deterministic engine → real editor+// pages — with EXACT text, EXACT colors, no clipping, no unintended+// overlap, WCAG-cleared contrast, and fully editable native output.+//+// The scripted-planner pattern: no live model is needed because the+// required copy and colors come from the brief itself — exactly+// what a planner would emit for this prompt.+import { describe, expect, it } from 'vitest'+import { extractBrief } from '@/lib/agent/brief'+import { specFromBrief } from '@/lib/design-spec/from-brief'+import { parseSpecResponse } from '@/lib/design-spec/parse'+import { compileSpec, exactEquals } from './compile'+import { fitFontSize } from './compositions'+import type { AnyElement, TextElement } from '@/lib/types'++const V0293_POSTER_PROMPT =+ 'Make a 1080x1080 poster with navy #090B1A background, purple #8B5CF6 and cyan #22D3EE accents, saying "Design Beyond Limits", "Create Smarter. Design Faster." and "Try Canvix Free"'++function textElements(els: AnyElement[]): TextElement[] {+ return els.filter((el): el is TextElement => el.type === 'text')+}++describe('the v0.29.3 poster brief, compiled end to end', () => {+ const brief = extractBrief(V0293_POSTER_PROMPT)+ const spec = specFromBrief(brief)+ const result = compileSpec(spec)+ const page = result.pages[0]++ it('all compile checks pass — no silent degradation', () => {+ expect(result.checks.passed).toBe(true)+ expect(result.checks.failures).toEqual([])+ })++ it('EXACT text: character-for-character, not case-insensitive substring', () => {+ const texts = textElements(page.elements).map((el) => el.text)+ expect(texts).toContain('Design Beyond Limits')+ expect(texts).toContain('Create Smarter. Design Faster.')+ expect(texts).toContain('Try Canvix Free')+ // the hardened contract: case/whitespace variants FAIL (the old+ // brief checker would accept 'DESIGN BEYOND LIMITS — really')+ expect(exactEquals('Design Beyond Limits', 'DESIGN BEYOND LIMITS')).toBe(false)+ expect(exactEquals('a\u0301', 'á')).toBe(true) // NFC equivalence holds+ expect(exactEquals('Try Canvix Free', 'Try Canvix Free')).toBe(false)+ for (const c of result.checks.exactTexts) expect(c.found).toBe(true)+ })++ it('EXACT colors: all three required hexes on the page', () => {+ expect(page.background).toEqual({ type: 'solid', color: '#090b1a' })+ const fills = page.elements+ .map((el) => ('fill' in el && typeof el.fill === 'string' ? el.fill.toLowerCase() : ''))+ .filter(Boolean)+ expect(fills).toContain('#8b5cf6')+ expect(fills).toContain('#22d3ee')+ for (const c of result.checks.colors) expect(c.found).toBe(true)+ })++ it('geometry: everything in-canvas, content mutually disjoint, text fits', () => {+ expect(result.checks.inCanvas).toBe(true)+ expect(result.checks.noUnintendedOverlap).toBe(true)+ expect(result.checks.textFits).toBe(true)+ })++ it('contrast: WCAG ≥ 4.5 on every checked pair', () => {+ for (const c of result.checks.contrast) {+ expect(c.ok, `${c.pair} = ${c.ratio}`).toBe(true)+ }+ })++ it('native, editable output: real factory elements with catalog fonts', () => {+ expect(page.elements.length).toBeGreaterThanOrEqual(5) // headline, subline, chip, chip text, underline+ for (const el of page.elements) {+ expect(el.id).toMatch(/^spec_\d+$/)+ expect(el.width).toBeGreaterThan(0)+ }+ for (const el of textElements(page.elements)) {+ expect(['Poppins', 'Inter', 'Montserrat', 'Work Sans', 'Space Grotesk', 'Oswald', 'Lato', 'Raleway', 'Open Sans']).toContain(el.fontFamily)+ }+ })++ it('deterministic: the same spec compiles byte-identically', () => {+ const again = compileSpec(specFromBrief(extractBrief(V0293_POSTER_PROMPT)))+ expect(JSON.stringify(again.pages)).toBe(JSON.stringify(result.pages))+ })+})++describe('feature-cards: the validator definition, inverted into a builder', () => {+ const r = parseSpecResponse(+ JSON.stringify({+ version: 'v2',+ format: { width: 1280, height: 720 },+ palette: { seeds: ['#101418'], mood: 'cool' },+ typography: { scale: 1.25 },+ blocks: [+ {+ kind: 'feature-cards',+ count: 3,+ content: [+ { role: 'label', source: 'model', text: 'Fast' },+ { role: 'label', source: 'model', text: 'Private' },+ { role: 'label', source: 'model', text: 'Yours' },+ ],+ },+ ],+ }),+ )+ const result = r.ok ? compileSpec(r.spec) : null++ it('emits N semi-transparent card rects, one to three texts each', () => {+ expect(r.ok).toBe(true)+ expect(result).not.toBeNull()+ if (!result) return+ expect(result.checks.passed).toBe(true)+ const cards = result.pages[0].elements.filter(+ (el) => el.type === 'rect' && 'opacity' in el && (el as { opacity: number }).opacity < 1,+ )+ expect(cards).toHaveLength(3)+ const texts = textElements(result.pages[0].elements)+ expect(texts).toHaveLength(3)+ // each text sits inside a card (the validator's structural check)+ for (const t of texts) {+ const host = cards.some((c) =>+ t.x >= c.x - 1 && t.y >= c.y - 1 && t.x + t.width <= c.x + c.width + 1 && t.y + t.height <= c.y + c.height + 1,+ )+ expect(host).toBe(true)+ }+ })+})++describe('honest failure: required copy is never truncated', () => {+ const long = 'This required headline is intentionally far too long to fit a one-thousand-eighty pixel band even at the minimum floor size'+ const r = parseSpecResponse(+ JSON.stringify({+ format: { width: 1080, height: 1080 },+ blocks: [+ {+ kind: 'hero',+ content: [+ { role: 'headline', source: 'user-required', text: long },+ { role: 'cta', source: 'user-required', text: 'Go' },+ ],+ },+ ],+ }),+ )+ const result = r.ok ? compileSpec(r.spec) : null++ it('an unfixable required text fails the check instead of being cut', () => {+ expect(r.ok).toBe(true)+ if (!result) return+ // the text survived INTACT — failure is reported, never truncated+ const texts = textElements(result.pages[0].elements).map((el) => el.text)+ expect(texts).toContain(long)+ expect(result.checks.textFits).toBe(false)+ expect(result.checks.passed).toBe(false)+ expect(result.checks.failures.some((f) => f.includes('never truncated'))).toBe(true)+ })+})++describe('fitFontSize', () => {+ it('shrinks toward the floor but never below it', () => {+ expect(fitFontSize('Short', 500, 96, 28)).toBe(96)+ const size = fitFontSize('A '.repeat(60), 500, 96, 28)+ expect(size).toBeGreaterThanOrEqual(28)+ expect(size).toBeLessThan(96)+ })+})diff --git a/src/lib/design-engine/compile.ts b/src/lib/design-engine/compile.tsnew file mode 100644index 0000000..52432a4--- /dev/null+++ b/src/lib/design-engine/compile.ts@@ -0,0 +1,193 @@+// ─────────────────────────────────────────────────────────────+// Design engine · compile (Phase A).+//+// DesignSpec → real editor pages. Pure, deterministic (ids are+// compile-scoped counters — same spec in, byte-identical pages+// out), and honest: the compile result carries a CHECK REPORT with+// the same discipline the v0.29.4 agent loop ships — every user+// requirement is verified and every failure is named, never+// silently degraded.+//+// Checks:+// exactTexts user-required slots appear character-for-character+// (NFC-normalized equality — NOT case-insensitive+// substring; the hardening over the brief checker)+// colors every seed/pinned hex appears on the page+// inCanvas every element rect inside the canvas+// overlap content elements are mutually disjoint (backdrops+// may sit under content — the declared channel)+// textFits every text element fits its box at the plan-route+// width estimate; required copy is never truncated+// to achieve this — an unfit required text FAILS+// contrast WCAG ≥ 4.5 for ink/inkSoft on the background, CTA+// text on its chip, card text on the card surface+// ─────────────────────────────────────────────────────────────++import type { AnyElement, PageData } from '@/lib/types'+import type { DesignSpec } from '@/lib/design-spec/types'+import { expandPalette, onColor, type ExpandedPalette } from './palette'+import { assignTypeScale, type AssignedTypography } from './typography'+import { bandLayout, isInCanvas, rectsOverlap, type Rect } from './layout'+import { buildBlock, estimateTextWidth } from './compositions'+import { contrast } from '@/lib/theme'++const MIN_TEXT_CONTRAST = 4.5++export interface ExactTextCheck {+ text: string+ found: boolean+}+export interface ColorCheck {+ hex: string+ found: boolean+}+export interface ContrastCheck {+ pair: string+ ratio: number+ ok: boolean+}++export interface CompileChecks {+ exactTexts: ExactTextCheck[]+ colors: ColorCheck[]+ inCanvas: boolean+ noUnintendedOverlap: boolean+ textFits: boolean+ contrast: ContrastCheck[]+ passed: boolean+ failures: string[]+}++export interface CompileResult {+ pages: PageData[]+ checks: CompileChecks+ /** non-fatal notes (palette defaults, pending builders, density) */+ warnings: string[]+ palette: ExpandedPalette+ typography: AssignedTypography+}++/** NFKC-free exact comparison: NFC normalization both sides, then+ * strict equality. Case/whitespace differences are FAILURES here.+ * Exported for the test matrix — this is the hardened contract the+ * agent brief checker's case-insensitive substring does not give. */+export function exactEquals(a: string, b: string): boolean {+ return a.normalize('NFC') === b.normalize('NFC')+}++function eqHex(a: string, b: string): boolean {+ return a.trim().toLowerCase() === b.trim().toLowerCase()+}++function elementRect(el: AnyElement): Rect {+ return { x: el.x, y: el.y, width: el.width, height: el.height }+}++/**+ * Compile a spec into pages. Always returns a result — a failed+ * check set is part of the result, not an exception (the caller+ * decides whether to ship, fix, or disclose).+ */+export function compileSpec(spec: DesignSpec): CompileResult {+ const warnings: string[] = []+ const palette = expandPalette(spec.palette)+ warnings.push(...palette.warnings)+ const typography = assignTypeScale(spec.typography, spec.palette.mood, spec.format.width)+ if (typography.warning) warnings.push(typography.warning)++ const backdrops: AnyElement[] = []+ const content: AnyElement[] = []+ let id = 0+ const nextId = () => `spec_${++id}`++ for (const placed of bandLayout(spec.blocks, spec.format)) {+ const composed = buildBlock(placed.block, {+ rect: placed.rect,+ palette,+ type: typography,+ canvas: spec.format,+ })+ warnings.push(...composed.warnings)+ backdrops.push(...composed.backdrops)+ content.push(...composed.content)+ }++ // z-order: backdrops first, content above — array order IS z-order+ const elements = [...backdrops, ...content].map((el) => ({ ...el, id: nextId() }))+ const page: PageData = {+ id: 'spec_page_1',+ background: { type: 'solid', color: palette.roles.background },+ elements,+ }++ // ── the check report ──+ const failures: string[] = []+ const textEls = elements.filter((el): el is AnyElement & { text: string; fontSize: number } => el.type === 'text')++ const exactTexts = spec.blocks+ .flatMap((b) => b.content)+ .filter((s) => s.source === 'user-required')+ .map((slot) => {+ const found = textEls.some((el) => exactEquals(el.text, slot.text))+ if (!found) failures.push(`required text missing or altered: "${slot.text}"`)+ return { text: slot.text, found }+ })++ const requiredHexes = [...spec.palette.seeds, ...Object.values(spec.palette.pinned ?? {})]+ const colors = [...new Set(requiredHexes)].map((hex) => {+ const found =+ eqHex(palette.roles.background, hex) ||+ elements.some((el) => 'fill' in el && typeof el.fill === 'string' && eqHex(el.fill, hex))+ if (!found) failures.push(`required color #${hex.slice(1).toUpperCase()} not used anywhere on the page`)+ return { hex, found }+ })++ const inCanvas = elements.every((el) => isInCanvas(elementRect(el), spec.format))+ if (!inCanvas) failures.push('an element sits outside the canvas')++ const noUnintendedOverlap = content+ .map(elementRect)+ .every((a, i, list) => list.every((b, j) => i === j || !rectsOverlap(a, b)))+ if (!noUnintendedOverlap) failures.push('content elements overlap (unintended)')++ const textFits = textEls.every((el) => estimateTextWidth(el.text, el.fontSize) <= el.width + 1)+ if (!textFits) {+ const offender = textEls.find((el) => estimateTextWidth(el.text, el.fontSize) > el.width + 1)+ failures.push(`text does not fit its box: "${offender?.text.slice(0, 40)}" (required copy is never truncated — fix by reflow)`)+ }++ const contrastPairs: { pair: string; ratio: number }[] = [+ { pair: `ink on background`, ratio: contrast(palette.roles.ink, palette.roles.background) },+ { pair: `inkSoft on background`, ratio: contrast(palette.roles.inkSoft, palette.roles.background) },+ ]+ if (elements.some((el) => el.type === 'rect' && el.fill === palette.roles.accent && 'cornerRadius' in el)) {+ contrastPairs.push({ pair: 'cta text on accent chip', ratio: contrast(onColor(palette.roles.accent), palette.roles.accent) })+ }+ if (elements.some((el) => el.type === 'rect' && el.fill === palette.roles.surface)) {+ contrastPairs.push({ pair: 'card text on surface', ratio: contrast(onColor(palette.roles.surface), palette.roles.surface) })+ }+ const contrastChecks = contrastPairs.map((p) => ({+ ...p,+ ok: p.ratio >= MIN_TEXT_CONTRAST,+ }))+ for (const c of contrastChecks) {+ if (!c.ok) failures.push(`contrast ${c.pair} = ${c.ratio.toFixed(2)} (< ${MIN_TEXT_CONTRAST})`)+ }++ return {+ pages: [page],+ checks: {+ exactTexts,+ colors,+ inCanvas,+ noUnintendedOverlap,+ textFits,+ contrast: contrastChecks,+ passed: failures.length === 0,+ failures,+ },+ warnings,+ palette,+ typography,+ }+}diff --git a/src/lib/design-engine/compositions.ts b/src/lib/design-engine/compositions.tsnew file mode 100644index 0000000..7f4efac--- /dev/null+++ b/src/lib/design-engine/compositions.ts@@ -0,0 +1,228 @@+// ─────────────────────────────────────────────────────────────+// Design engine · compositions (Phase A).+//+// Deterministic block builders. The inversion the architecture+// analysis proposes: the brief validator's structural definitions,+// read as constructors. A feature-card is "N semi-transparent card+// rects with one to three texts each" — buildFeatureCards EMITS+// exactly that, correct by construction instead of checked after+// the fact.+//+// Every builder returns two layers: backdrops (may sit under+// content — the intentional-overlap channel) and content (mutually+// disjoint, individually in-canvas). Text is placed with the+// plan-route width estimate (~0.62 × fontSize per char) and+// shrink-to-fit; user-required copy is NEVER truncated — when it+// cannot fit even at the floor size, the compile check fails+// honestly instead.+// ─────────────────────────────────────────────────────────────++import {+ createShapeElement,+ createTextElement,+ type AnyElement,+} from '@/lib/types'+import type { BlockNode, ContentRole, ContentSlot } from '@/lib/design-spec/types'+import type { ExpandedPalette } from './palette'+import { onColor } from './palette'+import type { AssignedTypography } from './typography'+import { gridInRect, stackInRect, type Rect } from './layout'++export interface BuildContext {+ rect: Rect+ palette: ExpandedPalette+ type: AssignedTypography+ canvas: { width: number; height: number }+}++export interface ComposedElements {+ /** decorative layers — under content, may overlap it intentionally */+ backdrops: AnyElement[]+ /** the real content — mutually disjoint by construction */+ content: AnyElement[]+ /** local, non-fatal notes for the compile report */+ warnings: string[]+}++/** Plan-route text estimate convention (conservative). */+export function estimateTextWidth(text: string, fontSize: number): number {+ return text.length * 0.62 * fontSize+}++/** Shrink-to-fit: largest size ≤ start that fits maxW, floored at+ * minSize. Never touches the text itself. */+export function fitFontSize(text: string, maxW: number, start: number, minSize: number): number {+ let size = Math.max(minSize, Math.round(start))+ while (size > minSize && estimateTextWidth(text, size) > maxW) size -= 2+ return size+}++const ROLE_STACK_ORDER: ContentRole[] = ['headline', 'subline', 'cta', 'tagline', 'body', 'label']++function stackOrder(slot: ContentSlot): number {+ const i = ROLE_STACK_ORDER.indexOf(slot.role)+ return i === -1 ? ROLE_STACK_ORDER.length : i+}++/** Hero: headline + subline + CTA chip, stacked in the band.+ * Emits an accent underline (backdrop) between headline and subline. */+export function buildHero(block: BlockNode, ctx: BuildContext): ComposedElements {+ const { palette, type, canvas } = ctx+ const slots = [...block.content].sort((a, b) => stackOrder(a) - stackOrder(b))+ const warnings: string[] = []+ const backdrops: AnyElement[] = []+ const content: AnyElement[] = []++ const subRects = stackInRect(ctx.rect, slots.map((s) => s.role))+ const headlineBoost = Math.round(canvas.height * 0.075)++ slots.forEach((slot, i) => {+ const rect = subRects[i]+ if (slot.role === 'cta') {+ // CTA chip: accent pill + centered text with guarded contrast+ const start = Math.max(type.sizes.cta, 24)+ const size = fitFontSize(slot.text, rect.width * 0.82, start, 20)+ const textW = Math.min(rect.width, estimateTextWidth(slot.text, size) + size * 0.8)+ const chipH = Math.max(44, Math.round(size * 2.1))+ const chipW = Math.min(rect.width, textW + chipH * 0.7)+ const chipX = rect.x + (rect.width - chipW) / 2+ const chipY = rect.y + (rect.height - chipH) / 2+ const chipFill = palette.roles.accent+ const chipText = onColor(chipFill)+ // chip = container (backdrop layer, sits UNDER its text — the+ // intentional-overlap channel); the text stays content+ backdrops.push(+ createShapeElement('rect', {+ x: Math.round(chipX),+ y: Math.round(chipY),+ width: Math.round(chipW),+ height: Math.round(chipH),+ fill: chipFill,+ cornerRadius: Math.round(chipH / 2),+ }),+ )+ content.push(+ createTextElement({+ text: slot.text,+ x: Math.round(chipX),+ y: Math.round(chipY + (chipH - size * 1.3) / 2),+ width: Math.round(chipW),+ height: Math.round(size * 1.3),+ fontSize: size,+ fontFamily: type.families.body,+ bold: true,+ fill: chipText,+ align: 'center',+ }),+ )+ return+ }++ const isHeadline = slot.role === 'headline' || slot.role === 'tagline'+ const startSize = isHeadline ? Math.max(type.sizes.headline, headlineBoost) : type.sizes[slot.role] ?? type.sizes.body+ const size = fitFontSize(slot.text, rect.width, startSize, isHeadline ? 28 : 18)+ const fill = isHeadline ? palette.roles.ink : palette.roles.inkSoft+ const h = Math.round(size * 1.3)+ content.push(+ createTextElement({+ text: slot.text,+ x: Math.round(rect.x),+ y: Math.round(rect.y + (rect.height - h) / 2),+ width: Math.round(rect.width),+ height: h,+ fontSize: size,+ fontFamily: isHeadline ? type.families.heading : type.families.body,+ bold: isHeadline,+ fill,+ align: 'center',+ ...(isHeadline ? { lineHeight: 1.15 } : {}),+ }),+ )++ if (isHeadline && i === 0 && subRects.length > 1) {+ // accent underline in the band gap — decorative backdrop+ const gapY = rect.y + rect.height+ const nextY = subRects[i + 1].y+ if (nextY - gapY >= 14) {+ backdrops.push(+ createShapeElement('rect', {+ x: Math.round(rect.x + rect.width * 0.28),+ y: Math.round(gapY + 8),+ width: Math.round(rect.width * 0.44),+ height: 6,+ fill: palette.roles.accentSoft,+ cornerRadius: 3,+ }),+ )+ }+ }+ })++ if (slots.length > ROLE_STACK_ORDER.length) warnings.push('hero band is dense — consider fewer slots')+ return { backdrops, content, warnings }+}++/** Feature cards: N semi-transparent card rects, one to three texts+ * each — emitted exactly in the brief validator's shape. */+export function buildFeatureCards(block: BlockNode, ctx: BuildContext): ComposedElements {+ const { palette, type } = ctx+ const warnings: string[] = []+ const backdrops: AnyElement[] = []+ const content: AnyElement[] = []++ const count = Math.max(1, Math.min(6, block.count ?? Math.max(1, block.content.length)))+ const cells = gridInRect(ctx.rect, count, { columns: 3, gap: 28, minCellWidth: 160, minCellHeight: 110 })+ if (cells.some((c) => c.width < 160 || c.height < 110)) {+ warnings.push(`feature-cards band too small for ${count} cards — minimum 160x110 not met`)+ }++ const cardFill = palette.roles.surface+ const cardText = onColor(cardFill)+ cells.forEach((cell, i) => {+ const slot = block.content[i]+ const label = slot?.text ?? `Feature ${i + 1}`+ backdrops.push(+ createShapeElement('rect', {+ x: Math.round(cell.x),+ y: Math.round(cell.y),+ width: Math.round(cell.width),+ height: Math.round(cell.height),+ fill: cardFill,+ cornerRadius: 20,+ opacity: 0.92,+ }),+ )+ const pad = Math.round(cell.width * 0.1)+ const boxW = cell.width - pad * 2+ const size = fitFontSize(label, boxW, type.sizes.body, 16)+ const h = Math.round(size * 1.3)+ content.push(+ createTextElement({+ text: label,+ x: Math.round(cell.x + pad),+ y: Math.round(cell.y + (cell.height - h) / 2),+ width: Math.round(boxW),+ height: h,+ fontSize: size,+ fontFamily: type.families.body,+ bold: true,+ fill: cardText,+ align: 'center',+ }),+ )+ })++ return { backdrops, content, warnings }+}++/** Dispatch: hero + feature-cards have dedicated builders today;+ * other kinds compile through the generic hero stack with a warning+ * (Phase C gives each kind its own builder). */+export function buildBlock(block: BlockNode, ctx: BuildContext): ComposedElements {+ if (block.kind === 'feature-cards') return buildFeatureCards(block, ctx)+ if (block.kind !== 'hero') {+ const composed = buildHero(block, ctx)+ return { ...composed, warnings: [...composed.warnings, `kind '${block.kind}' compiled with the generic stack — dedicated builder pending Phase C`] }+ }+ return buildHero(block, ctx)+}diff --git a/src/lib/design-engine/layout.test.ts b/src/lib/design-engine/layout.test.tsnew file mode 100644index 0000000..3938b67--- /dev/null+++ b/src/lib/design-engine/layout.test.ts@@ -0,0 +1,113 @@+// design-engine/layout.ts — the band solver's invariants.+// Bands are disjoint BY CONSTRUCTION; the property tests prove it+// holds for randomized block sets, which is what retires+// fix_overlaps for generated designs.+import { describe, expect, it } from 'vitest'+import {+ bandLayout,+ gridInRect,+ isInCanvas,+ LAYOUT_MARGIN,+ rectContains,+ rectsOverlap,+ stackInRect,+ type Rect,+} from './layout'+import type { BlockNode } from '@/lib/design-spec/types'++const CANVAS = { width: 1080, height: 1080 }++function blocks(n: number): BlockNode[] {+ return Array.from({ length: n }, (_, i) => ({+ kind: 'hero' as const,+ weight: 0.4 + ((i * 7) % 30) / 10,+ content: [{ role: 'body' as const, source: 'model' as const, text: `x${i}` }],+ }))+}++function withinMargin(rect: Rect): boolean {+ return (+ rect.x >= LAYOUT_MARGIN - 1 &&+ rect.y >= LAYOUT_MARGIN - 1 &&+ rect.x + rect.width <= CANVAS.width - LAYOUT_MARGIN + 1 &&+ rect.y + rect.height <= CANVAS.height - LAYOUT_MARGIN + 1+ )+}++describe('bandLayout', () => {+ it('bands tile the usable area and are mutually disjoint', () => {+ for (const n of [1, 2, 3, 5]) {+ const placed = bandLayout(blocks(n), CANVAS)+ expect(placed).toHaveLength(n)+ for (const p of placed) expect(withinMargin(p.rect)).toBe(true)+ for (let i = 0; i < placed.length; i++) {+ for (let j = i + 1; j < placed.length; j++) {+ expect(rectsOverlap(placed[i].rect, placed[j].rect)).toBe(false)+ }+ }+ }+ })+ it('heavier blocks get taller bands', () => {+ const placed = bandLayout(+ [+ { kind: 'hero', weight: 3, content: [{ role: 'body', source: 'model', text: 'a' }] },+ { kind: 'hero', weight: 1, content: [{ role: 'body', source: 'model', text: 'b' }] },+ ],+ CANVAS,+ )+ expect(placed[0].rect.height).toBeGreaterThan(placed[1].rect.height * 2)+ })+ it('empty input → empty output (total function)', () => {+ expect(bandLayout([], CANVAS)).toEqual([])+ })+})++describe('gridInRect', () => {+ it('returns n cells inside the rect, gap-separated', () => {+ const rect: Rect = { x: 60, y: 60, width: 960, height: 300 }+ const cells = gridInRect(rect, 3, { columns: 3, gap: 28 })+ expect(cells).toHaveLength(3)+ for (const c of cells) expect(rectContains(rect, c)).toBe(true)+ for (let i = 0; i < cells.length; i++) {+ for (let j = i + 1; j < cells.length; j++) {+ expect(rectsOverlap(cells[i], cells[j])).toBe(false)+ }+ }+ })+ it('shrinks columns until cells clear the 160px minimum width', () => {+ const narrow: Rect = { x: 0, y: 0, width: 400, height: 300 }+ const cells = gridInRect(narrow, 3, { columns: 3, gap: 24 })+ expect(cells.every((c) => c.width >= 160 - 1)).toBe(true)+ })+})++describe('stackInRect', () => {+ it('stacked sub-rects are disjoint and cover the band', () => {+ const rect: Rect = { x: 60, y: 60, width: 960, height: 400 }+ const subs = stackInRect(rect, ['headline', 'subline', 'cta'])+ expect(subs).toHaveLength(3)+ for (let i = 0; i < subs.length; i++) {+ expect(rectContains(rect, subs[i])).toBe(true)+ for (let j = i + 1; j < subs.length; j++) {+ expect(rectsOverlap(subs[i], subs[j])).toBe(false)+ }+ }+ const total = subs.reduce((s, r) => s + r.height, 0)+ expect(total).toBeLessThanOrEqual(rect.height + 1)+ })+})++describe('predicates', () => {+ it('rectsOverlap handles touching edges as NOT overlapping (1px tolerance)', () => {+ const a: Rect = { x: 0, y: 0, width: 100, height: 100 }+ const touching: Rect = { x: 100, y: 0, width: 100, height: 100 }+ const real: Rect = { x: 50, y: 0, width: 100, height: 100 }+ expect(rectsOverlap(a, touching)).toBe(false)+ expect(rectsOverlap(a, real)).toBe(true)+ })+ it('isInCanvas bounds rects with 1px tolerance', () => {+ expect(isInCanvas({ x: 0, y: 0, width: 1080, height: 1080 }, CANVAS)).toBe(true)+ expect(isInCanvas({ x: -1, y: 0, width: 10, height: 10 }, CANVAS)).toBe(false)+ expect(isInCanvas({ x: 0, y: 0, width: 1082, height: 10 }, CANVAS)).toBe(false)+ })+})diff --git a/src/lib/design-engine/layout.ts b/src/lib/design-engine/layout.tsnew file mode 100644index 0000000..31c2f4f--- /dev/null+++ b/src/lib/design-engine/layout.ts@@ -0,0 +1,160 @@+// ─────────────────────────────────────────────────────────────+// Design engine · layout (Phase A).+//+// The block solver: semantic blocks → vertical bands → pixel rects.+// Bands are disjoint BY CONSTRUCTION (stacked, gap-separated, inside+// the margin box), which is what retires fix_overlaps for generated+// designs: the overlap the agent loop repairs after the fact cannot+// occur here. Deliberate artistic layering stays possible through+// the declared two-layer output of the composition builders+// (backdrop elements may sit under content; content never overlaps+// content).+// ─────────────────────────────────────────────────────────────++import { clamp, type BlockNode } from '@/lib/design-spec/types'++export interface Rect {+ x: number+ y: number+ width: number+ height: number+}++export interface PlacedBlock {+ block: BlockNode+ rect: Rect+}++/** Layout safety defaults (60px margins match the plan-route contract). */+export const LAYOUT_MARGIN = 60+export const LAYOUT_GAP = 32++/** Weights by content role for inside-band stacking (headline-heavy). */+const ROLE_WEIGHT: Record<string, number> = {+ headline: 3,+ subline: 2,+ tagline: 1.8,+ body: 2,+ cta: 1.6,+ label: 1,+}++/**+ * Stack blocks top-to-bottom into disjoint bands. Each block's band+ * height is its weight's share of the available height (minus gaps).+ * Deterministic; total (empty input → empty output).+ */+export function bandLayout(+ blocks: BlockNode[],+ canvas: { width: number; height: number },+ margin = LAYOUT_MARGIN,+ gap = LAYOUT_GAP,+): PlacedBlock[] {+ if (!blocks.length) return []+ const usable = {+ x: margin,+ y: margin,+ width: Math.max(0, canvas.width - margin * 2),+ height: Math.max(0, canvas.height - margin * 2),+ }+ const weights = blocks.map((b) => clamp(b.weight ?? 1, 0.2, 3))+ const totalWeight = weights.reduce((s, w) => s + w, 0)+ const contentHeight = Math.max(0, usable.height - gap * (blocks.length - 1))++ let y = usable.y+ return blocks.map((block, i) => {+ const height = (contentHeight * weights[i]) / totalWeight+ const rect: Rect = { x: usable.x, y, width: usable.width, height }+ y += height + gap+ return { block, rect }+ })+}++/** Split a rect into n cells (≤ columns per row) with gaps.+ * Used by feature-cards / stat-row / timeline rows. */+export function gridInRect(+ rect: Rect,+ count: number,+ opts: { columns?: number; gap?: number; minCellWidth?: number; minCellHeight?: number } = {},+): Rect[] {+ const n = clamp(Math.round(count), 1, 12)+ const gap = clamp(opts.gap ?? 24, 0, 120)+ const maxColumns = clamp(opts.columns ?? 3, 1, 6)+ const minW = opts.minCellWidth ?? 160+ const minH = opts.minCellHeight ?? 110++ let columns = Math.min(n, maxColumns)+ let rows = Math.ceil(n / columns)+ // shrink the column count until cells clear the minimums (or 1 column)+ while (+ columns > 1 &&+ (rect.width - gap * (columns - 1)) / columns < minW+ ) {+ columns -= 1+ rows = Math.ceil(n / columns)+ }+ const cellW = (rect.width - gap * (columns - 1)) / columns+ const cellH = (rect.height - gap * (rows - 1)) / rows+ // if cells still cannot clear the minimum height, the band is too+ // short — return what fits (the compile check will flag it honestly)+ const cells: Rect[] = []+ for (let i = 0; i < n; i++) {+ const col = i % columns+ const row = Math.floor(i / columns)+ cells.push({+ x: rect.x + col * (cellW + gap),+ y: rect.y + row * (cellH + gap),+ width: cellW,+ height: cellH,+ })+ }+ return cells+}++/**+ * Stack content slots vertically inside a band, heights proportional+ * to role weight. Disjoint by construction.+ */+export function stackInRect(rect: Rect, roles: string[], gap = 24): Rect[] {+ const n = roles.length+ if (!n) return []+ const weights = roles.map((r) => ROLE_WEIGHT[r] ?? 1)+ const total = weights.reduce((s, w) => s + w, 0)+ const contentHeight = Math.max(0, rect.height - gap * (n - 1))+ let y = rect.y+ return roles.map((role, i) => {+ const height = (contentHeight * weights[i]) / total+ const out: Rect = { x: rect.x, y, width: rect.width, height }+ y += height + gap+ return out+ })+}++// ── geometry predicates (the compile checks + tests consume these) ──++export function rectsOverlap(a: Rect, b: Rect): boolean {+ return (+ a.x < b.x + b.width - 1 &&+ b.x < a.x + a.width - 1 &&+ a.y < b.y + b.height - 1 &&+ b.y < a.y + a.height - 1+ )+}++export function rectContains(outer: Rect, inner: Rect): boolean {+ return (+ inner.x >= outer.x &&+ inner.y >= outer.y &&+ inner.x + inner.width <= outer.x + outer.width + 1 &&+ inner.y + inner.height <= outer.y + outer.height + 1+ )+}++export function isInCanvas(rect: Rect, canvas: { width: number; height: number }): boolean {+ return (+ rect.x >= 0 &&+ rect.y >= 0 &&+ rect.x + rect.width <= canvas.width + 1 &&+ rect.y + rect.height <= canvas.height + 1+ )+}diff --git a/src/lib/design-engine/palette.test.ts b/src/lib/design-engine/palette.test.tsnew file mode 100644index 0000000..2a1c9d8--- /dev/null+++ b/src/lib/design-engine/palette.test.ts@@ -0,0 +1,72 @@+// design-engine/palette.ts — role expansion with WCAG at assignment time.+import { describe, expect, it } from 'vitest'+import { expandPalette, mixHex, onColor } from './palette'+import { contrast } from '@/lib/theme'++const POSTER_SEEDS = ['#090b1a', '#8b5cf6', '#22d3ee']++describe('expandPalette', () => {+ it('assigns the v0.29.3 poster seeds: darkest ground, accents by luminance', () => {+ const { roles, warnings } = expandPalette({ seeds: POSTER_SEEDS, mood: 'neutral' })+ expect(warnings).toHaveLength(0)+ expect(roles.background.toLowerCase()).toBe('#090b1a')+ // both remaining seeds preserved verbatim in accent roles+ expect([roles.accent.toLowerCase(), roles.accentSoft.toLowerCase()].sort()).toEqual(+ ['#22d3ee', '#8b5cf6'].sort(),+ )+ })++ it('ink clears WCAG 4.5 on the ground — checked at assignment, not after', () => {+ const { roles } = expandPalette({ seeds: POSTER_SEEDS, mood: 'neutral' })+ expect(contrast(roles.ink, roles.background)).toBeGreaterThanOrEqual(4.5)+ expect(contrast(roles.inkSoft, roles.background)).toBeGreaterThanOrEqual(4.5)+ })++ it('light ground with no seeds flips ink to near-black', () => {+ const { roles } = expandPalette({ seeds: [], mood: 'minimal' })+ expect(roles.background).toBe('#FFFFFF')+ expect(roles.ink).toBe('#10131A')+ expect(contrast(roles.ink, roles.background)).toBeGreaterThanOrEqual(4.5)+ })++ it('pinned roles are honored verbatim', () => {+ const { roles } = expandPalette({ seeds: POSTER_SEEDS, mood: 'neutral', pinned: { background: '#FFFFFF' } })+ expect(roles.background).toBe('#FFFFFF')+ expect(contrast(roles.ink, roles.background)).toBeGreaterThanOrEqual(4.5)+ })++ it('is deterministic — same seeds, same roles, same warnings', () => {+ const a = expandPalette({ seeds: POSTER_SEEDS, mood: 'warm' })+ const b = expandPalette({ seeds: POSTER_SEEDS, mood: 'warm' })+ expect(a).toEqual(b)+ })++ it('surface steps one shade off the ground toward ink', () => {+ const dark = expandPalette({ seeds: POSTER_SEEDS, mood: 'neutral' })+ expect(dark.roles.surface).not.toBe(dark.roles.background)+ const lum = (hex: string) => parseInt(hex.slice(1, 3), 16) + parseInt(hex.slice(3, 5), 16) + parseInt(hex.slice(5, 7), 16)+ // dark ground → surface is lighter; light ground → surface is darker+ expect(lum(dark.roles.surface)).toBeGreaterThan(lum(dark.roles.background))+ })+})++describe('color primitives', () => {+ it('mixHex is linear and clamped', () => {+ expect(mixHex('#000000', '#FFFFFF', 0.5)).toBe('#808080')+ expect(mixHex('#000000', '#FFFFFF', 0)).toBe('#000000')+ expect(mixHex('#000000', '#FFFFFF', 1)).toBe('#ffffff')+ expect(mixHex('#000000', '#FFFFFF', 9)).toBe('#ffffff')+ })+ it('onColor picks the higher-contrast ink for any fill', () => {+ expect(onColor('#090b1a')).toBe('#FFFFFF')+ expect(onColor('#FFFFFF')).toBe('#10131A')+ expect(onColor('#22d3ee')).toBe('#10131A')+ // mid-luminance fills: the contract is best-of-two, and the+ // compile contrast check reports honestly when even that misses 4.5+ for (const fill of ['#8b5cf6', '#7630d7', '#02c0cc', '#F4F5F7']) {+ const picked = contrast(onColor(fill), fill)+ const other = contrast(onColor(fill) === '#FFFFFF' ? '#10131A' : '#FFFFFF', fill)+ expect(picked).toBeGreaterThanOrEqual(other)+ }+ })+})diff --git a/src/lib/design-engine/palette.ts b/src/lib/design-engine/palette.tsnew file mode 100644index 0000000..20bbfe7--- /dev/null+++ b/src/lib/design-engine/palette.ts@@ -0,0 +1,146 @@+// ─────────────────────────────────────────────────────────────+// Design engine · palette (Phase A).+//+// Deterministic seed → role expansion. The inversion of theme.ts:+// where the theme engine recolors an existing design and guards+// contrast afterwards, this module assigns roles AT CONSTRUCTION+// TIME so no WCAG-violating pair can reach the canvas.+//+// Guarantees:+// · seed colors are preserved verbatim in some role — required+// brief colors therefore always appear on the page+// · contrast(ink, background) ≥ 4.5 is enforced by flipping or+// stepping the ink until it holds (bounded loop, never invents+// colors outside a mix of the seeds and two neutrals)+// · fully deterministic — same seeds, same roles, same warnings+// ─────────────────────────────────────────────────────────────++import { contrast } from '@/lib/theme'+import { PALETTE_ROLES, asHex, clamp, type PaletteMood, type PaletteRole, type PaletteSpec } from '@/lib/design-spec/types'++export interface ExpandedPalette {+ roles: Record<PaletteRole, string>+ /** non-fatal notes surfaced by the compile report (honest completion) */+ warnings: string[]+}++// ── color primitives (local; theme.ts exports only contrast) ──++function hexToRgb(hex: string): [number, number, number] | null {+ if (!/^#[0-9a-fA-F]{6}$/.test(hex)) return null+ return [+ parseInt(hex.slice(1, 3), 16),+ parseInt(hex.slice(3, 5), 16),+ parseInt(hex.slice(5, 7), 16),+ ]+}++function rgbToHex(r: number, g: number, b: number): string {+ const h = (n: number) => clamp(Math.round(n), 0, 255).toString(16).padStart(2, '0')+ return `#${h(r)}${h(g)}${h(b)}`+}++/** linear mix: t=0 → a, t=1 → b */+export function mixHex(a: string, b: string, t: number): string {+ const ca = hexToRgb(a)+ const cb = hexToRgb(b)+ if (!ca || !cb) return a+ const k = clamp(t, 0, 1)+ return rgbToHex(ca[0] + (cb[0] - ca[0]) * k, ca[1] + (cb[1] - ca[1]) * k, ca[2] + (cb[2] - ca[2]) * k)+}++function luminanceOf(hex: string): number {+ const rgb = hexToRgb(hex)+ if (!rgb) return 0+ const [r, g, b] = rgb.map((c) => {+ const s = c / 255+ return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4+ })+ return 0.2126 * r + 0.7152 * g + 0.0722 * b+}++/** Readable ink for any fill — white or near-black, whichever wins. */+export function onColor(hex: string): string {+ return contrast('#FFFFFF', hex) >= contrast('#10131A', hex) ? '#FFFFFF' : '#10131A'+}++// ── role expansion ───────────────────────────────────────────++const NEUTRAL_DARK = '#10131A'+const NEUTRAL_LIGHT = '#FFFFFF'+const MIN_TEXT_CONTRAST = 4.5++/**+ * Expand palette seeds into the full role set. Assignment order+ * (deterministic): pinned roles win; then the darkest seed becomes+ * background, remaining seeds fill accent/accentSoft by luminance;+ * ink/inkSoft/surface are derived and contrast-guarded.+ */+export function expandPalette(spec: PaletteSpec, mood: PaletteMood = spec.mood): ExpandedPalette {+ const warnings: string[] = []+ const roles = {} as Record<PaletteRole, string>++ // 1. pinned roles — validated hex, honored verbatim+ for (const role of PALETTE_ROLES) {+ const pinned = asHex(spec.pinned?.[role], '')+ if (pinned !== '') roles[role] = pinned+ }++ // 2. seeds: darkest → background; rest → accents by luminance+ const seeds = spec.seeds.map((s) => asHex(s, '')).filter((s) => s !== '')+ const unassignedSeeds = [...seeds]+ if (!roles.background && unassignedSeeds.length) {+ let darkest = 0+ for (let i = 1; i < unassignedSeeds.length; i++) {+ if (luminanceOf(unassignedSeeds[i]) < luminanceOf(unassignedSeeds[darkest])) darkest = i+ }+ roles.background = unassignedSeeds.splice(darkest, 1)[0]+ }+ if (!roles.background) {+ // no seeds at all: mood-derived neutral ground+ roles.background = mood === 'warm' ? '#F7F3EC' : mood === 'cool' ? '#F2F6FA' : '#FFFFFF'+ warnings.push('no palette seeds — background defaulted from mood')+ }+ const accentOrder = unassignedSeeds.sort((a, b) => luminanceOf(b) - luminanceOf(a))+ if (!roles.accent && accentOrder.length) roles.accent = accentOrder.shift() as string+ if (!roles.accentSoft && accentOrder.length) roles.accentSoft = accentOrder.shift() as string+ if (!roles.accent) {+ roles.accent = mood === 'warm' ? '#B45F3C' : mood === 'cool' ? '#2C7DA0' : '#00C4CC'+ warnings.push('accent defaulted from mood')+ }+ if (!roles.accentSoft) roles.accentSoft = mixHex(roles.accent, roles.background, 0.45)++ // 3. ink — white or near-black, whichever clears WCAG on the ground+ if (!roles.ink) {+ const whiteWins = contrast(NEUTRAL_LIGHT, roles.background) >= contrast(NEUTRAL_DARK, roles.background)+ roles.ink = whiteWins ? NEUTRAL_LIGHT : NEUTRAL_DARK+ }+ // guard even pinned/derived inks: step toward the opposite neutral+ if (contrast(roles.ink, roles.background) < MIN_TEXT_CONTRAST) {+ const opposite = roles.ink === NEUTRAL_LIGHT ? NEUTRAL_DARK : NEUTRAL_LIGHT+ if (contrast(opposite, roles.background) >= MIN_TEXT_CONTRAST) {+ warnings.push(`ink #${roles.ink.slice(1).toUpperCase()} failed WCAG on the background — flipped`)+ roles.ink = opposite+ } else {+ warnings.push('no ink clears WCAG 4.5 on this background — kept the higher-contrast option')+ roles.ink = opposite+ }+ }++ // 4. inkSoft — a dimmed ink that still clears 4.5 (bounded steps)+ if (!roles.inkSoft) {+ let candidate = mixHex(roles.ink, roles.background, 0.35)+ for (let step = 0; step < 8 && contrast(candidate, roles.background) < MIN_TEXT_CONTRAST; step++) {+ candidate = mixHex(candidate, roles.ink, 0.3)+ }+ roles.inkSoft = candidate+ }++ // 5. surface — a panel one step off the ground toward ink+ if (!roles.surface) {+ const toward = roles.ink === NEUTRAL_LIGHT ? NEUTRAL_LIGHT : NEUTRAL_DARK+ roles.surface = mixHex(roles.background, toward, 0.09)+ }++ return { roles, warnings }+}diff --git a/src/lib/design-engine/typography.test.ts b/src/lib/design-engine/typography.test.tsnew file mode 100644index 0000000..3dd1006--- /dev/null+++ b/src/lib/design-engine/typography.test.ts@@ -0,0 +1,48 @@+// design-engine/typography.ts — pairing selection + modular scale.+import { describe, expect, it } from 'vitest'+import { assignTypeScale, PAIRINGS, selectPairing } from './typography'+import { FONTS } from '@/lib/editor-utils'++describe('selectPairing', () => {+ it('honors pinned families that exist in the catalog', () => {+ const { pairing } = selectPairing({ heading: 'Oswald', body: 'Lato' }, 'warm')+ expect(pairing.heading).toBe('Oswald')+ expect(pairing.body).toBe('Lato')+ })+ it('falls back when a pinned family is not in the catalog', () => {+ const { pairing } = selectPairing({ heading: 'Not A Font', body: 'Inter' }, 'cool')+ expect(PAIRINGS.some((p) => p.id === pairing.id)).toBe(true)+ })+ it('maps mood to a pairing; every catalog mood resolves', () => {+ const cool = selectPairing({}, 'cool')+ expect(cool.pairing.moods).toContain('cool')+ const neutral = selectPairing({}, 'neutral')+ expect(neutral.pairing).toBeTruthy()+ })+ it('every pairing family exists in the live catalog', () => {+ for (const p of PAIRINGS) {+ expect(FONTS.some((f) => f.family === p.heading), p.heading).toBe(true)+ expect(FONTS.some((f) => f.family === p.body), p.body).toBe(true)+ }+ })+})++describe('assignTypeScale', () => {+ it('sizes follow the hierarchy: headline > subline > cta > label', () => {+ const t = assignTypeScale({ scale: 1.333 }, 'neutral', 1080)+ expect(t.sizes.headline).toBeGreaterThan(t.sizes.subline)+ expect(t.sizes.subline).toBeGreaterThan(t.sizes.cta)+ expect(t.sizes.cta).toBeGreaterThan(t.sizes.label)+ expect(t.sizes.body).toBeGreaterThanOrEqual(14)+ })+ it('scales with the canvas width', () => {+ const small = assignTypeScale({}, 'neutral', 400)+ const large = assignTypeScale({}, 'neutral', 1080)+ expect(large.sizes.body).toBeGreaterThan(small.sizes.body)+ })+ it('is deterministic', () => {+ expect(assignTypeScale({ scale: 1.618 }, 'warm', 1080)).toEqual(+ assignTypeScale({ scale: 1.618 }, 'warm', 1080),+ )+ })+})diff --git a/src/lib/design-engine/typography.ts b/src/lib/design-engine/typography.tsnew file mode 100644index 0000000..e6fb95e--- /dev/null+++ b/src/lib/design-engine/typography.ts@@ -0,0 +1,102 @@+// ─────────────────────────────────────────────────────────────+// Design engine · typography (Phase A).+//+// Font pairing from the live catalog's category/weight metadata —+// the data the 370-family catalog already carries and nothing in+// the AI stack consumes today — plus a modular type scale. Pure+// and deterministic: same spec in, same sizes out.+// ─────────────────────────────────────────────────────────────++import { FONTS } from '@/lib/editor-utils'+import {+ asString,+ clamp,+ type ContentRole,+ type PaletteMood,+ type TypographySpec,+} from '@/lib/design-spec/types'++/** Vetted pairings — families from the preloaded catalog core. The+ * catalog check at selection time keeps this honest if the list+ * evolves: unknown families fall back to the default pair. */+export interface FontPairing {+ id: string+ heading: string+ body: string+ moods: PaletteMood[]+}++export const PAIRINGS: FontPairing[] = [+ { id: 'poppins-inter', heading: 'Poppins', body: 'Inter', moods: ['neutral', 'vibrant'] },+ { id: 'montserrat-work', heading: 'Montserrat', body: 'Work Sans', moods: ['vibrant', 'cool'] },+ { id: 'space-grotesk-inter', heading: 'Space Grotesk', body: 'Inter', moods: ['cool', 'minimal'] },+ { id: 'oswald-lato', heading: 'Oswald', body: 'Lato', moods: ['vibrant', 'warm'] },+ { id: 'raleway-opensans', heading: 'Raleway', body: 'Open Sans', moods: ['warm', 'minimal'] },+]++const DEFAULT_PAIRING = PAIRINGS[0]++function inCatalog(family: string): boolean {+ return FONTS.some((f) => f.family === family)+}++export interface AssignedTypography {+ pairing: FontPairing+ families: { heading: string; body: string }+ /** px sizes per content role, derived from canvas width × scale */+ sizes: Record<ContentRole, number>+ scale: number+ /** non-fatal note for the compile report */+ warning?: string+}++/** Modular exponents per role (body = 0). */+const ROLE_EXPONENT: Record<ContentRole, number> = {+ headline: 3,+ subline: 1.35,+ tagline: 1.15,+ body: 0,+ cta: 0.55,+ label: -0.85,+}++/** Pick the pairing: explicit families win (validated), else the+ * first pairing whose moods include the brief mood, else default. */+export function selectPairing(spec: TypographySpec, mood: PaletteMood): { pairing: FontPairing; warning?: string } {+ const heading = asString(spec.heading)+ const body = asString(spec.body)+ if (heading && body && inCatalog(heading) && inCatalog(body)) {+ return { pairing: { id: 'pinned', heading, body, moods: [mood] } }+ }+ const byMood = PAIRINGS.find((p) => p.moods.includes(mood))+ const pairing = byMood ?? DEFAULT_PAIRING+ if (!byMood) return { pairing, warning: `no pairing for mood '${mood}' — defaulted to ${pairing.id}` }+ return { pairing }+}++/**+ * Assign per-role sizes from the modular scale. Base is proportional+ * to the canvas width (≈ 24px body at 1080) so formats scale together;+ * builders use these as starting points for shrink-to-fit, never as+ * hard requirements.+ */+export function assignTypeScale(+ spec: TypographySpec,+ mood: PaletteMood,+ width: number,+): AssignedTypography {+ const { pairing, warning } = selectPairing(spec, mood)+ const scale = clamp(spec.scale ?? 1.333, 1.05, 1.8)+ const base = clamp(Math.round(width * 0.022), 14, 44)+ const sizes = {} as Record<ContentRole, number>+ for (const role of Object.keys(ROLE_EXPONENT) as ContentRole[]) {+ sizes[role] = Math.max(10, Math.round(base * scale ** ROLE_EXPONENT[role]))+ }+ return {+ pairing,+ families: { heading: pairing.heading, body: pairing.body },+ sizes,+ scale,+ ...(warning ? { warning } : {}),+ }+}diff --git a/src/lib/design-spec/from-brief.ts b/src/lib/design-spec/from-brief.tsnew file mode 100644index 0000000..fe271d2--- /dev/null+++ b/src/lib/design-spec/from-brief.ts@@ -0,0 +1,90 @@+// ─────────────────────────────────────────────────────────────+// DesignBrief → DesignSpec (Phase A).+//+// The deterministic half of the planner: the zero-model brief+// extractor (src/lib/agent/brief.ts) already pulls required texts,+// required hexes and dimensions out of the raw prompt; this mapper+// turns that brief into a DesignSpec with all brief content marked+// source 'user-required'. A live planner emits the same shape and+// adds model-written copy — the compile path is identical.+//+// Type-only dependency on the agent layer: no runtime import, the+// dependency direction stays design-spec ← agent.+// ─────────────────────────────────────────────────────────────++import type { DesignBrief } from '@/lib/agent/brief'+import type { ContentRole, ContentSlot, DesignSpec } from './types'++/** Order the three poster-style slots fill: headline → subline → cta.+ * Extra required texts become body slots (never dropped). */+const ROLE_ORDER: ContentRole[] = ['headline', 'subline', 'cta']++function roleForIndex(i: number, hinted?: string): ContentRole {+ if (hinted === 'heading') return 'headline'+ if (ROLE_ORDER[i]) return ROLE_ORDER[i]+ return 'body'+}++/**+ * Build a spec from an extracted brief. Mandatory items become+ * user-required slots and seed colors; preferences shape format and+ * mood. Deterministic and total — worst case (empty brief) it emits+ * a single hero block with one model slot so the pipeline always+ * has something to compile.+ */+export function specFromBrief(brief: DesignBrief): DesignSpec {+ const width = brief.dimensions?.width ?? 1080+ const height = brief.dimensions?.height ?? 1080++ const required = brief.requiredTexts.filter((t) => !t.tier || t.tier === 'mandatory')+ const seeds = brief.requiredColors+ .filter((c) => !c.tier || c.tier === 'mandatory')+ .map((c) => c.hex)+ .slice(0, 4)++ const notes = [...brief.restrictions, ...brief.notes].join(' ').toLowerCase()+ const mood: DesignSpec['palette']['mood'] = /warm|cozy|golden|coffee|sunset/.test(notes)+ ? 'warm'+ : /cool|calm|ocean|fresh|tech/.test(notes)+ ? 'cool'+ : /bold|vibrant|neon|party|loud/.test(notes)+ ? 'vibrant'+ : /minimal|clean|simple|elegant/.test(notes)+ ? 'minimal'+ : 'neutral'++ const content: ContentSlot[] = required.map((t, i) => ({+ role: roleForIndex(i, t.role),+ source: 'user-required',+ text: t.text,+ }))+ if (!content.length) {+ content.push({ role: 'headline', source: 'model', text: 'Your Headline Here', maxWords: 6 })+ }++ const blocks: DesignSpec['blocks'] = [{ kind: 'hero', weight: 1, content, overlap: 'none' }]++ // feature requests the brief can name become sibling blocks+ for (const feature of brief.requiredFeatures ?? []) {+ if (feature.kind === 'feature-cards') {+ blocks.push({+ kind: 'feature-cards',+ weight: 0.8,+ count: Math.min(6, Math.max(1, feature.count ?? 3)),+ content: content.length+ ? []+ : [{ role: 'label', source: 'model', text: 'Feature', maxWords: 3 }],+ overlap: 'over-backdrop',+ })+ }+ }++ return {+ version: 'v2',+ name: `${brief.designType ?? brief.format ?? 'design'} — ${brief.requiredTexts[0]?.text.slice(0, 30) ?? 'generated'}`.slice(0, 80),+ format: { width, height, ...(brief.format ? { preset: brief.format } : {}) },+ palette: { seeds, mood },+ typography: { scale: 1.333 },+ blocks: blocks.filter((b) => b.content.length > 0 || b.kind !== 'hero'),+ }+}diff --git a/src/lib/design-spec/parse.test.ts b/src/lib/design-spec/parse.test.tsnew file mode 100644index 0000000..9ff853a--- /dev/null+++ b/src/lib/design-spec/parse.test.ts@@ -0,0 +1,141 @@+// design-spec/parse.ts — the shared structured-output parser.+// Extraction (fences, prose, trailing commas), hostile coercion,+// and the exact-text passthrough guarantee.+import { describe, expect, it } from 'vitest'+import { extractJsonObject, parseSpecResponse, SPEC_MODEL_TEXT_CAP } from './parse'+import type { DesignSpec } from './types'++function validSpecJson(): string {+ return JSON.stringify({+ version: 'v2',+ name: 'Poster',+ format: { width: 1080, height: 1080, preset: 'poster' },+ palette: { seeds: ['#090B1A', '#8B5CF6', '#22D3EE'], mood: 'neutral' },+ typography: { scale: 1.333 },+ blocks: [+ {+ kind: 'hero',+ weight: 1,+ content: [+ { role: 'headline', source: 'user-required', text: 'Design Beyond Limits' },+ { role: 'subline', source: 'model', text: 'Create smarter. Design faster.', maxWords: 5 },+ ],+ },+ ],+ })+}++describe('extractJsonObject', () => {+ it('accepts pre-parsed objects', () => {+ expect(extractJsonObject({ a: 1 })).toEqual({ a: 1 })+ })+ it('strips ```json fences', () => {+ expect(extractJsonObject('```json\n{"a":1}\n```')).toEqual({ a: 1 })+ })+ it('recovers the object from surrounding prose', () => {+ expect(extractJsonObject('Sure! Here is your design: {"a":1} hope it helps')).toEqual({ a: 1 })+ })+ it('repairs trailing commas', () => {+ expect(extractJsonObject('{"a":1,}')).toEqual({ a: 1 })+ })+ it('returns null on garbage', () => {+ expect(extractJsonObject('no json here at all')).toBeNull()+ expect(extractJsonObject(42)).toBeNull()+ expect(extractJsonObject('')).toBeNull()+ })+})++describe('parseSpecResponse', () => {+ it('parses a well-formed spec', () => {+ const r = parseSpecResponse(validSpecJson(), 1080, 1080)+ expect(r.ok).toBe(true)+ if (!r.ok) return+ expect(r.spec.format).toMatchObject({ width: 1080, height: 1080, preset: 'poster' })+ expect(r.spec.palette.seeds).toEqual(['#090B1A', '#8B5CF6', '#22D3EE'])+ expect(r.spec.blocks).toHaveLength(1)+ expect(r.spec.blocks[0].content).toHaveLength(2)+ })++ it('preserves user-required text EXACTLY — no case folding, no slicing', () => {+ const r = parseSpecResponse(validSpecJson(), 1080, 1080)+ expect(r.ok).toBe(true)+ if (!r.ok) return+ const slot = r.spec.blocks[0].content[0]+ expect(slot.source).toBe('user-required')+ expect(slot.text).toBe('Design Beyond Limits')+ })++ it('caps model slot text but never required slot text', () => {+ const long = 'x'.repeat(900)+ const json = JSON.stringify({+ format: { width: 1080, height: 1080 },+ blocks: [+ {+ kind: 'hero',+ content: [+ { role: 'body', source: 'model', text: long },+ { role: 'headline', source: 'user-required', text: long },+ ],+ },+ ],+ })+ const r = parseSpecResponse(json)+ expect(r.ok).toBe(true)+ if (!r.ok) return+ const [model, required] = r.spec.blocks[0].content+ expect(model.text.length).toBe(SPEC_MODEL_TEXT_CAP)+ expect(required.text.length).toBe(900)+ })++ it('coerces hostile input: numbers as strings, bad hexes, unknown kinds', () => {+ const json = JSON.stringify({+ name: 42,+ format: { width: '1080', height: 1080 },+ palette: { seeds: ['#090B1A', 'red', 7], mood: 'spooky' },+ blocks: [+ { kind: 'hologram', content: [{ role: 'headline', text: 'x' }] },+ { kind: 'hero', weight: 99, content: [{ role: 'headline', source: 'user-required', text: 'OK' }] },+ ],+ })+ const r = parseSpecResponse(json)+ expect(r.ok).toBe(true)+ if (!r.ok) return+ const spec: DesignSpec = r.spec+ expect(spec.name).toBe('AI design') // number name → default, never a crash+ expect(spec.format.width).toBe(1080)+ expect(spec.palette.seeds).toEqual(['#090B1A'])+ expect(spec.palette.mood).toBe('neutral')+ expect(spec.blocks).toHaveLength(1)+ expect(spec.blocks[0].weight).toBe(3)+ })++ it('fails honestly when no usable blocks exist', () => {+ const r = parseSpecResponse('{"format":{"width":100}}')+ expect(r.ok).toBe(false)+ if (r.ok) return+ expect(r.error).toContain('no usable blocks')+ })++ it('drops slots with empty text', () => {+ const json = JSON.stringify({+ blocks: [{ kind: 'hero', content: [{ role: 'body', text: ' ' }, { role: 'body', text: 'Real' }] }],+ })+ const r = parseSpecResponse(json)+ expect(r.ok).toBe(true)+ if (!r.ok) return+ expect(r.spec.blocks[0].content).toHaveLength(1)+ })++ it('snaps scale to the nearest legal value and validates fonts', () => {+ const json = JSON.stringify({+ typography: { heading: 'Not A Font', body: 'Inter', scale: 1.6 },+ blocks: [{ kind: 'hero', content: [{ role: 'body', text: 'x' }] }],+ })+ const r = parseSpecResponse(json)+ expect(r.ok).toBe(true)+ if (!r.ok) return+ expect(r.spec.typography.heading).toBeUndefined()+ expect(r.spec.typography.body).toBe('Inter')+ expect(r.spec.typography.scale).toBe(1.618)+ })+})diff --git a/src/lib/design-spec/parse.ts b/src/lib/design-spec/parse.tsnew file mode 100644index 0000000..f6b276e--- /dev/null+++ b/src/lib/design-spec/parse.ts@@ -0,0 +1,199 @@+// ─────────────────────────────────────────────────────────────+// The ONE structured-output parser for design generation (Phase A).+//+// Replaces the three hand-rolled JSON-repair paths (plan route,+// theme route, MCP tools) with a single module: extract JSON from+// whatever the model actually replied with (fences, prose, trailing+// commas), then coerce it hostile-input-safe into a DesignSpec —+// design-plan.ts semantics, spec-v2 vocabulary.+//+// Hard guarantees:+// · never throws — garbage yields { ok: false, error }+// · user-required slot text passes through EXACTLY (no slicing,+// no case folding); only 'model' slots get length caps+// · every numeric field is clamped into a legal range+// ─────────────────────────────────────────────────────────────++import { FONTS } from '@/lib/editor-utils'+import {+ asEnum,+ asHex,+ asNumber,+ asString,+ clamp,+ type BlockKind,+ type BlockNode,+ type ContentRole,+ type ContentSlot,+ type DesignSpec,+ type ParseSpecResult,+} from './types'++export const SPEC_MAX_BLOCKS = 6+export const SPEC_MAX_SLOTS_PER_BLOCK = 12+export const SPEC_MODEL_TEXT_CAP = 400+export const SPEC_REQUIRED_TEXT_CAP = 2000++const CONTENT_ROLES = ['headline', 'subline', 'tagline', 'body', 'cta', 'label'] as const+const BLOCK_KINDS: readonly BlockKind[] = [+ 'hero',+ 'feature-cards',+ 'mockup',+ 'timeline',+ 'stat-row',+ 'gallery',+ 'footer',+]+const MOODS = ['warm', 'cool', 'neutral', 'vibrant', 'minimal'] as const+const SCALES = [1.2, 1.25, 1.333, 1.618]++/** Known-family check against the live font catalog. */+function knownFont(v: unknown): string | undefined {+ const name = asString(v)+ return FONTS.some((f) => f.family === name) ? name : undefined+}++// ── 1. JSON extraction (the repair layer) ────────────────────++/**+ * Pull a JSON object out of raw model output. Handles, in order:+ * · already-parsed objects (route passed parsed JSON)+ * · ```json fenced blocks+ * · leading/trailing prose around a top-level { … } span+ * · trailing commas before } or ]+ * Returns null when no object can be recovered.+ */+export function extractJsonObject(raw: unknown): Record<string, unknown> | null {+ if (raw && typeof raw === 'object' && !Array.isArray(raw)) {+ return raw as Record<string, unknown>+ }+ if (typeof raw !== 'string') return null+ let text = raw.trim()+ if (!text) return null++ const fence = text.match(/```(?:json)?\s*([\s\S]*?)```/i)+ if (fence) text = fence[1].trim()++ const start = text.indexOf('{')+ const end = text.lastIndexOf('}')+ if (start === -1 || end === -1 || end <= start) return null+ let body = text.slice(start, end + 1)++ try {+ return JSON.parse(body) as Record<string, unknown>+ } catch {+ // one repair pass: trailing commas (the most common model slip)+ const repaired = body.replace(/,\s*([}\]])/g, '$1')+ try {+ return JSON.parse(repaired) as Record<string, unknown>+ } catch {+ return null+ }+ }+}++// ── 2. slot / block / spec coercion ──────────────────────────++function normalizeSlot(raw: unknown): ContentSlot | null {+ const el = (raw ?? {}) as Record<string, unknown>+ const source = asEnum(el.source, ['user-required', 'model'] as const, 'model')+ const text = asString(el.text).trim()+ if (!text) return null+ // the exact-text contract: required copy is never sliced or folded+ const capped =+ source === 'user-required' ? text.slice(0, SPEC_REQUIRED_TEXT_CAP) : text.slice(0, SPEC_MODEL_TEXT_CAP)+ const slot: ContentSlot = {+ role: asEnum(el.role, CONTENT_ROLES, 'body'),+ source,+ text: capped,+ }+ if (source === 'model') {+ const maxWords = Math.round(asNumber(el.maxWords, 0))+ if (maxWords > 0) slot.maxWords = clamp(maxWords, 1, 80)+ }+ return slot+}++function normalizeBlock(raw: unknown): BlockNode | null {+ const el = (raw ?? {}) as Record<string, unknown>+ const kind = asString(el.kind)+ if (!(BLOCK_KINDS as readonly string[]).includes(kind)) return null+ const contentRaw = Array.isArray(el.content) ? el.content : []+ const content = contentRaw+ .slice(0, SPEC_MAX_SLOTS_PER_BLOCK)+ .map(normalizeSlot)+ .filter((s): s is ContentSlot => s !== null)+ if (!content.length) return null++ const block: BlockNode = {+ kind: kind as BlockKind,+ content,+ weight: clamp(asNumber(el.weight, 1), 0.2, 3),+ overlap: asEnum(el.overlap, ['none', 'over-backdrop'] as const, 'none'),+ }+ const count = Math.round(asNumber(el.count, 0))+ if (count > 0) block.count = clamp(count, 1, 6)+ return block+}++/**+ * Coerce raw model output (string or object) into a DesignSpec.+ * Falls back to the caller's page dimensions when absent/invalid;+ * drops unusable blocks but requires at least one usable block.+ */+export function parseSpecResponse(+ raw: unknown,+ fallbackWidth = 1080,+ fallbackHeight = 1080,+): ParseSpecResult {+ const obj = extractJsonObject(raw)+ if (!obj) return { ok: false, error: 'no JSON object found in model output' }++ const blocks = (Array.isArray(obj.blocks) ? obj.blocks : [])+ .slice(0, SPEC_MAX_BLOCKS)+ .map(normalizeBlock)+ .filter((b): b is BlockNode => b !== null)+ if (!blocks.length) {+ return { ok: false, error: 'spec has no usable blocks (kind + content required)' }+ }++ const format = (obj.format ?? {}) as Record<string, unknown>+ const palette = (obj.palette ?? {}) as Record<string, unknown>+ const seedsRaw = Array.isArray(palette.seeds) ? palette.seeds : []+ const seeds = seedsRaw+ .map((s) => asHex(s, ''))+ .filter((s) => s !== '')+ .slice(0, 4)+ const pinned: Record<string, string> = {}+ const pinnedRaw = (palette.pinned ?? {}) as Record<string, unknown>+ for (const [role, value] of Object.entries(pinnedRaw)) {+ const hex = asHex(value, '')+ if (hex !== '') pinned[role] = hex+ }++ const typo = (obj.typography ?? {}) as Record<string, unknown>+ const scaleRaw = asNumber(typo.scale, 1.333)+ const scale = SCALES.reduce((best, s) => (Math.abs(s - scaleRaw) < Math.abs(best - scaleRaw) ? s : best), 1.333)++ const spec: DesignSpec = {+ version: 'v2',+ name: asString(obj.name, 'AI design').slice(0, 80) || 'AI design',+ format: {+ width: clamp(Math.round(asNumber(format.width, fallbackWidth)), 200, 8000) || fallbackWidth,+ height: clamp(Math.round(asNumber(format.height, fallbackHeight)), 200, 8000) || fallbackHeight,+ preset: asString(format.preset).slice(0, 40) || undefined,+ },+ palette: {+ seeds,+ mood: asEnum(palette.mood, MOODS, 'neutral'),+ ...(Object.keys(pinned).length ? { pinned } : {}),+ },+ typography: {+ heading: knownFont(typo.heading),+ body: knownFont(typo.body),+ scale,+ },+ blocks,+ }+ return { ok: true, spec }+}diff --git a/src/lib/design-spec/types.ts b/src/lib/design-spec/types.tsnew file mode 100644index 0000000..17242d1--- /dev/null+++ b/src/lib/design-spec/types.ts@@ -0,0 +1,118 @@+// ─────────────────────────────────────────────────────────────+// Canvix DesignSpec v2 (Phase A — one-prompt design generation).+//+// The single intermediate representation every generation path will+// emit and every consumer will validate. The model (planner) chooses+// SEMANTICS only — blocks, copy slots, palette seeds, typography+// hints; the deterministic design engine (src/lib/design-engine/)+// owns geometry, color math and type scale. Nothing in this module+// does model I/O: it is pure data plus coercion.+//+// The exact-text contract (hardened over the agent brief checker):+// a ContentSlot with source 'user-required' is IMMUTABLE. The+// compiler preserves it character-for-character (NFC-normalized+// equality), and fitting adjusts font size, box or reflow — never+// the text. Length budgets apply to 'model' slots only.+// ─────────────────────────────────────────────────────────────++import { THEME_ROLES, type ThemeRole } from '@/lib/theme'++/** One palette vocabulary across theme.ts (post-hoc recolor) and the+ * design engine (construction time). Import, don't duplicate. */+export type PaletteRole = ThemeRole+export const PALETTE_ROLES: readonly PaletteRole[] = THEME_ROLES++export type PaletteMood = 'warm' | 'cool' | 'neutral' | 'vibrant' | 'minimal'++/** Copy roles the engine knows how to size and place. */+export type ContentRole = 'headline' | 'subline' | 'tagline' | 'body' | 'cta' | 'label'++/** Where the copy came from — decides immutability. */+export type ContentSource = 'user-required' | 'model'++export interface ContentSlot {+ role: ContentRole+ /** 'user-required' text is preserved exactly — never truncated,+ * case-folded or paraphrased by the engine. */+ source: ContentSource+ text: string+ /** Model slots only: soft length budget (a warning, not a cut). */+ maxWords?: number+}++export type BlockKind =+ | 'hero'+ | 'feature-cards'+ | 'mockup'+ | 'timeline'+ | 'stat-row'+ | 'gallery'+ | 'footer'++/**+ * A semantic layout block. `weight` is relative vertical importance+ * (band height share). `overlap: 'over-backdrop'` is the intentional-+ * overlap channel: the block's decorative layers may sit under its+ * content — never hiding it — and text contrast is verified against+ * the composited backdrop, mirroring the shipped audit's semantics.+ */+export interface BlockNode {+ kind: BlockKind+ weight?: number+ content: ContentSlot[]+ overlap?: 'none' | 'over-backdrop'+ /** feature-cards / stat-row / timeline: how many units. */+ count?: number+}++export interface PaletteSpec {+ /** 1-3 hex seeds (from the brief or the planner). Preserved+ * verbatim in the compiled palette — required colors must appear. */+ seeds: string[]+ mood: PaletteMood+ /** Planner-pinned role colors (validated hex); engine fills the rest. */+ pinned?: Partial<Record<PaletteRole, string>>+}++export interface TypographySpec {+ /** Font families; validated against the catalog, defaulted by mood. */+ heading?: string+ body?: string+ /** Modular scale; one of 1.2 / 1.25 / 1.333 / 1.618. */+ scale?: number+}++export interface DesignSpec {+ version: 'v2'+ name: string+ format: { width: number; height: number; preset?: string }+ palette: PaletteSpec+ typography: TypographySpec+ /** Ordered top-to-bottom semantic blocks. */+ blocks: BlockNode[]+}++/** parseSpecResponse()'s result — an explicit, honest failure object+ * (never a silently-emptied spec). */+export type ParseSpecResult =+ | { ok: true; spec: DesignSpec }+ | { ok: false; error: string }++// ── coercion helpers (same semantics as design-plan.ts) ──────++export function asString(v: unknown, fallback = ''): string {+ return typeof v === 'string' ? v : fallback+}+export function asNumber(v: unknown, fallback: number): number {+ const n = typeof v === 'number' ? v : typeof v === 'string' ? Number(v) : NaN+ return Number.isFinite(n) ? n : fallback+}+export function clamp(n: number, min: number, max: number): number {+ return Math.min(max, Math.max(min, n))+}+export function asHex(v: unknown, fallback: string): string {+ return typeof v === 'string' && /^#[0-9a-fA-F]{6}$/.test(v.trim()) ? v.trim() : fallback+}+export function asEnum<T extends readonly string[]>(v: unknown, options: T, fallback: T[number]): T[number] {+ return typeof v === 'string' && (options as readonly string[]).includes(v) ? (v as T[number]) : fallback+}