design-to-react-algorithms

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

dot-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
    .sketch
    file (or equivalent design source) and emits React + CSS
  • 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
    ,
    MSImmutableStyleCorners
    ) into idiomatic CSS
  • 构建可读取
    .sketch
    文件(或等效设计源)并输出React + CSS的转换工具
  • 迭代现有转换工具,且每次优化都可能破坏其他组件
  • 排查转换后的组件“几乎匹配设计但视觉回归测试失败”的原因
  • 为设计转代码流水线设计快照校验/基准策略
  • 当源文件为自由形态几何图形时,选择flexbox、grid还是绝对定位
  • 将Sketch特定原语(
    MSImmutableFlexGroupLayout
    attributedString
    curvePoint
    MSImmutableStyleCorners
    )转换为符合规范的CSS

Rule Categories by Priority

按优先级排序的规则分类

The ordering is the cascade — fix earlier stages first; later-stage fixes are wasted if the upstream tree is wrong.
PriorityCategoryImpactPrefix
1Reverse-Engineering Iteration StrategyCRITICAL
iter-
2Tree Reconstruction & Symbol ResolutionCRITICAL
tree-
3Layout Algorithms (Flex/Freeform Inference)CRITICAL
layout-
4Coordinate & Geometry MathHIGH
geom-
5Visual Regression & Diff AlgorithmsHIGH
diff-
6Style Translation (Color, Gradient, Shadow, Border)MEDIUM-HIGH
style-
7Typography MathMEDIUM
type-
8Path & Shape RenderingMEDIUM
path-
排序遵循连锁效应原则——优先修复早期阶段的问题;若上游树结构错误,后期修复将毫无意义。
优先级分类影响级别前缀
1逆向工程迭代策略关键
iter-
2树结构重建与符号解析关键
tree-
3布局算法(弹性/自由形态推理)关键
layout-
4坐标与几何运算
geom-
5视觉回归与对比算法
diff-
6样式转换(颜色、渐变、阴影、边框)中高
style-
7排版运算
type-
8路径与形状渲染
path-

Quick Reference

快速参考

1. Reverse-Engineering Iteration Strategy (CRITICAL)

1. 逆向工程迭代策略(关键)

  • iter-bisect-from-root
    — Convert top-down, bisect bottom-up to localize regressions in O(log n)
  • iter-baseline-snapshot-gate
    — Every change must pass committed baselines before merge
  • iter-convert-symbols-before-instances
    — Topologically sort symbols → instances; never inline duplicates
  • iter-freeze-design-tokens-first
    — Extract sharedSwatches/layerStyles to CSS variables BEFORE any component
  • iter-one-family-per-pr
    — Scope conversions to one component family per iteration
  • iter-keep-known-good-branch
    — Maintain a baseline branch as a three-way regression triage anchor
  • iter-bisect-from-root
    — 自上而下转换,自下而上二分法定位回归问题,时间复杂度为O(log n)
  • iter-baseline-snapshot-gate
    — 所有变更必须通过已提交的基准测试才能合并
  • iter-convert-symbols-before-instances
    — 按拓扑顺序先转换符号再转换实例;绝不内联重复内容
  • iter-freeze-design-tokens-first
    — 在转换任何组件之前,先提取sharedSwatches/layerStyles为CSS变量
  • iter-one-family-per-pr
    — 每次迭代仅聚焦一个组件家族的转换
  • iter-keep-known-good-branch
    — 维护一个基准分支作为三方回归诊断的锚点

2. Tree Reconstruction & Symbol Resolution (CRITICAL)

2. 树结构重建与符号解析(关键)

  • tree-resolve-overrides-before-emit
    — Apply
    overrideValues
    against master into named props
  • tree-hash-subtrees-for-componentization
    — Structural hashing finds repetition designers missed
  • tree-collapse-passthrough-groups
    — Drop no-style single-child groups; preserve world coords
  • tree-hoist-shared-style-via-subtree-equivalence
    — Subtree equivalence + modifier classes, not per-property dedup
  • tree-clipping-mask-is-stacking-context
    hasClippingMask
    requires
    isolation: isolate
    + clip-path
  • tree-foreign-symbols-become-library-imports
    — Foreign symbols are package imports, not duplicates
  • 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
    需要
    isolation: isolate
    + clip-path
  • tree-foreign-symbols-become-library-imports
    — 外部符号作为包导入,而非重复内容

3. Layout Algorithms (CRITICAL)

