1+ import os
2+ import requests
3+ import json
4+ from dotenv import load_dotenv
5+
6+ load_dotenv () # Load environment variables from .env
7+
8+ # 配置参数
9+ FIGMA_TOKEN = os .getenv ("FIGMA_TOKEN" ) # 从环境变量读取Token,避免硬编码
10+ FILE_ID = "ZuZWPWcPLSqaX8d1p9uTpX" # 替换为你的Figma文件ID
11+ NODE_IDS = "3-1377" # 替换为你的按钮组件节点ID(多个用逗号分隔)
12+
13+ def fetch_figma_data ():
14+ """调用Figma API获取节点数据"""
15+ url = f"https://api.figma.com/v1/files/{ FILE_ID } /nodes?ids={ NODE_IDS } "
16+ headers = {"X-Figma-Token" : FIGMA_TOKEN }
17+
18+ response = requests .get (url , headers = headers )
19+ response .raise_for_status () # 如果HTTP请求失败则抛出异常
20+
21+ return response .json ()
22+
23+ def parse_button_data (raw_data ):
24+ """解析Figma数据,提取按钮颜色和尺寸"""
25+ buttons = []
26+
27+ for node_id , node_info in raw_data ["nodes" ].items ():
28+ doc = node_info ["document" ]
29+ name_parts = doc ["name" ].split ("/" ) # 假设组件命名为 "Button/Primary"
30+
31+ # 提取颜色(取第一个填充色)
32+ fills = doc .get ("fills" , [{}])[0 ].get ("color" , {})
33+ color = {
34+ "r" : fills .get ("r" , 0 ),
35+ "g" : fills .get ("g" , 0 ),
36+ "b" : fills .get ("b" , 0 ),
37+ "a" : fills .get ("a" , 1 )
38+ }
39+
40+ # 提取尺寸
41+ bbox = doc .get ("absoluteBoundingBox" , {})
42+ width = bbox .get ("width" , 100 ) # 默认值100px
43+ height = bbox .get ("height" , 40 ) # 默认值40px
44+
45+ buttons .append ({
46+ "component" : name_parts [0 ],
47+ "variant" : name_parts [1 ] if len (name_parts ) > 1 else "default" ,
48+ "color" : color ,
49+ "size" : {"width" : width , "height" : height }
50+ })
51+
52+ return buttons
53+
54+ def save_to_json (data , output_path = "../design_system/output.json" ):
55+ """保存解析后的数据到JSON文件"""
56+ with open (output_path , "w" ) as f :
57+ json .dump (data , f , indent = 2 )
58+ print (f"✅ 数据已保存至 { os .path .abspath (output_path )} " )
59+
60+ if __name__ == "__main__" :
61+ # 执行流程
62+ raw_data = fetch_figma_data ()
63+ buttons = parse_button_data (raw_data )
64+ save_to_json (buttons )
0 commit comments