design.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. """Normalize a bounded subset of Figma's document format into a safe UI tree.
  2. This is a deterministic design adapter, not a pixel-perfect Figma renderer. The
  3. warnings and visible placeholders are part of its contract: unsupported artwork
  4. must remain apparent to someone reviewing the generated page.
  5. """
  6. from __future__ import annotations
  7. import math
  8. import re
  9. from typing import Any
  10. MAX_NODES = 500
  11. MAX_DEPTH = 40
  12. SUPPORTED = {"FRAME", "GROUP", "COMPONENT", "INSTANCE", "COMPONENT_SET", "SECTION", "RECTANGLE", "ELLIPSE", "LINE", "TEXT"}
  13. def _number(value: Any, default: float = 0) -> float:
  14. if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
  15. return default
  16. return float(value)
  17. def _px(value: Any, minimum: float = 0) -> str:
  18. return f"{min(10000, max(minimum, _number(value))):g}px"
  19. def _color(value: Any, opacity: Any = 1) -> str | None:
  20. if not isinstance(value, dict):
  21. return None
  22. channels = [round(max(0, min(1, _number(value.get(c)))) * 255) for c in ("r", "g", "b")]
  23. alpha = max(0, min(1, _number(value.get("a"), 1) * _number(opacity, 1)))
  24. if alpha >= 1:
  25. return "#" + "".join(f"{channel:02x}" for channel in channels)
  26. return f"rgba({channels[0]}, {channels[1]}, {channels[2]}, {alpha:.3f})"
  27. def _children(node: dict) -> list[dict]:
  28. children = node.get("children", [])
  29. if not isinstance(children, list) or any(not isinstance(child, dict) for child in children):
  30. raise ValueError("Figma 节点 children 必须是对象数组")
  31. return children
  32. def _roots(payload: dict) -> list[dict]:
  33. if isinstance(payload.get("document"), dict):
  34. return [payload["document"]]
  35. if "nodes" in payload:
  36. if not isinstance(payload["nodes"], dict):
  37. raise ValueError("Figma nodes 必须是对象映射")
  38. return [entry["document"] for entry in payload["nodes"].values() if isinstance(entry, dict) and isinstance(entry.get("document"), dict)]
  39. if "type" in payload:
  40. return [payload]
  41. raise ValueError("需要 Figma /files 响应、/nodes 响应或单个设计节点")
  42. def _walk(nodes: list[dict], depth: int = 0):
  43. # Selection has a separate search budget because a file can contain many pages.
  44. stack = [(node, depth) for node in reversed(nodes)]
  45. searched = 0
  46. while stack:
  47. node, level = stack.pop()
  48. searched += 1
  49. if searched > 50000 or level > 200:
  50. raise ValueError("Figma 文件过大,请通过 node_id 或 /nodes 导入局部设计")
  51. yield node
  52. stack.extend((child, level + 1) for child in reversed(_children(node)))
  53. def normalize_design(payload: dict, node_id: str | None = None) -> dict:
  54. """Return a normalized, JSON-serializable design or raise ``ValueError``.
  55. The supported tree has at most 500 visible nodes and 40 levels (root level 0).
  56. DOCUMENT/CANVAS wrappers are removed. An explicit node id always wins over
  57. automatic first-frame selection. Figma URL ids such as ``12-34`` are accepted.
  58. """
  59. if not isinstance(payload, dict):
  60. raise ValueError("设计输入必须是 JSON 对象")
  61. warnings: list[str] = []
  62. roots = _roots(payload)
  63. if not roots:
  64. raise ValueError("Figma 响应中没有可用节点,请检查 node_id 和访问权限")
  65. selected: dict | None = None
  66. if node_id:
  67. lookup = str(node_id).replace("-", ":")
  68. selected = next((node for node in _walk(roots) if str(node.get("id")) in {str(node_id), lookup}), None)
  69. if selected is None:
  70. raise ValueError(f"未找到 Figma 节点 {node_id}")
  71. else:
  72. selected = roots[0]
  73. if len(roots) > 1:
  74. warnings.append(f"响应包含 {len(roots)} 个节点,默认仅导入第一个;请指定 node_id 选择其他节点。")
  75. if selected.get("visible") is False:
  76. raise ValueError("选中的设计节点已隐藏")
  77. while selected.get("type") in {"DOCUMENT", "CANVAS"}:
  78. candidates = [node for node in _children(selected) if node.get("visible") is not False]
  79. if not candidates:
  80. raise ValueError("选中的页面没有可见 Frame")
  81. preferred = [node for node in candidates if node.get("type") in {"FRAME", "COMPONENT", "INSTANCE", "CANVAS", "SECTION"}]
  82. if len(candidates) > 1:
  83. warnings.append(f"{selected.get('name', selected.get('type'))} 包含多个页面或 Frame,默认仅导入第一个;请指定 node_id。")
  84. selected = (preferred or candidates)[0]
  85. ids: set[str] = set()
  86. colors: set[str] = set()
  87. fonts: set[str] = set()
  88. stats = {"node_count": 0, "text_count": 0, "placeholder_count": 0, "hidden_count": 0, "max_depth": 0}
  89. def convert(node: dict, parent: dict | None, depth: int) -> dict:
  90. if depth > MAX_DEPTH:
  91. raise ValueError(f"设计层级超过 {MAX_DEPTH},请拆分 Frame")
  92. stats["node_count"] += 1
  93. if stats["node_count"] > MAX_NODES:
  94. raise ValueError(f"设计节点超过 {MAX_NODES},请缩小导入范围")
  95. stats["max_depth"] = max(stats["max_depth"], depth)
  96. ident = str(node.get("id") or f"generated-{stats['node_count']}")
  97. if ident in ids:
  98. raise ValueError(f"重复节点 ID:{ident}")
  99. ids.add(ident)
  100. kind = str(node.get("type", "UNKNOWN"))
  101. result: dict[str, Any] = {"id": ident, "name": str(node.get("name", kind)), "type": kind, "style": {"boxSizing": "border-box", "position": "relative", "minWidth": "0"}, "children": []}
  102. style = result["style"]
  103. box = node.get("absoluteBoundingBox") or node.get("size") or {}
  104. if not isinstance(box, dict):
  105. box = {}
  106. width = _number(box.get("width", box.get("x") if "absoluteBoundingBox" not in node else None))
  107. height = _number(box.get("height", box.get("y") if "absoluteBoundingBox" not in node else None))
  108. mode = node.get("layoutMode")
  109. auto = mode in {"HORIZONTAL", "VERTICAL"}
  110. sizing_x, sizing_y = node.get("layoutSizingHorizontal"), node.get("layoutSizingVertical")
  111. parent_auto = parent is not None and parent.get("layoutMode") in {"HORIZONTAL", "VERTICAL"}
  112. if parent is None:
  113. style.update({"width": "100%", "maxWidth": _px(width) if width else "1200px", "margin": "0 auto"})
  114. if height:
  115. style["minHeight"] = _px(height)
  116. elif parent_auto and (sizing_x == "FILL" or node.get("layoutAlign") == "STRETCH"):
  117. style["alignSelf"] = "stretch"
  118. if parent.get("layoutMode") == "HORIZONTAL":
  119. style.update({"flex": "1 1 0", "minWidth": "0"})
  120. else:
  121. style["width"] = "100%"
  122. elif width and sizing_x != "HUG":
  123. style.update({"width": _px(width), "maxWidth": "100%"})
  124. if parent_auto:
  125. style["flexShrink"] = "0"
  126. if parent is not None and height and sizing_y != "HUG" and kind != "TEXT":
  127. style["height"] = _px(height)
  128. if parent_auto and (_number(node.get("layoutGrow")) > 0 or sizing_y == "FILL" and parent.get("layoutMode") == "VERTICAL"):
  129. style["flexGrow"] = "1"
  130. if parent and (not parent_auto or node.get("layoutPositioning") == "ABSOLUTE"):
  131. parent_box = parent.get("absoluteBoundingBox") or {}
  132. style.update({"position": "absolute", "left": _px(_number(box.get("x")) - _number(parent_box.get("x")), -10000), "top": _px(_number(box.get("y")) - _number(parent_box.get("y")), -10000)})
  133. if auto:
  134. style.update({"display": "flex", "flexDirection": "row" if mode == "HORIZONTAL" else "column", "gap": _px(node.get("itemSpacing")), "paddingTop": _px(node.get("paddingTop")), "paddingRight": _px(node.get("paddingRight")), "paddingBottom": _px(node.get("paddingBottom")), "paddingLeft": _px(node.get("paddingLeft"))})
  135. align = {"MIN": "flex-start", "MAX": "flex-end", "CENTER": "center", "SPACE_BETWEEN": "space-between", "BASELINE": "baseline"}
  136. style["justifyContent"] = align.get(node.get("primaryAxisAlignItems"), "flex-start")
  137. style["alignItems"] = align.get(node.get("counterAxisAlignItems"), "flex-start")
  138. if node.get("layoutWrap") == "WRAP":
  139. style["flexWrap"] = "wrap"
  140. if node.get("counterAxisSpacing") is not None:
  141. style["rowGap"] = _px(node["counterAxisSpacing"])
  142. # Legacy Figma responses only expose sizing mode on auto-layout axes.
  143. if node.get("primaryAxisSizingMode") == "AUTO" and sizing_y is None and mode == "VERTICAL" and parent is not None:
  144. style.pop("height", None)
  145. if node.get("counterAxisSizingMode") == "AUTO" and sizing_y is None and mode == "HORIZONTAL" and parent is not None:
  146. style.pop("height", None)
  147. if kind == "TEXT":
  148. stats["text_count"] += 1
  149. result["text"] = str(node.get("characters", ""))
  150. text_style = node.get("style") if isinstance(node.get("style"), dict) else {}
  151. font = str(text_style.get("fontFamily", "Inter"))
  152. font = re.sub(r"[^\w\s,\-]", "", font, flags=re.UNICODE)[:100] or "Inter"
  153. fonts.add(font)
  154. style.update({"margin": "0", "whiteSpace": "pre-wrap", "overflowWrap": "anywhere", "fontFamily": f'"{font}", "PingFang SC", "Microsoft YaHei", sans-serif', "fontSize": _px(text_style.get("fontSize", 16)), "fontWeight": str(int(max(100, min(900, _number(text_style.get("fontWeight"), 400))))), "lineHeight": _px(text_style["lineHeightPx"]) if text_style.get("lineHeightPx") else "1.5"})
  155. if text_style.get("italic"):
  156. style["fontStyle"] = "italic"
  157. style["textAlign"] = {"LEFT": "left", "CENTER": "center", "RIGHT": "right", "JUSTIFIED": "justify"}.get(text_style.get("textAlignHorizontal"), "left")
  158. if text_style.get("letterSpacing"):
  159. style["letterSpacing"] = _px(text_style["letterSpacing"], -100)
  160. if node.get("characterStyleOverrides") or node.get("styleOverrideTable"):
  161. warnings.append(f"{ident}:富文本混合样式暂使用主文本样式,请人工核对。")
  162. placeholders: list[str] = []
  163. if kind not in SUPPORTED:
  164. placeholders.append(f"{kind} 图形待替换")
  165. fills = [fill for fill in node.get("fills", []) if isinstance(fill, dict) and fill.get("visible") is not False] if isinstance(node.get("fills", []), list) else []
  166. if len(fills) > 1:
  167. warnings.append(f"{ident}:多重填充暂仅保留一个纯色层,其余填充需人工核对。")
  168. for fill in fills:
  169. fill_type = fill.get("type", "SOLID")
  170. if fill_type == "SOLID":
  171. color = _color(fill.get("color"), fill.get("opacity", 1))
  172. if color:
  173. style["color" if kind == "TEXT" else "backgroundColor"] = color
  174. colors.add(color)
  175. elif fill_type == "IMAGE":
  176. placeholders.append("图片资源待接入")
  177. else:
  178. placeholders.append(f"{fill_type} 填充待还原")
  179. strokes = node.get("strokes") or []
  180. if isinstance(strokes, list):
  181. stroke = next((s for s in strokes if isinstance(s, dict) and s.get("visible") is not False), None)
  182. if stroke:
  183. color = _color(stroke.get("color"), stroke.get("opacity", 1))
  184. if stroke.get("type", "SOLID") != "SOLID":
  185. placeholders.append("非纯色描边待还原")
  186. elif color:
  187. style["border"] = f"{_px(node.get('strokeWeight', 1))} solid {color}"
  188. colors.add(color)
  189. if kind == "ELLIPSE":
  190. style["borderRadius"] = "50%"
  191. elif node.get("rectangleCornerRadii"):
  192. radii = node["rectangleCornerRadii"]
  193. if isinstance(radii, list) and len(radii) == 4:
  194. style["borderRadius"] = " ".join(_px(radius) for radius in radii)
  195. elif node.get("cornerRadius") is not None:
  196. style["borderRadius"] = _px(node["cornerRadius"])
  197. shadows = []
  198. for effect in node.get("effects", []) if isinstance(node.get("effects", []), list) else []:
  199. if not isinstance(effect, dict) or effect.get("visible") is False:
  200. continue
  201. if effect.get("type") in {"DROP_SHADOW", "INNER_SHADOW"}:
  202. offset = effect.get("offset") or {}
  203. color = _color(effect.get("color")) or "rgba(0, 0, 0, 0.100)"
  204. shadows.append(f"{'inset ' if effect['type'] == 'INNER_SHADOW' else ''}{_px(offset.get('x'), -10000)} {_px(offset.get('y'), -10000)} {_px(effect.get('radius'))} {_px(effect.get('spread'), -10000)} {color}")
  205. else:
  206. warnings.append(f"{ident}:暂未还原 {effect.get('type', '未知')} 效果。")
  207. if shadows:
  208. style["boxShadow"] = ", ".join(shadows)
  209. if node.get("opacity") is not None:
  210. style["opacity"] = f"{max(0, min(1, _number(node['opacity'], 1))):g}"
  211. if node.get("clipsContent"):
  212. style["overflow"] = "hidden"
  213. if node.get("rotation"):
  214. warnings.append(f"{ident}:旋转节点暂按轴对齐布局呈现。")
  215. if placeholders:
  216. result["placeholder"] = " · ".join(dict.fromkeys(placeholders))
  217. stats["placeholder_count"] += 1
  218. warnings.append(f"{ident}({result['name']}):{result['placeholder']}。")
  219. style.setdefault("minHeight", "56px")
  220. style.setdefault("backgroundColor", "#f1f3f7")
  221. for child in _children(node):
  222. if child.get("visible") is False:
  223. stats["hidden_count"] += 1
  224. else:
  225. result["children"].append(convert(child, node, depth + 1))
  226. if result["children"] and not auto and not height:
  227. warnings.append(f"{ident}:自由布局容器缺少高度,使用最小占位高度,请人工核对。")
  228. style.setdefault("minHeight", "160px")
  229. return result
  230. root = convert(selected, None, 0)
  231. return {"name": str(selected.get("name", payload.get("name", "Figma D2C 页面"))), "root": root, "tokens": {"colors": sorted(colors), "fonts": sorted(fonts)}, "warnings": warnings, "stats": stats}