@easyv/screen-cli 0.1.3 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@easyv/screen-cli",
3
- "version": "0.1.3",
3
+ "version": "0.1.4",
4
4
  "description": "用自然语言驱动 EasyV 大屏的命令行工具:搭建、修改、排查,以及从零开发组件",
5
5
  "bin": {
6
6
  "easyv-screen": "bin/easyv-screen.js"
@@ -0,0 +1,194 @@
1
+ ---
2
+ name: figma-asset-slice
3
+ description: 用于从 Figma 大屏设计稿中导出适配 EasyV 的可复用资产,整合切图与组装规律、Figma 导出限制、EasyV 组件补位及 Fable 5.2 产物中的可借鉴规则。
4
+ ---
5
+ # figma-asset-slice
6
+
7
+ 从可视化大屏 Figma 稿导出可复用资产。规则是通用的,不针对某一份稿。布局在运行时是绝对定位,切出来的应该是风格标本,不是一张烘死的整屏图。
8
+
9
+ ## 前提:不依赖稿面规范
10
+
11
+ 这些规则必须能在不规范的设计稿上执行。不要把「图层已命名、编组完整、尺寸整数对齐、结构清晰」当成前置条件。设计师产出通常层级混乱、图层不命名或错命名、一个 group 装不下该单元的全部元素。
12
+
13
+ 识别一律按画布上看到的内容、位置和视觉关系,不按图层名,不按是否在同一个 group 里。拿不准时在清单里写明判断,不要默默跳过。
14
+
15
+ ## 硬性规则
16
+
17
+ 1. **透明背景**。位图必须是带 alpha 的 PNG,禁止压到白底、灰底或页面背景上。正确的半透明壳在浅底上会发白,这是通道,不是切坏了;验证时要同时衬浅底和深底。
18
+ 2. **SVG 同样必须透明**。导出后若出现铺满画布的实色底板(Figma 常见为 `#F5F5F5` 或其他浅灰/白底 rect),必须去掉,只留字形本身。
19
+ 3. **背景模糊要去掉再导出**。若节点或任何子级有 Background Blur,在副本上移除再导出——Figma 会把当前背后的内容烘进 PNG。把半径记入清单,便于之后补毛玻璃。Layer Blur、Drop Shadow、Inner Shadow、外发光等图形自身的光效要保留。
20
+ 4. **动态文字不能出现在导出图里**。导出前隐藏副本上所有 TEXT,包括标题、标签、数值和单位。品牌 logo 里的字标是 logo 本身的一部分,跟 logo 一起保留。
21
+ 5. **只在画布外的空框里操作副本**。切完恢复隐藏的文字,删掉临时框和副本,不改原稿。
22
+ 6. **图层名和编组不可信**。按可见内容和空间聚类识别模块。同属固定完整视觉单元的字形与自身光效、壳和金角、徽标和条带等兄弟图层,先合组再导出;跨模块复用且需要独立定位的装饰按下文独立,不因分组不同就拆碎,也不一概合并。图表底座、平台、托盘仍按图表规则排除。
23
+
24
+ ## 格式与倍率
25
+
26
+ - **判定为图标的,只导出透明 SVG,不要再附一份 PNG。**
27
+ - 若字形里嵌了栅格图,保留 SVG 内嵌形式,仍不要另存 PNG;按下述规则处理内嵌位图体积,不把“包进 SVG”当成自动变为矢量。
28
+ - **其余位图默认 2x 透明 PNG**。不能为了透明退回 1x;要解决的是导出方法(隔离渲染、不压底),不是降低倍率。
29
+
30
+ ### SVG 内嵌位图的清晰度与体积
31
+
32
+ - 依据该资产的实际显示布局尺寸、内嵌图在其中的变换/占比,以及目标输出与合理放大时的清晰度需求,判断原位图像素是否明显过量。过量时在导出副本中合理降采样,不用原图像素大小直接决定 SVG 包体;不设脱离用途的统一像素或文件体积硬阈值。
33
+ - 只处理内嵌的栅格图,不将 SVG 中的矢量路径、矢量字标、渐变等内容栅格化。保留 SVG 的透明度、蒙版、裁切、变换及自身光效;图标仍为透明 SVG-only,其余位图仍默认 2x 透明 PNG,不能借优化之名改为正式图标 PNG 或降低其他位图的导出倍率。
34
+ - 在 manifest 的 `specialJudgments` 或 `notes` 中记录每个已处理内嵌图的原始/处理后像素尺寸、目标显示尺寸与清晰度依据、处理方式,以及优化前后体积;同时保留资产最终真实文件大小。没有降采样时记录保留原因,不为凑小包体牺牲清晰度或编造压缩结果。
35
+ - 按目标显示尺寸和所需清晰度复核处理前后外观,检查边缘、透明区域、蒙版和光晕;不清楚用途或无法可靠确认清晰度时先说明,不盲目降采样。
36
+
37
+ ## 图标盘点
38
+
39
+ 按整页穷尽收集独立字形,不限于大尺寸指标图标。列表行、图例旁、Tab、指标旁的小图标,以及组合模块标题上随实例变化的小图标,都要收。同一视觉只留一份,不要把同一图标内部的布尔碎片再切一次。打开 SVG 衬深色底检查:只能看到字形,不能有一整块浅灰或白底。
40
+
41
+ **先穷尽盘点独有内容,再对壳去重。** 模块外壳相同,不代表内部或旁边的图标、徽标、箭头、端饰等也相同。比较每个实例的可见内容和空间关系,不能因为已留一份壳就跳过整个实例。源清单中每个独有图标/装饰都要有去向:独立资产、包含它的组合资产,或按图表等现有规则排除的具体原因;不能借盘点之名把图表整体或其平台重新导出。重复内容只导出一份,但保留出现/引用节点、目标复用资产和位置/对齐关系;这些去向与引用可写入 `specialJudgments` / `notes`,并保留清单已有的覆盖/跳过记录。
42
+
43
+ ## Tab / 选项卡:先识别交互,再切页头与装饰
44
+
45
+ - **按视觉与用途识别,不靠图层名字或编组。** 观察并列选项、当前选中提示、导航/内容切换关系;在导出页面外框、header、标题或模块壳之前先盘点 Tab。即使选项嵌在一体的异形页头、与静态装饰同组,仍是可切换的交互单元,不能当成固定装饰整体烤死。
46
+ - **能由 EasyV 选项卡组件直接配置的普通样式不切图。** 对规整矩形、圆角及可通过现有组件配置实现的填充/描边/选中样式,记录组件补位、源节点、占位布局和可配置样式的判断依据,由组件呈现选项及状态。不能仅因图层名叫“矩形”就忽略实际复杂状态装饰,也不能把未切图的组件补位误报为漏项。
47
+ - **真正异形或组件不能直接配置的复杂状态装饰,按单项可替换背景切两态。** 去掉文字,分别导出真实的“默认状态”“选中状态”背景及该状态专属装饰;不导出一整组多个选项和当前高亮的烘死截图。状态专属斜角、描边、光效等随该状态资产走;独立图标仍按既有盘点与 SVG-only 规则处理,不顺便烤入 PNG。需输出的非图标状态位图仍为 2x 透明 PNG。
48
+ - **状态不是尺寸档,也不能被去重折叠。** 按同结构、同用途、同实际布局档位及端型,默认/选中每态各留一份真实标本;复用时记录来源与引用。左右不对称、首尾不同端型等确有视觉差异时保留相应变体,不镜像猜造;不能因为同尺寸就把两个状态去重成一份,也不能把“默认/选中”填写成布局档位。
49
+ - **两态使用统一的逻辑布局基准,光晕分别记 overflow。** 为可相互替换的两态确认同一按钮占位、锚点/基线和组装尺寸基准,分别测量实际导出尺寸与四边溢出;切换时按共同布局位置减去各态自己的 overflow 对齐,不因高亮外接框较大而挪动按钮或缩放裁掉光晕。若两态取自不同源实例,保留各自真实来源位置,在 `specialJudgments` / `notes` 中说明统一组装基准和对应偏移,不伪造源坐标。无法可靠确定共同基准时记录问题并沟通,不硬凑。
50
+ - **切页头/标题/壳时排除完整 Tab,但不挖掉真实共享结构。** 在副本中剥离 Tab 自有的整块底图、所有状态装饰与文字;不只隐藏文字而留下选中高亮,也不把始终存在的 Tab 自有底图误当作 header 共享底。真正静态共用的 header 结构留在 header,Tab 专属装饰跟状态走。按视觉归属而非矩形区域一刀抠除;若共用路径或边界模糊,指出具体范围、共享关系和疑问后沟通确认,其他可确定内容继续处理,不能随意挖掉共享底或无说明地把 Tab 烤入 header。
51
+ - **缺态不自行设计。** 原稿缺少某结构/档位/端型的一种状态时,记录已存在的真实状态、缺失的状态及来源范围,沟通确认;不靠改色、删光效、镜像等手段伪造另一态,也不以空白文件充数。未补齐前不能宣称两态齐全;预览脚本的资源校验通过,也不等于已完成 Tab 状态覆盖。
52
+ - **清单与预览明确标态。** 在 manifest 的 `specialJudgments` 或 `notes` 中记录导航/切换用途、默认/选中状态、来源、结构/端型与尺寸档位、互换/组装关系、统一布局基准及各态 overflow 对齐、重复引用、组件补位依据或缺态/边界疑问。资产的可见命名及说明要让 `index.html` 清楚区分状态;参考图不代替状态资产。无需出图的组件补位,以及缺态/边界疑问,可放入清单已有的跳过/覆盖判断记录并在其中用 `notes` 说明,不能伪造正式图片条目来凑数。沿用现有说明字段与已有记录即可在预览查看,不强制新 schema,不修改预览 helper,也不把状态当尺寸档。
53
+
54
+ ## 不要切的:图表
55
+
56
+ 有坐标轴、刻度、网格、数据系列(柱、线、面积、点、扇区、环形、仪表盘、进度条、数据条等)的区域判定为图表,不切图,到目标产品里用图表组件补位。
57
+
58
+ 看起来是图表底座、平台、托盘的装饰,也算图表的一部分,不要单独切。图例色块不切。
59
+
60
+ **贴在装饰模块上的图表同样不切。** 环形图、仪表盘、扇形、进度条等即使和这一组模块视觉上连在一起,也不要切进组合模块里。进度条要整条去掉,轨道和填充都不要留,留给组件补位。去掉这块图表之后,把剩下的装饰壳(行槽、侧沿、色标、异形卡壳、标题装饰等)按组合模块整段切。判断看画面结构,不看图层是否叫「图表」。
61
+
62
+ **不要因为卡片里有数字或进度条,就把整张内容卡当成图表跳过。** 自带异形外壳和标题装饰的内容卡(进度卡、内层指标卡等)按组合模块切。
63
+
64
+ ## 组合模块
65
+
66
+ 组合模块是去字、且不含图表的完整装饰单元。中间镶徽标的横条、带侧沿的多行槽、自带异形外壳和标题装饰的内容卡,都算。按画布上的视觉单元识别,不按是否在同一个 group 里。
67
+
68
+ - 导出前隐藏全部动态文字。
69
+ - 贴着的环形图、仪表盘、进度条等整块去掉,剩下的壳继续切。进度条不要只去填充、留下轨道。
70
+ - **固定一体的装饰默认合图**(如固定中心徽标、端饰、行色标、侧沿、标题栏斜切及固定造型槽托),作为完整视觉单元整段切,不把所有东西拆成碎片。若某装饰确实跨不同模块复用,并需要独立的位置/尺寸控制,则作为独立装饰资产导出,从相应壳副本中移除;记录来源、复用实例与相对布局/对齐关系。仅仅图层分组独立或在一张图里出现过,不足以作为拆分依据。标题内纹理仍随标题保留,不另切 tile。
71
+ - 可变位数的数字/字母槽不因与壳同组就固定烤入整排,按「数字 / 字母槽」处理;有依据的固定完整造型例外也须记录。图表、进度条及其平台排除规则优先,不能把它们改称“复用装饰”保留。
72
+ - 随实例变化的标题小图标,以及多处复用的趋势箭头,单独出透明 SVG,不要烤进壳里;不随数据位数变化的固定装饰槽托可以留,但图表底座/平台不能留。
73
+ - 同一结构按布局档位分套,每一档一份标本。某一档在稿里没有实例,就不要空造。
74
+ - Tab 不按静态固定一体装饰合入壳;先按「Tab / 选项卡」规则剥离交互区域,再判断剩余固定结构的合图。Tab 默认/选中是独立的状态维度,不因同结构同尺寸档位而互相去重。
75
+
76
+ ### 数字 / 字母槽:先分用途,再分尺寸档
77
+
78
+ - 先按源稿实际用途区分数字槽、字母/评级槽等语义与造型变体,再在同用途、同结构内归布局尺寸档。不能仅凭宽高把字母槽当成数字槽的放大档,也不能靠名字叫“数字牌”就合并不同用途。
79
+ - 位数随数据变化时,以去字后的**单格**为重复单元,提供相应数字/字母变体及拼装规则,不按某次示例数据的字符数烤死整排。manifest 的 `specialJudgments` 或 `notes` 中写明单格资产、适用字符/用途、实测尺寸与档位、横向/纵向间距、起点/对齐和字符变化时的重复排列方式;单位、数值等动态文字仍由目标组件承载,不烤图。
80
+ - 只有造型和排列本身确为固定完整装饰单元,且有源稿结构和复用用途的明确依据,才保留整组例外;不能仅因当前数据恰好有固定几位就当成固定造型。记录例外依据、固定范围和装配方式,避免与单格方案重复叠加。
81
+
82
+ ### 整壳与独立标题:明确互斥的替代装配方案
83
+
84
+ - 整壳已经包含标题装饰时,不得再把同一独立标题叠上去。如果同时提供整壳与独立标题,必须明确是**替代方案**而不是让使用方猜:整壳方案使用已含标题的壳;拆分方案必须使用实际存在的去标题空壳与匹配标题资产。没有去标题空壳,就不能宣称该整壳可同时作为拆分方案的底图。
85
+ - 在 manifest 的 `specialJudgments` 或 `notes` 中列明涉及的资产文件、包含/替代关系、各方案应同用和不可同用的项、相对布局与含 overflow 的对齐方式、可复用实例及对应真实布局档位。已有其他关系字段可保留,不强制新增预览脚本不认识的 schema;关键说明必须在这些明确可显示字段中可见。
86
+ - 各方案仍按实际存在的布局档位选择标本,不通过拉伸或九宫格把异形标题/壳变成另一档;没有证据的档位或去标题资产不空造。不为“提供更多选择”重复烤入相同装饰而不交代装配关系。
87
+
88
+ ## 不要另切:已烘进其他资产的纹理
89
+
90
+ 只出现在标题栏、模块壳等已经要导出的资产里面的点阵、纹理、底纹,不要再把原始 tile 单独切一份。它已经跟那个标题或壳一起被切走了。
91
+
92
+ 只有这块纹理会被独立平铺、且还没被任何已切资产包进去时,才保留原始 tile。
93
+
94
+ ## 页面大背景
95
+
96
+ 大背景 = 把画布上所有前景内容去掉之后剩下的东西:模块、标题、图表、文字、图标、页面外框(左右栏、底栏、页头装饰)都算前景。
97
+
98
+ 不要只切名为「背景」的图层。背景常常分散在多个未命名或错命名的层里(大面积色块、渐变、光斑、网格、底纹等)。按视觉从画板底层往上收集这些层,在副本上隐藏全部前景后导出一张「页面背景」(默认 2x)。漏切或误把前景烘进去都不行。
99
+
100
+ ## 泛光与对齐
101
+
102
+ 投影、外发光、图层模糊会撑大视觉外接矩形,导出尺寸可能大于设计稿上的布局框。
103
+
104
+ - **保留光晕**,按视觉外接矩形导出,不要为了对尺寸把光效裁掉。
105
+ - 清单里必须同时记:设计稿布局框 `(x, y, width, height)`,导出画布尺寸,以及四边溢出 `overflow.left / top / right / bottom`(布局单位,不受导出倍率影响)。
106
+ - 上传到绝对定位画布时:`left = layout.x - overflow.left`,`top = layout.y - overflow.top`;贴图宽高用导出画布尺寸(若是 2x,再按倍率折算回布局单位)。
107
+ - 没有溢出时,四边记 `0`,不要省略这三组数据。
108
+
109
+ ## 异形标题 / 模块壳的多尺寸
110
+
111
+ 结构看起来一样、但跨了不同布局档位的标题装饰或模块背景,因为常是异形(斜切、端饰、不等比装饰),不能靠拉伸或九宫格变成另一档,必须按档各出一份。
112
+
113
+ 按布局倍数分档,不要用固定像素差去切:
114
+
115
+ 1. 先按用途与结构分族(尤其数字槽与字母/评级槽不能混为一族),并确认整壳/独立标题的装配方案,再在画布上找到该族最小的那一档,作为 **1x 基准**。看可见的模块宽度(高度若在变则看高度),以及模块之间的间距;不要依赖名为「布局」的图层是否存在。
116
+ 2. 预设档位:**1x、1.5x、2x**。若还有明显更大的,按同样节奏继续加 2.5x、3x。
117
+ 3. **2x 的预期尺寸通常是「两个 1x 加上中间那条模块间距」**,不是 1x 的精确两倍。1.5x 按「一档半」去靠,同样要把间距算进去,不要用精确乘法去卡。
118
+ 4. 把每个实例归到最近的一档:落在两档中点及以内算当前档,超过中点进下一档。档内的小数、几个像素偏差、以及「2x 并不等于 1x×2」这类误差,都还算同一档,只留一份标本。
119
+ 5. 同一结构每一档出一份;清单里注明该标本的布局档位(1x / 1.5x / 2x …)和实测宽高。某一档在稿里没有实例,就不要空造。
120
+
121
+ 这里的 1x / 2x 是布局档位,和位图默认按 2 倍分辨率导出不是一回事。
122
+
123
+ ## 品牌 logo 与页面外框
124
+
125
+ 品牌 logo(徽标、字标,或两者组合在一起的那一块)始终单独作为品牌资产切出来。
126
+
127
+ - **切底栏、侧栏等页面外框时,要把 logo 藏掉,不要烘进外框图里。** 外框只留装饰条、端饰、分割线这些边框专属部分。
128
+ - **logo 只出画布上看到的那一份:** 颜色、蒙版、裁切都以画布呈现为准。不要再切一份未蒙版、未着色的源图——源图常常是另一套颜色,在稿上并不是最终样子。
129
+ - 同一视觉只留一份。
130
+ - **先识别 Tab,再切 header / 页头外框。** 即使 Tab 位于异形页头结构内,也要在副本中剥离其整块自有底图、状态装饰和文字,不能只去字留选中高亮;真正静态共享的 header 结构仍保留。Tab 专属装饰随状态导出,普通组件可配置的样式记录组件补位。边界不清时指出疑问并沟通,不随意挖掉共享底,详见 Tab 专节。
131
+
132
+ ## 切图类型
133
+
134
+ | 类型 | 切什么 | 说明 |
135
+ | --- | --- | --- |
136
+ | 页面背景 | 去掉全部前景后剩下的画布底 | 按视觉收集,不按图层名。 |
137
+ | 模块背景 | 空的模块 / 卡片外壳 | 固定一体的兄弟金角一起切;跨模块复用且需独立定位的装饰见组合模块规则。去掉背景模糊。按 1x / 1.5x / 2x 布局档位,每档各出一份。 |
138
+ | 大标题 | 页头装饰,不带字 | 常有泛光,必须记溢出。按布局档位,每档各出一份。 |
139
+ | 一级标题 | 面板标题栏装饰,不带字 | 含角标、端饰。按布局档位,每档各出一份。栏内纹理跟标题一起切,不另存 tile。 |
140
+ | 二级标题 / 三级标题 | 标题装饰,不带字 | 只切装饰。按布局档位,每档各出一份。 |
141
+ | Tab / 选项卡 | 按视觉识别的单项可替换状态背景,不含文字 | 普通矩形/圆角及组件可直接配置的样式不切,记录 EasyV 选项卡补位;真正异形/复杂状态装饰默认、选中各出一份,保留真实端型差异,缺态不造。两态统一布局基准、各记 overflow;先从 header/标题/壳剥离完整 Tab,自有装饰跟状态,真实共享结构仍保留。 |
142
+ | 组合模块 | 去字、且不含图表的完整装饰单元 | 固定一体装饰默认整段切;跨模块复用且需独立定位的装饰按规则独立,其他不碎拆。贴着的环形图、仪表盘、进度条等整块除掉,留下的壳继续切。随实例变化的标题图标、复用趋势单独出 SVG。可变数字槽按单格及拼装规则;整壳/独立标题同时提供时写明互斥装配方案。 |
143
+ | 图标整体 | 固定一体的图标 + 自身光晕 / 非图表平台的装饰,作为一个单元 | 独特字形和自身装饰可能是兄弟层,按视觉合组;图表底座、平台、托盘仍排除。只出透明 SVG,内嵌位图按用途控制体积。 |
144
+ | 图标 | 独立小字形 | 只出透明 SVG。壳去重前穷尽盘点独有图标;保留去向与重复引用,不把壳相同当成内容相同。 |
145
+ | 页面外框 | 左右边框、底栏等画布边框 | 按完整视觉单元整图切,不要拆成角标、花饰、分割线。**不包含 logo。** 左右镜像可只出一份并注明可翻转。 |
146
+ | 品牌 logo | 画布上呈现的 logo | 只出看到的那份,不另出源图。 |
147
+ | 装饰背景 | 独立平铺贴图等 | 仅当该纹理会被独立平铺、且未被其他已切资产包含时才保留原始 tile。图表底座不算此类。已烘进标题或模块壳的纹理不另切。 |
148
+
149
+ ## 导出步骤
150
+
151
+ 1. 先按整帧盘点,按可见内容而不是图层名:页面大背景、模块壳(按 1x / 1.5x / 2x 布局档位)、各级标题装饰(同样按档)、组合模块(含自带异形壳的内容卡;去掉贴着的图表和进度条)、全部独立图标(含组合模块标题上随实例变化的小图标)、页面外框(不含 logo)、画布上的 logo、其余确实独立的非图表装饰。先逐实例盘点独有图标/装饰,记录其去向与重复引用,再对填充、描边、装饰和布局档位均相同的壳/资产去重;不能跳过仍含独有内容的整个模块。先按用途分清数字/字母槽,再分档。跳过图表及其底座、平台、托盘、进度条整条,以及已被标题或壳包含的纹理 tile。 在页头、标题和壳切图之前,先按视觉与导航/切换用途识别 Tab,不以层名或分组为前置;区分组件可配置样式与需切的复杂状态背景,盘点默认/选中及端型变体。Tab 底图、状态装饰和文字也属于页面背景导出时须去掉的前景。
152
+ 2. 在画布外建一个无填充、`clipsContent: false` 的临时框,把目标克隆进去。
153
+ 3. 隐藏所有 TEXT(logo 字标除外);去掉 BACKGROUND_BLUR;隐藏贴在组合模块上的图表和进度条(轨道与填充整条去掉)。固定一体装饰按视觉合组;跨模块复用且需独立定位的装饰、随实例变化的标题图标及复用趋势,从壳副本移除后另出。可变位数槽取去字单格并记录拼装;固定整组例外须有依据。确认整壳/独立标题的互斥替代方案,避免把同一标题重复烤入待叠加的两张图。切外框时隐藏 logo。 对 Tab,不只去文字:从 header/标题/壳副本中排除完整自有底图及状态装饰,保留真实静态共享结构;复杂 Tab 单项分别提取真实默认/选中状态,普通可配置样式留给选项卡组件。归属边界不明或缺态时记录问题并沟通,不随意拆共享底或补造状态。
154
+ 4. 记录每个目标的布局框,以及视觉外接矩形相对布局框的四边溢出;在 `specialJudgments` / `notes` 中记录独有项去向、重复引用、独立装饰的位置/对齐、单格用途与间距/拼装、固定整组例外依据,以及整壳/标题的包含和互斥替代关系。 Tab 另外在这些说明字段中写明用途、状态、真实来源、结构/端型/档位、统一组装基准及各态 overflow、互换/复用关系、组件补位或缺态疑问;不改为强制新 schema。
155
+ 5. 图标只出透明 SVG(去掉导出器加的实色底板);内嵌位图按显示尺寸和清晰度合理降采样并记录原/后尺寸、体积与处理依据,不栅格化矢量内容。其余走隔离透明渲染的 2x PNG。页面背景在隐藏全部前景后导出。禁止把图层压到页面背景或灰底上再导出。
156
+ 6. 校验:位图 alpha 不能全部是 255;标题和组合模块里不能出现动态文案,也不能夹进图表或进度条;外框里不能出现 logo;SVG 打开后没有整块浅底;清单里布局框、导出尺寸、溢出三项齐全;同用途同结构在稿里出现过的布局档位都有标本。逐个核对独有图标/装饰有去向、重复实例有复用引用;拆分后不漏固定一体装饰,同一装配方案内不重复烤入/叠用相同的独立装饰;互斥方案按记录选择。检查数字/字母槽分类、可变位数拼装与间距,固定整组例外依据;检查整壳/标题各方案可实际组装、互斥项不叠加、异形不被跨档拉伸;检查 SVG 内嵌位图处理前后清晰度/透明度/光效和真实文件体积记录。 Tab 另验收:header/标题/壳内无残留 Tab 自有底图或选中高亮,真实共享底未误删;复杂状态背景单项去字、默认/选中覆盖及端型变体有据,同档状态未被去重;两态按共同基准和各自 overflow 对齐不跳动;组件补位/缺态/边界问题有说明。index.html 中状态标记清楚,缺态不能宣称齐全。
157
+ 7. 删掉临时框,确认原稿未被改。
158
+
159
+ ## 切完之后
160
+
161
+ - 清单里记录:类型、来源节点、格式与导出倍率、布局框、导出尺寸、四边溢出、去掉的背景模糊半径;多尺寸标本注明布局档位(1x / 1.5x / 2x …)和该档宽高。这份清单是给后续对齐和组装用的机器可读记录,不是要上传的素材本身。
162
+ - 独有项去向与重复引用、独立装饰的关系/对齐/复用、单格用途/间距/拼装及固定整组例外、整壳与标题的互斥替代方案、内嵌位图的尺寸/清晰度依据/处理与前后体积,写入清单中明确可展示的 `specialJudgments` 或 `notes`。不要求改预览脚本或强制引入新 schema;不得只有生成者脑中知道的装配约定。
163
+ - 图表区域和进度条留给图表组件,不要用切图去贴。
164
+ - Tab 的用途/状态/来源/尺寸档位、组装对齐与引用、组件补位及其依据、缺态/边界疑问,同样写入 `specialJudgments` / `notes` 并在固定 index.html 预览中可查看。状态不可代替布局档位;资源校验通过不替代人工核对状态齐全与切换对齐。
165
+
166
+ ## 固定交付与离线切图预览(每次必做)
167
+
168
+ 每次切图必须在**本次正式导出目录**同时交付 `index.html`、`manifest.json`、`README.md`;不能用聊天里的几张截图、临时自主编写的页面或仅提供文件列表替代。预览采用本技能固定脚本 `scripts/build_preview.py`,不得每次依赖模型重新发挥实现。
169
+
170
+ ### 固定执行步骤
171
+
172
+ 本节接在「导出步骤」的源稿恢复确认之后执行:
173
+
174
+ 1. 完成本次 `manifest.json`、`README.md` 和全部正式素材。清单必须逐项登记真实文件路径、类型、源节点、布局框、实际导出尺寸、格式与导出倍率、布局档位、四边溢出、移除的背景模糊记录及特殊说明;不适用/无值应有明确记录(如 `layoutTier: "not-applicable"`、空说明或空模糊数组),不能为了通过校验编造字段。`counts.total` 应与逐项记录一致;PNG/SVG及分类统计如已记录也必须一致。没有跳过项时显式记录 `skipped: []`,否则保留跳过/去重及其原因。
175
+ 2. 使用 **Skill 返回的本技能目录** 中的脚本,不调用来源不明的项目脚本。设置以下变量后运行:
176
+
177
+ ```bash
178
+ SKILL_DIR="<当前 Skill 返回的技能目录>"
179
+ EXPORT_DIR="<本次正式导出目录的绝对路径>"
180
+ python3 "$SKILL_DIR/scripts/build_preview.py" "$EXPORT_DIR"
181
+ ```
182
+
183
+ 脚本只依赖 Python 3 标准库,只读取清单与素材,写入该导出目录的 `index.html` 和 `preview-validation.json`,不改素材、清单或README,不生成图标PNG。不要对历史导出目录运行以免改写它的预览;回归测试使用复制的清单/README及只读素材副本或软链接。
184
+ 3. 原稿参考图可选。有时仅需切图目录,不必强行添加原稿截图。若已具备参考图,放在本次导出目录内,使用 `--reference "refs/source-reference.png"`(可重复),或在清单 `referenceImages` 中显式登记 `{ "file": "refs/source-reference.png", "label": "原稿参考" }`。必须标为参考、不计正式资产,不能靠猜文件名把未登记的素材排除出统计。
185
+ 4. 检查脚本退出码及 `preview-validation.json`。**退出0仅表示资源/元数据机械校验通过,不代表切法及画面已经验收。** 缺资源、重复记录、未登记图片、尺寸/格式/hash/统计不一致、未知schema或必需metadata缺失时,脚本返回非0,并生成显著标红的诊断页;不得以“生成了HTML”为由宣布完成,不能静默省略错误记录,也不能自动补造旧清单字段。先核实并补全本次清单/导出,再重跑。
186
+ 5. 用浏览器直接双击本次 `index.html`,离线验收:正式卡片数与清单一致;分类和搜索可用;深色/浅色/棋盘底切换有效;缩略图保持比例;点击可放大并打开原图;所有图片加载成功;可查看文件名、类型、实际像素或SVG视口、布局尺寸、格式/倍率、布局档位、四边溢出、真实体积、源节点及特殊说明;跳过/去重判断与参考图区分清楚。没有浏览器测试条件时如实记录“未做浏览器交互/视觉验收”,不能声称已验证这些UI。
187
+
188
+ ### 预览约束与固定验收
189
+
190
+ - 页面必须可本地离线打开:内置CSS/JS,不使用CDN,不通过 `fetch` 读取manifest,不依赖服务器。素材图片用相对路径;有真实fileKey/nodeId才生成Figma源链接(只有主动点击才访问Figma),不能伪造外部服务或大屏工程。
191
+ - 深浅/棋盘衬底、缩略显示及放大都**仅作用于预览**,不得烤入素材;不输出图标的正式PNG伴随文件。原稿参考图不计正式资产。
192
+ - 支持当前清单的 `type/sourceNodeIds/backgroundBlurRemoved/specialJudgments` 及旧版 `kind/sourceNode/blurRemoved/notes` 等明确别名;对无法识别的schema明示失败,不静默少图。缺失metadata在卡片上明确标记“未记录”,不按文件名、颜色或像素大小猜测。
193
+ - 固定验收顺序是:脚本返回0 → 核对文件/统计/错误报告 → 离线浏览器逐项检查 → 原有透明度、动态内容剥离、切法、覆盖与源稿恢复等验收。预览脚本不代替原有切图规则和人工判断。
194
+ - 发布/维护本技能时,`scripts/build_preview.py` 必须与本节一起交付到技能目录。缺脚本、缺必交文件、清单缺字段或预览缺图,均不能视为本次切图完成。
@@ -0,0 +1,446 @@
1
+ #!/usr/bin/env python3
2
+ """Build a local-only asset catalogue from manifest.json (Python standard library).
3
+
4
+ Never edits assets/manifest/README. Writes index.html and preview-validation.json only.
5
+ Exit 0: structural/metadata checks pass; exit 2: diagnostic HTML, NOT deliverable.
6
+ Supported manifests: object with assets:[{file,...}], current + v1/v2/v3 aliases.
7
+ Supported formal assets: PNG and SVG. No visual slicing/deduplication is performed.
8
+ """
9
+ from __future__ import annotations
10
+ import argparse
11
+ from collections import Counter, defaultdict
12
+ import hashlib
13
+ import html
14
+ import json
15
+ import math
16
+ from pathlib import Path, PurePosixPath
17
+ import re
18
+ import struct
19
+ import sys
20
+ from urllib.parse import quote, urlsplit, unquote
21
+ import xml.etree.ElementTree as ET
22
+ import zlib
23
+
24
+ MISSING = '未记录(metadata缺失,不推测)'
25
+ IMAGE_EXTS = {'.png', '.svg', '.jpg', '.jpeg', '.webp', '.gif', '.avif'}
26
+ REQUIRED_SIDES = ('left', 'top', 'right', 'bottom')
27
+
28
+
29
+ def esc(value):
30
+ return html.escape(str(value), quote=True)
31
+
32
+
33
+ def pretty(value):
34
+ if value is None:
35
+ return MISSING
36
+ if isinstance(value, (list, dict)):
37
+ return json.dumps(value, ensure_ascii=False, indent=2)
38
+ return str(value)
39
+
40
+
41
+ def first(obj, *keys):
42
+ for key in keys:
43
+ if key in obj and obj[key] is not None:
44
+ return obj[key]
45
+ return None
46
+
47
+
48
+ def number(value, positive=False):
49
+ return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) and (not positive or value > 0)
50
+
51
+
52
+ def human_bytes(n):
53
+ if n is None:
54
+ return MISSING
55
+ for unit, divisor in [('MiB', 1024 ** 2), ('KiB', 1024)]:
56
+ if n >= divisor:
57
+ return f'{n / divisor:.2f} {unit}({n:,} bytes)'
58
+ return f'{n} bytes'
59
+
60
+
61
+ def local_path(value):
62
+ if not isinstance(value, str) or not value or '\\' in value or '\x00' in value:
63
+ raise ValueError('文件路径必须为非空POSIX相对路径')
64
+ parsed = urlsplit(value)
65
+ p = PurePosixPath(value)
66
+ if parsed.scheme or parsed.netloc or p.is_absolute() or '..' in p.parts or value.startswith('//'):
67
+ raise ValueError(f'不允许外部/绝对/向上跳转路径: {value}')
68
+ if value in ('.', ''):
69
+ raise ValueError('文件路径不能是目录')
70
+ return p.as_posix()
71
+
72
+
73
+ def inspect_png(data):
74
+ if data[:8] != b'\x89PNG\r\n\x1a\n':
75
+ raise ValueError('不是有效PNG签名')
76
+ offset, size, has_data, ended = 8, None, False, False
77
+ while offset + 12 <= len(data):
78
+ length = struct.unpack('>I', data[offset:offset + 4])[0]
79
+ kind = data[offset + 4:offset + 8]
80
+ end = offset + 12 + length
81
+ if end > len(data):
82
+ raise ValueError('PNG块被截断')
83
+ body = data[offset + 8:offset + 8 + length]
84
+ expected = struct.unpack('>I', data[offset + 8 + length:end])[0]
85
+ if zlib.crc32(kind + body) & 0xffffffff != expected:
86
+ raise ValueError('PNG CRC不匹配')
87
+ if kind == b'IHDR':
88
+ if offset != 8 or length != 13:
89
+ raise ValueError('PNG IHDR无效')
90
+ width, height, depth, color, compression, filtering, interlace = struct.unpack('>IIBBBBB', body)
91
+ if not width or not height:
92
+ raise ValueError('PNG尺寸为0')
93
+ size = {'width': width, 'height': height, 'dimensionKind': 'PNG实际像素', 'colorType': color, 'alphaChannel': color in (4, 6)}
94
+ elif kind == b'tRNS' and size is not None:
95
+ size['transparencyChunk'] = True
96
+ elif kind == b'IDAT':
97
+ has_data = True
98
+ elif kind == b'IEND':
99
+ ended = True
100
+ break
101
+ offset = end
102
+ if not size or not has_data or not ended:
103
+ raise ValueError('PNG缺少IHDR/IDAT/IEND')
104
+ return size
105
+
106
+
107
+ def svg_length(s):
108
+ if s is None:
109
+ return None
110
+ m = re.fullmatch(r'\s*([+]?(?:\d+(?:\.\d*)?|\.\d+))(px|pt|pc|in|cm|mm)?\s*', s)
111
+ if not m:
112
+ return None
113
+ return float(m[1]) * {'px': 1, 'pt': 96 / 72, 'pc': 16, 'in': 96, 'cm': 96 / 2.54, 'mm': 96 / 25.4, None: 1}[m[2]]
114
+
115
+
116
+ def inspect_svg(data, path, root_dir):
117
+ text = data.decode('utf-8-sig')
118
+ if re.search(r'<!DOCTYPE|<!ENTITY|<\?xml-stylesheet', text, re.I):
119
+ raise ValueError('SVG含外部实体/样式声明,不能保证离线安全预览')
120
+ tree = ET.fromstring(text)
121
+ if tree.tag.split('}')[-1] != 'svg':
122
+ raise ValueError('根节点不是SVG')
123
+ for node in tree.iter():
124
+ tag = node.tag.split('}')[-1]
125
+ if tag in ('script', 'foreignObject'):
126
+ raise ValueError(f'SVG含可执行/嵌入内容: {tag}')
127
+ for key, value in node.attrib.items():
128
+ if key.split('}')[-1].lower().startswith('on'):
129
+ raise ValueError('SVG含事件脚本')
130
+ if key.split('}')[-1] in ('href', 'src') and not value.startswith(('#', 'data:image/')):
131
+ parsed = urlsplit(value)
132
+ if parsed.scheme or parsed.netloc:
133
+ raise ValueError(f'SVG依赖外部资源: {value[:100]}')
134
+ rel = unquote(parsed.path)
135
+ dep = path.parent / rel
136
+ if '..' in PurePosixPath(rel).parts or not dep.is_file():
137
+ raise ValueError(f'SVG相对依赖不存在或向上跳转: {rel}')
138
+ # Symlinked read-only fixtures are allowed, but the URL path remains local.
139
+ if dep.suffix.lower() not in IMAGE_EXTS:
140
+ raise ValueError('SVG相对依赖不是本地图片')
141
+ snippets = list(node.attrib.values()) + ([node.text] if node.text else [])
142
+ for snippet in snippets:
143
+ if re.search(r'@import', snippet, re.I):
144
+ raise ValueError('SVG样式含@import,不能保证离线')
145
+ for match in re.finditer(r'url\(\s*([^)]*?)\s*\)', snippet, re.I):
146
+ resource = match[1].strip().strip('\"\'')
147
+ if resource.startswith(('#', 'data:image/')):
148
+ continue
149
+ parsed = urlsplit(resource)
150
+ if parsed.scheme or parsed.netloc:
151
+ raise ValueError('SVG样式依赖外部资源')
152
+ dependency = unquote(parsed.path)
153
+ if '..' in PurePosixPath(dependency).parts or not (path.parent / dependency).is_file():
154
+ raise ValueError('SVG样式本地依赖缺失或向上跳转: ' + dependency)
155
+ if (path.parent / dependency).suffix.lower() not in IMAGE_EXTS:
156
+ raise ValueError('SVG样式依赖不是本地图片: ' + dependency)
157
+ width, height = svg_length(tree.get('width')), svg_length(tree.get('height'))
158
+ result = {'width': width, 'height': height, 'dimensionKind': 'SVG视口(CSS px,非栅格像素)', 'viewBox': tree.get('viewBox')}
159
+ if width is None or height is None:
160
+ result['dimensionKind'] = 'SVG固有视口缺失;viewBox仅作坐标参考'
161
+ return result
162
+
163
+
164
+ def inspect_image(path, root_dir):
165
+ data = path.read_bytes()
166
+ if path.suffix.lower() == '.png':
167
+ info = inspect_png(data)
168
+ elif path.suffix.lower() == '.svg':
169
+ info = inspect_svg(data, path, root_dir)
170
+ else:
171
+ raise ValueError(f'不支持的正式资产格式: {path.suffix}(当前切图规范仅PNG/SVG)')
172
+ return {**info, 'bytes': len(data), 'sha256': hashlib.sha256(data).hexdigest(), 'format': path.suffix.lower()[1:]}
173
+
174
+
175
+ def document_issues(manifest):
176
+ coverage = manifest.get('coverage') if isinstance(manifest.get('coverage'), dict) else {}
177
+ return {k: v for k, v in {
178
+ '跳过项': manifest.get('skipped'), '覆盖/跳过': coverage.get('skipped'),
179
+ '覆盖与去重判断': coverage.get('regions'), '去重记录': manifest.get('deduplicated'),
180
+ '重复项说明': manifest.get('duplicates'), '导出说明': manifest.get('exportNotes'),
181
+ }.items() if v is not None}
182
+
183
+
184
+ def audit(root, manifest_name, reference_args):
185
+ errors, warnings, rows = [], [], []
186
+ report = {'generator': 'figma-asset-slice/build_preview.py', 'manifestFile': manifest_name, 'errors': errors, 'warnings': warnings, 'assets': rows}
187
+ mpath = root / manifest_name
188
+ try:
189
+ local_path(manifest_name)
190
+ manifest = json.loads(mpath.read_text(encoding='utf-8-sig'))
191
+ except (OSError, ValueError) as exc:
192
+ errors.append(f'无法读取清单: {exc}')
193
+ return {}, report, []
194
+ if not isinstance(manifest, dict) or not isinstance(manifest.get('assets'), list):
195
+ errors.append('未知清单schema:只接受顶层对象且assets为数组;未静默省略任何记录')
196
+ return manifest if isinstance(manifest, dict) else {}, report, []
197
+ if not manifest['assets']:
198
+ errors.append('assets为空,不能声明切图完成')
199
+ source = manifest.get('source') if isinstance(manifest.get('source'), dict) else {}
200
+ file_key = source.get('fileKey')
201
+ if not isinstance(file_key, str) or not re.fullmatch('[A-Za-z0-9]{22,128}', file_key):
202
+ warnings.append('source.fileKey缺失或无效:不会编造Figma链接')
203
+ file_key = None
204
+ # References are opt-in and excluded from formal counts. Never guess by filename.
205
+ reference_values = list(reference_args)
206
+ for value in (manifest.get('referenceImages'), manifest.get('referenceImage'), source.get('referenceImage')):
207
+ if value is not None:
208
+ reference_values.extend(value if isinstance(value, list) else [value])
209
+ refs, ref_paths = [], set()
210
+ for value in reference_values:
211
+ name = value.get('file') if isinstance(value, dict) else value
212
+ try:
213
+ name = local_path(name)
214
+ if name in ref_paths:
215
+ continue
216
+ ref_paths.add(name)
217
+ p = root / name
218
+ if not p.is_file():
219
+ raise ValueError(f'参考图不存在: {name}')
220
+ if p.suffix.lower() not in IMAGE_EXTS:
221
+ raise ValueError(f'参考图不是支持的图片扩展名: {name}')
222
+ refs.append({'file': name, 'label': value.get('label', '原稿参考(不计正式资产)') if isinstance(value, dict) else '原稿参考(不计正式资产)'})
223
+ except (ValueError, OSError) as exc:
224
+ errors.append(str(exc))
225
+ seen, hashes = {}, defaultdict(list)
226
+ formats, types = Counter(), Counter()
227
+ for index, item in enumerate(manifest['assets']):
228
+ row = {'index': index, 'record': item, 'problems': [], 'missingFields': [], 'actual': None, 'file': None, 'sourceLinks': []}
229
+ rows.append(row)
230
+ if not isinstance(item, dict):
231
+ errors.append(f'assets[{index}]不是对象;保留诊断卡片,不丢弃记录')
232
+ row['problems'].append(errors[-1])
233
+ continue
234
+ label = f'assets[{index}]'
235
+ def fail(message):
236
+ message = f'{label}: {message}'
237
+ errors.append(message)
238
+ row['problems'].append(message)
239
+ def missing(field):
240
+ row['missingFields'].append(field)
241
+ fail(f'缺少/无效metadata字段 {field}')
242
+ try:
243
+ name = local_path(first(item, 'file', 'path'))
244
+ row['file'] = name
245
+ label = name
246
+ folded = name.casefold()
247
+ if folded in seen:
248
+ fail(f'重复文件记录(含大小写冲突): {seen[folded]}')
249
+ else:
250
+ seen[folded] = name
251
+ if name in ref_paths:
252
+ fail('同一路径同时声明为正式资产和参考图')
253
+ if not (root / name).is_file():
254
+ fail('资源文件缺失')
255
+ else:
256
+ row['actual'] = inspect_image(root / name, root)
257
+ hashes[row['actual']['sha256']].append(name)
258
+ formats[row['actual']['format']] += 1
259
+ except (ValueError, OSError, ET.ParseError, UnicodeError) as exc:
260
+ fail(str(exc))
261
+ typ = first(item, 'type', 'kind', 'category')
262
+ row['type'] = typ if isinstance(typ, str) and typ else None
263
+ if row['type'] is None:
264
+ missing('type/kind')
265
+ else:
266
+ types[row['type']] += 1
267
+ exported = item.get('export') if isinstance(item.get('export'), dict) else {}
268
+ fmt = first(item, 'format') or exported.get('format')
269
+ row['format'] = fmt.lower() if isinstance(fmt, str) else None
270
+ if row['format'] not in ('png', 'svg'):
271
+ missing('format')
272
+ scale = first(item, 'scale')
273
+ if scale is None:
274
+ scale = exported.get('scale')
275
+ row['scale'] = scale if number(scale, positive=True) else None
276
+ if row['scale'] is None:
277
+ missing('scale(导出倍率)')
278
+ row['layout'] = item.get('layout') if isinstance(item.get('layout'), dict) else {}
279
+ for k, alias in [('x', 'left'), ('y', 'top'), ('width', 'width'), ('height', 'height')]:
280
+ v = first(row['layout'], k, alias)
281
+ if not number(v, positive=k in ('width', 'height')):
282
+ missing('layout.' + k)
283
+ row['overflow'] = item.get('overflow') if isinstance(item.get('overflow'), dict) else {}
284
+ for k in REQUIRED_SIDES:
285
+ if not number(row['overflow'].get(k)) or row['overflow'][k] < 0:
286
+ missing('overflow.' + k)
287
+ row['tier'] = first(item, 'layoutTier', 'tier')
288
+ if row['tier'] is None or row['tier'] == '':
289
+ missing('layoutTier(不适用也需显式记not-applicable;不按文件名推测)')
290
+ row['blur'] = first(item, 'backgroundBlurRemoved', 'blurRemoved', 'strippedBlur')
291
+ if row['blur'] is None:
292
+ missing('backgroundBlurRemoved/blurRemoved(无则[])')
293
+ row['notes'] = first(item, 'specialJudgments', 'notes', 'specialNotes')
294
+ if row['notes'] is None:
295
+ missing('specialJudgments/notes(无则[])')
296
+ nodes = first(item, 'sourceNodeIds', 'sourceNode', 'sourceNodeId')
297
+ nodes = [nodes] if isinstance(nodes, str) else nodes
298
+ row['nodes'] = nodes
299
+ if not isinstance(nodes, list) or not nodes or not all(isinstance(n, str) and re.fullmatch(r'\d+[:-]\d+(?:;.*)?', n) for n in nodes):
300
+ missing('sourceNodeIds/sourceNode')
301
+ elif file_key:
302
+ # Exact real IDs only; instance-path node IDs are displayed but not invented into URLs.
303
+ row['sourceLinks'] = [(n, f'https://www.figma.com/design/{file_key}/?node-id={quote(n, safe="")}') for n in nodes if re.fullmatch(r'\d+[:-]\d+', n)]
304
+ for key in ('width', 'height'):
305
+ if not number(exported.get(key), positive=True):
306
+ missing('export.' + key)
307
+ if row['actual']:
308
+ actual = row['actual']
309
+ if row['format'] and actual['format'] != row['format']:
310
+ fail('格式记录与实际文件不一致')
311
+ for key in ('width', 'height'):
312
+ if actual.get(key) is None:
313
+ fail(f'不能验证实际{key}: {actual["dimensionKind"]}')
314
+ elif number(exported.get(key)) and abs(actual[key] - exported[key]) > 1e-6:
315
+ fail(f'export.{key}记录{exported[key]}与实际{actual[key]}不一致')
316
+ if 'bytes' in item and item['bytes'] != actual['bytes']:
317
+ fail(f'bytes记录{item["bytes"]}与实际{actual["bytes"]}不一致')
318
+ if 'sha256' in item and (not isinstance(item['sha256'], str) or item['sha256'].lower() != actual['sha256']):
319
+ fail('sha256与实际文件不一致')
320
+ unlisted = []
321
+ for p in sorted(root.rglob('*')):
322
+ if p.is_file() and p.suffix.lower() in IMAGE_EXTS:
323
+ name = p.relative_to(root).as_posix()
324
+ if name.casefold() not in seen and name not in ref_paths:
325
+ unlisted.append(name)
326
+ if unlisted:
327
+ errors.append('实际目录存在未登记图片(不能静默少图;参考图须显式声明): ' + ', '.join(unlisted))
328
+ duplicates = [v for v in hashes.values() if len(v) > 1]
329
+ if duplicates:
330
+ warnings.append('存在内容相同的多个文件,需人工确认,不自动合并: ' + pretty(duplicates))
331
+ counts = manifest.get('counts')
332
+ if not isinstance(counts, dict) or not isinstance(counts.get('total'), int) or isinstance(counts.get('total'), bool):
333
+ errors.append('缺少counts.total,无法核对清单统计')
334
+ else:
335
+ if counts['total'] != len(rows):
336
+ errors.append(f'counts.total={counts["total"]},记录数实际={len(rows)}')
337
+ for key in ('png', 'svg'):
338
+ if key in counts and counts[key] != formats[key]:
339
+ errors.append(f'counts.{key}={counts[key]},实际有效文件数={formats[key]}')
340
+ if isinstance(counts.get('byType'), dict) and counts['byType'] != dict(types):
341
+ errors.append('counts.byType与实际类型记录不一致')
342
+ if not ('skipped' in manifest or (isinstance(manifest.get('coverage'), dict) and 'skipped' in manifest['coverage'])):
343
+ errors.append('缺少skipped/coverage.skipped记录(没有跳过也需显式[])')
344
+ if not (root / 'README.md').is_file():
345
+ errors.append('缺少必交README.md(生成器不会代写切图说明)')
346
+ report.update(records=len(rows), validResources=sum(r['actual'] is not None for r in rows), declaredCounts=counts,
347
+ actualFormats=dict(formats), actualTypes=dict(types), unlistedImages=unlisted,
348
+ duplicateContent=duplicates, referenceImages=refs, schema='assets-array/current-and-legacy-aliases')
349
+ return manifest, report, refs
350
+
351
+
352
+ STYLE = r'''
353
+ :root{color-scheme:dark;--bg:#081426;--fg:#e0ebfa;--card:#102139;--line:#30445f;--muted:#a8bdd7;--surface:#07152a}
354
+ *{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--fg);font:15px/1.6 system-ui,-apple-system,"PingFang SC","Microsoft YaHei",sans-serif}header,main,footer{max-width:1640px;margin:auto;padding:24px}h1{font-size:28px;margin:0 0 8px}h2{font-size:21px}.muted{color:var(--muted)}a{color:#8fd7ff}button,input,select{font:inherit}button,select,input{background:var(--card);color:var(--fg);border:1px solid var(--line);border-radius:6px;padding:8px 12px}button{cursor:pointer}button:hover{border-color:#86caff}button:focus-visible,a:focus-visible{outline:3px solid #ffda75;outline-offset:2px}.status{padding:16px;border:1px solid #3b896a;border-radius:8px;background:#123b2b}.status.failed{border-color:#f98e9c;background:#4c1723}.toolbar{position:sticky;top:0;z-index:10;background:var(--bg);padding:12px 24px;border-block:1px solid var(--line);display:flex;gap:12px;flex-wrap:wrap;align-items:center}.toolbar input{flex:1;min-width:200px}.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(290px,1fr));gap:18px}.card{background:var(--card);border:1px solid var(--line);border-radius:10px;overflow:hidden;min-width:0}.card[hidden]{display:none}.card h3{margin:12px 14px 0;font-size:17px;overflow-wrap:anywhere}.surface{background:var(--surface)}.thumb{display:flex;width:100%;height:206px;border:0;border-radius:0;align-items:center;justify-content:center;padding:16px}.thumb img{display:block;max-width:100%;max-height:100%;width:auto;height:auto;object-fit:contain}.meta{padding:8px 14px 14px}.actions{display:flex;gap:14px;flex-wrap:wrap}details{padding:10px 0}summary{cursor:pointer}dl{margin:0}dt{color:var(--muted);font-size:13px;margin-top:9px}dd{margin:0;white-space:pre-wrap;overflow-wrap:anywhere}pre{white-space:pre-wrap;overflow-wrap:anywhere;max-height:520px;overflow:auto}.badge{border:1px solid var(--line);padding:2px 8px;border-radius:5px;margin-right:6px;display:inline-block}.missing,.error{color:#ffb1bd}.notes{font-size:14px}.reference img{max-width:100%;max-height:500px;object-fit:contain}.reference{border:1px dashed var(--line);padding:14px;margin-bottom:14px}dialog{color:var(--fg);background:var(--bg);border:1px solid var(--line);border-radius:10px;width:min(1400px,96vw);max-height:94vh;padding:18px}dialog::backdrop{background:#000b}.modalbar{display:flex;gap:10px;align-items:center;flex-wrap:wrap}.zoomport{height:64vh;overflow:auto;text-align:center;margin-top:14px;padding:10px}.zoomport img{display:block;margin:auto;max-width:none;max-height:none}.zoomport.fit img{max-width:100%;max-height:100%;width:auto;height:auto}.sr-only{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%)}body[data-surface=light]{--surface:#f5f5f5}body[data-surface=checker] .surface{background-color:#d5d9df;background-image:conic-gradient(#b2bac5 25%,transparent 0 50%,#b2bac5 0 75%,transparent 0);background-size:24px 24px}footer{border-top:1px solid var(--line)}
355
+ '''
356
+ SCRIPT = r'''
357
+ 'use strict';
358
+ const cards=[...document.querySelectorAll('.card')];
359
+ function imageFailure(img){if(img.dataset.failed)return;img.dataset.failed='true';const card=img.closest('.card');if(card){const msg=document.createElement('p');msg.className='error';msg.textContent='浏览器图片加载失败:'+card.dataset.file+'(不可验收)';card.querySelector('.meta').prepend(msg);}const status=document.querySelector('.status');status.classList.add('failed');status.querySelector('strong').textContent='浏览器加载失败 · 当前预览不可宣称完成/交付';}
360
+ document.querySelectorAll('.thumb img').forEach(img=>{img.addEventListener('error',()=>imageFailure(img));if(img.complete&&img.naturalWidth===0)imageFailure(img)});
361
+ const search=document.getElementById('search'), category=document.getElementById('category');
362
+ function filter(){const q=search.value.trim().toLocaleLowerCase();let count=0;cards.forEach(c=>{const show=(!category.value||c.dataset.type===category.value)&&(!q||c.dataset.search.includes(q));c.hidden=!show;if(show)count++});document.getElementById('visible-count').textContent=count;}
363
+ search.addEventListener('input',filter);category.addEventListener('change',filter);
364
+ document.querySelectorAll('[data-set-surface]').forEach(b=>b.addEventListener('click',()=>{document.body.dataset.surface=b.dataset.setSurface;document.querySelectorAll('[data-set-surface]').forEach(x=>x.setAttribute('aria-pressed',String(x===b)))}));
365
+ const modal=document.getElementById('viewer'), port=document.getElementById('zoomport'), image=document.getElementById('zoom-image'), slider=document.getElementById('zoom'), scaleLabel=document.getElementById('zoom-label');
366
+ function setZoom(v){port.classList.remove('fit');image.style.width=(Number(image.dataset.width)*v/100)+'px';image.style.height='auto';slider.value=v;scaleLabel.textContent=v+'%(按实际视口/像素)';}
367
+ function fit(){port.classList.add('fit');image.style.width='';image.style.height='';scaleLabel.textContent='适应窗口';}
368
+ cards.forEach(card=>{card.querySelectorAll('[data-enlarge]').forEach(button=>button.addEventListener('click',()=>{const src=card.querySelector('.thumb img');if(!src)return;image.src=src.getAttribute('src');image.alt=src.alt;image.dataset.width=card.dataset.width;document.getElementById('viewer-title').textContent=card.dataset.file;document.getElementById('original-link').href=src.getAttribute('src');document.getElementById('viewer-meta').replaceChildren(card.querySelector('dl').cloneNode(true));fit();modal.showModal();}));});
369
+ document.getElementById('close-viewer').addEventListener('click',()=>modal.close());modal.addEventListener('click',event=>{if(event.target===modal)modal.close()});document.getElementById('fit').addEventListener('click',fit);document.getElementById('one-to-one').addEventListener('click',()=>setZoom(100));slider.addEventListener('input',()=>setZoom(Number(slider.value)));filter();
370
+ '''
371
+
372
+
373
+ def render(manifest, report, refs):
374
+ rows = report['assets']
375
+ source = manifest.get('source') if isinstance(manifest.get('source'), dict) else {}
376
+ frame = source.get('frame') if isinstance(source.get('frame'), dict) else {}
377
+ title = source.get('frameName') or frame.get('name') or source.get('fileName') or source.get('fileNameFromUrl') or '切图资产目录'
378
+ cards = []
379
+ for row in rows:
380
+ item = row['record'] if isinstance(row['record'], dict) else {}
381
+ actual, name = row['actual'], row['file'] or f'未识别记录 #{row["index"] + 1}'
382
+ typ = row.get('type') or MISSING
383
+ size = f'{actual["width"]:g} × {actual["height"]:g}' if actual and actual.get('width') and actual.get('height') else MISSING
384
+ facts = {
385
+ '文件': name, '类型': row.get('type'), '实际尺寸': size,
386
+ '尺寸性质': actual.get('dimensionKind') if actual else None,
387
+ '设计布局(布局单位,不是导出像素)': row.get('layout') or None,
388
+ '清单导出尺寸': item.get('export'), '格式 / 导出倍率': f'{row.get("format") or MISSING} / {str(row.get("scale"))+"×" if row.get("scale") else MISSING}',
389
+ '布局档位(≠导出倍率)': row.get('tier'), '四边溢出(布局单位)': row.get('overflow') or None,
390
+ '实际文件体积': human_bytes(actual.get('bytes') if actual else None),
391
+ '源节点': row.get('nodes'), '剥离背景模糊记录': row.get('blur'), '特殊说明': row.get('notes'),
392
+ }
393
+ # Preserve other metadata as text so new keys cannot silently disappear.
394
+ facts['原始清单记录(全部字段)'] = item if item else row['record']
395
+ dl = ''.join(f'<dt>{esc(k)}</dt><dd class="{"missing" if v is None else ""}">{esc(pretty(v))}</dd>' for k, v in facts.items())
396
+ links = ' '.join(f'<a href="{esc(url)}" target="_blank" rel="noopener noreferrer">Figma {esc(node)}</a>' for node, url in row['sourceLinks'])
397
+ if not links:
398
+ links = '<span class="muted">无可验证的fileKey/nodeId组合,不生成源链接</span>'
399
+ src = quote(name, safe='/') if row['file'] else ''
400
+ picture = f'<button class="thumb surface" data-enlarge aria-label="放大 {esc(name)}"><img src="{src}" alt="{esc(name)}" loading="lazy" decoding="async"></button>' if actual else '<div class="thumb surface error">资源缺失或无效;此记录没有被省略</div>'
401
+ actions = f'<button data-enlarge>放大查看</button><a href="{src}" target="_blank" rel="noopener noreferrer">打开原图</a>' if actual else '<span class="error">不可交付</span>'
402
+ problems = '<ul class="error">' + ''.join(f'<li>{esc(s)}</li>' for s in row['problems']) + '</ul>' if row['problems'] else ''
403
+ searchtext = (name + ' ' + typ + ' ' + pretty(item)).lower()
404
+ cards.append(f'<article class="card" data-file="{esc(name)}" data-width="{actual.get("width") if actual else 0}" data-type="{esc(typ)}" data-search="{esc(searchtext)}">{picture}<h3>{esc(name)}</h3><div class="meta"><p><span class="badge">{esc(typ)}</span><span class="badge">{esc(size)}</span></p><p class="muted">{esc(human_bytes(actual.get("bytes") if actual else None))}</p><div class="actions">{actions}</div>{problems}<details><summary>元数据 / 特殊说明 / 源节点</summary><dl>{dl}</dl><p>{links}</p></details></div></article>')
405
+ options = ''.join(f'<option value="{esc(t)}">{esc(t)}({n})</option>' for t, n in sorted(Counter(r.get('type') or MISSING for r in rows).items()))
406
+ failed = bool(report['errors'])
407
+ errors = ''.join(f'<li>{esc(s)}</li>' for s in report['errors'])
408
+ warnings = ''.join(f'<li>{esc(s)}</li>' for s in report['warnings'])
409
+ reference_html = ''.join(f'<figure class="reference"><figcaption>{esc(r["label"])} · 参考图,不计入{len(rows)}项正式资产</figcaption><a href="{quote(r["file"],safe="/")}" target="_blank" rel="noopener noreferrer"><img src="{quote(r["file"],safe="/")}" alt="原稿参考"></a></figure>' for r in refs)
410
+ decisions = document_issues(manifest)
411
+ decisions_html = ''.join(f'<details><summary>{esc(k)}</summary><pre>{esc(pretty(v))}</pre></details>' for k, v in decisions.items()) or '<p class="missing">清单未记录跳过/去重判断;不代表没有跳过项。</p>'
412
+ return f'''<!doctype html>
413
+ <html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src 'self' file: data:; style-src 'unsafe-inline'; script-src 'unsafe-inline'; connect-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'"><title>{esc(title)} · 切图预览</title><style>{STYLE}</style></head>
414
+ <body data-surface="dark"><header><h1>{esc(title)} · 切图预览</h1><p>正式清单 <strong>{len(rows)}</strong> 项 · 实际有效资源 <strong>{report.get('validResources',0)}</strong> 项 · {esc(pretty(report.get('actualFormats',{})))}</p><p class="muted">中文本地离线目录;无CDN、无接口、无需fetch manifest。图片均为相对路径。源Figma链接仅在点击时离开本页。</p><div class="status {'failed' if failed else ''}"><strong>{'校验未通过 · 不可宣称完成/交付' if failed else '资源及元数据校验通过 · 仍须人工浏览器视觉验收'}</strong><ul>{errors}</ul>{'<h3>提示(不自动修复)</h3><ul>'+warnings+'</ul>' if warnings else ''}</div><p><a href="{quote(report.get('manifestFile','manifest.json'),safe='/')}">manifest.json</a> · <a href="README.md">README.md</a> · <a href="preview-validation.json">校验明细</a></p><noscript><p class="error">JavaScript未启用:仍可查看全部卡片与元数据、打开原图;分类/搜索/底色切换/弹窗放大需要本页内置脚本。</p></noscript></header>
415
+ <nav class="toolbar" aria-label="资产浏览工具"><label for="search" class="sr-only">搜索资产</label><input id="search" type="search" placeholder="搜索文件名、类型、源节点或说明"><label for="category" class="sr-only">分类</label><select id="category"><option value="">全部分类</option>{options}</select><span>显示 <b id="visible-count">{len(rows)}</b> / {len(rows)}</span><span role="group" aria-label="透明底检查"><button data-set-surface="dark" aria-pressed="true">深色底</button><button data-set-surface="light" aria-pressed="false">浅色底</button><button data-set-surface="checker" aria-pressed="false">棋盘底</button></span></nav>
416
+ <main><section aria-label="正式资产" class="grid">{''.join(cards)}</section><section><h2>跳过 / 去重 / 覆盖判断</h2>{decisions_html}</section>{'<section><h2>原稿参考(非正式资产)</h2>'+reference_html+'</section>' if refs else ''}</main>
417
+ <dialog id="viewer" aria-labelledby="viewer-title"><div class="modalbar"><h2 id="viewer-title">查看资产</h2><button id="close-viewer">关闭(Esc)</button><button id="fit">适应窗口</button><button id="one-to-one">原尺寸100%</button><label>缩放 <input id="zoom" type="range" min="10" max="400" step="10" value="100"></label><span id="zoom-label">适应窗口</span><a id="original-link" target="_blank" rel="noopener noreferrer">打开原图</a></div><div class="zoomport surface fit" id="zoomport"><img id="zoom-image" alt=""></div><details><summary>本资产元数据</summary><div id="viewer-meta"></div></details></dialog>
418
+ <footer>衬底、缩略图布局和缩放仅用于检查,未烤入素材;不会生成图标PNG伴随文件。SVG尺寸为矢量视口,不是假定栅格像素。预览不是大屏工程,也不是外部服务。</footer><script>{SCRIPT}</script></body></html>'''
419
+
420
+
421
+ def main(argv=None):
422
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
423
+ parser.add_argument('export_dir', type=Path, help='含manifest.json、README.md与正式PNG/SVG的导出目录')
424
+ parser.add_argument('--manifest', default='manifest.json', help='目录内清单相对路径(默认manifest.json)')
425
+ parser.add_argument('--reference', action='append', default=[], help='可重复:目录内参考图相对路径;明确排除正式统计')
426
+ args = parser.parse_args(argv)
427
+ root = args.export_dir.absolute()
428
+ if not root.is_dir():
429
+ parser.error(f'导出目录不存在: {root}')
430
+ manifest, report, refs = audit(root, args.manifest, args.reference)
431
+ report['passed'] = not report['errors']
432
+ # Incomplete inputs still get clearly failed diagnostic HTML; never a misleading stale success page.
433
+ html_text = render(manifest, report, refs)
434
+ out = root / 'index.html'
435
+ temp = root / '.index.html.preview-tmp'
436
+ temp.write_text(html_text, encoding='utf-8')
437
+ temp.replace(out)
438
+ (root / 'preview-validation.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
439
+ print(json.dumps({'passed': report['passed'], 'records': report.get('records',len(report['assets'])), 'validResources':report.get('validResources',0), 'actualFormats':report.get('actualFormats',{}), 'errors':len(report['errors']), 'warnings':len(report['warnings']), 'index':str(out)}, ensure_ascii=False))
440
+ for message in report['errors']:
441
+ print('ERROR: ' + message, file=sys.stderr)
442
+ return 0 if report['passed'] else 2
443
+
444
+
445
+ if __name__ == '__main__':
446
+ sys.exit(main())