
Design To Code
- 1 installs
- 6 repo stars
- Updated May 25, 2026
- fitoe/designtocode
Turn segmented design images into a project-matched UnoCSS page after a short pre-implementation brief, with atlas-based asset fulfillment when bitmaps are missing.
About
DesignToCode is an agent skill for developers who have static design segments—Figma exports, marketing slices, or reference screenshots—and want implementation that respects an existing frontend stack rather than a generic HTML dump. The default flow asks the agent to run a pre-implementation brief first so spacing, typography, and UnoCSS conventions match the repo, then generates page structure and styles from the segmented images. When bitmaps are missing, Asset Fulfillment may use atlas generation only for small batches of visually related assets within strict guardrails: two to eight images in the same family, with mandatory post-generation cropping into separate files referenced in code. The skill explicitly rejects atlas shortcuts for heroes, CTA backgrounds, portraits, logos, and unrelated mixed roles, pushing CSS or individual generations where quality control matters. Intermediate to advanced users get the most value when they already use UnoCSS and can review cropped assets and layout fidelity. It accelerates frontend work for landing pages and marketing surfaces without replacing design critique or accessibility review.
- Converts segmented design images into high-fidelity UnoCSS pages aligned to the existing project
- Requires a pre-implementation brief before codegen to match conventions and layout
- Asset atlas sub-strategy for 2–8 same-family bitmaps with shared lighting and crop targets
- Hard rule: crop atlas to independent files—no CSS background-position card fakery in production
- Explicit do-not-use list for heroes, CTA banners, portraits, icons, and mixed unrelated asset roles
Design To Code by the numbers
- 1 all-time installs (skills.sh)
- Ranked #1,912 of 2,245 Frontend Development skills by installs in the Skillselion catalog
- Security screen: LOW risk (skills.sh audit)
- Data as of Jul 23, 2026 (Skillselion catalog sync)
npx skills add https://github.com/fitoe/designtocode --skill design-to-codeAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 1 |
|---|---|
| repo stars | ★ 6 |
| Security audit | 3 / 3 scanners passed |
| Last updated | May 25, 2026 |
| Repository | fitoe/designtocode ↗ |
What it does
Turn segmented design images into a project-matched UnoCSS page after a short pre-implementation brief, with atlas-based asset fulfillment when bitmaps are missing.
Files
Design to Code
Purpose
Turn an approved visual source into maintainable code without relying on prose precision. Prefer structured inputs, small implementation passes, and screenshot-backed parity evidence.
Ownership Boundary
design-to-code owns work after design approval/handoff:
- implementation mapping and code changes
- extracting implementation details from approved visual sources
data-sectionanchors and section-level parity evidence- visual repair, mismatch/debt notes, accepted deviations
Return to idea-to-design only when the approved source is missing/stale, scope changed, the handoff predates approval, or the user asks for a design change.
Input Priority
1. implementation-blueprint.json + page-matrix.json + component-blueprint.json + debt-ledger.json 2. Visual IR / section contract (visual-ir/<page-id>.json, visual-contracts/*, section crops) 3. Approved design images / Figma context / persisted mockups 4. Page briefs and prose notes
Prose briefs are supporting context, not the source of truth.
Fidelity Path
D2C has one default path: highest-fidelity-regeneration.
Use D2C only when converting or repairing against an approved visual source and the expected result is the highest practical design-source fidelity. Do not downgrade to quick, standard, or "structure-first" modes unless the user explicitly waives fidelity for that specific task.
For every visual D2C page/section:
- approved visual source is the source of truth; prose only supports it
- load the highest-fidelity references before coding, not after a mismatch appears
- extract executable section-level IR before implementation
- inventory visible text, icons, shapes, tokens, assets, and controls before coding; for mobile pages include icon anatomy, icon size tokens, and Iconify visual compensation
- implement from the inventory/IR, then generate left-design/right-live evidence
- any shortcut, placeholder, missing icon, or simplified asset is debt and must be named before showing the result
Required references for visual D2C work:
references/design-extraction-analysis-gate.mdreferences/full-page-regeneration-guard.mdreferences/high-fidelity-rules.mdreferences/section-driven-high-fidelity.mdreferences/executable-visual-ir.mdreferences/asset-atlas-generation.mdwhen multiple related bitmap assets are neededreferences/functional-component-handoff-guard.mdwhen controls/forms/tabs/pickers affect behavior
Non-visual or minor project-convention edits should not use D2C and must not claim design parity.
Fidelity Kernel
These rules are always active for GPT Image 2/mockup work:
- approved visual source is the source of truth; prose only supports it
- preserve page type, section order, first-screen density, card/list/form anatomy, and action hierarchy
- preserve icon anatomy and icon size tokens: box size, glyph size, container/radius/color/alignment, and Iconify visual compensation must be explicit before L4/L5 claims
- for mobile H5 / phone-width work, preserve readability floors as part of fidelity; do not copy or generate tiny 10-12px-equivalent text for meaningful content just to match density
- do not convert list/detail/form/product pages into generic dashboards
- do not replace populated designs with empty states unless the source says so
- do not claim parity from DOM/text smoke alone; use screenshot or section evidence
- maintain or create lightweight Visual IR for the active page/section
- before strict visual repair, perform design extraction and analysis from the approved source; load
references/design-extraction-analysis-gate.mdwhen fidelity depends on a screenshot/mockup - for high-fidelity page rewrites, enrich Visual IR to executable section-level layout/asset/anatomy/token contracts before coding
- if visual repair keeps producing "similar but not restored", treat under-specified IR as the blocker and load
references/executable-visual-ir.mdbefore more CSS - generated media must match its final display role and aspect ratio; do not hide asset mismatch with
object-fitor background-position tricks - atlas generation is for creation efficiency only; crop atlas outputs into independent files before implementation
- fix the largest 1-3 visual gaps per pass and record remaining debt
Default Workflow
1. Intake: identify source of truth, target routes/files, framework constraints, current maturity target. 2. Foundation: map tokens/shell/base components before page-specific polish. 3. Coverage: make every in-scope route/page visibly present before deep fidelity work. 4. Section Anchors: add stable data-section markers for key sections. 5. Fidelity Loop: compare source vs implementation by section; fix the largest 1-3 gaps per pass. 6. Handoff: report page maturity, evidence, debt, and deviations.
Highest-Fidelity Gate
Before coding any visual D2C page/section, the required references above must be loaded and applied. Section-level executable IR is mandatory: each major section needs bbox/height or density, component anatomy, text/icon/shape inventory, token targets including mobile typography floors, media/asset role, crop strategy, text safe areas, screenshot target, pass criteria, and must-not-substitute rules.
If any required field is missing, stop and enrich the IR/brief before changing code.
Asset Strategy Kernel
Use generated media by role:
| role | strategy |
|---|---|
| hero main visual | generate as an independent asset |
| CTA/banner background | generate as an independent asset |
| repeated card thumbnails | atlas generation allowed, then crop to independent files |
| application/factory scene groups | atlas generation allowed, then crop to independent files |
| certificates, logos, nav, buttons, labels | render with HTML/CSS/SVG/Iconify; do not bake into images |
Hard rule: an atlas is never a production UI asset. Final code must reference the cropped output files, not use CSS background-position against the atlas to fake separate images.
Visual IR Minimum
Use or create a lightweight Visual IR for PNG/GPT Image 2/mockup sources when fidelity matters:
{
"page_id": "application-list",
"route": "/pages/applications/index",
"viewport": [390, 844],
"page_type": "list",
"source_refs": ["design-to-code-inputs/mockup.png"],
"sections": [
{"name": "topbar", "order": 1, "bbox": [0,0,390,72]},
{"name": "card-list", "order": 4, "density": "2.5 cards visible"}
],
"section_anchors": ["topbar", "card-list"],
"must_not_do": ["do not replace list with dashboard"]
}Do not over-model every pixel. Capture page type, section order, bbox, first-screen density, card/list anatomy, action hierarchy, must-not-do, and asset strategy.
Required Output Evidence
For each meaningful checkpoint, report:
- route/page coverage
- maturity level: L0 route-ready, L1 skeleton, L2 content, L3 system-styled, L4 core-fidelity, L5 functional
- section parity: PASS/WARN/FAIL for major sections when fidelity is claimed
- largest remaining visual gaps and whether they are debt or accepted deviation
- verification actually run; do not claim checks that were skipped
Hard Rules
- Do not claim design parity from DOM/text smoke alone.
- Do not replace populated designs with empty states unless the design/source says so.
- Do not convert list/detail/form pages into generic dashboards.
- Do not run broad lint/type/build repeatedly during active visual editing unless a failure signal or gate requires it.
- Do not handwave “close enough”; record section-level debt.
- Do not invent visual effects or decorative assets beyond the approved source; when strict detail is needed, load
references/high-fidelity-rules.md. - Functional controls must follow existing project/UI-library patterns first; load
IdeaToTechonly when API/state/permission/cross-platform/verification risk is non-trivial.
Mandatory Reference Loading
For visual D2C work, load these before coding; they are not optional or deferred:
references/high-fidelity-rules.md— exactness, text/icon/shape inventory, asset/layer rules, functional-control escalationreferences/design-extraction-analysis-gate.md— design extraction from screenshots/mockups into section IR, component anatomy, asset roles, token targets, must-not-substitute rules, and pass criteriareferences/full-page-regeneration-guard.md— complete-page token table, text inventory, icon anatomy, asset grouping map, and section-level asset planreferences/section-driven-high-fidelity.md— section-by-section restoration and strict visual repairreferences/executable-visual-ir.md— executable section-level layout/asset/anatomy/token contractsreferences/asset-atlas-generation.md— when multiple related bitmap assets are present or may be neededreferences/functional-component-handoff-guard.md— when controls/forms/tabs/pickers affect behaviorreferences/blueprint-driven-implementation.md— when project blueprint files existreferences/visual-measurements.md— extracting sizes, colors, densityreferences/width-normalization.md— canonical page width, responsive/H5 viewport metrics, and real mobile screenshot evidencereferences/mobile-recomposition.md— when desktop/PC-only sources must become mobilereferences/playwright-section-diff.md— screenshot comparison and Mobile H5 visual audit packreferences/main-skill-full-reference.md— if the compact guide is insufficient
Common Pitfalls
| Pitfall | Fix |
|---|---|
| Implementing from prose only | Build/read Visual IR and source crops |
| Broad route smoke treated as visual pass | Require section screenshots for parity claims |
| Reusing a dashboard template everywhere | Preserve page type and first-screen anatomy |
| Pixel-chasing before coverage | Cover routes first, then L4/L5 selected pages |
| Coding starts before extracting design | Stop; run design extraction and analysis, then write executable IR before implementation |
| IR only names sections | Add executable IR: bbox/height, density, component anatomy, asset role, token targets, pass criteria, and must-not-substitute rules |
| Repeated CSS tuning still feels unlike source | Stop coding; classify mismatch as asset/structure/anatomy/token/verification and enrich references/executable-visual-ir.md fields first |
| Using one generated atlas as many CSS backgrounds | Crop atlas into independent files and reference cropped assets only |
| Hero/banner mixed into thumbnail atlas | Generate hero/CTA as independent assets with final safe areas |
interface:
display_name: "DesignToCode"
short_description: "Convert design images into high-fidelity UnoCSS pages."
default_prompt: "Use $design-to-code to turn segmented design images into a project-matched UnoCSS page after a pre-implementation brief."
Asset Atlas Generation
Use atlas generation only as a sub-strategy of Asset Fulfillment. Atlas is for generation efficiency, not a final UI implementation primitive.
When To Use
Use atlas when:
- 2-8 missing bitmap assets are needed
- assets are the same visual family, role, lighting, and intended crop size
- assets are small or medium content images, card visuals, thumbnails, avatars, or decorative illustrations
- exact output pixel size matters
- one generation can save cost without reducing quality
Do not use atlas for:
- hero main visuals
- CTA/banner backgrounds with text safe areas
- complex product shots needing individual quality control
- people or portraits that need individual quality control
- icons, logo-like marks, certificates, or simple vector graphics
- CSS-reproducible backgrounds
- images with important generated text
- unrelated roles mixed together, e.g. hero + category cards + application scenes
Hard Rule: Crop Before Implementation
An atlas is never the production asset. After generation, crop independent files and reference only those files in code.
Forbidden final implementation patterns:
- using one atlas with CSS
background-positionto fake separate cards - using percentages as crop definitions
- stretching atlas fragments with arbitrary
background-size - hiding wrong aspect ratios behind
object-fitwithout recording accepted deviation
Allowed implementation pattern:
- generate atlas → crop to independent
.webp/.pngfiles → use each file with explicitwidth/heightoraspect-ratio→ section screenshot verifies no stretch/crop pollution
Atlas Plan
Record:
- atlas source path
- atlas generation prompt
- atlas canvas pixel size and ratio
- each crop id
- crop coordinates:
x,y,width,height - safe padding around each block
- final output path
- intended display size
- final pixel size
- intended aspect ratio
- object-fit/object-position strategy
- section and component that consumes the crop
Use pixel coordinates only. Do not use percentages.
Layout Rules
- Keep each crop at 1:1 intended output pixels inside the atlas when possible.
- Add 8-16px safe padding around each crop when possible.
- Do not place unrelated visual styles or roles in one atlas.
- Keep enough spacing to avoid edge pollution between crops.
- Ensure each crop has no text, logo, watermark, UI labels, certificate names, or button copy unless the approved source explicitly uses a photographic sign.
- If a crop needs a text safe area, mark it and verify the crop after generation.
Role Decision Table
| role | atlas? | notes |
|---|---|---|
| category cards | yes | same ratio/family; crop independent files |
| application scenes | yes | same ratio/family; crop independent files |
| factory/process thumbnails | yes | same ratio/family; crop independent files |
| hero main visual | no | generate independently with final safe area |
| CTA/banner background | no | generate independently with overlay/safe area |
| product detail hero | usually no | individual quality matters |
| logos/certificates/text marks | no | render with HTML/SVG/CSS/Iconify |
Commands
npm run crop-atlas -- --manifest path/to/asset-fulfillment-manifest.json
npm run validate-atlas -- --manifest path/to/asset-fulfillment-manifest.jsoncrop-atlas writes independent .webp files from declared pixel coordinates. validate-atlas checks source readability, crop bounds, output existence, and output dimensions.
If project scripts do not exist, use a small local script but keep the same manifest fields and verification outputs.
Asset Compression Rules
Use these rules for bitmap asset governance inside DesignToCode.
Roles
critical content imagedecorative bitmapui/icon-like assetcrop fallback / temporary asset
Rules
critical content image: preferwebp, compress conservatively, exempt explicitly when fidelity loss is visibledecorative bitmap: preferwebp, compress aggressively, replace with CSS when reproducibleui/icon-like asset: prefersvg, use bitmap only when vector is unavailable or inappropriatecrop fallback / temporary asset: mark explicitly, keep easy to replace, do not present as a true original
Validation
- fail on hard size threshold violations without exemption
- warn on soft threshold violations and preferred-format mismatches
- require explicit fallback or exemption reporting in the brief
Asset Fulfillment Pipeline
Use this when required page images are missing or unreliable before implementation.
Goal
补足页面图片资源,但不默认生成图片。先选最轻、最稳的来源,再写代码。
Strategy Order
Use this order for every required visual asset:
1. existing/crop - use provided originals, project assets, or reliable design/reference crops. 2. css/svg - use CSS gradients, effects, textures, simple vector shapes, icons, and logo-like marks when reproducible. 3. single-generation - use one generated image for hero visuals, product scenes, people, complex illustrations, or high-impact content images. 4. atlas-generation - use one atlas image for 2-8 same-family small or medium bitmap assets. 5. formal-fallback - use a polished production-looking fallback when the asset is low risk or generation is not worth the cost.
Do not use placeholder wording such as "image here", "待替换图片", or "这里是图片" in user-facing output.
Asset Fulfillment Plan
Before code, list each required asset:
- asset id
- page/section usage
- media role:
backgroundorcontent image - display size
- required pixel size
- chosen strategy
- source or generation note
- output path
- temporary/final status
- risk or replacement note
Keep this plan inside the Pre-Implementation Brief.
Strategy Rules
- Use
existing/cropwhen the design or source image already contains the visual with enough resolution. - Use
css/svgfor icons, logo-like marks, line art, simple ornaments, gradients, glows, and repeatable textures. - Use
single-generationfor important hero, product, people, editorial, or scene images where quality matters. - Use
atlas-generationonly when multiple bitmap assets share style, scale, and visual family. - Use
formal-fallbackonly when it will not mislead the user or break the layout.
Gate
If a critical asset is missing, do not write page code until one of these is true:
- the asset exists locally
- a crop source and output path are declared
- a CSS/SVG substitute is declared
- a generation plan is confirmed
- a formal fallback is approved
The final implementation must reference independent local asset files or CSS/SVG code, not temporary chat-only images.
Blueprint-driven Implementation
Use this reference when implementation-blueprint.json is present or when converting a prepared design handoff into broad frontend coverage.
Principle
Do not interpret images repeatedly during execution. Implement the approved post-visual blueprint like a frontend engineer who already received a prepared handoff.
A blueprint is valid only when it was refreshed after visual freeze. implementation-blueprint.json must include visual_freeze_ref.status = "approved" and visual_freeze_ref.post_visual_extraction_status = "complete". If this is missing or stale, return to idea-to-design; do not let implementation choose between old text and approved images.
Do not implement one page to high fidelity while the rest of the product is missing. Build like a human frontend engineer: establish the system, cover all routes, fill content, then refine and target fidelity.
Required default read path
1. implementation-blueprint.json 2. Current pass files from implementation-blueprint.json.read_by_pass 3. page-matrix.json for page maturity and sweep order 4. component-blueprint.json for extraction timing 5. debt-ledger.json for accepted fallback and revisit work
Do not load full Design-Spec.md, all page briefs, all visual contracts, or source images unless the current pass needs them.
Passes
Foundation Pass
Implement global system first:
- tokens, CSS variables, UnoCSS shortcuts/presets where appropriate
- app shell, page background, layout container, navigation shell
- foundation components: button, card, tab, list item, form control, status tag, empty/loading/error states
Stop only for framework ambiguity, viewport ambiguity, or a blueprint contradiction that affects the whole system.
Coverage Pass
Sweep horizontally across all pages: 1. create every planned route/page (L0) 2. add approved section order (L1) 3. fill realistic content/mock data (L2) 4. apply global system styling (L3)
Do not stop for minor missing icons, decorative images, wording gaps, or non-core assets. Use fallback, record debt, continue.
Refinement Pass
Normalize after coverage:
- extract repeated components after a pattern appears 2-3 times
- consolidate mock data and content structures
- replace cheap fallbacks that affect perception
- close medium/high debt that blocks
L3
Do not abstract one-off page-local layouts just because they look reusable.
Fidelity Pass
Spend fidelity effort only where it matters:
- core pages
- first screens
- key CTA/card/navigation areas
- user-requested high-fidelity regions
Use screenshots and visual contracts here. Repair only the top 1-3 mismatches first.
Maturity reporting
Report compactly:
Coverage: routes 8/8, skeleton 8/8, content 7/8, system styled 6/8
Core first-screen: 2/3 at L4
Foundation: tokens/app shell/base components ready
Debt: 5 open, 0 blockers
Next: move settings/profile from L2 to L3Never say simply "done" when pages are at different maturity levels.
Asset fallback levels
A: source asset required; stop if unavailable and no approved substitute exists.B: crop/reuse approved source asset.C: CSS/SVG/gradient substitute allowed.D: placeholder allowed; must record debt.
Engineering deviation rule
Allowed without stopping if recorded: small copy length changes, icon substitution, minor spacing/line-height differences, component-library constraints, responsive adaptation.
Not allowed silently: changing page structure, module order, navigation count/labels, dominant card anatomy, major color blocks, or core first-screen hierarchy.
Confidence And Escalation
Use confidence to decide whether to proceed or ask.
Levels
high: evidence clearmedium: likely right, minor uncertainty remainslow: critical uncertainty remains
Critical Inference Types
- framework resolution
- width resolution
- required text recovery
- media-role classification
- key layout relationship
Escalation Rule
lowon critical item -> stop and askmediumon non-critical item -> proceed with note
Good Uses
- flag mixed Vue/Astro repo
- flag uncertain hero image role
- flag width inferred from weak evidence
Bad Uses
- do not over-score every decorative decision
- do not block on minor visual polish uncertainty
Design Extraction & Analysis Gate
Use before visual repair or strict implementation when a design source image/screenshot/mockup exists. This gate prevents "content-similar but visually different" implementations.
Core Rule
Do not code from a visual source until you have extracted and analyzed the design. The extraction result must be detailed enough to constrain implementation decisions: asset class, component anatomy, first-screen density, must-not-substitute rules, and token targets.
A failed or partial visual analysis is not permission to skip the gate. Retry with a better prompt, crop, higher-resolution source, or section crops. If full-page analysis is available, prefer one comprehensive pass; use section crops only when the image is too long, too small, or the model times out.
Why This Improves Fidelity
Strict restoration improves when the agent switches from:
- "recognize sections and tune CSS" to "extract design and implement the extracted contract";
- "module order parity" to "component anatomy parity";
- "visual impression" to "first-screen density + tokens + forbidden substitutions";
- "CSS polish loop" to "asset/structure/anatomy/token diagnosis".
Extraction Prompt Requirements
Ask for one complete executable IR when possible. The prompt must request:
1. page-level first-screen density: exactly what should be visible at the initial mobile viewport; 2. section bbox/height/vertical gaps and horizontal padding; 3. component anatomy: every visible role inside cards, lists, bars, heroes, tabs, buttons; 4. asset role inventory: real photo / generated bitmap / CSS gradient / SVG / icon / HTML text; 5. token table: colors, type scale, weight, radius, shadow, border, padding, gap, fixed bar height; 6. must-not-substitute rules: what cannot be replaced by generic components or gradients; 7. pass criteria and negative checks.
Template:
This is the approved design source. Perform DesignToCode design extraction and analysis.
Output one executable visual IR for a 390px mobile H5 implementation.
Include: first_screen_density; each section bbox/height/gaps; component anatomy; asset role inventory; token measurement table; must-not-substitute; pass criteria; negative checks.
Be specific enough to guide implementation. Do not describe only high-level sections.Full-Page vs Section-Crop Decision
Prefer a single full-page extraction when:
- the source is a complete page screenshot or board crop;
- image resolution is sufficient for text and component details;
- the vision tool can process it without timeout.
Use section crops when:
- full-page extraction times out;
- the page is very long;
- small text/icons are unreadable;
- you need to inspect a critical component anatomy.
When section crops are used, merge them into one page IR before coding. Do not implement from only the first successful crop unless the scope is explicitly limited to that crop.
Minimum Pass Before Coding
Before coding, the extracted IR must answer:
- What exact asset class is used by each visual region? What substitutes are forbidden?
- What roles are inside the component? Are any visible roles missing from planned code?
- What is the intended first-screen density?
- Which values should be compact vs spacious, flat vs raised, photo vs vector/CSS?
- What negative checks would make the implementation fail?
If these answers are missing, the next action is more extraction/analysis, not CSS editing.
Implementation Guidance From IR
During implementation:
1. Preserve source section order and first-screen density first. 2. Recreate component anatomy before polishing tokens. 3. Fulfill or explicitly mark asset debt before claiming parity. 4. Apply token targets: height, radius, padding, type, color, shadow. 5. Capture dev screenshots and compare side-by-side. 6. Repair by mismatch class: asset, structure, anatomy, token, verification.
Common Failure Pattern
| Symptom | Likely missed in extraction | Correct response |
|---|---|---|
| "Looks like a redesign" | asset class + must-not-substitute | re-extract asset roles, replace substitutes |
| "Content is there but unlike source" | component anatomy | enumerate roles and rebuild structure |
| "Too loose / too sparse" | first-screen density + heights | compress to source density before decoration |
| "CSS tweaks do not help" | structure/anatomy mismatch | stop CSS loop, update executable IR |
| "Wrong visual language" | token table + asset class | restore colors, shadows, radius, image kind |
Evidence Standard
A visual repair checkpoint should include:
- extracted IR path or summary;
- implementation screenshot from dev or target runtime;
- side-by-side comparison with design source;
- remaining gaps classified as asset / structure / anatomy / token / verification.
Do not report only "adjusted styles" as the reason for improvement. Report which extracted constraints were applied.
Examples
Use these as regression-style prompts and sanity checks.
1. Marketing Landing Page
- 4-5 sections
- clear hero background
- feature grid
- CTA band
- footer
Checks:
- width inference
- text wrapping
- CTA prominence
2. Dashboard Cards Page
- cards
- stat blocks
- chart-like visuals
- sidebar or header shell
Checks:
- grid regularity
- chart visuals treated correctly
- hierarchy holds under real text
3. Listing/Features Page
- repeated card/list structure
- content images inside cards
Checks:
- repeated structure only lightly abstracted
- content images remain semantic
4. Ambiguous Media Case
- hero visual could be backdrop or semantic product render
Checks:
- stop and ask instead of guessing
5. Width-Inference Failure
- repo gives no clear container width
- user omitted
pageWidth
Checks:
- stop and ask
6. Shared Background Across Sections
- gradient or field spans two adjacent sections
Checks:
- cross-section continuity considered
7. Decorative Text Effect Case
- glow or underline around heading
Checks:
- effect not emitted as fake content image
Executable Visual IR
Use when a visual implementation remains "similar but not restored", the user asks why it is not faithful enough, or the likely cause is under-specified IR.
Design Extraction Gate Dependency
Executable IR is the output of design extraction and analysis. Before filling this file from a visual source, load references/design-extraction-analysis-gate.md and extract first-screen density, component anatomy, asset roles, token targets, must-not-substitute rules, pass criteria, and negative checks. Do not invent these fields from memory when the source image can be analyzed.
Core Rule
If the source is visual but the IR only names page sections, stop coding. Build executable IR first. A page cannot be strictly restored from section names, prose, or generic component labels.
Under-Specified IR Red Flags
- IR says only
hero,card,list,tabbar, orsectionwithout bbox/height/density. - Asset roles are vague:
main visual,thumbnail,illustrationwithout saying real photo vs CSS/SVG vs generated bitmap. - Component anatomy is missing: list cards do not enumerate image/title/description/tags/metrics/button/floater.
- Tokens are missing: color, type size, radius, shadow, padding, gap, line-height, and fixed bar height.
- Verification criteria are missing: no per-section pass/fail checklist or overlay targets.
- Implementation has substituted assets (CSS gradient, letter tile, generic icon) where the design shows real images or detailed UI layers.
Required Executable IR Fields
For each page:
{
"page_id": "cases-list",
"route": "/pages/cases/index",
"viewport": { "width": 390, "height": 844, "dpr": 2 },
"source_refs": ["project-state/design/references/board-02-mall-news-cases.png"],
"source_crop": { "x": 0, "y": 0, "w": 390, "h": 844 },
"first_screen_density": "header + search + chips + featured card + 2.5 list cards + fixed tabbar",
"must_not_substitute": [
"real industry photos must not become CSS gradients or single-letter tiles",
"featured-card metrics floater must not be removed",
"case-card CTA button must not be omitted"
],
"sections": []
}Each section must include:
{
"id": "featured-case",
"bbox": [16, 184, 358, 236],
"shell": "contained card",
"layout": "photo background + dark overlay + copy stack + bottom metrics floater",
"asset_role": {
"kind": "real-photo",
"subject": "new-energy vehicle factory / industrial inspection",
"strategy": "use provided crop or generate independent final-ratio image",
"forbidden_substitutes": ["CSS gradient only", "abstract chart decoration", "letter tile"]
},
"anatomy": [
"badge: 精选案例",
"title",
"description",
"tags row",
"three-column metrics floater"
],
"tokens": {
"height": "source-measured px/rpx",
"radius": "source-measured",
"padding": "source-measured",
"shadow": "source-matched light/medium/heavy",
"title_font": "source-measured",
"body_font": "source-measured"
},
"pass_criteria": [
"same asset class as source",
"same internal layer order",
"same first-screen vertical density",
"no missing visible roles"
]
}Three Inventories Before Coding
1. Asset Role Inventory
| section | source visual | required kind | final file/DOM strategy | forbidden substitute |
|---|---|---|---|---|
| hero | server-room banner | real/generative bitmap | independent image/crop | pure gradient orb |
| case card thumb | hospital photo | real/generative bitmap | independent thumbnail | one-letter tile |
Rules:
- "Need image" is not enough. Say what kind of image and what substitutes are forbidden.
- If the source uses realistic photos, a CSS gradient is a known debt, not parity.
- If assets are missing, either fulfill them before implementation or label the page blocked for strict parity.
2. Component Anatomy Inventory
| component | required visible roles | optional roles | forbidden omissions |
|---|---|---|---|
| case list card | thumbnail, title, desc, tags, metric, CTA | customer name | CTA button, thumbnail |
| purchase bar | favorite icon+label, consult button, buy button | safe-area pad | reducing to two buttons |
Rules:
- A component is not restored if visible roles are missing, even if the section order matches.
- Record role placement: left/right/top/bottom/overlay/floater.
3. Token and Measurement Table
| token | source observation | implementation target | acceptable variance |
|---|---|---|---|
| section height | measured from source | px/rpx value | ±4px for key sections |
| card radius | measured/described | value | close visual class |
| list density | cards visible in first screen | count | no lower by >0.5 card |
| fixed bar height | measured | value | ±4px |
Rules:
- Key sections need measured or explicitly estimated values before coding.
- If exact measurement is not possible, record a source-observed class: compact / medium / spacious, flat / raised, photo / vector / CSS.
Stop/Proceed Decision
Proceed to strict coding only when:
- page-level source crop is known;
- every major section has bbox/height, anatomy, asset role, token targets, and pass criteria;
- all source-visible roles are accounted for;
- all substitutions are either forbidden, fulfilled, or explicitly marked as accepted debt.
Otherwise update IR first. Do not "just tune CSS" when the gap is caused by missing assets, missing anatomy, or missing token measurements.
Repair Loop
1. Compare current screenshot against source. 2. Classify mismatch as one of: asset, structure, anatomy, token, verification. 3. If mismatch is asset/anatomy/structure, update executable IR before code. 4. If mismatch is token only, code a focused CSS repair. 5. Re-capture side-by-side evidence and record pass/fail per section.
Common Mistakes
| Mistake | Fix |
|---|---|
| Treating "IR exists" as sufficient | Check whether it is executable: bbox + anatomy + asset + token + pass criteria |
| Replacing source photos with gradients | Fulfill final-ratio images or mark strict parity blocked |
| Fixing CSS when component roles are missing | Update component anatomy then reimplement structure |
| Only comparing whole-page screenshots | Use section crops and first-screen density counts |
| Saying "close enough" after content matches | Require source-visible roles and asset class match |
Typography Floor Field
Every mobile/phone-width section IR that carries business information must include typography_floor:
{
"typography_floor": {
"viewport": "375/390px",
"unit_convention": "rpx + px",
"conversion": "font_px = rpx * viewport_width / 750",
"primary_body": "26-28rpx ≈ 13-14px @375",
"secondary_label": "24-26rpx ≈ 12-13px @375",
"hard_gate_roles": ["title", "body", "CTA", "form", "price", "spec", "status", "KPI", "navigation", "search", "filter"],
"warning_exceptions": ["decorative kicker", "sparse non-critical metadata", "tiny illustration label"],
"post_implementation_check": "screenshot or DOM sampled font sizes"
}
}If the source design uses 10-12px-equivalent text for critical business content, do not copy it blindly; recompose spacing/layout first and record the source issue/debt.
Icon System Field
Every mobile/phone-width Visual IR for pages with icon-like marks must include icon_system in addition to typography_floor:
{
"icon_system": {
"viewport": "375/390px",
"unit_convention": "rpx + px",
"conversion": "visual_px = rpx * viewport_width / 750",
"tokens": {
"nav_action": "48-56rpx box ≈ 24-28px @375; 26-32rpx glyph ≈ 13-16px",
"quick_entry": "52-64rpx box ≈ 26-32px; 30-36rpx glyph ≈ 15-18px",
"function_card": "52-64rpx box; 28-34rpx glyph",
"list_meta": "28-40rpx box; 20-26rpx glyph",
"hero_illustration": "section-specific, not reused as UI token"
},
"inventory": [
{
"role": "service category icon",
"source_anatomy": "colored rounded tile + centered line icon + centered label",
"implementation": "Iconify class + tile",
"box": "58rpx ≈ 29px @375",
"glyph": "32rpx ≈ 16px @375",
"color": "source-matched",
"compensation": "thin icons +2rpx; filled icons -2rpx",
"must_not_change": ["do not remove tile", "do not left-align if source is centered"]
}
],
"post_implementation_check": "rendered screenshot or DOM computed style sample for box/glyph sizes"
}
}A page is not ready for strict fidelity coding if it has many icons but no icon inventory/token mapping. Do not assume semantic Iconify replacement is visually faithful; semantic fit and visual anatomy are separate checks.
If current implementation uses ad hoc icon sizes per page, mark icon fidelity as WARN/debt and run an Icon Fidelity Pass before claiming L4/L5.Failure Handling
Stop unsafe guessing early. Report clearly.
Must Stop And Ask
- framework unresolved
- page width unresolved
- required text unreadable and not supplied
- critical media role ambiguous
- critical asset missing and crop fallback unusable
- core layout relationship unclear
Pre-Implementation Briefnot confirmed
Ask Templates
Missing Width
State:
- repo width could not be inferred
- exact width is needed for scaled analysis and diff
- ask for
pageWidth
Unreadable Text
State:
- image text is not reliable
- exact text affects wrapping and layout
- ask user to provide real copy
Ambiguous Media Role
State:
- visual could be background or content image
- wrong choice changes DOM semantics and diff outcome
- ask user which role is intended
Unusable Asset Crop
State:
- original asset unavailable
- screenshot crop is not isolated enough
- ask for source asset or permission to approximate
May Continue With Note
- exact font family unknown
- minor decorative effect approximated
- non-critical ornamental asset simplified
Font Fidelity
Use when a design source contains multiple fonts, typography is a visual parity concern, source fonts are unavailable/commercial/unknown-license, or homepage-first work needs a provisional site-wide font system.
Core Principle
Do not blindly load every design-source font as a webfont, and do not collapse all typography to a generic sans-serif. Restore typography by role, licensing, performance budget, and site-wide governance stage.
Font Modes
font-basic: small/non-core pages. Use project/system font stack, record obvious deviations, and do not claim font fidelity.font-fidelity: default for multi-font sources or typography-sensitive websites. Inventory fonts, choose exact/substitute/project-stack/asset/css/deviation decisions, consolidate, self-host, and record manifest.font-strict: homepage, core landing page, brand-heavy page, or explicit typography fidelity. Manifest and screenshot evidence required; over-budget usage needs reason/waiver.font-pipeline: multilingual/large brand/CJK/subsetting/performance-sensitive work. Use subset, preload, budget, fallback metrics, and LCP/CLS checks where needed.
Standard Passes
1. Font Inventory Pass
- record source family, weight, style, role, language, page/section, text sample, priority, asset-vs-text, and repeated use;
- roles: brand/logo, hero/display, heading, body, UI/nav/button/form, numeric/stat/price, decorative, CJK/multilingual;
- if the font name is unknown, describe traits such as serif/sans/slab/geometric/grotesk/humanist/condensed/rounded/handwritten/display, x-height, contrast, width, terminals, number style, and case behavior.
2. Font Decision Pass Use one decision type per source font or role:
exact-self-hosted: authorized/project-owned/open-source exact font, stored in project;substitute-self-hosted: commercial/unavailable/unknown source replaced by close free/open-source font, stored in project;project-stack: existing project/system stack for body/UI/low-priority text;asset-rendered: SVG/image/inline SVG for logo, brand wordmark, or special lettering;css-feature: numeric/minor typography via CSS features such asfont-variant-numeric, weight, spacing, transform, or line-height;deviation: accepted non-restoration with reason.
3. Font Consolidation Pass
- do not turn 5-8 design fonts into 5-8 webfonts;
- keep at most one critical display font unless waived;
- use one main body/UI stack;
- map regular headings to display/body weights where acceptable;
- handle numbers with existing fonts plus numeric CSS first;
- preserve decorative fonts only when critical;
- merge similar/low-priority fonts.
4. Font Implementation Pass
- all production font files must be self-hosted in the project (
src/assets/fonts/,public/fonts/, or project-standard path); - prefer woff2;
- include only required weights/styles;
- define
@font-facewithfont-display: swaporoptional; - preload only justified critical display fonts;
- do not rely on Google Fonts CDN or user-local fonts for production;
- define fallback stacks;
- map to semantic tokens/utilities instead of scattered raw
font-familyvalues.
5. Font Evidence Pass Report font mode, system status, role slots, decision table, file paths/sizes, weights/styles, preload, font-display, fallback, exact/substitute/deviation, budget result, screenshots, open questions, and remaining debt.
Licensing and Substitution Rules
- Commercial source font -> choose a close free/open-source substitute unless the project provides authorization and files.
- Unknown-license source font -> choose a close free/open-source substitute.
- Missing source font file -> choose a close free/open-source substitute.
- Never download from unofficial font mirrors.
- Do not write a commercial font name into CSS as if it is available.
- A local system fallback is not evidence of restoration.
Font Matching Criteria
Choose substitutes with role-weighted scoring:
| Role | Priority | Default Strategy |
|---|---|---|
| brand/logo | brand mood, glyph silhouette, special letters, existing assets | use SVG/image/brand asset first; avoid loading a full font for one word unless justified |
| hero/display | mood, glyph detail, width, weight, spacing, case behavior | allow one self-hosted open-source display font when important |
| heading | hierarchy, mood, compatibility with display/body | reuse display/body family and weight before adding another font |
| body/UI | readability, multilingual harmony, coverage, performance, project consistency | prefer project stack; do not add fonts for small differences |
| numeric/stat/price | tabular/proportional, lining/oldstyle, digit width | use font-variant-numeric: tabular-nums; or existing fonts first |
| CJK/multilingual | CJK coverage, Latin/CJK harmony, punctuation, digits, file size | system/project CJK fallback by default; subset or waiver for specific CJK typeface |
Homepage-first Font Planning
When only homepage or a few pages are designed:
- do not claim final site-wide typography;
- create Font System v0.1;
- define provisional global role slots: brand/logo, display, heading, body, ui, numeric, cjk/multilingual, decorative;
- map homepage fonts to role slots;
- record unknown future page needs as
open_questions; - every role slot needs
status,scope,confidence,source, andfuture_pages_policy.
Role slot statuses:
provisional: inferred from current page; future pages can challenge it;active: currently used;locked: confirmed by user or brand rules;page-specific: only one page/section;deprecated: being replaced;rejected: considered but not used.
Font Governance Gate
When a later page introduces a new font style, answer before adding assets:
- Can it map to an existing role slot?
- Is it merely a near variant of an existing font?
- Can existing font + weight/spacing/line-height reasonably replace it?
- Does it represent a new role?
- Is it a core visual requirement?
- Is it free/open-source/project-authorized?
- Does it require self-hosted files?
- Does it exceed first-screen budget?
- Should it be global or page-specific?
- Does it need subset, lazy loading, or waiver?
Stage behavior:
provisional: later pages may challenge homepage choices, but must pass the gate. New fonts default to page-specific/substitute and do not automatically become global.active: new pages should reuse existing tokens by default. Add fonts only for clear new roles or strong visual requirements.locked: follow the locked system unless the user approves a brand-level typography change. Update manifest version when changed.
Performance Budget
Default first-screen budget:
- <= 2 font families;
- <= 3 font files;
- woff2 preferred;
- only required weights/styles;
- full CJK package requires subset/waiver.
Over budget choices must record reason, alternatives considered, and waiver/debt.
Manifest
Recommended paths:
project-state/implementation/font-manifest.jsonwith PlanToDelivery;src/assets/fonts/font-manifest.jsonfor asset ownership;docs/design-system/font-manifest.jsonfor design-system documentation.
Minimum fields:
schema_version;font_system_version;font_system_status;scope;font_mode;budget;role_slots;decisions;open_questions;evidence.
Decision rows should include source font, role, usage, weight/style, availability, license, chosen font/license, implementation, files, fallback, CSS token, reason, and deviation.
Framework Resolution
Resolve framework from the current project before generating code.
Resolution Order
1. inspect repo files and dependencies 2. prefer explicit framework markers over heuristics 3. if clear Vue project, generate Vue 4. if clear Astro project, generate Astro 5. if mixed or unclear, stop and ask
Common Vue Signals
package.jsondepends onvue,vite,nuxt,@vitejs/plugin-vue.vuepages/components dominate- existing routes/pages are Vue-based
Common Astro Signals
package.jsondepends onastro.astropages/components dominatesrc/pages/*.astroand Astro config present
Mixed/Unclear Cases
Stop and ask when:
- repo contains both Vue and Astro surfaces with no clear target
- repo is empty and user did not specify framework
- mono-repo contains multiple frontends and the target is unclear
Do Not
- silently default to Vue
- silently default to Astro
- emit framework-neutral pseudo markup as final deliverable
Full-page Regeneration Guard
Use before a complete page rewrite from approved mockups. Do not start coding until the brief has the artifacts below.
0. Approved visual source gate
Before full-page regeneration, confirm the target page has an approved/bindable visual source, such as a persisted page mockup, Figma frame, board crop, or equivalent screenshot/design image.
If the page has only prose briefs, route lists, product notes, or a generic board that does not show the target page clearly, do not implement from prose. First generate or obtain a page-level effect image/mockup (for this workflow, GPT Image 2 is the default), persist it under the project design artifacts, and treat that approved image as the visual source for the rest of DesignToCode.
Rules:
- No approved/bindable effect image = no full-page coding, unless the user explicitly waives visual-source generation for that page.
- A page brief can guide prompt content, but it is not a substitute for a visual source.
- When generating a missing effect image, include real product copy, mobile viewport, design-system constraints, and the page's required information order in the prompt.
- Record the generated image path in Visual IR/source refs before implementation.
1. Visual token table
Record source-derived values for the whole page and each major section:
| token | source observation | implementation value | deviation? |
|---|---|---|---|
| page background | |||
| panel/card background | |||
| border visibility/color | |||
| radius | |||
| shadow strength | |||
| horizontal padding | |||
| vertical padding | |||
| section gap | |||
| grid gap | |||
| list row height | |||
| primary content font floor | |||
| secondary/meta font floor |
For component-specific shapes, add rows instead of relying on one global radius:
| section | element | source shape | width/height | radius model | padding | implementation value | deviation? |
|---|---|---|---|---|---|---|---|
| list | priority chip | capsule / rounded-rect / square-ish / circle | |||||
| tabs | active tab pill | ||||||
| card | hero panel |
For complex hero/status cards, add a layer-stack table before coding:
| section | layer | source observation | implementation strategy | DOM/SVG/asset | debt? |
|---|---|---|---|---|---|
| hero/status | base gradient | ||||
| hero/status | ring/chart geometry | ||||
| hero/status | metric columns/separators | ||||
| hero/status | decoration/background media | ||||
| hero/status | inner glow/shadow |
For icon grids/action modules, add cell-alignment rows:
| section | element | icon relation | cell alignment model | icon box | label alignment | implementation value | deviation? |
|---|---|---|---|---|---|---|---|
| module grid | module item | icon above label / left of label / badge | centered icon + centered label / left row | ||||
| quick action | action item |
Rules:
- Do not use generic dashboard defaults without filling this table.
- If exact color cannot be sampled, describe it and choose the closest token deliberately.
- Prefer fixing proportion/spacing before decorative effects.
- Preserve the design hierarchy, but do not copy unreadably small typography for main content. On mobile/H5, primary readable text should generally stay at or above 12px, section/card titles at or above 13-14px, and 10-11px should be reserved for dense metadata, badges, timestamps, or units only when the source and available space require it.
- If increasing tiny source text affects density, compensate with spacing/line-height/layout rather than shrinking important content below readability floors.
- Do not infer small control shapes from page/card radius. Chips, priority labels, tab pills, and badges must keep their own source shape model and dimensions.
- Do not convert centered module/action icon grids into left-aligned flex rows. Record and preserve the alignment model for the whole cell, not only the icon asset.
- Complex hero/status/cockpit cards are not a single background rectangle. Map layers and decide which layers are DOM, SVG, or asset-backed before writing CSS.
2. Text inventory
Every visible string in the source must be mapped before coding.
| section | text | role | approximate position | must keep? |
|---|---|---|---|---|
| header | page-title / badge / tenant / role / status | yes | ||
| hero/card | title / source / value / label | yes | ||
| KPI | title / value / unit / status | yes | ||
| list | label / title / time / link | yes |
Rules:
- A visible label may not be omitted because a value already implies it.
- Do not merge separate roles into one text node if that changes hierarchy.
- Generation is incomplete if title/label/value/unit/status/link placement differs from the source without a recorded deviation.
3. Icon anatomy inventory
Every icon-like mark must be mapped before coding.
| section | source role | Iconify/local class | size | color | container? | alignment | notes |
|---|---|---|---|---|---|---|---|
| header | dropdown | no | inline after role | ||||
| header | refresh | no | inline | ||||
| KPI | primary icon | yes/no from source | left of value / above value / badge / centered | ||||
| grid | module icon | yes/no from source | centered in cell / left row / other | ||||
| action | action icon | yes/no from source | centered in cell / left row / other |
Rules:
- Resolve from Iconify first; search existing project icon sets before drawing.
- Source bare icon = no colored tile/background wrapper.
- Inline dropdown/arrow/refresh icons must use icon classes, not glyph text (
⌄,›,↻) unless the source is typographic. - Record icon color and stroke/fill style; do not infer color only from semantic meaning.
- Record icon-to-text relation and cell alignment. If the source has centered module/action icons, implementation must center both icon and label within the cell unless an accepted deviation is recorded.
4. Section-level regeneration contract
For high-fidelity page rewrites, every major section must have an implementation contract before coding:
| section | bbox/height | shell/background | inner container | grid/layout | media role/aspect | text safe area | screenshot target | pass criteria |
|---|---|---|---|---|---|---|---|---|
| hero | independent hero asset / final ratio | |||||||
| categories | atlas crops / card ratio |
Rules:
- A section name is not enough. Record proportions, media role, and verification target.
- If the current page looks only half-accurate, stretched, or rough, enrich the IR here before more CSS.
- Treat adjacent sections jointly when a background field, decoration, or rhythm crosses their boundary.
- Each section must have a stable
data-sectionanchor for screenshots.
5. Asset role and atlas plan
For generated imagery, record whether each asset is independent, atlas-generated then cropped, CSS/SVG, or HTML text.
| section | visual group | bbox | strategy | include together | exclude | final files |
|---|---|---|---|---|---|---|
| hero | main product visual | independent image | product composition, shadows, safe area | text, logos, buttons | ||
| categories | card thumbnails | atlas -> cropped files | same family category photos | text, logos, UI labels |
Rules:
- Hero/CTA/banner assets are independent files, not atlas cells.
- Repeated card/application/factory images may use an atlas, but the atlas must be cropped into independent files before implementation.
- Final code must not use one atlas with CSS
background-positionas separate UI images. - Images must match final display aspect ratio closely; do not rely on heavy object-fit cropping to hide a wrong source ratio.
- Text, labels, nav, buttons, certificates, logos, and partner names are rendered in HTML/CSS/SVG/Iconify, not baked into AI images.
- Temporary CSS/SVG placeholders must stay low-emphasis and be reported as debt.
- Do not claim parity complete while asset-required groups are pending.
Pre-generation checklist
All must be true before coding a full-page rewrite:
- [ ] Visual token table filled
- [ ] Text inventory filled
- [ ] Icon anatomy inventory filled
- [ ] Section-level regeneration contract filled for each major section
- [ ] Asset role/atlas plan filled; atlas crops have final output paths
- [ ] Must-not-add effects listed
- [ ] Known accepted deviations listed
If any box is empty, update the brief first instead of guessing in code.
Functional Component Handoff Guard
Use before implementing visual elements that are also functional controls.
Trigger controls
If the binding source contains any of these, perform a lightweight IdeaToTech/project-pattern check before coding:
- tabs / segmented controls
- search bars or inputs
- filters, dropdowns, pickers, date/calendar filters
- pagination, batch action bars
- form fields, upload controls, toggles, switches
- list navigation rows with actions
Required technical classification
Record a compact handoff before code:
| visual element | functional role | existing component/pattern | state | interaction | must-not-do |
|---|---|---|---|---|---|
| 待处理/全部申请/已处理 | tabs | wot-design-uni tabs or project tab pattern | active tab | switch list query | do not implement as decorative text row |
| 搜索框 | search input | project search pattern / input | keyword | submit/clear | do not use static placeholder only |
| 状态/优先级/申请类型 | filter triggers | dropdown/picker/action sheet pattern | selected filter | open selector | no wrapping label text |
Rules:
- Prefer existing project patterns and installed UI components before custom views.
- If using a custom view for styling, preserve component semantics: active state, no-wrap labels, disabled/loading states, keyboard/input behavior where applicable, and stable selectors.
- Do not replace a functional component with decorative DOM just because the mockup is visual.
- If the component library is unsuitable or unavailable, record an accepted deviation and implement a semantic fallback.
Visual anatomy for functional controls
For each control, record both:
1. component semantics: state, events, data binding, accessibility/keyboard where relevant 2. visual anatomy: label position, icon position, separator count, active indicator, no-wrap/overflow behavior
Examples:
- Risk summary tile with icon+number: record whether icon is above, left of number, right of number, or badge-like. Do not only record icon name/color.
- Filter pill: record min width,
white-space: nowrap, dropdown icon placement, and overflow strategy (horizontal scroll vs shrinking vs wrapping). - Tabs: record active underline, scroll behavior, active state binding, and list-query relationship.
Handoff to DesignToCode
Before coding, DesignToCode should consume: 1. visual brief / Visual IR 2. this functional classification 3. nearby project pattern or UI library choice
If missing, pause and create/update the handoff instead of guessing component semantics in CSS.
High-Fidelity Mode
Use this when an approved design image must be faithfully turned into code, especially after formal mockups were accepted.
Trigger
Enter high-fidelity mode when any is true:
- user asks for high fidelity, design parity, or close restoration
- implementation is based on approved mockups
- previous implementation drifted from the reference
- an orchestrator provides Level 3 handoff inputs
Required Inputs
Before code generation, require:
- persisted page/section image, not only a multi-screen board
- target viewport and target page width
- pre-implementation brief
- visual anchors and not-accepted deviations
- asset fulfillment plan for important imagery/icons
- verification and repair plan
Input Processing
Preferred structure:
design-to-code-inputs/
manifest.json
pages/<page-id>.png
sections/<page-id>-<section-id>.png
pre-implementation-briefs/<page-id>.mdManifest item shape:
{
"page_id": "workbench",
"source": "assets/mockup-board.png",
"page_crop": "design-to-code-inputs/pages/workbench.png",
"target_viewport": [390, 844],
"source_size": [512, 1024],
"sections": [
{
"id": "hero",
"crop": "design-to-code-inputs/sections/workbench-hero.png",
"bbox": [0, 0, 512, 310],
"role": "background+header"
}
]
}Width Normalization
Do not reason from raw screenshot pixels alone. Record:
- source width
- target width
- scale = target / source
- critical normalized measurements
Minimum measurements:
- section top/height for full-bleed shells
- card top/height/width/margins
- grid column count and gap
- first-screen density target
- fixed footer/safe-area relationship
Two-Pass Build
1. Skeleton pass: section order, DOM anatomy, grid, interaction placeholders. 2. Fidelity pass: proportions, spacing, type, color, radius, shadow, assets, details.
Do not claim visual completion after skeleton only.
Four-Layer Acceptance
Score each checkpoint:
- structure
- proportion
- style
- detail
Guidance:
- structure < 80: fix structure first
- proportion < 75: not a high-fidelity checkpoint
- style < 75: call it structural/balanced, not high fidelity
- detail < 60: record asset/detail debt or continue repair
Mandatory detail gates for common drift:
- Complex hero/status cards: compare layer stack, not only outer card size. Base gradient, chart/ring geometry, metric columns, separators, decoration/media role, and glow/shadow treatment must each be PASS/WARN/FAIL.
- Small labels/chips: compare shape class and dimensions, not only color/text. A capsule, rounded rectangle, square-ish tag, and circular badge are different components.
- Module/action grids: compare icon cell alignment. Centered icon + centered label must not become a left-aligned row unless explicitly accepted.
- Repeated separators and metric columns: count each visible divider and preserve its location before polishing effects.
Mandatory Repair Loop
High-fidelity pages require at least one screenshot repair loop: 1. capture screenshot 2. compare to source crop 3. list top 1-3 mismatches 4. repair biggest mismatch first 5. capture again or record why blocked
Max 3 repair rounds per section unless user asks for more.
Output Requirement
Provide or update a parity report with:
- source image path
- target route/file
- screenshot paths
- scores
- matched points
- fixed mismatches
- remaining differences
- accepted deviations
- design debt
High-Fidelity Rules
Use this reference only when the current slice is in strict-fidelity, regenerate, asset, or repeated visual-repair mode. Do not load it for routine standard-fidelity work unless a specific rule below is needed.
Exactness Rules
- Exactness beats style intuition: implement only effects visible in the binding source. Do not add glow, blur, glass, shadow, gradient intensity, decorations, or micro-effects because they feel consistent with the style. If the source ring has no outer glow, keep it clean; additive effects are visual drift unless recorded as an accepted enhancement.
- Count repeated separators explicitly. Metric groups, segmented controls, tabs, lists, and grids must map every visible divider/separator before coding. Do not collapse two internal separators into one parent divider, and do not move group dividers to the section edge.
- Extract visual tokens before full-page regeneration. For each page/section, record source-derived background color, border visibility/color, radius, shadow strength, horizontal/vertical padding, grid gaps, row heights, section spacing, and readable typography floors for primary content. Do not replace these with generic dashboard defaults unless explicitly accepted as a deviation; however, do not copy source text sizes below platform readability floors for main content just because the mockup uses tiny text.
Mobile Typography Readability Floors
- For mobile H5 / mini-program / phone-width web, fidelity must include usability: do not copy or generate tiny text that falls below readable platform floors just to match density. Treat typography below the floor as a design-source issue or implementation debt, not as a parity target.
- Scope (default): all mobile pages that carry business information. This includes homepage, TabBar pages, lists, details, forms, pricing/spec/KPI/status cards, navigation, search, filters, CTAs, and any page where the user must read, decide, or act. Purely decorative splash/ornamental text may be an exception only if recorded as non-critical.
- Unit convention: write rpx + px together. Before coding mobile pages, convert
rpx/design units to CSS pixels at the target viewport. For uni-app 750-design-width math,font_px = rpx * viewport_width / 750; examples:28rpx ≈ 14px @375,26rpx ≈ 13px @375,24rpx ≈ 12px @375,22rpx ≈ 11px @375,20rpx ≈ 10px @375. - Default mobile floors unless the project explicitly defines stronger tokens:
- primary body / card subtitle / form label: >= 28rpx ≈ 14px @375 preferred, >= 26rpx ≈ 13px @375 minimum;
- secondary label / status chip / metadata: >= 24-26rpx ≈ 12-13px @375, avoid large-area use below 26rpx;
- page/card titles: 30-34rpx+ ≈ 15-17px+ @375; page hero titles usually 40-48rpx+ ≈ 20-24px+ @375;
- functional controls and inputs: text >= 26-28rpx ≈ 13-14px @375, touch target near 44px when feasible.
- Tiered gate: decision-critical business text is a hard gate. Page/section titles, body/description, CTA, form labels/placeholders/errors, prices, specs, quantities, status, KPI labels/values, navigation, search, filters, and operation entries must not render below the floor. Decorative kicker text, sparse non-critical metadata, and tiny labels inside illustrations may be warning-only exceptions, but must be explicitly recorded in the debt/parity report.
- Text below 24rpx ≈ 12px @375 may only be decorative, non-critical, or extremely sparse. It must not carry decision-critical labels, prices, specs, form hints, status, CTA text, or long reading content.
- Implementation artifacts must include
typography_floorin Visual IR or the parity report: target viewport(s), rpx-to-px examples, project overrides, hard-gate violations, warning exceptions, and post-implementation screenshot/DOM sampled font sizes. - When increasing tiny text, rebalance the component instead of merely scaling fonts: adjust line-height, padding, grid columns, card density, label copy length, truncation, progressive disclosure, or horizontal scrolling. Do not solve readability by causing overflow.
Mobile Icon Fidelity Gate
- Mobile high-fidelity work must not treat icons as decorative afterthoughts. Before coding or repairing a mobile page, extract an
icon_systemalongside typography: each icon-like mark needs role, source size, container size, glyph size, color, stroke/fill weight, alignment model, and whether it is a bare icon, icon tile, badge, illustration detail, or functional control. - Unit convention: write rpx + px together. Example for uni-app 750-design-width math:
56rpx box ≈ 28px @375,32rpx glyph ≈ 16px @375. Do not mixfont-size,width/height, and visual glyph size without recording which one is the token. - Establish project/page icon tokens before implementation instead of hand-tuning per selector. Typical mobile tokens should distinguish at least:
- navigation/action icon: box + glyph, e.g.
48-56rpx box ≈ 24-28px @375,26-32rpx glyph ≈ 13-16px @375; - quick-entry/grid icon:
52-64rpx box ≈ 26-32px,30-36rpx glyph ≈ 15-18px; - card/function icon:
52-64rpx box,28-34rpx glyph; - list/meta/status icon:
28-40rpx box,20-26rpx glyph; - hero/illustration icon: section-specific, not shared with UI controls.
- Iconify caveat:
font-sizeis not the same as visual glyph size. Different icon viewBoxes and stroke/fill weights have different perceived sizes. Apply recorded visual compensation (+/-2rpx,transform: scale(...), or separate token) for thin, filled, or padded icons, and verify by rendered screenshot/DOM sampling rather than assuming equalfont-sizeequals equal size. - Preserve source anatomy: if the design shows a bare icon, do not wrap it in a colored tile; if it shows an icon tile, record tile radius/background/shadow and icon-to-text alignment. Do not change centered grid icons into left-row icons or vice versa unless recorded as a deliberate deviation.
- When a user reports “icons do not match the design,” do an Icon Fidelity Pass before more broad layout polish: inventory icon roles, normalize tokens, fix the largest inconsistent icon classes first, and record remaining icon debt.
Text, Icon, And Shape Inventory
- Maintain a text inventory before coding. Every visible text fragment in the binding source must be mapped to a role (
title,label,value,unit,caption,status,link) and an approximate position. Generation is incomplete if a visible label is omitted, merged into another role, or moved to a different hierarchy level. - Maintain an icon anatomy map before coding. For every icon-like mark, record source role, chosen library class, size, color, container/background yes/no, stroke/fill style, and inline alignment. If the source shows a bare icon, do not wrap it in a colored tile. If an inline dropdown/arrow/refresh is visible, use an icon library class instead of text glyphs like
⌄,›, or↻unless the source is explicitly typographic. - Resolve page icons from Iconify first. Search existing project Iconify sets for the closest semantic/visual match before drawing anything. If no suitable installed icon exists, install the smallest appropriate Iconify package/set rather than inventing a custom icon. For simple multicolor icons, recreate a small inline/local SVG only when Iconify cannot match the source.
- Icon anatomy must include icon-to-text/value relation, not only icon identity. For metric tiles and summaries, record whether the icon is above, left of the number, right of the number, badge-like, or centered in a grid cell, and preserve that layout. Grid/action icons must record the alignment model for the whole cell (
centered icon + centered label,left icon + right text, etc.); do not default to left alignment just because the implementation uses flex rows. - Shape tokens must be component-specific, not only global. Status chips, priority labels, tabs, pills, cards, and hero panels each need their own radius/height/padding entry. A page-level radius token is insufficient for small labels; record whether the source chip is capsule, rounded-rect, square-ish, or circular, plus approximate width/height.
- Filter/tab labels must not wrap unless the source explicitly wraps them. Use component sizing, nowrap, horizontal scroll, or overflow strategy before allowing labels to break lines.
Asset And Layer Rules
- Do not hand-draw final substitutes for asset-required GPT Image 2 decorations. If a rich background/3D/resource-pool illustration is not feasible as CSS/SVG with high fidelity, add it to an asset backlog for a later GPT Image 2/image-asset pass with bbox, prompt notes, transparent-background requirement, export size, and layer placement. Treat attached grids, platforms, glow fields, and base shadows that visually belong to that illustration as part of the same asset unless the source clearly separates them as independent UI geometry.
- Temporary CSS/SVG placeholders must be low-emphasis and reported as debt, not parity-complete.
- For complex colorful icons, group them with other generated visual assets in the GPT Image 2/image-asset pass and record prompt notes, bbox, transparent-background requirement, export size, and layer placement.
- Complex hero/status cards require a layer-stack contract before coding. For cockpit/resource/3D/illustration-heavy cards, record base gradient, inner shadows, glows, ring/chart geometry, separators, metric layout, decoration/media role, and which layers are dynamic DOM vs generated/static asset. If a decoration cannot be faithfully reproduced in CSS/SVG, use a low-emphasis placeholder and mark the section WARN/debt instead of presenting it as parity.
Functional Control Rule
Before implementing visual elements that are functional controls, classify them with a project-pattern check first. Tabs, segmented controls, search bars, filters, dropdowns, pickers, date/calendar filters, pagination, form fields, toggles, upload controls, and action list rows must map to existing project patterns or UI-library components when available. Load IdeaToTech only when the control affects API, state, permissions, cross-platform behavior, complex forms, or verification strategy.
Pre-Generation Checklist
Before complete page rewrites, confirm:
- tokens covered
- text inventory covered
- icon anatomy covered
- asset backlog updated
- must-not-add effects listed
If any item is missing, create/update the brief first instead of guessing in code.
Layer Stack Model
Model each section as stacked layers before coding.
Layers
section-shellinner-containerbase-backgrounddecorative-overlaycontent-mediatext-contentfloating-accent
Purpose
This prevents confusion between:
- shell vs inner container
- background vs semantic media
- decoration vs content
- overlay vs independent block
Common Patterns
Section Shell
- shell: full-bleed background, texture, or bleed field
- inner container: centered content width with readable rhythm
- content stack: text, CTA, and semantic media
Hero
- shell base background: gradient/photo/texture
- shell decorative overlay: mask/noise/glow
- inner container content media: product shot or illustration
- inner container text content: heading, copy, CTA
Card Grid
- shell base background: page/card field
- inner container content media: icon or illustration
- inner container text content: card copy
Split Section
- shell can be full-bleed when the background spans the viewport
- inner container can hold one side text and one side content media
- optional floating accent on top
Rule
If missing one layer makes section visually wrong, capture it in brief and verification plan.
DesignToCode
Purpose
Use this skill when the user wants an approved implementation blueprint, visual contract package, screenshots, cropped sections, or Figma-derived context turned into production-style Vue/Astro page code with UnoCSS.
Default to blueprint-driven implementation when implementation-blueprint.json exists. Treat images and page briefs as traceability inputs during Foundation/Coverage, but treat approved mockup images, persisted crops, and Visual IR files as binding visual-anatomy sources during Fidelity Pass, section repair, or any user-reported parity problem. Prefer structured Visual IR over prose whenever both exist.
When technical-decisions.json, feature-recipes.json, or verification-matrix.json exist, treat them as the source of truth for dependencies, services, stores, composables, API seams, mock-to-real transitions, and functional verification.
Standalone Rule
This skill is standalone by default. It accepts approved design inputs from any source, including direct screenshots, Figma context, section images, or equivalent briefs. PlanToDelivery may route work into this skill, but PlanToDelivery is not required.
Ownership boundary: after a visual source is approved and the preparation owner has completed Visual Freeze, Post-Visual Extraction, and an implementation-ready handoff package or equivalent binding inputs, design-to-code owns implementation, visual extraction-for-code, fidelity repair, screenshot-to-source verification, and deviation reporting. Do not route routine implementation back to idea-to-design just to re-explain an approved mockup; only route back when the approved source is missing/stale, the handoff package predates approval, product scope changed, or a design change/new visual source is required.
Default Blueprint-driven Workflow
When implementation-blueprint.json exists and the implementation gate is open or user-waived, use it as the execution source of truth for scope, routes, pass order, and file refs. Do not re-analyze every design image during Foundation/Coverage. During Fidelity Pass, section repair, or any user-reported parity problem, reopen the bound mockup/crop and compare the implementation against Visual IR and image-derived anatomy instead of relying on brief text alone.
Run implementation like a frontend engineer, from broad coverage to detail:
1. blueprint-intake: read implementation-blueprint.json, then current-scope technical files (technical-decisions.json, feature-recipes.json, verification-matrix.json) when present, then only files listed for the current pass. 2. foundation-pass: implement global tokens, app shell, layout containers, navigation shell, and foundation components. 3. coverage-pass: create every route/page, fill approved section order, realistic content/mock data, and visible states across the whole surface. 4. refinement-pass: extract repeated components after patterns appear 2-3 times, normalize content/assets/fallbacks, and close medium debt. 5. fidelity-pass: compare and repair only core pages, first screens, key components, or user-requested high-fidelity regions. 6. handoff: report page maturity, global system status, core first-screen fidelity, verification, and debt.
Target: use roughly 20% of effort to complete 80% of visible coverage, then invest fidelity work where it changes user perception most.
Use trust-first, checkpoint-based verification during implementation. Do not run full lint, full type-check, full build, or broad regression after every small edit. Preserve coding flow during Foundation, Coverage, and Refinement passes; verify at pass completion, core fidelity checkpoints, handoff, merge readiness, or when a high-risk foundation changes.
High-risk foundation changes that justify earlier verification:
- dependency manifests or lockfiles
- build, bundler, lint, test, or TypeScript configuration
- shared types, public APIs, routing foundations, or cross-module contracts
- auth, permissions, payment, security, privacy, data mutation, schema, migration, or persistence code
- broad refactors with cross-module blast radius
Use page maturity levels:
L0 route-ready: route/page exists and is reachable.L1 skeleton-ready: major sections exist in approved order.L2 content-ready: realistic content/mock data fills sections.L3 system-styled: global tokens/components/layout rules applied consistently.L4 core-fidelity: priority first screen or core region matches binding source within accepted deviations.L5 functional-ready: real interactions/API/state for the current implementation scope work.
Input Gate
Before code generation, verify:
- when
implementation-blueprint.jsonexists: blueprint mode isblueprint-driven, routes/pages are listed, current pass is clear, page matrix exists, component blueprint exists, and debt ledger exists - if Visual IR files exist, they are the primary implementation constraint for page type, section order, normalized section bounds, first-screen density, card/list anatomy, action hierarchy, must-not-do rules, and section anchors; prose briefs explain intent but do not override Visual IR
- blueprint must be post-visual:
visual_freeze_ref.status = "approved",visual_freeze_ref.post_visual_extraction_status = "complete", and the blueprint source version matches the approved visual source version when state/contract metadata is available - if the blueprint was generated before visual freeze, lacks
visual_freeze_ref, or conflicts with approved image metadata, stop and route back toidea-to-designfor Post-Visual Extraction refresh; do not reconcile stale text and images insidedesign-to-code - if current-scope technical blueprint files exist, dependency choices, feature recipes, mock-to-real seams, and verification expectations are followed; do not pick competing libraries or state architecture during coding unless the technical plan is blocked or user-waived
- if approved image and blueprint disagree on visual style, component anatomy, or layout proportions, treat the blueprint as stale unless the difference is recorded as an accepted deviation
- if no blueprint exists, approved persisted design source exists
- target framework is resolved
- page or section target is clear
- required assets are available, or an
Asset Fulfillment Planis confirmed - high-fidelity work has page/section crops or equivalent processed inputs
Pre-Implementation Briefexists and is confirmed when confirmation is required- the brief declares visual source mode as
bindingordirectional; default approved UI mockups arebindingunless the user explicitly chose directional-only implementation - binding sources include visual-parity constraints: layout order, major proportions, card anatomy, color blocks, navigation labels/count, first-screen composition, spacing rhythm, and action hierarchy
- binding briefs include a Non-negotiables / Must Not Do list before code generation
- if a visual contract exists, obey its drift budget, reference viewport, project constraints, accepted deviations, and parity waiver fields
If any item is missing, block code generation and ask for the missing artifact or approval. When a critical image asset is missing, do not improvise a messy page. Plan the asset source first: existing/crop, CSS/SVG substitute, single generation, atlas generation, or formal fallback.
Output Gate
Before handoff, provide:
- code changes
- mapped blueprint/design source path
- page maturity matrix summary: routes, skeleton, content, system-styled, core-fidelity, functional-ready
- global foundation status: tokens, shell, base components, layout rules
- section anchors when applicable
- verification evidence or a clear reason verification could not run
- layered parity notes: coverage, system consistency, targeted fidelity
- screenshot-to-source comparison for binding visual sources only where fidelity verification is required
- mismatch, debt, accepted deviation, and repair notes when visual diff was used
When orchestrated, these may be summarized in an implementation handoff manifest.
Verification evidence may be layered by pass. Before final handoff, report which checks were intentionally deferred during active coding, which stage-gate checks were run, and whether any failures are current-scope blockers, baseline debt, environment issues, third-party issues, or deferred work.
For binding sources under fidelity verification, do not accept "required regions exist" as success. The report must compare the implemented priority surface against the approved source on layout order, major proportions, card anatomy, color blocks, navigation labels/count, first-screen visible content, spacing rhythm, and primary/secondary action hierarchy.
For non-core pages or passes before fidelity, success means coverage and system consistency: route exists, approved section order is present, content is realistic or mock-labeled, global tokens/components are used, and any missing asset/detail is recorded in the debt ledger.
If screenshot comparison is explicitly waived by the user, report the waiver and still verify all non-negotiables that can be checked from code and local build output. A screenshot waiver is not permission to change layout, navigation, module order, dominant cards, or major color blocks.
Keep It Light
The main skill should stay short. Use references for the details.
Minimal enhancement set:
- prefer
implementation-blueprint.jsonover repeated image interpretation - implement global design system first: tokens, shell, containers, base components, navigation, page backgrounds
- sweep horizontally across all pages: routes -> skeleton -> content -> system styling -> core fidelity
- extract components after repetition appears; do not let architecture polish block visible coverage
- use page maturity levels and debt ledger instead of binary complete/incomplete claims
- use asset fallback levels: A source required, B crop/reuse allowed, C CSS/SVG/gradient allowed, D placeholder allowed with debt
- use targeted visual anchors for fidelity: headline, main visual, CTA, boundaries, spacing rhythm
- use Visual IR when available to avoid prose-only implementation: page type, section order, section bbox, first-screen density, card/list anatomy, action hierarchy, must-not-do rules, and section anchors
- for approved UI mockups, preserve binding anchors: screen order, dominant card shapes, first-screen composition, navigation labels/count, color blocks, density, and action hierarchy
- write explicit Non-negotiables only for core fidelity surfaces or when no blueprint exists
- use the visual contract drift budget when present; treat layout, module order, and navigation drift as zero-budget unless the contract says otherwise
- use a fixed reference viewport for implementation and verification when provided, such as 390x844 for mobile H5
- judge output with three layers: coverage, system consistency, targeted fidelity
- after diff, repair only the top 1-3 mismatches first
Core loop: 1. inspect the project essentials and locate blueprint/handoff files 2. if implementation-blueprint.json exists, use blueprint-driven workflow and do not regenerate briefs or re-analyze images 3. if no blueprint exists, choose the input mode and fidelity mode, then prepare/verify page or section inputs 4. run Foundation Pass before page detail: tokens, app shell, layout, foundation components 5. run Coverage Pass across all pages/routes to reach the target maturity as broadly as possible 6. run Refinement Pass for component extraction, content normalization, asset fallback cleanup, and debt closure 7. run Fidelity Pass only for core pages, first screens, key components, or explicit high-fidelity targets 8. verify by layer: coverage check, system check, targeted fidelity check 9. update page matrix/debt ledger or report the equivalent state before handoff 10. for high-fidelity targets, run at least one repair loop unless blocked or waived
If the task is mostly about design style, structure, or assets, keep the reasoning in the brief instead of expanding the main skill.
Visual IR and Section Diff Loop
Do not depend on prose precision when structured visual data can be produced. Prefer this chain for binding PNG/mockup workflows:
approved mockup/crop -> Visual IR -> implementation mapping -> code with section anchors -> Playwright section screenshots -> parity report -> targeted repair.
Visual IR is a compact, machine-readable design intermediate representation. Keep v1 small and high-signal; it should prevent the common failures, not describe every pixel. Recommended fields:
page_id,route,viewport,page_type, and visual source refs- ordered
sectionswithname,bboxor normalized bounds, expected anatomy, visible labels/counts, dominant color/card shape, and first-screen density section_anchors: requireddata-sectionnames that implementation must emitmust_not_do: concrete drift rules such as “do not replace list with dashboard” or “do not show empty state for populated mockup”asset_strategy: A source/crop required, B SVG/vector, C CSS/gradient, D icon-library substitute, E optional/deferred
Implementation rules:
- read Visual IR before prose briefs when both exist
- add stable
data-section="..."anchors for each major section in implemented pages/components - if a section from Visual IR cannot be represented, record a visual debt or accepted deviation before claiming parity
- use native screenshots/DOM only to support the diff loop; they do not replace the bound visual source
Verification rules:
- capture full viewport and the 2-5 most important
data-sectionscreenshots for core/fidelity pages - compare section order, normalized top/height/margins, first-screen density, card/list anatomy, color blocks, and action hierarchy
- report PASS/WARN/FAIL per page and per major section
- after a FAIL, repair only the biggest 1-3 mismatches first instead of rewriting the whole page
Binding Section Parity Guard
For binding mockups, brief text is not the visual source of truth. The source hierarchy is: user-approved mockup/crop > page visual contract/section contract > page brief > existing implementation > DOM text/unit/smoke tests. Lower levels cannot justify drift from higher levels.
Before coding or claiming L4 core-fidelity for a high-fidelity page/section, extract or read a section-level contract for each priority region:
- section name and source image/crop path
- exact layout pattern such as 4-row list, 2x4 grid, hero + metrics, bottom action bar
- required counts, labels, row/card order, and visible first-screen content
- dominant card anatomy, color blocks, density, spacing rhythm, icon/image role, and action hierarchy
- allowed approximations and accepted deviations
- forbidden substitutions, especially replacing bespoke mockup anatomy with a generic card/list/dashboard component
Generic component drift guard: reuse existing shell/card/list/button primitives only when they preserve the approved section anatomy. If a generic component changes padding, title treatment, grid density, icon style, row count, dominant color block, or action hierarchy, build the first fidelity pass as a bespoke page-local section. Extract components only after visual parity is accepted and extraction does not change structure or spacing.
Icon and interactive primitive guard: for icon-bearing UI, first inspect the target project's existing icon system and dependencies, such as Iconify/UnoCSS presetIcons, i-mdi-*, i-carbon-*, component-library icons, or local icon assets. Use semantically matched icons from that existing system instead of CSS-drawn pseudo-icons, text glyphs, emoji, Chinese-character placeholders, or improvised shapes. Only create CSS/SVG icons when the project has no usable icon source or the visual contract explicitly requires a custom mark, and record that as an asset fallback.
Do not use native <button> elements for visual cards, KPI tiles, module-grid cells, or dashboard entry cards unless the approved design shows button behavior or the platform requires it. In uni-app/H5, native button defaults can change width, margin, border, padding, line-height, and pseudo-element borders, causing parity drift. Prefer the project's card/link/navigation primitive or a clickable view/router element that preserves the visual anatomy.
UnoCSS/Iconify static-discovery rule: icon utility classes must be statically discoverable by the build. Do not rely on dynamic concatenation like `:class="i-mdi-${name}" unless the full i-mdi-* classes also appear as literals or are safelisted. Prefer storing complete class names such as i-mdi-server-network` in data, or add a safelist, then verify the icon visibly renders in dev.
Evidence rule: text presence, route reachability, unit tests, smoke tests, or DOM audits are functional/coverage evidence, not visual-parity evidence. A parity PASS needs screenshot-to-source or section-by-section mismatch notes against the approved mockup/crop.
User correction trigger: when the user says a page is not like the design, has low fidelity, shows no visible change, or differs greatly from the mockup, stop normal implementation. First verify dev freshness and viewport, reopen the bound mockup/crop, identify the top 1-3 section mismatches, explain the root cause without defending the current code, then repair those mismatches before continuing. Do not use "brief matches", "text exists", or "tests pass" as a rebuttal to visual feedback.
Section-first repair loop: for L4/high-fidelity regions, do not jump directly from crop to Vue/CSS. First write a short implementation mapping for the target section: visual anchor -> DOM structure -> CSS/asset strategy. Repair one section at a time and keep a mismatch note with source observation, current deviation, and repair action. If the user says the same section is still unlike the source, update the mapping before editing more code.
Asset strategy guard: complex GPT Image 2 decorations are not automatically CSS tasks. Before implementing a visually rich section, classify each visual element as: A source/crop asset required, B SVG/local vector, C CSS/gradient feasible, D Iconify/library icon, or E optional/deferred. Use CSS for geometry, rings, glass panels, grids, and light glows; prefer crop/SVG/asset for complex 3D, illustration, device, character, or photorealistic elements. Record visible deviations instead of silently replacing an asset-required element with generic div art.
Multi-page Design Parity Guard
Route coverage is not design parity. Creating a route, showing realistic content, or passing smoke tests does not permit changing the approved page type.
When implementing multiple pages from binding visual sources:
- bind every route to its
page_id, visual source, crop/brief/contract, and expected page type before claiming design compliance - preserve page type at every maturity level: a list mockup remains a list, a detail mockup renders a populated detail state, a form mockup remains a form, and a placeholder mockup remains a placeholder
- do not reuse a workbench/dashboard template to replace list, detail, form, approval, editor, or placeholder anatomy unless an accepted deviation or refreshed visual contract explicitly allows it
- do not use empty, not-found, fallback, or demo-only states as proof that a populated binding mockup was implemented; record them as blocked, debt, or FAIL until the populated state renders
- do not expose debug/version/fallback/demo badges in a visual parity surface unless the approved source or accepted deviation includes them
- if implementation upgrades product state, such as turning a placeholder into an active demo dashboard, stop the fidelity claim and record a design change request, accepted deviation, or route back to
idea-to-designfor a refreshed visual source - checkpoint parity with screenshot-to-source PASS/WARN/FAIL per page; smoke/navigation success only proves reachability, not fidelity
For broad Coverage Pass, pages may be L1/L2 and not pixel-perfect, but their primary anatomy, module order, dominant cards, action hierarchy, and density must still follow the bound source. If a page intentionally uses a common dashboard shell, the visual contract must say so.
Use When
- user provides screenshots, cropped sections, or Figma-derived context
- target output is Vue or Astro page code
- fidelity to the reference matters
- a verification pass is expected
Do Not Use When
- the user only wants inspiration or pseudo-code
- the task is backend/routing/data work
- the framework target is unrelated to the current repo
Input Priority
Prefer stronger input first: 1. Figma node / frame 2. explicit metadata / layer map 3. full-page screenshot 4. ordered section screenshots 5. cropped fragments
If input quality is weak, state the limits clearly and keep assumptions explicit.
Lightweight Workflow
1) Inspect the project
Resolve only the essentials:
- framework: Vue or Astro
- page/container width
- reference viewport for visual parity when supplied
- reusable components/tokens worth keeping, but only if they do not change the approved visual structure
2) Pick an input mode and fidelity mode
If implementation-blueprint.json exists, input mode is blueprint-driven mode and fidelity is controlled by each page's maturity target and verification policy. Do not ask the user to reconfirm the brief unless the blueprint is missing, contradictory, or user-waived.
Fallback input modes when no blueprint exists:
image-only modemetadata-assisted modefigma-direct modefigma-assisted mode
Choose one fidelity mode:
structural: section anatomy onlybalanced: structure + proportion + basic stylehigh-fidelity: structure + proportion + style + key details, with repair loop
Name both modes in the brief.
3) Make a short reuse map
Before code, map the page to existing primitives:
- section -> shell / wrapper / component / token
- mark any bespoke part explicitly
- if several mappings are plausible, note the ambiguity instead of guessing
Do not let existing component libraries override an approved mockup. For strong visual pages, first reproduce the approved layout even if the initial implementation is a single-file or repetitive. Extract reusable components only after visual parity is accepted, and only if the extraction does not change structure, spacing, or hierarchy.
4) Classify media
For each important visual, decide:
backgroundcontent image
Use the media-role reference. If a critical media role is ambiguous, stop and ask.
5) Plan missing assets
If required images are missing, include an Asset Fulfillment Plan in the brief. Use atlas generation only for 2-8 same-family bitmap assets; keep hero, product, people, icon, and CSS-reproducible visuals out of atlas.
6) Emit a concise Pre-Implementation Brief
Use the required brief format. Keep each section short and actionable. No code before the user confirms the brief.
For approved UI mockups, the brief must explicitly state visual_source_mode: binding unless the user explicitly chose directional-only implementation. Binding briefs must list the visual anchors that code must preserve; do not reduce them to generic required regions.
Binding briefs must include:
- Non-negotiables: source layout, navigation count/labels, module order, dominant cards, and major color blocks that must match
- Must Not Do: concrete drift examples such as changing a 2x2 grid into a list, adding an extra tab, or replacing a gradient hero card with white metric tiles
- Drift Budget: default layout/module order/navigation
0%; copy, spacing, and icons may vary only within the recorded budget - Accepted Deviations: route, component, or asset constraints already approved before coding
- Reference Viewport: fixed viewport used for implementation and verification when available
7) Generate code
After confirmation:
- Vue repo -> Vue page/component
- Astro repo -> Astro page/component
Rules:
- UnoCSS first
- global design system first; do not start by polishing a single page when multiple routes are in scope
- create all planned route/page shells before deep detail unless a route is blocked
- use local assets only
- reference final independent asset files, not atlas source images
- use fallback asset levels from the blueprint; record D-level placeholders in debt ledger and continue
- keep scoped CSS minimal unless fidelity requires page-local detail
- use
data-section="..."anchors on major sections - reuse existing tokens/components when they fit and do not alter the approved source structure
- avoid unnecessary abstractions
- allow first-pass repetition for speed; extract reusable components in Refinement Pass after patterns repeat
- for first-pass high-fidelity reproduction, prefer straightforward code over premature component extraction; refactor only after the visual match is accepted
8) Verify and repair
Verify by layer:
- Coverage Check: all planned routes/pages exist, major sections exist in approved order, page matrix maturity is updated.
- System Check: global tokens, shell, base components, layout rhythm, and platform constraints are consistently applied.
- Fidelity Check: run Playwright screenshot comparison only for core pages, first screens, key components, or explicit high-fidelity targets.
Verification timing:
- active editing: default to no command-driven verification unless a concrete failure signal appears
- Foundation/Coverage/Refinement pass completion: run focused checks for touched or impacted routes/components
- Fidelity pass: run targeted screenshot/parity checks only for core pages, first screens, key components, or requested high-fidelity regions
- handoff, merge readiness, or release readiness: run full lint, full type-check, full build, and required regression unless explicitly waived with recorded risk
Treat full lint, full type-check, full build, broad regression, and broad E2E as stage-gate checks. If a stage-gate check fails, classify it before fixing:
- blocker: caused by current scope and prevents the current pass or handoff goal
- baseline: pre-existing or unrelated project debt
- environment: local setup, network, tool, or third-party issue
- third-party: external package, service, or upstream type issue outside the current scope
- deferred: real issue outside the current pass goal
If a fidelity check fails, repair only the biggest mismatch first. Do not rewrite the whole page unless the error is structural. In high-fidelity targets, produce layered parity notes and run at least one repair loop unless blocked or waived. For binding visual sources in Fidelity Pass, verification must include a direct screenshot-to-source comparison unless explicitly waived. If the implementation changes the source layout, navigation count/labels, first-screen composition, dominant card anatomy, or major color blocks without a recorded accepted deviation, stop and repair instead of committing.
When screenshot comparison is waived, explicitly state that waiver and verify from code/build artifacts that Non-negotiables still hold: expected modules exist, forbidden modules/names do not appear, navigation count/labels match the accepted plan, and route/component deviations are recorded.
What to Pay Attention To
- structure and proportions before decoration
- typography and spacing before tiny polish
- section boundaries and shell/container split
- background vs content-image role
- asset provenance and whether a crop fallback is needed
- whether missing assets need fulfillment before code
Stop Conditions
Stop and ask when:
- blueprint is missing or contradictory for required routes/pages
- blueprint lacks approved visual freeze metadata, predates visual approval, or was not refreshed by Post-Visual Extraction
- framework is unclear
- width/reference viewport is unclear and no safe project default exists
- core visual direction conflicts with implementation constraints
- main navigation or core flow cannot be inferred
- critical text for a core first screen is missing
- a key media role is ambiguous for an A-level asset
- an A-level required asset is unavailable and no acceptable fallback is recorded
- the user explicitly requires pixel-level parity for the current surface
- the change affects real data, permissions, payments, deletion, or production safety
- the user has not confirmed the brief when no approved blueprint/gate exists
Do not stop for routine choices: minor icons, small spacing uncertainty, non-core image fallback, normal mock data, copy fill, component extraction timing, or ordinary page order. Use blueprint defaults, record debt, and continue.
References
Load details only when needed:
- references/blueprint-driven-implementation.md
- references/prompt-shape.md
- references/framework-resolution.md
- references/width-normalization.md
- references/visual-measurements.md
- references/high-fidelity-mode.md
- references/media-role-classification.md
- references/asset-fulfillment-pipeline.md
- references/asset-atlas-generation.md
- references/pre-implementation-brief.md
- references/vue-astro-unocss-output-rules.md
- references/playwright-section-diff.md
- references/parity-report.md
- references/failure-handling.md
- references/visual-checklist.md
- references/examples.md
Media Role Classification
Classify each important visual as either background or content image.
Decision Order
1. explicit user note 2. visual + semantic inference 3. stop and ask if critical ambiguity remains
Background Signals
- fills a hero/card/section area
- acts as atmosphere or backdrop
- text/CTA overlays it
- wants cover/crop treatment
- has little standalone meaning
Content Image Signals
- product image, illustration, avatar, logo, chart, gallery asset, article media
- belongs in content flow
- carries meaning on its own
- should behave like semantic media
Output Mapping
background-> CSS background layerscontent image-><img>or<picture>
Ambiguous Cases
Stop and ask when:
- the same visual could be backdrop or content image
- crop hides whether the media sits in flow
- the choice would remove important information
Mobile Recomposition
Use when a page is implemented from a desktop/PC-first design source but mobile output must feel intentionally composed rather than mechanically stacked.
Core Principle
PC high fidelity does not mean mobile mechanical replication. Preserve design intent, brand language, hierarchy, critical content, CTA priority, and trust signals; recompose layout for mobile scroll rhythm and touch usability.
Mobile Modes
responsive-basic: small changes, admin/backoffice, non-core pages. Ensure no overflow and usable controls, but do not claim strong mobile conversion quality.mobile-recomposition: default for desktop-only websites, B2B pages, marketing pages, product pages, and landing sections that need good mobile output.mobile-strict: homepage, core landing page, mobile-heavy page, complex mobile composition, or repeated mobile failure. Requires Mobile IR.mobile-repair: existing implementation is too long, too single-column, overflowing, or mechanically adapted. Fix the largest 1-3 mobile issues first.
Standard Passes
1. Desktop Fidelity Pass
- implement credible desktop layout first;
- inventory visible content and section anchors;
- do not let desktop grid, coordinates, gap, or image ratios automatically define mobile.
2. Mobile Recomposition Pass For each section classify: section type, item count, content density, visual priority, primary action, scroll cost, touch needs, and compression options.
3. Mobile Acceptance Pass Check design intent, critical content, non-mechanical layout, scroll rhythm, readable typography floors, touch usability, no horizontal overflow, and accepted deviations.
Mobile Typography And Density Rules
Mobile recomposition must protect readability, not only responsiveness:
- Establish a
typography_floorbefore implementing or repairing mobile pages. For 750-widthrpxprojects, explicitly convert critical sizes at 375/390px viewport and write rpx + px together, e.g.26rpx ≈ 13px @375,24rpx ≈ 12px @375. - Do not use repeated 19-23rpx labels for meaningful content on phone H5. At common mobile widths they render around 9.5-12px and feel uncomfortable even if technically legible. For business-information pages, this is a hard gate for decision-critical text and a recorded warning for purely decorative/sparse metadata.
- Prefer these default floors when no project token system overrides them: body/card descriptions/forms 26-28rpx ≈ 13-14px @375 minimum; secondary labels/chips 24-26rpx ≈ 12-13px @375; titles 30rpx+ ≈ 15px+ @375; hero/page titles 40rpx+ ≈ 20px+ @375.
- If a mobile layout only works by making text tiny, the layout is over-dense. Fix structure first: reduce columns, shorten labels, group secondary specs, use cards/accordions, or move less important information below the fold.
- When preserving an approved mobile structure such as a KPI strip, compress padding/gaps/icons/decorations before reducing text below the floor. If it still fails, record overflow evidence and ask for a layout change.
Section Strategies
Hero / CTA / Core Selling Point
- preserve headline, primary CTA, core trust signal, and brand mood;
- use text-first mobile layout unless the visual is the main conversion object;
- convert desktop side-by-side composition into stacked, background, cropped, or simplified composition;
- reduce decorative layers that compete with first-screen content;
- keep primary CTA visible early.
Product / Service / Case Cards
- preserve product/service names and decision-making details;
- line-clamp long descriptions;
- reduce secondary tags;
- choose compact single-column cards, horizontal scrollers, featured + carousel, or expansion based on density;
- avoid full desktop card height and spacing on mobile.
Features / Stats / Logos / Trust Grids
- do not default to one-column lists;
- icon + title + short copy: use 2-column compact grid;
- stats/logos/trust markers: use 2-3 columns, logo cloud, chips, or stat clusters;
- 8+ repeated items: group, horizontal scroll, show more, or show selected first 4-6;
- compress padding, shadow, and card height.
Forms / Filters / Navigation / Controls
- prioritize usability over visual replication;
- touch targets should be at least 44px where possible;
- keep labels, errors, and submit action clear;
- convert filters to drawer/bottom sheet when needed;
- ensure sticky/fixed UI does not block content or CTA.
Long Content / FAQ / Specs
- use accordions, grouping, summaries, or progressive disclosure;
- avoid direct desktop tables that overflow;
- preserve critical legal, pricing, limitation, safety, and risk details.
Grid Density Rules
Never mechanically convert desktop repeated grids:
- PC 4x1 -> mobile 1x4
- PC 4x2 -> mobile 1x8
- PC 3x2 -> mobile 1x6
But do not use recomposition as permission to change an approved mobile/mockup structure. If the source itself is a mobile design or explicitly shows a business-critical row/grid (for example a 1×4 KPI strip), preserve that structure first. Solve narrow screens by reducing padding, gap, icon size, typography, label length, or decoration overlap. Only change 1×4 to 2×2/scroll/stack after recording the overflow evidence and getting user/design approval.
Classify item density instead:
| Density | Content | Mobile Strategy |
|---|---|---|
| Ultra-light | icon/number/logo + label | 2-3 columns, chips, mini-cards, logo cloud |
| Light card | icon + title + 1-2 lines | 2-column compact grid; 4 -> 2x2, 6 -> 2x3 |
| Medium card | image/icon + title + 2-3 lines + optional tags | compact one-column, horizontal scroller, or readable 2-column only if it still works |
| Heavy card | large image + long copy + tags/CTAs | featured + carousel, horizontal scroll, expansion, or detail page |
| 8+ repeated entries | many repeated cards/items | group, horizontal scroll, show more, selected first 4-6, or accordion |
Content Compression Rules
Record accepted deviations or mobile notes when content is removed from immediate view.
Must preserve:
- page title, section title, core selling points, primary CTA;
- product/service names and critical conversion details;
- key certification, customer proof, trust indicators, stats;
- legal, compliance, pricing, limitation, safety, and risk details;
- required form fields and errors.
May summarize:
- long descriptions, case summaries, parameter previews, FAQ previews, card body text.
May fold:
- technical specs, long feature lists, large logo/category groups, long FAQ lists, secondary parameters.
May hide or re-express:
- decorative desktop layers, repeated badges, low-priority secondary CTAs, non-essential balance icons, excessive borders/shadows/textures.
Mobile IR Escalation
Create or update Mobile IR when:
- the page is homepage or a core landing page;
- the user says mobile is important;
- mobile-recomposition still feels heavy/mechanical after two repair loops;
- desktop-only source has high mobile business value;
- the page has complex hero, grids, product cards, forms, or interactions.
Minimum Mobile IR:
{
"page_id": "homepage",
"source": "desktop-design-only",
"mobile_mode": "mobile-strict",
"viewports": [375, 390, 414, 768],
"sections": [
{
"name": "hero",
"desktop_source_ref": "section-hero",
"mobile_strategy": "recompose",
"priority": "critical",
"must_preserve": ["headline", "primary CTA", "trust badge", "brand mood"],
"may_summarize": ["subtitle"],
"may_hide": ["decorative background rings"],
"layout": {
"mobile": "text-first, visual-second",
"tablet": "two-column if width allows"
},
"acceptance": [
"primary CTA visible within first screen on 390px",
"no horizontal overflow",
"hero height does not exceed 85vh unless content requires it"
]
}
],
"global_mobile_rules": [
"touch targets >= 44px",
"typography_floor records rpx + px conversions, e.g. body/card text >= 26-28rpx ≈ 13-14px @375; critical labels never below 24rpx ≈ 12px @375",
"no horizontal overflow at 320px",
"avoid mechanical 1-column conversion for repeated grids"
]
}Evidence
When mobile work is in scope, report:
- mobile mode;
- viewports checked, usually 390/414/768 and 320 when risk exists;
typography_floorchecked, including rpx + px conversion, hard-gate violations, warning-only sub-floor exceptions, and screenshot/DOM sampled font sizes;- section result PASS/WARN/FAIL;
- grid decisions;
- accepted deviations;
- remaining mobile debt;
- screenshots or browser evidence.
Parity Report
Create this after a screenshot comparison. Keep it short and actionable.
Template
# <page-id> Parity Report
- source: <design crop path>
- route: <runtime route>
- target file: <code file>
- screenshot: <screenshot path>
- viewport: 390x844
- mode: structural | balanced | high-fidelity
## Scores
| Layer | Score | Notes |
| --- | ---: | --- |
| Structure | 0-100 | |
| Proportion | 0-100 | |
| Style | 0-100 | |
| Detail | 0-100 | |
| Overall | 0-100 | |
## Matched
-
## Top Mismatches
1.
2.
3.
## Repair Log
### Round 1
- fixed:
- remaining:
## Accepted Deviations
-
## Design Debt
- Scoring Intent
Scores are not exact science. They force layered judgment so “structure exists” is not confused with “high fidelity”.
Stop Labels
Use these labels:
structural: structure is present, proportion/style/detail may be poorbalanced: structure and basic style are acceptablehigh-fidelity: structure, proportion, style, and key details have passed at least one repair loop
Playwright Section Diff
Use Playwright for page and section-level screenshot verification.
Anchors
Every major section should have data-section="section-name".
Optional debug aids:
data-media-role="background|content"data-diff-target="true"data-visual-anchor="..."
Capture Set
For high-fidelity mode, capture:
- full viewport screenshot
- section screenshots for the 2-5 most important sections
- screenshots after each repair round when practical
Mobile H5 Visual Audit Pack
For mobile H5/homepage repair, do not rely on one full-page screenshot plus eyeballing. One verification run should produce an audit pack:
1. full viewport screenshot at the real mobile viewport; 2. screenshots for all major data-section anchors visible in or near the first screen; 3. DOM metrics JSON: viewport, document/body scroll width, key section bounding boxes, grid column sizes, fixed/sticky overlays; 4. a prioritized repair list: P0 structure, P1 obvious visual/overflow, P2 polish/debt.
Use one audit pack to collect all obvious issues before editing. Then batch-fix P0/P1 together and run one follow-up audit. Avoid the slow loop of screenshot → fix one padding/font issue → screenshot again.
Priority Rules
| Priority | Meaning | Action |
|---|---|---|
| P0 structure | wrong section order, missing content, approved layout changed, key grid/card anatomy wrong | block handoff; fix first |
| P1 obvious visual | overflow/cropping, severe misalignment, unreadable text, CTA hidden, density far off | fix in same batch as P0 when possible |
| P2 polish/debt | small spacing/color/radius/font mismatch, non-critical decoration variance | record as debt unless strict fidelity is required |
Batch Repair Rule
After an audit pack, change code only after naming the top P0/P1 issues and the likely root layers (container, section, grid, typography, asset, overlay). A good repair pass fixes the largest 1-3 root causes, not isolated pixels.
What to Verify
Layered checks:
Structure
- section order
- DOM regions present
- primary actions visible
Proportion
- section width / alignment
- shell vs inner container split
- normalized top/height/margins
- first-screen density
Style
- typography hierarchy
- spacing rhythm
- color/radius/shadow
- button hierarchy and status colors
Detail
- media-role correctness
- important illustration/icon fidelity
- badge/divider/wave/ornament details
- no distorted images
- complex card layer stack: base, chart/ring, metrics, dividers, decorations, shadows/glows
- chip/label shape class and dimensions, especially priority/status labels
- module/action grid icon alignment: centered cell vs left row, icon-label relation
Tolerated Differences
- tiny font anti-aliasing noise
- small font engine variance
- documented accepted deviations
Not Tolerated
- wrong section width or alignment
- collapsed full-bleed shell
- broken hierarchy
- missing primary CTA
- wrong media role
- treating structural similarity as high fidelity when proportion/style/detail fail
After Failure
1. report failed section and layer 2. name the likely failure category 3. repair the biggest mismatch first 4. do not silently regenerate the whole page 5. update or create a parity report
Pre-Implementation Brief
Emit this before page code. Keep it short, measurable, and actionable. Wait for user confirmation when the workflow requires confirmation.
Required Shape
## Page Understanding
## Fidelity Target
## Source Inputs
## Section Breakdown
## Input Mode
## Visual Anchors
## Reuse Mapping
## Media Role Decisions
## Asset Fulfillment Plan
## Asset Compression Plan
## Normalized Measurements
## Layout Implementation Plan
## Framework/Output Plan
## Accepted Deviations
## Not Accepted Deviations
## Known Ambiguities
## Verification and Repair PlanGuidance
Page Understanding
- page purpose
- main hierarchy
- what must feel closest to the source
Fidelity Target
- mode:
structural,balanced, orhigh-fidelity - target viewport and page width
- minimum score targets when high fidelity is expected
Source Inputs
- persisted source image path
- page crop path
- section crop paths if available
- manifest path
Section Breakdown
- section order
- what each section does
- primary content vs decoration
Input Mode
- chosen mode and confidence limits
- whether metadata/measurements are available
Visual Anchors
- must-preserve structure/proportion/style/detail anchors
- first-screen density target
Reuse Mapping
- section/pattern -> existing component / shell / token
- mark visual reuse as allowed, conditional, or blocked
- note only important ambiguities
Media Role Decisions
- which visuals are
background - which are
content image - fallback assumptions
Asset Fulfillment Plan
- required image/icon assets
- strategy:
existing/crop,css/svg,single-generation,atlas-generation, orformal-fallback - display size and required pixel size
- source path, output path, or generation note
- blocking status: required-before-code / required-before-final / accepted-fallback
Asset Compression Plan
- asset role summary
- preferred output format
- expected size risk
- fallback or exemption status
Normalized Measurements
- source width, target width, scale
- critical bboxes and target measurements
- omit low-value pixel trivia
Layout Implementation Plan
- layout system per section
- shell vs inner container
- shared width/alignment assumptions
- spacing rhythm
Framework/Output Plan
- resolved framework
- output file type/location
- repo conventions to follow
Accepted Deviations
- differences allowed by product/project constraints
Not Accepted Deviations
- differences that must be repaired, not explained away
Known Ambiguities
- unresolved text
- unresolved asset status
- ambiguous media roles
- ambiguous section relationships
Verification and Repair Plan
- screenshots/sections to capture
- layers to score: structure, proportion, style, detail
- top repair priorities
- max repair rounds
Hard Rule
No code generation until this brief exists. In high-fidelity mode, do not claim completion until at least one screenshot repair loop or an explicit blocker/waiver is recorded.
Prompt Shape
Use this input contract.
Required Fields
- page goal
- target project context: existing project or new page
- ordered sections
- for each section:
nameimage pathpurposerequired textinteraction requirementsmust-not-miss points
Optional Fields
pageWidth- style keywords
- acceptable approximations
- media notes
- asset availability notes
Canonical Template
目标:页面用途
全局要求:
- 目标项目:现有项目 / 新页面
- pageWidth:1440
- 风格关键词:...
- 允许近似项:...
区块 1:
- 名称:hero
- 图片:/path/hero.png
- 说明:首屏,左文右图
- 必须出现文案:...
- 交互要求:按钮 hover
- 不能错的点:标题换行、主 CTA 层级
- 媒体说明:背景有渐变纹理;右侧是内容主图
区块 2:
- 名称:features
- 图片:/path/features.png
- 说明:三列卡片
- 必须出现文案:...
- 交互要求:无
- 不能错的点:卡片等宽、图标对齐Minimal Acceptable Input
If input is sparse, still require:
- image order
- section names
- required text
- must-not-miss points
Weak Input That Needs Follow-Up
Examples:
- one uncropped full-page screenshot without section ordering
- missing real text for unreadable design copy
- no project context and no target framework
- no
pageWidthwhen repo cannot reveal width
Repair Loop Policy
Use local repair only after verification failure. Do not make repair mandatory for first pass.
Scope
- repair failed sections only
- avoid whole-page regeneration by default
Max Iterations
- maximum 3 repair rounds per failed section
Repair Priority
1. width/container alignment 2. hierarchy/layout 3. real-text wrapping 4. spacing rhythm 5. media-role correctness 6. decorative detail
Stop Instead Of Looping
Stop when:
- same failure persists after 3 rounds
- failure root cause is blocked by missing source info
- repair would destabilize neighboring confirmed sections
Reporting
After stop, report:
- failed section
- likely root cause
- what was tried
- remaining mismatch
Section Boundary And Cross-Section Rules
Avoid “each section looks fine alone, full page feels wrong”.
What To Check
- section shell spans the intended viewport width
- inner container remains aligned to the canonical page/container width
- shared container width across adjacent sections
- vertical rhythm between sections
- continued background fields across section boundaries
- decorative bleed or overlap between neighboring sections
When To Treat Sections Jointly
- one section shell clearly owns a full-bleed background field
- one gradient/background clearly spans both sections
- one container shell visually wraps multiple sections
- decorative element crosses boundary
- spacing relationship is critical to hero-to-next-section transition
When To Keep Sections Independent
- shell and inner container are self-contained inside one section
- sections sit on clearly separate background bands
- layout shells reset fully between sections
- no shared decorative or structural continuity
Output Impact
Cross-section decisions affect:
- wrapper structure
- padding boundaries
- background layering
- diff diagnosis
Section-Driven High Fidelity
Use when a page technically exists but the user reports it is rough, only half restored, stretched, under-specified, or not close enough to the approved source.
Core Rule
Do not keep polishing a rough full page from vague IR. Stop, enrich the IR, fulfill assets by role, then implement and verify section by section.
Required Artifacts Before Coding
- approved visual source path
- section-level Visual IR with layout ratios and pass criteria
- text inventory for visible labels/values/buttons
- icon anatomy map for each icon-like mark
- asset role classification and atlas/crop manifest
- section screenshot plan with stable
data-sectionanchors
Section IR Fields
Each major section needs:
{
"id": "product-categories",
"order": 3,
"layout": {
"shell": "full-bleed or contained",
"container_width": "1280px",
"height": "observed or target",
"columns": 4,
"gap": 16,
"card_aspect_ratio": "4:3"
},
"media": {
"role": "card-thumbnail",
"strategy": "atlas-crop",
"required_ratio": "4:3",
"final_files": ["hand-tools.webp"],
"forbidden": ["production background-position against atlas"]
},
"text_safe_area": "bottom overlay, 24px padding",
"screenshot_target": "[data-section='product-categories']",
"pass_criteria": ["no image stretch", "all card titles visible", "grid rhythm matches source"]
}Asset Role Rules
- Hero and CTA/banner visuals are independent images with final safe areas.
- Repeated thumbnails/scenes may be generated as atlas, but must be cropped to independent files before implementation.
- Certificates, logos, partner names, buttons, headings, labels, and UI text are HTML/CSS/SVG/Iconify, not baked into images.
- Do not mix unrelated roles in one atlas.
- Do not use a wrong-ratio image and hope
object-fithides it; regenerate or crop correctly.
Section Implementation Loop
For each section:
1. Read section IR and asset manifest. 2. Implement only that section and its shared tokens/components. 3. Capture a section screenshot. 4. Compare against source/IR. 5. Fix the largest 1-3 section gaps. 6. Record remaining debt before moving on.
After all sections pass locally, capture a full-page screenshot for rhythm/boundary checks.
Cross-Section Checks
Check full-page rhythm for:
- container alignment across sections
- vertical gaps and density
- background band continuity
- hero-to-next-section transition
- repeated card heights and media ratios
- no section-specific polish that breaks overall page balance
Maturity Levels
- L0 route-ready
- L1 skeleton
- L2 content-complete
- L3 system-styled
- L4 section-fidelity: major sections match structure and media roles
- L5 page-rhythm fidelity: full page spacing, density, and section boundaries feel right
- L6 asset-correct fidelity: generated/cropped media matches final ratios and no asset debt blocks parity
Red Flags
Stop and enrich IR/assets when:
- user says the page is only half done or rough
- images look stretched, blurry, or cropped wrong
- a single atlas is used directly in production CSS for many cards
- hero/CTA/category/application assets are mixed together
- section screenshots are skipped
- parity is claimed from text smoke tests only
Section Taxonomy
Use taxonomy to stabilize layout reasoning. Do not force a type when evidence is weak.
Common Types
herologo-cloudfeature-gridfeature-splitstatstestimonialpricingfaqcta-bandfooterdashboard-panelcard-listgalleryarticle-list
Typical Cues
hero
- dominant headline
- primary CTA
- large media or backdrop
- may use a full-bleed section shell with a centered inner container
feature-grid
- repeated cards in 2-4 columns
feature-split
- left/right text-media split
- may use a full-bleed shell with inner container alignment when the background spans the viewport
pricing
- repeated plan cards
testimonial
- quote, avatar, social proof
dashboard-panel
- data blocks, charts, shell chrome
- may use a shell/container split when the panel spans the viewport
Use
Taxonomy should influence:
- likely layout system
- likely media role
- likely spacing rhythm
It should not override clear visual evidence.
Visual Checklist
Use this after code generation and screenshot comparison.
Core Fidelity
- full-bleed shells stay full-bleed when intended
- inner content containers stay centered and aligned
- section order correct
- shared container widths consistent
- dominant hierarchy matches design
- spacing rhythm feels consistent
- key alignments hold
Proportion
- target viewport and page width are recorded
- important section tops/heights match normalized measurements closely enough
- overlapping elements overlap by the intended amount
- first-screen density matches the reference intent
- fixed footer/safe-area does not cover required content
Text
- heading wraps plausibly
- button labels fit
- body text does not collide or clip
- real text did not break card heights unexpectedly
Media and Assets
- background vs content-image choices still look correct
- images are not stretched
- visually important assets are fulfilled or explicitly marked as accepted fallback
- decorative layers are not missing where visually critical
- optimized assets preserve acceptable visual fidelity
- new bitmap assets use local project files
Interaction
- explicit buttons/links visible
- focusable controls exist for explicit interactions
- route/API behavior needed by the page still works
Layered Score
Assign rough scores:
- structure
- proportion
- style
- detail
- overall
Do not call an output high-fidelity when only structure passes.
Structural Smoke Checks
- no horizontal overflow
- no catastrophic overlap
- no empty critical section
- no invisible primary CTA
- shell/background field not accidentally boxed in
Mobile Floor
- layout does not explode at narrow width
- text remains readable
- images remain proportionate
{
"version": "1.0",
"tiers": {
"foundation_first": ["AppShell", "PageContainer", "BaseCard", "PrimaryButton", "StatusTag"],
"extract_after_repetition": ["StatsCard", "ListItem", "SectionHeader"],
"page_local_first": ["HomeHero"],
"deferred": ["RareModal"]
},
"rules": [
"first pass may duplicate page-local structures for coverage speed",
"extract repeated patterns after they appear 2-3 times",
"do not let abstraction block visible coverage",
"foundation components should obey tokens before page-specific decoration"
],
"states_required": ["default", "loading", "empty", "error", "disabled"]
}
Related skills
FAQ
Is Design To Code safe to install?
skills.sh reports 3 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.