3. 布局算法(关键)

  • layout-flex-group-enum-mapping
    — Map
    MSImmutableFlexGroupLayout
    enums 1:1 to CSS flex properties
  • layout-infer-flex-from-axis-projection-overlap
    — 1D separating-axis test for freeform → flex row/column
  • layout-detect-grid-via-2d-coordinate-clustering
    — Cluster edge coordinates with ε to detect CSS Grid
  • layout-promote-freeform-when-equal-gaps
    — Equal gaps within tolerance →
    display: flex; gap: Npx
  • layout-reverse-engineer-padding-not-margin
    — Insets become parent padding; rebase children
  • layout-preserve-wrapping-enabled
    wrappingEnabled
    is the only way the source signals responsive intent
  • layout-ignore-layout-is-absolute-escape
    flexItem.ignoreLayout: true
    position: absolute
    over
    position: relative
    parent
  • layout-flex-group-enum-mapping
    — 将
    MSImmutableFlexGroupLayout
    枚举与CSS flex属性1:1映射
  • layout-infer-flex-from-axis-projection-overlap
    — 通过一维分离轴测试将自由形态转换为flex行/列
  • layout-detect-grid-via-2d-coordinate-clustering
    — 通过ε聚类边缘坐标检测CSS Grid
  • layout-promote-freeform-when-equal-gaps
    — 间隙在公差范围内相等时,使用
    display: flex; gap: Npx
  • layout-reverse-engineer-padding-not-margin
    — 内边距转换为父元素padding;重新定位子元素
  • layout-preserve-wrapping-enabled
    wrappingEnabled
    是源文件表达响应式意图的唯一方式
  • layout-ignore-layout-is-absolute-escape
    flexItem.ignoreLayout: true
    → 在相对定位父元素上使用
    position: absolute

4. Coordinate & Geometry Math (HIGH)

4. 坐标与几何运算(高)

  • geom-compose-parent-transforms-before-emit
    — Compose 2D affine matrices, don't concatenate raw x/y
  • geom-round-only-at-leaves
    — Carry floats through; round once at the CSS boundary
  • geom-rotation-is-css-transform
    — Frame is unrotated AABB; emit
    transform: rotate()
  • geom-shape-group-bounds-via-union
    — Bounds = axis-aligned union of children, rebase to origin
  • geom-clipping-bounds-intersect-not-union
    — Nested clips intersect; never union or replace
  • geom-compose-parent-transforms-before-emit
    — 组合2D仿射矩阵,而非直接拼接原始x/y坐标
  • geom-round-only-at-leaves
    — 全程保留浮点数;仅在CSS边界处进行一次取整
  • geom-rotation-is-css-transform
    — 框架为未旋转的轴对齐包围盒;输出
    transform: rotate()
  • geom-shape-group-bounds-via-union
    — 边界=子元素的轴对齐并集,重新定位到原点
  • geom-clipping-bounds-intersect-not-union
    — 嵌套裁剪取交集;绝不取并集或替换

5. Visual Regression & Diff Algorithms (HIGH)

5. 视觉回归与对比算法(高)

  • diff-use-ssim-for-aa-content
    — SSIM for antialiased content; raw pixel diff false-positives on every retest
  • diff-region-budgeted-tolerances
    — Per-region SSIM floors (text 0.99, gradient 0.95, image 1.0)
  • diff-antialias-aware-pixelmatch-threshold
    — Pixelmatch
    includeAA: false
    for icon defect detection
  • diff-perceptual-hash-for-wrong-component-detection
    — Hamming distance buckets route triage automatically
  • diff-subtree-bisection-to-localize-regression
    — Disable subtrees in binary search to find the offending node
  • diff-baseline-per-component-not-per-page
    — Storybook per-story snapshots; scope = blast radius
  • diff-use-ssim-for-aa-content
    — 对带抗锯齿的内容使用SSIM;原始像素对比在每次重测时都会产生误报
  • diff-region-budgeted-tolerances
    — 按区域设置SSIM阈值(文本0.99,渐变0.95,图片1.0)
  • diff-antialias-aware-pixelmatch-threshold
    — Pixelmatch设置
    includeAA: false
    以检测图标缺陷
  • diff-perceptual-hash-for-wrong-component-detection
    — 汉明距离桶可自动分配诊断任务
  • diff-subtree-bisection-to-localize-regression
    — 通过二分法禁用子树定位问题节点
  • diff-baseline-per-component-not-per-page
    — 使用Storybook按组件快照;范围=影响半径

6. Style Translation (MEDIUM-HIGH)

