补充 9.9.1 机巢交付资料并切换运行配置
This commit is contained in:
@@ -0,0 +1,198 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build an offline review gallery from untouched, locally captured app screenshots."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import html
|
||||
import json
|
||||
import pathlib
|
||||
import hashlib
|
||||
import struct
|
||||
import subprocess
|
||||
import zipfile
|
||||
from collections import Counter
|
||||
|
||||
|
||||
TITLES = {
|
||||
"home": "机巢工作台", "statistics": "工作台 · 统计区域", "orders": "我的拍摄订单",
|
||||
"payment-empty": "套餐收款 · 未选择套餐", "payment": "套餐收款", "receipts": "收款记录",
|
||||
"preparation": "拍摄准备", "task-ready": "拍摄任务 · 到达待开拍", "task-shooting": "拍摄任务 · 拍摄中",
|
||||
"task-completion-dialog": "拍摄任务 · 完成提示", "task-completed": "拍摄任务 · 拍摄已完成",
|
||||
"task-paused": "拍摄任务 · 手动暂停", "task-returning": "拍摄任务 · 返航中",
|
||||
"task-returned": "拍摄任务 · 已回巢", "task-pending-pause": "拍摄任务 · 暂停指令等待",
|
||||
"task-starting": "拍摄任务 · 起飞准备", "task-failed": "拍摄任务 · 失败",
|
||||
"task-going": "拍摄任务 · 前往点位",
|
||||
"materials": "订单素材库", "material-preview": "素材预览", "delivery-method": "交付方式选择",
|
||||
"delivery-cloud": "云端交付", "delivery-nearby": "面对面闪传", "confirmation": "订单交付确认",
|
||||
"confirmation-code": "确认收货二维码", "confirmation-completed": "订单交付确认 · 已完成",
|
||||
"project-picker": "套餐选择", "amount-edit": "设置金额", "live-fullscreen": "图传全屏",
|
||||
}
|
||||
|
||||
ALIASES = {
|
||||
"dock-workbench": "home", "dock-workbench-statistics": "statistics", "dock-orders": "orders",
|
||||
"dock-payment-before-selection": "payment-empty", "dock-payment": "payment", "dock-receipts": "receipts",
|
||||
"dock-preparation": "preparation", "dock-materials": "materials", "dock-material-preview": "material-preview",
|
||||
"dock-delivery-methods": "delivery-method", "dock-delivery-cloud": "delivery-cloud",
|
||||
"dock-delivery-nearby": "delivery-nearby", "dock-confirmation-manifest": "confirmation",
|
||||
"dock-confirmation-code": "confirmation-code", "task-returning-complete": "task-completed",
|
||||
"task-control-paused": "task-paused", "task-control-returning": "task-returning",
|
||||
"task-control-returned": "task-returned", "task-control-pending-pause": "task-pending-pause",
|
||||
"task-control-starting": "task-starting",
|
||||
}
|
||||
|
||||
ORDER = ["home", "statistics", "orders", "payment-empty", "payment", "project-picker", "amount-edit", "receipts", "preparation",
|
||||
"task-starting", "task-going", "task-ready", "task-shooting", "task-paused", "task-returning", "task-returned", "task-completed",
|
||||
"task-completion-dialog", "task-failed", "task-pending-pause", "materials", "material-preview", "delivery-method",
|
||||
"delivery-cloud", "delivery-nearby", "confirmation", "confirmation-code", "confirmation-completed", "live-fullscreen"]
|
||||
|
||||
|
||||
def read_manifest(root: pathlib.Path, platform: str):
|
||||
directory = root / platform
|
||||
path = directory / "manifest.json"
|
||||
metadata = json.loads(path.read_text()) if path.exists() else {}
|
||||
if isinstance(metadata, list):
|
||||
records = metadata
|
||||
metadata = {}
|
||||
else:
|
||||
records = metadata.get("screenshots", metadata.get("screens", metadata.get("pages", [])))
|
||||
files = {p.name: p for p in directory.glob("*.png")}
|
||||
result = []
|
||||
seen = set()
|
||||
for record in records:
|
||||
if isinstance(record, str):
|
||||
record = {"filename": record}
|
||||
filename = record.get("filename", record.get("file", record.get("path", "")))
|
||||
filename = pathlib.Path(filename).name
|
||||
if filename not in files:
|
||||
continue
|
||||
stem = pathlib.Path(filename).stem
|
||||
key = record.get("pageKey", record.get("key", record.get("page", stem)))
|
||||
key = ALIASES.get(key, ALIASES.get(stem, key))
|
||||
item = {**record, "filename": filename, "key": key, "platform": platform,
|
||||
"path": str(files[filename].relative_to(root)), "title": record.get("title", TITLES.get(key, stem))}
|
||||
result.append(item)
|
||||
seen.add(filename)
|
||||
for filename, path in files.items():
|
||||
if filename in seen:
|
||||
continue
|
||||
key = ALIASES.get(path.stem, path.stem)
|
||||
result.append({"filename": filename, "key": key, "platform": platform,
|
||||
"path": str(path.relative_to(root)), "title": TITLES.get(key, path.stem)})
|
||||
used_keys = {}
|
||||
for item in result:
|
||||
path = root / item["path"]
|
||||
raw = path.read_bytes()
|
||||
width, height = struct.unpack(">II", raw[16:24])
|
||||
item["dimensions"] = f"{width} × {height}"
|
||||
item["sha256"] = hashlib.sha256(raw).hexdigest()
|
||||
if item["key"] == "task-failed" and platform == "ios":
|
||||
item["note"] = "执行失败,等待设备确认回巢;右侧为中断后已回巢,模拟状态不同。"
|
||||
if item["key"] == "delivery-method":
|
||||
item["note"] = "由工作台打开交付方式弹层。" if platform == "ios" else "由订单素材库打开交付方式弹层。"
|
||||
count = used_keys.get(item["key"], 0) + 1
|
||||
used_keys[item["key"]] = count
|
||||
if count > 1:
|
||||
item["original_key"] = item["key"]
|
||||
item["key"] = f'{item["key"]}-extra-{count}'
|
||||
return metadata, result
|
||||
|
||||
|
||||
def pair_records(ios, android):
|
||||
ios_map = {r["key"]: r for r in ios}
|
||||
android_map = {r["key"]: r for r in android}
|
||||
keys = list(dict.fromkeys(ORDER + list(ios_map) + list(android_map)))
|
||||
return [{"key": k, "title": TITLES.get(k, (ios_map.get(k) or android_map.get(k))["title"]),
|
||||
"ios": ios_map.get(k), "android": android_map.get(k)}
|
||||
for k in keys if k in ios_map or k in android_map]
|
||||
|
||||
|
||||
def build_html(root: pathlib.Path, pairs, platforms):
|
||||
escaped = lambda value: html.escape(str(value), quote=True)
|
||||
navigation = "".join(f'<a href="#{escaped(p["key"])}">{i:02d} {escaped(p["title"])}</a>' for i, p in enumerate(pairs, 1))
|
||||
sections = []
|
||||
for i, pair in enumerate(pairs, 1):
|
||||
columns = []
|
||||
for platform, label in [("ios", "iOS"), ("android", "Android")]:
|
||||
screen = pair[platform]
|
||||
if screen:
|
||||
path = escaped(screen["path"])
|
||||
title = escaped(pair["title"])
|
||||
dimensions = screen.get("dimensions", "")
|
||||
note = screen.get("note", screen.get("notes", ""))
|
||||
if isinstance(note, list):
|
||||
note = ";".join(note)
|
||||
columns.append(f'<figure><figcaption><strong>{label}</strong><span>{escaped(dimensions)}</span></figcaption>'
|
||||
f'<a href="{path}" target="_blank" aria-label="打开 {label} {title} 原图"><img src="{path}" loading="lazy" alt="{label} {title}"></a>'
|
||||
f'<p class="caption">{escaped(note)}</p></figure>')
|
||||
else:
|
||||
columns.append(f'<figure><figcaption><strong>{label}</strong></figcaption><div class="missing">本次未提供该状态截图</div></figure>')
|
||||
recommendation = pair["recommendation"]
|
||||
note = recommendation.get("note", "")
|
||||
note_html = f'<p class="rec-note">{escaped(note)}</p>' if note else ''
|
||||
columns.append(
|
||||
f'<aside class="recommendation" aria-labelledby="rec-{escaped(pair["key"])}">'
|
||||
f'<h3 id="rec-{escaped(pair["key"])}">推荐以哪端为准</h3>'
|
||||
f'<p class="rec-choice rec-{escaped(recommendation["baseline"])}">{escaped(recommendation["label"])}</p>'
|
||||
f'<p class="rec-reason">{escaped(recommendation["reason"])}</p>'
|
||||
f'<p class="rec-action"><strong>建议同步</strong>{escaped(recommendation["action"])}</p>'
|
||||
f'{note_html}</aside>'
|
||||
)
|
||||
unmatched = '' if pair['ios'] and pair['android'] else '<span class="tag">单端补充</span>'
|
||||
comparison_path = f'comparison/{i:02d}-{pair["key"]}.png'
|
||||
sections.append(f'<section id="{escaped(pair["key"])}"><h2><span>{i:02d}</span> {escaped(pair["title"])} {unmatched} '
|
||||
f'<a class="combined" href="{escaped(comparison_path)}" target="_blank">三列图</a></h2><div class="pair">{"".join(columns)}</div></section>')
|
||||
source = escaped(json.dumps(platforms, ensure_ascii=False, indent=2))
|
||||
output = '''<!doctype html>
|
||||
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>机巢控制台 · iOS / Android UI 对比</title>
|
||||
<style>
|
||||
:root{font-family:-apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;color:#20242c;background:#f4f6f8;font-size:15px;line-height:1.6}
|
||||
*{box-sizing:border-box}body{margin:0}a{color:#1556b3}header{max-width:1640px;margin:auto;padding:34px 28px 24px}h1{font-size:26px;line-height:1.3;margin:0 0 12px}header p{margin:6px 0;color:#53606f}header .links{display:flex;gap:20px;flex-wrap:wrap;margin-top:14px}
|
||||
.layout{max-width:1640px;margin:auto;display:grid;grid-template-columns:208px minmax(0,1fr);gap:24px;padding:0 28px 40px}nav{position:sticky;top:16px;align-self:start;max-height:calc(100vh - 32px);overflow:auto;padding-bottom:14px}nav a{display:block;text-decoration:none;color:#3c4656;padding:7px 10px;border-radius:5px;font-size:13px}nav a:hover,nav a:focus{background:#e1e8f1}main{min-width:0}section{scroll-margin-top:18px;margin:0 0 32px;padding:18px 20px 22px;background:white;border-radius:10px;box-shadow:0 2px 10px #1c2a3e08}h2{margin:0 0 16px;font-size:18px;font-weight:600}h2>span:first-child{font-variant-numeric:tabular-nums;color:#8390a1;margin-right:5px}.combined{font-size:12px;font-weight:400;float:right;margin-top:4px}.tag{font-size:11px;color:#6a7482;background:#edf0f4;padding:3px 7px;border-radius:4px;vertical-align:2px;white-space:nowrap}.pair{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr) minmax(220px,.74fr);gap:18px;align-items:start}figure{margin:0;min-width:0}figcaption{display:flex;align-items:baseline;justify-content:space-between;gap:10px;margin-bottom:9px}figcaption span{color:#7b8795;font-size:11px}img{display:block;width:100%;height:auto;background:#f4f6f8;border:1px solid #e5e9ef}a:focus img{outline:3px solid #2b74ca;outline-offset:3px}.caption{font-size:12px;color:#738093;margin:8px 0 0}.missing{background:#f4f6f8;padding:55px 16px;text-align:center;color:#7c8795;font-size:13px}details{margin:20px 0}summary{cursor:pointer;color:#4c5b70}pre{font-size:12px;background:white;padding:16px;overflow:auto;white-space:pre-wrap;overflow-wrap:anywhere}
|
||||
.recommendation{min-width:0;border-left:1px solid #dce3ec;padding-left:18px;overflow-wrap:anywhere}.recommendation h3{font-size:15px;font-weight:600;margin:0 0 12px;color:#475467}.rec-choice{display:inline-block;margin:0 0 12px;padding:5px 10px;background:#edf3fc;color:#174b91;border-radius:5px;font-size:15px;font-weight:600}.rec-keep{background:#f0f3f6;color:#475467}.rec-insufficient{background:#fff5dd;color:#805d13}.rec-reason{margin:0 0 14px;color:#273448}.rec-action{margin:0 0 14px;color:#465569}.rec-action strong{display:block;font-size:13px;margin-bottom:4px;color:#28384e}.rec-note{margin:0;color:#687587;font-size:12px;line-height:1.65}.review-scope{border-left:3px solid #b5c9e5;padding-left:12px}
|
||||
@media(max-width:1240px){.layout{display:block}nav{position:static;max-height:160px;columns:3;margin-bottom:24px;background:#eaf0f6;padding:10px}}@media(max-width:900px){.pair{grid-template-columns:repeat(2,minmax(0,1fr))}.recommendation{grid-column:1/-1;border-left:0;border-top:1px solid #dce3ec;padding:16px 0 0}.recommendation h3{margin-bottom:8px}.rec-action strong{display:inline;margin-right:8px}}
|
||||
@media(max-width:760px){header{padding:24px 16px}.layout{display:block;padding:0 12px 24px}nav{position:static;max-height:200px;margin-bottom:20px;background:#eaf0f6;padding:10px;columns:2}section{padding:14px 10px}.pair{gap:9px}h2{font-size:16px}figcaption{font-size:13px;display:block}figcaption span{display:block}}@media print{nav,.links{display:none}.layout{display:block}section{box-shadow:none;break-inside:avoid}header{padding:0}body{background:white}.pair{gap:20px}}
|
||||
</style></head><body><header><h1>机巢控制台 · iOS / Android</h1><p>2026-11-05 · 当前源码正式页面 · 隔离模拟数据</p><p>左列 iOS,中列 Android,右列为推荐基准与理由;窄屏时建议显示在截图下方。点击截图可查看完整原图,两端按等宽展示。</p><p>iOS 使用截图专用副本,仅加入依赖替身和启动入口,正式页面布局原样保留。Android 使用当前正式 Screen 与隔离测试替身。</p><p>任务、设备、游客、图传均为本地模拟来源;两端模拟图传配置及业务数据可能不同,画面状态差异不能代表真实设备行为。二维码为本地测试图形,不对应真实付款或收货。</p><p class="review-scope">推荐仅针对本次可见的布局、文案与操作层级。两端一致时保留各端;缺图或模拟状态不同的组注明待核对。系统导航、键盘与安全区遵循平台习惯。</p><div class="links"><a href="overview.png">查看总览图</a><a href="screenshots.zip" download>下载全部截图与图集</a><a href="manifest.json">查看截图清单</a></div></header><div class="layout"><nav aria-label="页面导航">NAVIGATION</nav><main>SECTIONS<details><summary>运行环境和截图来源</summary><pre>SOURCE</pre></details></main></div></body></html>'''
|
||||
(root / "index.html").write_text(output.replace("NAVIGATION", navigation).replace("SECTIONS", "".join(sections)).replace("SOURCE", source))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("root", type=pathlib.Path)
|
||||
parser.add_argument("--render-swift", default=str(pathlib.Path(__file__).with_name("render_gallery.swift")))
|
||||
parser.add_argument("--no-render", action="store_true")
|
||||
args = parser.parse_args()
|
||||
root = args.root.resolve()
|
||||
ios_metadata, ios = read_manifest(root, "ios")
|
||||
android_metadata, android = read_manifest(root, "android")
|
||||
if not ios or not android:
|
||||
raise SystemExit(f"Both screenshot sets required: iOS {len(ios)}, Android {len(android)}")
|
||||
pairs = pair_records(ios, android)
|
||||
review = json.loads((root / "recommendations.json").read_text())
|
||||
recommendations = {entry["key"]: entry for entry in review["entries"]}
|
||||
expected_keys = {pair["key"] for pair in pairs}
|
||||
if len(recommendations) != len(review["entries"]) or set(recommendations) != expected_keys:
|
||||
raise SystemExit("Recommendations must cover every comparison group exactly once")
|
||||
for pair in pairs:
|
||||
pair["recommendation"] = recommendations[pair["key"]]
|
||||
metadata = {"ios": ios_metadata, "android": android_metadata}
|
||||
manifest = {"title": "机巢控制台 iOS / Android UI 对比", "capture_date": "2026-11-05", "source": "当前正式页面 + 隔离模拟数据",
|
||||
"platforms": metadata, "pair_count": len(pairs), "paired_count": sum(bool(p["ios"] and p["android"]) for p in pairs),
|
||||
"ui_review": {"reviewed_at": review["reviewed_at"], "scope": review["scope"],
|
||||
"baseline_counts": dict(Counter(r["baseline"] for r in recommendations.values()))},
|
||||
"pairs": pairs}
|
||||
(root / "manifest.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=2))
|
||||
build_html(root, pairs, metadata)
|
||||
if not args.no_render:
|
||||
subprocess.run(["swift", "-module-cache-path", "/private/tmp/drone-gallery-swift-cache", args.render_swift, str(root)], check=True)
|
||||
archive = root / "screenshots.zip"
|
||||
with zipfile.ZipFile(archive, "w", zipfile.ZIP_DEFLATED) as target:
|
||||
for path in sorted(root.rglob("*")):
|
||||
if path.is_file() and path != archive and path.suffix not in {".log", ".apk", ".pyc"}:
|
||||
target.write(path, path.relative_to(root))
|
||||
print(json.dumps({"pairs": len(pairs), "paired": manifest["paired_count"], "ios": len(ios), "android": len(android),
|
||||
"html": str(root / "index.html"), "archive_bytes": archive.stat().st_size}, ensure_ascii=False))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,217 @@
|
||||
import AppKit
|
||||
import Foundation
|
||||
|
||||
/// Renders review derivatives with two untouched screenshots and an independently sized recommendation column.
|
||||
let root = URL(fileURLWithPath: CommandLine.arguments[1], isDirectory: true)
|
||||
let manifestData = try Data(contentsOf: root.appendingPathComponent("manifest.json"))
|
||||
let manifest = try JSONSerialization.jsonObject(with: manifestData) as! [String: Any]
|
||||
let pairs = manifest["pairs"] as! [[String: Any]]
|
||||
let output = root.appendingPathComponent("comparison", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true)
|
||||
|
||||
/// Returns review fields as display text while accepting optional or array-valued notes.
|
||||
func textValue(_ value: Any?) -> String {
|
||||
if let string = value as? String { return string.trimmingCharacters(in: .whitespacesAndNewlines) }
|
||||
if let strings = value as? [String] { return strings.joined(separator: "\n") }
|
||||
return ""
|
||||
}
|
||||
|
||||
/// Supplies a readable conclusion if a review object only specifies its baseline.
|
||||
func recommendationLabel(_ recommendation: [String: Any]) -> String {
|
||||
let label = textValue(recommendation["label"])
|
||||
if !label.isEmpty { return label }
|
||||
let baseline = textValue(recommendation["baseline"])
|
||||
switch baseline.lowercased() {
|
||||
case "ios": return "以 iOS 为准"
|
||||
case "android": return "以 Android 为准"
|
||||
case "both", "mixed", "mix", "hybrid": return "结合两端"
|
||||
case "keep", "native", "platform": return "保留平台习惯"
|
||||
case "", "pending": return "待补充建议"
|
||||
default: return baseline
|
||||
}
|
||||
}
|
||||
|
||||
/// Measures wrapped Chinese or Latin paragraphs with the same attributes used during drawing.
|
||||
func styledText(_ text: String, size: CGFloat, color: NSColor = .black, weight: NSFont.Weight = .regular) -> NSAttributedString {
|
||||
let paragraph = NSMutableParagraphStyle()
|
||||
paragraph.lineBreakMode = .byWordWrapping
|
||||
paragraph.lineSpacing = 4
|
||||
return NSAttributedString(string: text, attributes: [
|
||||
.font: NSFont.systemFont(ofSize: size, weight: weight),
|
||||
.foregroundColor: color,
|
||||
.paragraphStyle: paragraph
|
||||
])
|
||||
}
|
||||
|
||||
/// Includes a small drawing allowance so the last line never clips at a fractional glyph boundary.
|
||||
func textHeight(_ text: NSAttributedString, width: CGFloat) -> CGFloat {
|
||||
let bounds = text.boundingRect(with: NSSize(width: width, height: CGFloat.greatestFiniteMagnitude),
|
||||
options: [.usesLineFragmentOrigin, .usesFontLeading])
|
||||
return ceil(bounds.height) + 6
|
||||
}
|
||||
|
||||
/// Draws every wrapped line and returns the consumed vertical space.
|
||||
@discardableResult
|
||||
func wrappedLabel(_ text: NSAttributedString, x: CGFloat, y: CGFloat, width: CGFloat) -> CGFloat {
|
||||
let height = textHeight(text, width: width)
|
||||
text.draw(with: NSRect(x: x, y: y, width: width, height: height),
|
||||
options: [.usesLineFragmentOrigin, .usesFontLeading], context: nil)
|
||||
return height
|
||||
}
|
||||
|
||||
/// Draws short headings with the same minimum type size as all other review text.
|
||||
func label(_ text: String, x: CGFloat, y: CGFloat, width: CGFloat, size: CGFloat,
|
||||
color: NSColor = .black, weight: NSFont.Weight = .regular) {
|
||||
wrappedLabel(styledText(text, size: size, color: color, weight: weight), x: x, y: y, width: width)
|
||||
}
|
||||
|
||||
/// Reads source screenshots without writing or transforming their files.
|
||||
func image(_ record: [String: Any]?) -> NSImage? {
|
||||
guard let path = record?["path"] as? String else { return nil }
|
||||
return NSImage(contentsOf: root.appendingPathComponent(path))
|
||||
}
|
||||
|
||||
/// Creates a correctly oriented PNG canvas used exclusively for derived comparison images.
|
||||
func render(width: Int, height: Int, file: URL, draw: () -> Void) throws {
|
||||
let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: width, pixelsHigh: height,
|
||||
bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false,
|
||||
colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0)!
|
||||
let context = NSGraphicsContext(bitmapImageRep: rep)!
|
||||
NSGraphicsContext.saveGraphicsState()
|
||||
context.cgContext.translateBy(x: 0, y: CGFloat(height))
|
||||
context.cgContext.scaleBy(x: 1, y: -1)
|
||||
let flipped = NSGraphicsContext(cgContext: context.cgContext, flipped: true)
|
||||
NSGraphicsContext.current = flipped
|
||||
flipped.imageInterpolation = .high
|
||||
NSColor.white.setFill()
|
||||
NSRect(x: 0, y: 0, width: width, height: height).fill()
|
||||
draw()
|
||||
NSGraphicsContext.restoreGraphicsState()
|
||||
try rep.representation(using: .png, properties: [:])!.write(to: file)
|
||||
}
|
||||
|
||||
/// Scales each complete source image to its column width without cropping.
|
||||
func drawImage(_ img: NSImage?, x: CGFloat, y: CGFloat, width: CGFloat, placeholderHeight: CGFloat) {
|
||||
guard let img else {
|
||||
NSColor(white: 0.96, alpha: 1).setFill()
|
||||
NSRect(x: x, y: y, width: width, height: placeholderHeight).fill()
|
||||
label("本次未截图", x: x + 20, y: y + 50, width: width - 40, size: 20, color: .secondaryLabelColor)
|
||||
return
|
||||
}
|
||||
let height = img.size.height * width / img.size.width
|
||||
img.draw(in: NSRect(x: x, y: y, width: width, height: height), from: .zero,
|
||||
operation: .sourceOver, fraction: 1, respectFlipped: true, hints: nil)
|
||||
}
|
||||
|
||||
/// Describes one measured block in the right-hand review column.
|
||||
struct ReviewBlock {
|
||||
let content: NSAttributedString
|
||||
let trailingSpace: CGFloat
|
||||
}
|
||||
|
||||
/// Separates the conclusion, rationale, action, and limitations without truncating any field.
|
||||
func reviewBlocks(_ recommendation: [String: Any]) -> [ReviewBlock] {
|
||||
var blocks = [ReviewBlock(content: styledText(recommendationLabel(recommendation), size: 25, weight: .semibold), trailingSpace: 28)]
|
||||
for (key, heading) in [("reason", "理由"), ("action", "建议调整"), ("note", "对照说明")] {
|
||||
let value = textValue(recommendation[key])
|
||||
guard !value.isEmpty else { continue }
|
||||
blocks.append(ReviewBlock(content: styledText(heading, size: 18, color: .secondaryLabelColor, weight: .medium), trailingSpace: 6))
|
||||
blocks.append(ReviewBlock(content: styledText(value, size: key == "note" ? 18 : 20), trailingSpace: 26))
|
||||
}
|
||||
return blocks
|
||||
}
|
||||
|
||||
let screenshotWidth: CGFloat = 540
|
||||
let reviewX: CGFloat = 1180
|
||||
let reviewWidth: CGFloat = 320
|
||||
let canvasWidth = 1534
|
||||
|
||||
for (index, pair) in pairs.enumerated() {
|
||||
let a = image(pair["ios"] as? [String: Any])
|
||||
let b = image(pair["android"] as? [String: Any])
|
||||
let recommendation = pair["recommendation"] as? [String: Any] ?? [:]
|
||||
let blocks = reviewBlocks(recommendation)
|
||||
let reviewHeight = blocks.reduce(CGFloat(0)) { $0 + textHeight($1.content, width: reviewWidth) + $1.trailingSpace }
|
||||
let imageHeight = max(a.map { $0.size.height * screenshotWidth / $0.size.width } ?? 240,
|
||||
b.map { $0.size.height * screenshotWidth / $0.size.width } ?? 240)
|
||||
let contentHeight = max(imageHeight, reviewHeight)
|
||||
let filename = String(format: "%02d-", index + 1) + (pair["key"] as! String) + ".png"
|
||||
try render(width: canvasWidth, height: Int(ceil(contentHeight + 190)), file: output.appendingPathComponent(filename)) {
|
||||
label(pair["title"] as! String, x: 34, y: 20, width: CGFloat(canvasWidth - 68), size: 30, weight: .semibold)
|
||||
label("iOS", x: 34, y: 76, width: screenshotWidth, size: 25, weight: .medium)
|
||||
label("Android", x: 606, y: 76, width: screenshotWidth, size: 25, weight: .medium)
|
||||
label("推荐以哪端为准", x: reviewX, y: 76, width: reviewWidth, size: 24, weight: .medium)
|
||||
drawImage(a, x: 34, y: 120, width: screenshotWidth, placeholderHeight: 240)
|
||||
drawImage(b, x: 606, y: 120, width: screenshotWidth, placeholderHeight: 240)
|
||||
NSColor(white: 0.88, alpha: 1).setFill()
|
||||
NSRect(x: 1162, y: 120, width: 1, height: contentHeight).fill()
|
||||
var y: CGFloat = 120
|
||||
for block in blocks {
|
||||
y += wrappedLabel(block.content, x: reviewX, y: y, width: reviewWidth) + block.trailingSpace
|
||||
}
|
||||
label("本地模拟 · 2026-11-05 · 完整原图请查看 ios / android 目录", x: 34, y: contentHeight + 144,
|
||||
width: CGFloat(canvasWidth - 68), size: 18, color: .secondaryLabelColor)
|
||||
}
|
||||
}
|
||||
|
||||
/// Stores measured overview geometry so long recommendation labels expand the corresponding row.
|
||||
struct OverviewCell {
|
||||
let pair: [String: Any]
|
||||
let iosImage: NSImage?
|
||||
let androidImage: NSImage?
|
||||
let title: NSAttributedString
|
||||
let recommendation: NSAttributedString
|
||||
let titleHeight: CGFloat
|
||||
let recommendationHeight: CGFloat
|
||||
let imageOffset: CGFloat
|
||||
let height: CGFloat
|
||||
}
|
||||
|
||||
let overviewColumns = 3
|
||||
let cellWidth: CGFloat = 476
|
||||
let cellContentWidth: CGFloat = 450
|
||||
let overviewImageWidth: CGFloat = 216
|
||||
let cells: [OverviewCell] = pairs.enumerated().map { index, pair in
|
||||
let a = image(pair["ios"] as? [String: Any])
|
||||
let b = image(pair["android"] as? [String: Any])
|
||||
let title = styledText(String(format: "%02d ", index + 1) + (pair["title"] as! String), size: 20, weight: .medium)
|
||||
let recommendation = styledText("建议:" + recommendationLabel(pair["recommendation"] as? [String: Any] ?? [:]),
|
||||
size: 18, color: .systemBlue, weight: .medium)
|
||||
let titleHeight = textHeight(title, width: cellContentWidth)
|
||||
let recommendationHeight = textHeight(recommendation, width: cellContentWidth)
|
||||
let imageOffset = titleHeight + 6 + recommendationHeight + 8 + 32
|
||||
let imageHeight = max(a.map { $0.size.height * overviewImageWidth / $0.size.width } ?? 180,
|
||||
b.map { $0.size.height * overviewImageWidth / $0.size.width } ?? 180)
|
||||
return OverviewCell(pair: pair, iosImage: a, androidImage: b, title: title, recommendation: recommendation,
|
||||
titleHeight: titleHeight, recommendationHeight: recommendationHeight,
|
||||
imageOffset: imageOffset, height: imageOffset + imageHeight + 64)
|
||||
}
|
||||
let rows = Int(ceil(Double(cells.count) / Double(overviewColumns)))
|
||||
let rowHeights: [CGFloat] = (0..<rows).map { row in
|
||||
cells[(row * overviewColumns)..<min((row + 1) * overviewColumns, cells.count)].map(\.height).max() ?? 0
|
||||
}
|
||||
let overviewHeight = Int(ceil(rowHeights.reduce(0, +) + 130))
|
||||
try render(width: Int(CGFloat(overviewColumns) * cellWidth + 40), height: overviewHeight,
|
||||
file: root.appendingPathComponent("overview.png")) {
|
||||
label("机巢控制台 · iOS / Android UI 对比与建议", x: 28, y: 18, width: 1380, size: 32, weight: .semibold)
|
||||
label("每组左 iOS、右 Android · 当前正式页面 + 隔离模拟数据 · 2026-11-05", x: 28, y: 67,
|
||||
width: 1380, size: 20, color: .secondaryLabelColor)
|
||||
var rowY: CGFloat = 124
|
||||
for row in 0..<rows {
|
||||
for column in 0..<overviewColumns {
|
||||
let index = row * overviewColumns + column
|
||||
guard index < cells.count else { continue }
|
||||
let cell = cells[index]
|
||||
let x = 24 + CGFloat(column) * cellWidth
|
||||
wrappedLabel(cell.title, x: x, y: rowY, width: cellContentWidth)
|
||||
wrappedLabel(cell.recommendation, x: x, y: rowY + cell.titleHeight + 6, width: cellContentWidth)
|
||||
let platformY = rowY + cell.titleHeight + 6 + cell.recommendationHeight + 8
|
||||
label("iOS", x: x, y: platformY, width: overviewImageWidth, size: 18, color: .secondaryLabelColor)
|
||||
label("Android", x: x + 230, y: platformY, width: overviewImageWidth, size: 18, color: .secondaryLabelColor)
|
||||
drawImage(cell.iosImage, x: x, y: rowY + cell.imageOffset, width: overviewImageWidth, placeholderHeight: 180)
|
||||
drawImage(cell.androidImage, x: x + 230, y: rowY + cell.imageOffset, width: overviewImageWidth, placeholderHeight: 180)
|
||||
}
|
||||
rowY += rowHeights[row]
|
||||
}
|
||||
}
|
||||
print("Rendered \(pairs.count) three-column comparison PNGs and recommendation overview.png")
|
||||
Reference in New Issue
Block a user