-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode.ts
More file actions
212 lines (194 loc) · 7.85 KB
/
Copy pathcode.ts
File metadata and controls
212 lines (194 loc) · 7.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
// code.ts — v13: proxy fetch через plugin sandbox (обход CORS для Gitea)
figma.showUI(__html__, { width: 560, height: 820, themeColors: true });
interface FrameInfo { name: string; width: number; height: number; section?: string; }
function isIOSScreenshot(name: string): boolean { return /^\d+_APP_/.test(name); }
const ANDROID_SECTIONS: Record<string, { folder: string; scale: number }> = {
"ANDROID PHONE": { folder: "phoneScreenshots", scale: 3 },
"ANDROID TAB 7 INCH": { folder: "sevenInchScreenshots", scale: 3 },
"ANDROID TAB 10 INCH":{ folder: "tenInchScreenshots", scale: 2 },
"ANDROID TV": { folder: "tvScreenshots", scale: 2 },
"FEATUREGRAPHIC": { folder: "__feature__", scale: 1 },
};
function norm(s: string) { return s.trim().toUpperCase().replace(/\s+/g, " "); }
function extractFrameIndex(frameName: string): number | null {
const m = frameName.match(/^(\d+)/);
return m ? parseInt(m[1]) : null;
}
function getIOSFrames(page: PageNode): FrameInfo[] {
return page.children
.filter(n => (n.type === "FRAME" || n.type === "COMPONENT" || n.type === "INSTANCE") && isIOSScreenshot(n.name))
.map(f => ({ name: f.name, width: Math.round(f.width), height: Math.round(f.height) }));
}
function getAndroidFrames(page: PageNode): { frames: FrameInfo[]; sections: string[] } {
const frames: FrameInfo[] = [], sections: string[] = [];
for (const child of page.children) {
if (child.type === "SECTION" && ANDROID_SECTIONS[norm(child.name)]) {
sections.push(child.name);
for (const sub of (child as SectionNode).children) {
if (sub.type === "FRAME" || sub.type === "COMPONENT" || sub.type === "INSTANCE")
frames.push({ name: sub.name, width: Math.round(sub.width), height: Math.round(sub.height), section: child.name });
}
}
}
return { frames, sections };
}
function sendDocInfo() {
figma.ui.postMessage({ type: "doc-info", docName: figma.root.name });
}
function sendPagesInfo(storeType: string) {
const pages: any[] = figma.root.children.map(p => {
const all = p.children.length;
if (storeType === "playmarket") {
const { frames, sections } = getAndroidFrames(p);
return { id: p.id, name: p.name, frames, sections, allFramesCount: all, skippedCount: all - frames.length };
}
const frames = getIOSFrames(p);
return { id: p.id, name: p.name, frames, allFramesCount: all, skippedCount: all - frames.length };
});
figma.ui.postMessage({ type: "pages-info", pages });
}
// ─── Proxy fetch (обход CORS) ────────────────────────────────────────────────
// UI не может напрямую обращаться к Gitea из-за отсутствия CORS-заголовков.
// Все HTTP-запросы к Git API проксируются через plugin sandbox — он не ограничен CORS.
async function proxyFetch(reqId: string, url: string, options: any) {
try {
const res = await fetch(url, {
method: options.method || "GET",
headers: options.headers || {},
body: options.body != null ? options.body : undefined,
});
// Читаем тело как текст (JSON либо пустое)
const text = await res.text();
figma.ui.postMessage({
type: "proxy-response",
reqId,
ok: res.ok,
status: res.status,
body: text,
});
} catch (e: any) {
figma.ui.postMessage({
type: "proxy-response",
reqId,
ok: false,
status: 0,
body: JSON.stringify({ message: e.message || String(e) }),
});
}
}
let stopRequested = false;
async function exportFrames(
pageIds: string[],
storeType: string,
scaleMap: Record<string, number> | null,
defaultScale: number,
sectionFilter: string[] | null
) {
stopRequested = false;
const toExport = figma.root.children.filter(p => pageIds.includes(p.id));
let total = 0;
for (const p of toExport) {
if (storeType === "playmarket") {
const { frames } = getAndroidFrames(p);
total += sectionFilter
? frames.filter(f => f.section && sectionFilter.includes(norm(f.section))).length
: frames.length;
} else {
total += getIOSFrames(p).length;
}
}
figma.ui.postMessage({ type: "export-start", total });
let done = 0;
for (const page of toExport) {
if (stopRequested) break;
figma.currentPage = page;
if (storeType === "playmarket") {
for (const child of page.children) {
if (stopRequested) break;
if (child.type !== "SECTION") continue;
const sectionNorm = norm(child.name);
const cfg = ANDROID_SECTIONS[sectionNorm];
if (!cfg) continue;
if (sectionFilter && !sectionFilter.includes(sectionNorm)) continue;
const sectionScale = (scaleMap && scaleMap[sectionNorm] != null)
? scaleMap[sectionNorm]
: cfg.scale;
for (const frame of (child as SectionNode).children) {
if (stopRequested) break;
if (frame.type !== "FRAME" && frame.type !== "COMPONENT" && frame.type !== "INSTANCE") continue;
try {
const bytes = await (frame as FrameNode).exportAsync({ format: "PNG", constraint: { type: "SCALE", value: sectionScale } });
done++;
const frameIndex = extractFrameIndex(frame.name);
figma.ui.postMessage({
type: "frame-exported",
pageName: page.name,
frameName: frame.name,
frameIndex,
width: Math.round(frame.width),
height: Math.round(frame.height),
scale: sectionScale,
section: child.name,
folder: cfg.folder,
bytes: Array.from(bytes),
current: done,
total
});
} catch (e) {
done++;
figma.ui.postMessage({ type: "log", level: "error", text: `Fail: ${frame.name}: ${e}` });
}
}
}
} else {
const frames = page.children.filter(n =>
(n.type === "FRAME" || n.type === "COMPONENT" || n.type === "INSTANCE") && isIOSScreenshot(n.name)
);
for (const frame of frames) {
if (stopRequested) break;
try {
let scale = defaultScale;
if (scaleMap) {
const u = frame.name.toUpperCase();
for (const [k, v] of Object.entries(scaleMap)) { if (u.includes(k)) { scale = v; break; } }
}
const bytes = await (frame as FrameNode).exportAsync({ format: "PNG", constraint: { type: "SCALE", value: scale } });
done++;
figma.ui.postMessage({
type: "frame-exported",
pageName: page.name,
frameName: frame.name,
frameIndex: null,
width: Math.round(frame.width),
height: Math.round(frame.height),
scale,
bytes: Array.from(bytes),
current: done,
total
});
} catch (e) {
done++;
figma.ui.postMessage({ type: "log", level: "error", text: `Fail: ${frame.name}: ${e}` });
}
}
}
}
figma.ui.postMessage({ type: "export-done", exported: done, total, stopped: stopRequested });
}
figma.ui.onmessage = msg => {
if (msg.type === "get-doc-info") sendDocInfo();
if (msg.type === "get-pages") sendPagesInfo(msg.store || "appstore");
if (msg.type === "export-frames") exportFrames(
msg.pages || [],
msg.store || "appstore",
msg.scaleMap || null,
msg.scale || 2,
msg.sectionFilter || null
);
if (msg.type === "stop-export") stopRequested = true;
if (msg.type === "cancel") figma.closePlugin();
// Проксируем HTTP-запросы из UI через sandbox (обход CORS)
if (msg.type === "proxy-fetch") proxyFetch(msg.reqId, msg.url, msg.options || {});
};
sendDocInfo();
sendPagesInfo("appstore");