6. 样式转换(中高)

  • style-srgb-float-to-hex-via-gamma-correct-path
    — Sketch sRGB floats are already gamma-encoded; direct conversion only
  • style-preserve-display-p3
    colorSpace: 1
    → emit
    color(display-p3 …)
    with sRGB fallback
  • style-gradient-angle-via-atan2
    atan2(dx, -dy)
    reframes Sketch vector to CSS gradient angle
  • style-stack-multi-shadow-in-paint-order
    — Reverse shadow array — Sketch paints last-first, CSS first-last
  • style-reconcile-border-position
    — Border position 0/1/2 → frame expansion or
    outline
    for outside
  • style-per-corner-radii-shorthand
    — Per-corner radii map to
    TL TR BR BL
    clockwise (not Sketch's row order)
  • style-srgb-float-to-hex-via-gamma-correct-path
    — Sketch的sRGB浮点数已完成伽马编码;仅需直接转换
  • style-preserve-display-p3
    colorSpace: 1
    → 输出
    color(display-p3 …)
    并提供sRGB降级方案
  • style-gradient-angle-via-atan2
    — 通过
    atan2(dx, -dy)
    将Sketch向量转换为CSS渐变角度
  • style-stack-multi-shadow-in-paint-order
    — 反转阴影数组——Sketch从后往前绘制,CSS从前往后绘制
  • style-reconcile-border-position
    — 边框位置0/1/2 → 扩展框架或使用
    outline
    实现外边框
  • style-per-corner-radii-shorthand
    — 每个角的圆角半径按
    左上 右上 右下 左下
    顺时针映射(而非Sketch的行顺序)

7. Typography Math (MEDIUM)

7. 排版运算(中)

  • type-split-attributed-string-runs-only-when-differ
    — Coalesce identical adjacent attribute runs; single-run case needs no inner span
  • type-pt-lineheight-to-unitless
    lineHeight / fontSize
    → CSS unitless that scales with the font
  • type-kerning-pt-to-em-letter-spacing
    kerning / fontSize
    → em-relative
    letter-spacing
  • type-build-font-fallback-ladder
    — Sketch family → web stack; SF Pro needs
    -apple-system, BlinkMacSystemFont, …
  • type-paragraph-spacing-between-not-after
    — Use
    gap
    on the parent, not
    margin-bottom
    with
    :last-child
  • type-split-attributed-string-runs-only-when-differ
    — 合并相邻的相同属性文本段;单段文本无需内部span
  • type-pt-lineheight-to-unitless
    lineHeight / fontSize
    → 转换为CSS无单位值,随字体大小缩放
  • type-kerning-pt-to-em-letter-spacing
    kerning / fontSize
    → 转换为相对em单位的
    letter-spacing
  • type-build-font-fallback-ladder
    — Sketch字体家族→网页字体栈;SF Pro需要
    -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
    M
    + per-segment
    C
    from
    curveFrom
    /
    curveTo
  • path-rectangle-with-fixed-radius-is-css
    — Detect axis-aligned rounded rects early; emit
    <div>
    not
    <svg>
  • path-apple-smooth-corners-via-superellipse
    — Apple smooth corners are superellipses (n≈5), not circular arcs
  • path-flatten-boolean-ops-at-parse-time
    — Resolve union/subtract via paper.js in Node; ship one flat path
  • path-honor-winding-rule
    windingRule
    0/1 → SVG
    fill-rule
    nonzero/evenodd; explicit, not default
  • path-curve-point-to-svg-cubic-bezier
    — 从
    curveFrom
    /
    curveTo
    生成
    M
    + 每段
    C
    命令
  • path-rectangle-with-fixed-radius-is-css
    — 提前检测轴对齐圆角矩形;输出
    <div>
    而非
    <svg>
  • path-apple-smooth-corners-via-superellipse
    — Apple平滑角是超椭圆(n≈5),而非圆弧
  • path-flatten-boolean-ops-at-parse-time
    — 在Node中通过paper.js解析并合并布尔运算;输出单一扁平化路径
  • path-honor-winding-rule
    windingRule
    0/1 → SVG
    fill-rule
    nonzero/evenodd;需显式声明,而非使用默认值

How to Use

使用方法

  1. Read
    references/_sections.md
    for category definitions and the cascade rationale
  2. Start with the iteration strategy (
    iter-*
    )
    — without the regression gate, every other rule is just techniques
  3. Then tree (
    tree-*
    ) and layout (
    layout-*
    )
    — these are the load-bearing structural decisions
  4. Then geometry (
    geom-*
    ) and diff (
    diff-*
    )
    — these are the precision and validation layers
  5. 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.
  1. 阅读
    references/_sections.md
    了解分类定义和连锁效应原理
  2. 从迭代策略(
    iter-*
    )开始
    ——若无回归校验机制,其他规则都只是技术手段
  3. 接下来处理树结构(
    tree-*
    )和布局(
    layout-*
    ——这些是承载结构的核心决策
  4. 然后是几何运算(
    geom-*
    )和对比(
    diff-*
    ——这些是精度和验证层
  5. 样式、排版和路径是优化层——提升还原度但影响范围多为局部
对于全新的转换工具,请按优先级顺序遵循规则。对于现有工具,先定位回归问题所属的阶段(使用[[diff-subtree-bisection-to-localize-regression]] + [[diff-perceptual-hash-for-wrong-component-detection]]进行诊断),并在负责该问题的最高优先级阶段进行修复。

Reference Files

参考文件

FileDescription
references/_sections.mdCategory definitions, impact levels, cascade rationale
assets/templates/_template.mdTemplate for adding new rules to this skill
metadata.jsonVersion, discipline, references
AGENTS.mdAuto-built TOC (regenerate via
scripts/build-agents-md.js
)
文件描述
references/_sections.md分类定义、影响级别、连锁效应原理
assets/templates/_template.md向本技能添加新规则的模板
metadata.json版本、领域、参考链接
AGENTS.md自动生成的目录(可通过
scripts/build-agents-md.js
重新生成)