design-to-react-algorithms
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinesedot-skills Design-to-React Conversion Best Practices
dot-skills 设计转React转换最佳实践
The reverse-engineering pipeline that converts Sketch files into pixel-perfect React + CSS, with regression-safe iteration as the load-bearing constraint. The skill is organized around the cascade effect of design-to-code conversion: a wrong call in stage N corrupts every output from stage N+1 onward, so categories are ordered by how much downstream they own.
The user's primary requirement — "each improvement doesn't cause regressions" — is enforceable only if the iteration loop, the layer tree, and the layout solver are correct before you start polishing styles. Read the rules in priority order.
本逆向工程流水线可将Sketch文件转换为像素级完美的React + CSS,以支持无回归迭代为核心约束。技能围绕设计转代码转换的连锁效应展开:若第N阶段出现错误,会影响后续所有N+1阶段的输出,因此各分类按其影响下游范围的大小排序。
用户的核心需求——“每次优化都不会引发回归问题”——只有在迭代流程、图层树和布局求解器均正确的前提下才能实现,之后再进行样式打磨。请按优先级顺序遵循规则。
When to Apply
适用场景
- Building a converter that ingests a file (or equivalent design source) and emits React + CSS
.sketch - Iterating on an existing converter where each improvement risks breaking other components
- Diagnosing why a converted component "almost matches" the design but visual-regression fails
- Designing the snapshot-gate / baseline strategy for a design-to-code pipeline
- Choosing between flexbox vs grid vs absolute positioning when the source is freeform geometry
- Translating Sketch-specific primitives (,
MSImmutableFlexGroupLayout,attributedString,curvePoint) into idiomatic CSSMSImmutableStyleCorners
- 构建可读取文件(或等效设计源)并输出React + CSS的转换工具
.sketch - 迭代现有转换工具,且每次优化都可能破坏其他组件
- 排查转换后的组件“几乎匹配设计但视觉回归测试失败”的原因
- 为设计转代码流水线设计快照校验/基准策略
- 当源文件为自由形态几何图形时,选择flexbox、grid还是绝对定位
- 将Sketch特定原语(、
MSImmutableFlexGroupLayout、attributedString、curvePoint)转换为符合规范的CSSMSImmutableStyleCorners
Rule Categories by Priority
按优先级排序的规则分类
The ordering is the cascade — fix earlier stages first; later-stage fixes are wasted if the upstream tree is wrong.
| Priority | Category | Impact | Prefix |
|---|---|---|---|
| 1 | Reverse-Engineering Iteration Strategy | CRITICAL | |
| 2 | Tree Reconstruction & Symbol Resolution | CRITICAL | |
| 3 | Layout Algorithms (Flex/Freeform Inference) | CRITICAL | |
| 4 | Coordinate & Geometry Math | HIGH | |
| 5 | Visual Regression & Diff Algorithms | HIGH | |
| 6 | Style Translation (Color, Gradient, Shadow, Border) | MEDIUM-HIGH | |
| 7 | Typography Math | MEDIUM | |
| 8 | Path & Shape Rendering | MEDIUM | |
排序遵循连锁效应原则——优先修复早期阶段的问题;若上游树结构错误,后期修复将毫无意义。
| 优先级 | 分类 | 影响级别 | 前缀 |
|---|---|---|---|
| 1 | 逆向工程迭代策略 | 关键 | |
| 2 | 树结构重建与符号解析 | 关键 | |
| 3 | 布局算法(弹性/自由形态推理) | 关键 | |
| 4 | 坐标与几何运算 | 高 | |
| 5 | 视觉回归与对比算法 | 高 | |
| 6 | 样式转换(颜色、渐变、阴影、边框) | 中高 | |
| 7 | 排版运算 | 中 | |
| 8 | 路径与形状渲染 | 中 | |
Quick Reference
快速参考
1. Reverse-Engineering Iteration Strategy (CRITICAL)
1. 逆向工程迭代策略(关键)
- — Convert top-down, bisect bottom-up to localize regressions in O(log n)
iter-bisect-from-root - — Every change must pass committed baselines before merge
iter-baseline-snapshot-gate - — Topologically sort symbols → instances; never inline duplicates
iter-convert-symbols-before-instances - — Extract sharedSwatches/layerStyles to CSS variables BEFORE any component
iter-freeze-design-tokens-first - — Scope conversions to one component family per iteration
iter-one-family-per-pr - — Maintain a baseline branch as a three-way regression triage anchor
iter-keep-known-good-branch
- — 自上而下转换,自下而上二分法定位回归问题,时间复杂度为O(log n)
iter-bisect-from-root - — 所有变更必须通过已提交的基准测试才能合并
iter-baseline-snapshot-gate - — 按拓扑顺序先转换符号再转换实例;绝不内联重复内容
iter-convert-symbols-before-instances - — 在转换任何组件之前,先提取sharedSwatches/layerStyles为CSS变量
iter-freeze-design-tokens-first - — 每次迭代仅聚焦一个组件家族的转换
iter-one-family-per-pr - — 维护一个基准分支作为三方回归诊断的锚点
iter-keep-known-good-branch
2. Tree Reconstruction & Symbol Resolution (CRITICAL)
2. 树结构重建与符号解析(关键)
- — Apply
tree-resolve-overrides-before-emitagainst master into named propsoverrideValues - — Structural hashing finds repetition designers missed
tree-hash-subtrees-for-componentization - — Drop no-style single-child groups; preserve world coords
tree-collapse-passthrough-groups - — Subtree equivalence + modifier classes, not per-property dedup
tree-hoist-shared-style-via-subtree-equivalence - —
tree-clipping-mask-is-stacking-contextrequireshasClippingMask+ clip-pathisolation: isolate - — Foreign symbols are package imports, not duplicates
tree-foreign-symbols-become-library-imports
- — 将
tree-resolve-overrides-before-emit应用于主符号并转换为命名属性overrideValues - — 结构哈希可发现设计师遗漏的重复内容
tree-hash-subtrees-for-componentization - — 删除无样式的单孩子组;保留全局坐标
tree-collapse-passthrough-groups - — 通过子树等价性+修饰符类提取共享样式,而非逐属性去重
tree-hoist-shared-style-via-subtree-equivalence - —
tree-clipping-mask-is-stacking-context需要hasClippingMask+ clip-pathisolation: isolate - — 外部符号作为包导入,而非重复内容
tree-foreign-symbols-become-library-imports
3. Layout Algorithms (CRITICAL)
3. 布局算法(关键)
- — Map
layout-flex-group-enum-mappingenums 1:1 to CSS flex propertiesMSImmutableFlexGroupLayout - — 1D separating-axis test for freeform → flex row/column
layout-infer-flex-from-axis-projection-overlap - — Cluster edge coordinates with ε to detect CSS Grid
layout-detect-grid-via-2d-coordinate-clustering - — Equal gaps within tolerance →
layout-promote-freeform-when-equal-gapsdisplay: flex; gap: Npx - — Insets become parent padding; rebase children
layout-reverse-engineer-padding-not-margin - —
layout-preserve-wrapping-enabledis the only way the source signals responsive intentwrappingEnabled - —
layout-ignore-layout-is-absolute-escape→flexItem.ignoreLayout: trueoverposition: absoluteparentposition: relative
- — 将
layout-flex-group-enum-mapping枚举与CSS flex属性1:1映射MSImmutableFlexGroupLayout - — 通过一维分离轴测试将自由形态转换为flex行/列
layout-infer-flex-from-axis-projection-overlap - — 通过ε聚类边缘坐标检测CSS Grid
layout-detect-grid-via-2d-coordinate-clustering - — 间隙在公差范围内相等时,使用
layout-promote-freeform-when-equal-gapsdisplay: flex; gap: Npx - — 内边距转换为父元素padding;重新定位子元素
layout-reverse-engineer-padding-not-margin - —
layout-preserve-wrapping-enabled是源文件表达响应式意图的唯一方式wrappingEnabled - —
layout-ignore-layout-is-absolute-escape→ 在相对定位父元素上使用flexItem.ignoreLayout: trueposition: absolute
4. Coordinate & Geometry Math (HIGH)
4. 坐标与几何运算(高)
- — Compose 2D affine matrices, don't concatenate raw x/y
geom-compose-parent-transforms-before-emit - — Carry floats through; round once at the CSS boundary
geom-round-only-at-leaves - — Frame is unrotated AABB; emit
geom-rotation-is-css-transformtransform: rotate() - — Bounds = axis-aligned union of children, rebase to origin
geom-shape-group-bounds-via-union - — Nested clips intersect; never union or replace
geom-clipping-bounds-intersect-not-union
- — 组合2D仿射矩阵,而非直接拼接原始x/y坐标
geom-compose-parent-transforms-before-emit - — 全程保留浮点数;仅在CSS边界处进行一次取整
geom-round-only-at-leaves - — 框架为未旋转的轴对齐包围盒;输出
geom-rotation-is-css-transformtransform: rotate() - — 边界=子元素的轴对齐并集,重新定位到原点
geom-shape-group-bounds-via-union - — 嵌套裁剪取交集;绝不取并集或替换
geom-clipping-bounds-intersect-not-union
5. Visual Regression & Diff Algorithms (HIGH)
5. 视觉回归与对比算法(高)
- — SSIM for antialiased content; raw pixel diff false-positives on every retest
diff-use-ssim-for-aa-content - — Per-region SSIM floors (text 0.99, gradient 0.95, image 1.0)
diff-region-budgeted-tolerances - — Pixelmatch
diff-antialias-aware-pixelmatch-thresholdfor icon defect detectionincludeAA: false - — Hamming distance buckets route triage automatically
diff-perceptual-hash-for-wrong-component-detection - — Disable subtrees in binary search to find the offending node
diff-subtree-bisection-to-localize-regression - — Storybook per-story snapshots; scope = blast radius
diff-baseline-per-component-not-per-page
- — 对带抗锯齿的内容使用SSIM;原始像素对比在每次重测时都会产生误报
diff-use-ssim-for-aa-content - — 按区域设置SSIM阈值(文本0.99,渐变0.95,图片1.0)
diff-region-budgeted-tolerances - — Pixelmatch设置
diff-antialias-aware-pixelmatch-threshold以检测图标缺陷includeAA: false - — 汉明距离桶可自动分配诊断任务
diff-perceptual-hash-for-wrong-component-detection - — 通过二分法禁用子树定位问题节点
diff-subtree-bisection-to-localize-regression - — 使用Storybook按组件快照;范围=影响半径
diff-baseline-per-component-not-per-page
6. Style Translation (MEDIUM-HIGH)
6. 样式转换(中高)
- — Sketch sRGB floats are already gamma-encoded; direct conversion only
style-srgb-float-to-hex-via-gamma-correct-path - —
style-preserve-display-p3→ emitcolorSpace: 1with sRGB fallbackcolor(display-p3 …) - —
style-gradient-angle-via-atan2reframes Sketch vector to CSS gradient angleatan2(dx, -dy) - — Reverse shadow array — Sketch paints last-first, CSS first-last
style-stack-multi-shadow-in-paint-order - — Border position 0/1/2 → frame expansion or
style-reconcile-border-positionfor outsideoutline - — Per-corner radii map to
style-per-corner-radii-shorthandclockwise (not Sketch's row order)TL TR BR BL
- — Sketch的sRGB浮点数已完成伽马编码;仅需直接转换
style-srgb-float-to-hex-via-gamma-correct-path - —
style-preserve-display-p3→ 输出colorSpace: 1并提供sRGB降级方案color(display-p3 …) - — 通过
style-gradient-angle-via-atan2将Sketch向量转换为CSS渐变角度atan2(dx, -dy) - — 反转阴影数组——Sketch从后往前绘制,CSS从前往后绘制
style-stack-multi-shadow-in-paint-order - — 边框位置0/1/2 → 扩展框架或使用
style-reconcile-border-position实现外边框outline - — 每个角的圆角半径按
style-per-corner-radii-shorthand顺时针映射(而非Sketch的行顺序)左上 右上 右下 左下
7. Typography Math (MEDIUM)
7. 排版运算(中)
- — Coalesce identical adjacent attribute runs; single-run case needs no inner span
type-split-attributed-string-runs-only-when-differ - —
type-pt-lineheight-to-unitless→ CSS unitless that scales with the fontlineHeight / fontSize - —
type-kerning-pt-to-em-letter-spacing→ em-relativekerning / fontSizeletter-spacing - — Sketch family → web stack; SF Pro needs
type-build-font-fallback-ladder-apple-system, BlinkMacSystemFont, … - — Use
type-paragraph-spacing-between-not-afteron the parent, notgapwithmargin-bottom:last-child
- — 合并相邻的相同属性文本段;单段文本无需内部span
type-split-attributed-string-runs-only-when-differ - —
type-pt-lineheight-to-unitless→ 转换为CSS无单位值,随字体大小缩放lineHeight / fontSize - —
type-kerning-pt-to-em-letter-spacing→ 转换为相对em单位的kerning / fontSizeletter-spacing - — Sketch字体家族→网页字体栈;SF Pro需要
type-build-font-fallback-ladder-apple-system, BlinkMacSystemFont, … - — 在父元素上使用
type-paragraph-spacing-between-not-after,而非给gap加margin-bottom清除:last-child
8. Path & Shape Rendering (MEDIUM)
8. 路径与形状渲染(中)
- —
path-curve-point-to-svg-cubic-bezier+ per-segmentMfromC/curveFromcurveTo - — Detect axis-aligned rounded rects early; emit
path-rectangle-with-fixed-radius-is-cssnot<div><svg> - — Apple smooth corners are superellipses (n≈5), not circular arcs
path-apple-smooth-corners-via-superellipse - — Resolve union/subtract via paper.js in Node; ship one flat path
path-flatten-boolean-ops-at-parse-time - —
path-honor-winding-rule0/1 → SVGwindingRulenonzero/evenodd; explicit, not defaultfill-rule
- — 从
path-curve-point-to-svg-cubic-bezier/curveFrom生成curveTo+ 每段M命令C - — 提前检测轴对齐圆角矩形;输出
path-rectangle-with-fixed-radius-is-css而非<div><svg> - — Apple平滑角是超椭圆(n≈5),而非圆弧
path-apple-smooth-corners-via-superellipse - — 在Node中通过paper.js解析并合并布尔运算;输出单一扁平化路径
path-flatten-boolean-ops-at-parse-time - —
path-honor-winding-rule0/1 → SVGwindingRulenonzero/evenodd;需显式声明,而非使用默认值fill-rule
How to Use
使用方法
- Read for category definitions and the cascade rationale
references/_sections.md - Start with the iteration strategy () — without the regression gate, every other rule is just techniques
iter-* - Then tree () and layout (
tree-*) — these are the load-bearing structural decisionslayout-* - Then geometry () and diff (
geom-*) — these are the precision and validation layersdiff-* - Style, type, and path are the polish layer — high fidelity but mostly local impact
For a brand-new converter, follow the rules in priority order. For an existing converter, identify which stage owns the regression you're seeing (use [[diff-subtree-bisection-to-localize-regression]] + [[diff-perceptual-hash-for-wrong-component-detection]] to triage) and fix at the highest stage that owns it.
- 阅读了解分类定义和连锁效应原理
references/_sections.md - 从迭代策略()开始——若无回归校验机制,其他规则都只是技术手段
iter-* - 接下来处理树结构()和布局(
tree-*)——这些是承载结构的核心决策layout-* - 然后是几何运算()和对比(
geom-*)——这些是精度和验证层diff-* - 样式、排版和路径是优化层——提升还原度但影响范围多为局部
对于全新的转换工具,请按优先级顺序遵循规则。对于现有工具,先定位回归问题所属的阶段(使用[[diff-subtree-bisection-to-localize-regression]] + [[diff-perceptual-hash-for-wrong-component-detection]]进行诊断),并在负责该问题的最高优先级阶段进行修复。
Reference Files
参考文件
| File | Description |
|---|---|
| references/_sections.md | Category definitions, impact levels, cascade rationale |
| assets/templates/_template.md | Template for adding new rules to this skill |
| metadata.json | Version, discipline, references |
| AGENTS.md | Auto-built TOC (regenerate via |
| 文件 | 描述 |
|---|---|
| references/_sections.md | 分类定义、影响级别、连锁效应原理 |
| assets/templates/_template.md | 向本技能添加新规则的模板 |
| metadata.json | 版本、领域、参考链接 |
| AGENTS.md | 自动生成的目录(可通过 |