@easyv/screen-cli 0.1.2 → 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.
@@ -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())