figma-handoff-kit 0.0.0-stage → 0.2.3

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,945 @@
1
+ <!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <title>Figma Handoff Kit</title>
6
+ <style>
7
+ /* AAP light theme snapshot; see design-tokens.md. No runtime dependency on the app. */
8
+ :root {
9
+ --spacing: 4px;
10
+ --color-bg-brand-primary: var(--color-brand-50);
11
+ --color-bg-brand-secondary: var(--color-brand-100);
12
+ --color-bg-brand-solid: var(--color-brand-600);
13
+ --color-bg-brand-solid_hover: var(--color-brand-700);
14
+ --color-bg-error-primary: var(--color-red-50);
15
+ --color-bg-primary: var(--color-white);
16
+ --color-bg-secondary: var(--color-neutral-50);
17
+ --color-bg-success-primary: var(--color-green-50);
18
+ --color-bg-tertiary: var(--color-neutral-100);
19
+ --color-blue-400: rgb(96 165 250);
20
+ --color-border-brand: var(--color-brand-500);
21
+ --color-border-primary: var(--color-neutral-300);
22
+ --color-border-secondary: var(--color-neutral-200);
23
+ --color-brand-100: rgb(231 236 244);
24
+ --color-brand-50: rgb(243 246 251);
25
+ --color-brand-500: rgb(67 78 93);
26
+ --color-brand-600: rgb(32 42 56);
27
+ --color-brand-700: rgb(18 27 40);
28
+ --color-brand-900: rgb(6 12 22);
29
+ --color-fg-error-primary: var(--color-red-600);
30
+ --color-fg-success-primary: var(--color-green-600);
31
+ --color-green-400: rgb(74 222 128);
32
+ --color-green-50: rgb(240 253 244);
33
+ --color-green-600: rgb(22 163 74);
34
+ --color-green-700: rgb(21 128 61);
35
+ --color-neutral-100: rgb(245 245 245);
36
+ --color-neutral-200: rgb(229 229 229);
37
+ --color-neutral-300: rgb(212 212 212);
38
+ --color-neutral-400: rgb(163 163 163);
39
+ --color-neutral-50: rgb(250 250 250);
40
+ --color-neutral-600: rgb(82 82 82);
41
+ --color-neutral-700: rgb(64 64 64);
42
+ --color-neutral-900: rgb(23 23 23);
43
+ --color-red-400: rgb(255 104 86);
44
+ --color-red-50: rgb(254 242 240);
45
+ --color-red-600: rgb(209 23 15);
46
+ --color-red-700: rgb(178 14 8);
47
+ --color-text-brand-primary: var(--color-brand-900);
48
+ --color-text-brand-secondary: var(--color-brand-700);
49
+ --color-text-error-primary: var(--color-red-600);
50
+ --color-text-primary: var(--color-neutral-900);
51
+ --color-text-secondary: var(--color-neutral-700);
52
+ --color-text-tertiary: var(--color-neutral-600);
53
+ --color-white: rgb(255 255 255);
54
+ --font-body: var(--font-sans);
55
+ --font-mono: ui-monospace, 'Roboto Mono', SFMono-Regular, Menlo, Monaco, Consolas,
56
+ 'Liberation Mono', 'Courier New', monospace;
57
+ --font-sans: 'IBM Plex Sans', -apple-system, 'Segoe UI', Roboto, Arial, sans-serif;
58
+ --font-weight-semibold: 600;
59
+ --radius-full: 9999px;
60
+ --radius-md: 8px;
61
+ --radius-sm: 6px;
62
+ --radius-xs: 4px;
63
+ --text-sm: calc(var(--spacing) * 3.5);
64
+ --text-xs: calc(var(--spacing) * 3);
65
+ }
66
+
67
+ * { box-sizing: border-box; margin: 0; padding: 0; font-family: var(--font-body); }
68
+ body { padding: 16px; background: var(--color-bg-secondary); color: var(--color-text-primary); font-size: 13px; line-height: 1.4; }
69
+
70
+ .header { margin-bottom: 12px; }
71
+ .title { font-size: 16px; font-weight: 700; color: var(--color-text-primary); display: flex; align-items: center; gap: 6px; }
72
+ .subtitle { font-size: 12px; color: var(--color-text-tertiary); margin-top: 2px; }
73
+
74
+ .status-card {
75
+ background: var(--color-bg-primary); border: 1px solid var(--color-border-secondary); border-radius: var(--radius-md);
76
+ padding: 10px 12px; margin-bottom: 12px; display: flex; align-items: center; justify-content: space-between;
77
+ }
78
+ .badge { display: inline-flex; align-items: center; gap: 5px; font-weight: 600; font-size: 11px; padding: 3px 8px; border-radius: var(--radius-full); }
79
+ .badge-online { background: var(--color-bg-success-primary); color: var(--color-green-700); }
80
+ .badge-offline { background: var(--color-bg-error-primary); color: var(--color-red-700); }
81
+
82
+ .features-banner {
83
+ background: var(--color-bg-brand-primary); border: 1px solid var(--color-border-brand); border-radius: var(--radius-sm); padding: 8px 10px; margin-bottom: 12px;
84
+ font-size: 11px; color: var(--color-text-brand-secondary); line-height: 1.4;
85
+ }
86
+ .features-banner strong { color: var(--color-text-brand-primary); }
87
+
88
+ .scope-box {
89
+ background: var(--color-bg-primary); border: 1px solid var(--color-border-secondary); border-radius: var(--radius-md);
90
+ padding: 12px; margin-bottom: 12px;
91
+ }
92
+ .scope-label { font-size: 11px; font-weight: 600; text-transform: uppercase; color: var(--color-text-tertiary); margin-bottom: 8px; }
93
+
94
+ .radio-option {
95
+ display: flex; align-items: flex-start; gap: 8px; margin-bottom: 8px; cursor: pointer;
96
+ padding: 6px; border-radius: var(--radius-sm); transition: background 0.1s;
97
+ }
98
+ .radio-option:hover { background: var(--color-bg-tertiary); }
99
+ .radio-option input[type=\"radio\"] { margin-top: 2px; }
100
+ .radio-title { font-weight: 600; color: var(--color-text-secondary); font-size: 12px; }
101
+ .radio-desc { font-size: 11px; color: var(--color-text-tertiary); margin-top: 1px; }
102
+
103
+ .control-group { margin-bottom: 12px; }
104
+ .control-label { font-size: 12px; font-weight: 600; color: var(--color-text-secondary); margin-bottom: 4px; display: block; }
105
+ select {
106
+ width: 100%; padding: 8px 10px; border: 1px solid var(--color-border-primary); border-radius: var(--radius-sm);
107
+ background: var(--color-bg-primary); font-size: 12px; color: var(--color-text-primary); outline: none;
108
+ }
109
+
110
+ button.btn-primary {
111
+ width: 100%; padding: 10px 14px; background: var(--color-bg-brand-solid); color: var(--color-bg-primary);
112
+ border: none; border-radius: var(--radius-sm); font-size: 13px; font-weight: 600; cursor: pointer;
113
+ display: flex; align-items: center; justify-content: center; gap: 6px; transition: background 0.15s;
114
+ }
115
+ button.btn-primary:hover:not(:disabled) { background: var(--color-bg-brand-solid_hover); }
116
+ button.btn-primary:disabled { background: var(--color-neutral-400); cursor: not-allowed; }
117
+
118
+ .logs-container {
119
+ margin-top: 12px; background: var(--color-text-primary); border-radius: var(--radius-sm); padding: 10px;
120
+ height: 180px; overflow-y: auto; font-family: var(--font-mono);
121
+ font-size: 11px; color: var(--color-border-secondary);
122
+ }
123
+ .log-entry { margin-bottom: 4px; word-break: break-all; }
124
+ .log-success { color: var(--color-green-400); }
125
+ .log-info { color: var(--color-blue-400); }
126
+ .log-error { color: var(--color-red-400); }
127
+
128
+ .tip { margin-top: 10px; font-size: 11px; color: var(--color-text-tertiary); text-align: center; }
129
+ body { font-size:13px; }
130
+ .header { display:flex; align-items:center; justify-content:space-between; gap:16px; }
131
+ h1 { font-size:18px; }
132
+ .language { font-size:12px; }
133
+ .language select { width:auto; display:block; padding:6px; }
134
+ .destination { background:white; padding:12px; border:1px solid var(--color-border-primary); border-radius:var(--radius-md); margin-bottom:12px; }
135
+ .destination-heading { display:flex; flex-wrap:wrap; justify-content:space-between; gap:8px; margin-bottom:8px; }
136
+ #project-name, #output-directory { display:block; overflow-wrap:anywhere; }
137
+ #output-directory { margin-top:4px; color:var(--color-text-tertiary); font-size:12px; }
138
+ #connection-error { color:var(--color-text-error-primary); margin-top:6px; }
139
+ .radio-desc,.scope-label,.badge,.logs-container { font-size:12px; }
140
+ .radio-title,.control-label { font-size:13px; }
141
+ .radio-option { min-height:44px; }
142
+ :where(button,select,input,summary,[tabindex]):focus-visible { outline:3px solid var(--color-bg-brand-solid); outline-offset:3px; }
143
+ .actions { display:flex; flex-wrap:wrap; gap:8px; margin-top:8px; }
144
+ .actions button { background:white; color:var(--color-text-secondary); border:1px solid var(--color-neutral-400); padding:7px 10px; border-radius:5px; cursor:pointer; }
145
+ summary { cursor:pointer; padding:10px 0; font-weight:600; }
146
+ .help { color:var(--color-text-tertiary); margin-top:8px; }
147
+ #progress { min-height:36px; padding:8px 0; }
148
+ .logs-container { margin-top:8px; height:150px; }
149
+ .log-entry { overflow-wrap:anywhere; word-break:normal; font-family:var(--font-mono); }
150
+ #btn-export { margin-top:12px; }
151
+ [hidden] { display:none !important; }
152
+ .header { margin-bottom:16px; }
153
+ .language-toggle { display:inline-flex; gap:6px; align-items:center; font-size:11px; font-weight:600; color:var(--color-text-tertiary); cursor:pointer; min-height:32px; position:relative; }
154
+ .language-toggle input { position:absolute; width:100%; height:100%; opacity:0; cursor:pointer; }
155
+ .toggle-track { width:32px; height:18px; background:var(--color-neutral-300); border-radius:12px; padding:2px; pointer-events:none; }
156
+ .toggle-track::before { content:""; display:block; width:14px; height:14px; background:white; border-radius:50%; transition:transform .15s; }
157
+ .language-toggle input:checked + .toggle-track { background:var(--color-bg-brand-solid); }
158
+ .language-toggle input:checked + .toggle-track::before { transform:translateX(14px); }
159
+ .language-toggle:has(input:focus-visible) { outline:3px solid var(--color-bg-brand-solid); outline-offset:3px; border-radius:var(--radius-xs); }
160
+ .destination { background:transparent; padding:10px 12px; }
161
+ .destination-heading { margin-bottom:4px; font-size:12px; color:var(--color-text-tertiary); }
162
+ .badge-online::before { content:""; width:6px; height:6px; background:var(--color-fg-success-primary); border-radius:50%; }
163
+ .badge-offline::before { content:""; width:6px; height:6px; background:var(--color-fg-error-primary); border-radius:50%; }
164
+ .destination-path summary { font-size:12px; font-weight:400; padding:3px 0 0; color:var(--color-text-tertiary); }
165
+ .scope-box { padding:12px; }
166
+ .scope-label { font-size:11px; letter-spacing:.04em; }
167
+ .radio-option { margin-bottom:4px; }
168
+ .advanced { border-bottom:1px solid var(--color-border-secondary); }
169
+ .advanced > summary,.log-panel > summary,.help > summary { font-size:12px; color:var(--color-text-tertiary); }
170
+ .advanced .control-group { margin-top:8px; }
171
+ .log-panel,.help { margin-top:4px; }
172
+ .actions button { font-size:12px; padding:5px 8px; }
173
+ @media (prefers-reduced-motion:reduce) { .toggle-track::before { transition:none; } }
174
+ .export-options { display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:12px; margin:8px 0 12px; }
175
+ .scale-options { border:0; display:flex; gap:8px; align-items:center; min-width:0; }
176
+ .scale-options legend { float:left; font-size:12px; color:var(--color-text-tertiary); margin-right:8px; padding:8px 0; }
177
+ .segments { display:flex; border:1px solid var(--color-border-primary); border-radius:var(--radius-sm); overflow:hidden; }
178
+ .segments label { position:relative; cursor:pointer; }
179
+ .segments input { position:absolute; opacity:0; width:100%; height:100%; }
180
+ .segments span { display:block; padding:8px 12px; font-size:12px; background:white; }
181
+ .segments input:checked + span { background:var(--color-bg-brand-secondary); color:var(--color-bg-brand-solid_hover); font-weight:700; }
182
+ .segments input:focus-visible + span { box-shadow:inset 0 0 0 2px var(--color-bg-brand-solid); }
183
+ .segments input:disabled + span { opacity:.5; cursor:not-allowed; }
184
+ .force-toggle { position:relative; display:flex; gap:8px; align-items:center; min-height:36px; font-size:12px; cursor:pointer; color:var(--color-text-tertiary); }
185
+ .force-toggle input { position:absolute; right:0; width:32px; height:24px; opacity:0; }
186
+ .force-toggle input:checked + .toggle-track { background:var(--color-bg-brand-solid); }
187
+ .force-toggle input:checked + .toggle-track::before { transform:translateX(14px); }
188
+ .force-toggle:has(input:focus-visible) { outline:2px solid var(--color-bg-brand-solid); outline-offset:3px; border-radius:var(--radius-xs); }
189
+ .force-toggle input:disabled + .toggle-track { opacity:.5; }
190
+ .actions .icon-button { display:inline-flex; align-items:center; justify-content:center; width:32px; height:32px; padding:0; background:transparent; border-color:transparent; }
191
+ .actions .icon-button:hover { background:var(--color-border-secondary); }
192
+
193
+ .logs-container { background:var(--color-neutral-900); color:var(--color-neutral-200); }
194
+ .segments span { background:var(--color-bg-primary); }
195
+ .toggle-track::before { background:var(--color-white); }
196
+ .log-panel { margin-top:12px; border:1px solid var(--color-border-secondary); border-radius:var(--radius-sm); }
197
+ .log-toolbar { position:sticky; top:0; z-index:1; display:flex; align-items:center; justify-content:space-between; gap:8px; padding:4px 8px; background:var(--color-bg-secondary); border-radius:var(--radius-sm) var(--radius-sm) 0 0; }
198
+ .log-toolbar strong { font-size:12px; color:var(--color-text-secondary); }
199
+ .log-toolbar .actions { margin:0; flex-wrap:nowrap; }
200
+ .log-panel .logs-container { margin-top:0; border-radius:0 0 var(--radius-sm) var(--radius-sm); }
201
+ .help-steps { padding:0 0 0 20px; margin:4px 0 12px; }
202
+ .help-steps li { padding:4px 0; }
203
+ .help-steps code { display:block; padding:8px; margin-top:6px; background:var(--color-bg-tertiary); border-radius:var(--radius-xs); user-select:all; }
204
+ .storage-note { padding:10px; background:var(--color-bg-brand-primary); border-radius:var(--radius-sm); }
205
+ .toast { position:fixed; bottom:16px; left:50%; transform:translateX(-50%); z-index:10; max-width:calc(100% - 32px); padding:10px 16px; background:var(--color-neutral-900); color:var(--color-white); border-radius:var(--radius-md); box-shadow:0 4px 16px #0003; font-size:13px; }
206
+ dialog { margin:auto; padding:20px; width:calc(100% - 32px); max-width:440px; border:1px solid var(--color-border-primary); border-radius:var(--radius-md); background:var(--color-bg-primary); color:var(--color-text-primary); }
207
+ dialog::backdrop { background:#0006; }
208
+ dialog h2 { font-size:16px; margin-bottom:8px; }
209
+ dialog textarea { width:100%; height:180px; margin:12px 0; padding:8px; font-family:var(--font-mono); }
210
+ dialog button { padding:8px 16px; cursor:pointer; }
211
+ .help { margin-top:12px; border-top:1px solid var(--color-border-secondary); padding-top:4px; }
212
+ .help-steps { list-style:none; counter-reset:setup; margin:6px 0 12px; padding:0; }
213
+ .help-steps li { counter-increment:setup; position:relative; padding:6px 0 12px 34px; }
214
+ .help-steps li::before { content:counter(setup); position:absolute; left:0; top:6px; width:24px; height:24px; display:grid; place-items:center; border-radius:50%; background:var(--color-bg-brand-secondary); color:var(--color-text-brand-secondary); font-size:12px; font-weight:600; }
215
+ .help-steps strong { display:block; font-size:13px; line-height:1.5; color:var(--color-text-primary); }
216
+ .help-steps p { margin-top:3px; font-size:12px; line-height:1.65; color:var(--color-text-tertiary); }
217
+ .help-steps code { font-family:var(--font-mono); font-size:12px; border:1px solid var(--color-border-secondary); background:var(--color-bg-primary); padding:9px 12px; }
218
+ .storage-note { font-size:12px; line-height:1.65; padding:8px 0; background:transparent; border-top:1px solid var(--color-border-secondary); color:var(--color-text-tertiary); }
219
+ .destination { position:relative; }
220
+ .destination-heading { padding-right:38px; min-height:28px; align-items:center; }
221
+ .retry-action { position:absolute; right:8px; top:8px; margin:0; }
222
+ #connection-actions { display:flex; align-items:center; justify-content:space-between; background:var(--color-bg-tertiary); border:1px solid var(--color-border-secondary); border-radius:var(--radius-sm); padding:4px 6px 4px 10px; margin-top:10px; }
223
+ #connection-actions code { font-family:var(--font-mono); font-size:12px; user-select:all; }
224
+ #connection-error { font-size:12px; line-height:1.6; color:var(--color-text-secondary); }
225
+ .icon-button { position:relative; }
226
+ .icon-button::after { content:attr(data-tooltip); position:absolute; right:0; bottom:calc(100% + 6px); z-index:20; width:max-content; max-width:240px; white-space:normal; text-align:left; padding:6px 9px; font-size:12px; line-height:1.4; border-radius:var(--radius-xs); background:var(--color-neutral-900); color:var(--color-white); box-shadow:0 2px 8px #0003; opacity:0; visibility:hidden; pointer-events:none; }
227
+ .icon-button:hover::after,.icon-button:focus-visible::after { opacity:1; visibility:visible; }
228
+ .retry-action .icon-button::after { bottom:auto; top:calc(100% + 6px); }
229
+ .help-command { display:flex; align-items:center; justify-content:space-between; gap:8px; margin-top:7px; padding:4px 6px 4px 10px; background:var(--color-bg-primary); border:1px solid var(--color-border-secondary); border-radius:var(--radius-sm); }
230
+ .help-command code { display:block; margin:0; padding:0; border:0; background:transparent; font-family:var(--font-mono); font-size:12px; overflow-wrap:anywhere; user-select:all; }
231
+ .help-command .icon-button { display:inline-flex; flex-shrink:0; align-items:center; justify-content:center; width:32px; height:32px; padding:0; border:0; border-radius:var(--radius-xs); background:transparent; color:var(--color-text-secondary); cursor:pointer; }
232
+ .help-command .icon-button:hover { background:var(--color-bg-tertiary); }
233
+ .help-steps { margin-bottom:8px; }
234
+ .help-steps li { padding-bottom:10px; }
235
+ .scope-label { text-transform:none; letter-spacing:0; font-size:13px; color:var(--color-text-primary); }
236
+ .export-options { display:grid; grid-template-columns:1fr; gap:5px; margin-bottom:0; }
237
+ .scale-options { display:flex; align-items:center; }
238
+ .scale-options legend { margin-right:auto; }
239
+ .force-toggle { justify-content:space-between; margin-top:8px; font-size:13px; color:var(--color-text-secondary); }
240
+ .option-hint { font-size:12px; line-height:1.5; color:var(--color-text-tertiary); margin:2px 0 6px; }
241
+ .scope-label { display:flex; align-items:center; justify-content:space-between; gap:8px; }
242
+ .help-trigger,.popover-header .icon-button { display:inline-flex; align-items:center; justify-content:center; width:32px; height:32px; border:0; border-radius:var(--radius-xs); background:transparent; color:var(--color-text-tertiary); cursor:pointer; }
243
+ .help-trigger:hover,.popover-header .icon-button:hover { background:var(--color-bg-tertiary); }
244
+ #options-help { position:fixed; inset:0; margin:auto; width:calc(100% - 32px); max-width:400px; max-height:calc(100% - 48px); overflow-y:auto; padding:14px; border:1px solid var(--color-border-primary); border-radius:var(--radius-md); background:var(--color-bg-primary); color:var(--color-text-primary); box-shadow:0 8px 30px #0003; }
245
+ .popover-header { display:flex; align-items:center; justify-content:space-between; gap:8px; }
246
+ #options-help dt { margin-top:12px; font-size:13px; font-weight:600; }
247
+ #options-help dd { margin:4px 0 0; font-size:12px; line-height:1.65; color:var(--color-text-secondary); }
248
+ body { padding:14px; line-height:1.5; }
249
+ .header { margin-bottom:14px; }
250
+ .destination { padding:10px 12px; margin-bottom:12px; }
251
+ .scope-box { padding:10px; margin-bottom:8px; }
252
+ .scope-label { padding:0 2px; margin-bottom:4px; font-weight:600; }
253
+ .radio-option { padding:9px 10px; margin-bottom:3px; border:1px solid transparent; gap:10px; }
254
+ .radio-option:has(input:checked) { background:var(--color-bg-brand-primary); border-color:var(--color-border-secondary); }
255
+ .radio-option input { flex-shrink:0; margin-top:4px; accent-color:var(--color-bg-brand-solid); }
256
+ .radio-option > div { min-width:0; }
257
+ .radio-title { font-size:13px; line-height:1.5; overflow-wrap:anywhere; font-weight:500; }
258
+ .radio-option:has(input:checked) .radio-title { font-weight:600; }
259
+ .radio-desc { line-height:1.5; margin-top:2px; color:var(--color-text-tertiary); }
260
+ .export-options { background:var(--color-bg-primary); border:1px solid var(--color-border-secondary); border-radius:var(--radius-md); padding:0 12px; gap:0; margin-top:10px; }
261
+ .scale-options { min-height:46px; }
262
+ .scale-options legend { padding:0; font-size:12px; }
263
+ .segments span { padding:6px 11px; }
264
+ .force-toggle { margin:0; min-height:46px; border-top:1px solid var(--color-border-secondary); font-size:12px; }
265
+ #force-hint:not([hidden]) { margin:6px 2px; }
266
+ #btn-export { min-height:40px; }
267
+ #options-help { padding:0; max-width:380px; box-shadow:0 12px 36px #0003; }
268
+ #options-help::backdrop { background:rgb(0 0 0 / .12); }
269
+ .popover-header { position:sticky; top:0; padding:12px 16px; background:var(--color-bg-primary); border-bottom:1px solid var(--color-border-secondary); }
270
+ .popover-header > strong { font-size:14px; }
271
+ .explain-section { margin:0 16px; padding:14px 0; }
272
+ .explain-section + .explain-section { border-top:1px solid var(--color-border-secondary); }
273
+ .explain-section h3 { font-size:13px; margin-bottom:8px; }
274
+ .explain-section p { font-size:12px; line-height:1.65; color:var(--color-text-secondary); }
275
+ .explain-list { list-style:none; padding:0; display:grid; gap:10px; }
276
+ .explain-list li { display:grid; grid-template-columns:100px 1fr; gap:10px; font-size:12px; line-height:1.6; }
277
+ .explain-list strong { font-weight:500; color:var(--color-text-primary); }
278
+ .explain-list span { color:var(--color-text-tertiary); }
279
+ .scale-explainer { display:grid; grid-template-columns:repeat(3,1fr); gap:8px; }
280
+ .scale-explainer > div { display:flex; flex-direction:column; gap:3px; padding:8px; background:var(--color-bg-secondary); border-radius:var(--radius-sm); }
281
+ .scale-explainer strong { font-size:13px; }
282
+ .scale-explainer span { font-size:12px; color:var(--color-text-tertiary); }
283
+ .explain-warning { margin-top:8px; padding:8px 10px; background:var(--color-bg-brand-primary); border-radius:var(--radius-sm); }
284
+ /* Compact controls: one hierarchy, minimal decoration. */
285
+ .destination { background:transparent; border:0; border-bottom:1px solid var(--color-border-secondary); border-radius:0; padding:0 0 12px; }
286
+ .retry-action { top:0; right:0; }
287
+ .scope-box { border:0; background:transparent; padding:0; }
288
+ .scope-label { margin-bottom:2px; }
289
+ .radio-option { padding:7px 8px; }
290
+ .radio-option:has(input:checked) { border-color:transparent; }
291
+ .export-options { display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:8px; border:0; border-top:1px solid var(--color-border-secondary); border-radius:0; padding:8px 0 0; background:transparent; margin-top:8px; }
292
+ .scale-options { min-height:34px; }
293
+ .scale-options legend { margin-right:8px; }
294
+ .force-toggle { min-height:34px; border:0; gap:8px; }
295
+ .log-panel { margin-top:10px; }
296
+ #options-help { max-width:350px; }
297
+ .popover-header { padding:10px 12px; }
298
+ .explain-section { margin:0 12px; padding:10px 0; }
299
+ .explain-list { gap:6px; }
300
+ .explain-list li { grid-template-columns:88px 1fr; gap:8px; }
301
+ .scale-explainer { display:flex; justify-content:space-between; gap:12px; }
302
+ .scale-explainer > div { padding:0; background:transparent; border-radius:0; }
303
+ .explain-warning { padding:0; background:transparent; border-radius:0; margin-top:4px; }
304
+ #force-hint { text-align:right; font-size:11px; font-style:italic; line-height:1.5; color:var(--color-text-brand-secondary); margin:6px 0 8px; }
305
+ #force-hint::before { content:"* "; font-style:normal; }
306
+ .scope-label { color:var(--color-text-brand-secondary); font-weight:700; font-size:14px; }
307
+ .scope-label > span { border-left:3px solid var(--color-bg-brand-solid); padding-left:8px; }
308
+ .scope-label { background:var(--color-bg-brand-secondary); border-radius:var(--radius-sm); padding:6px 8px; margin-bottom:6px; }
309
+ .scope-box { background:var(--color-bg-brand-primary); border:1px solid var(--color-border-secondary); border-radius:var(--radius-md); padding:10px; }
310
+ .scope-label { background:transparent; padding:0 2px; }
311
+ .radio-option:has(input:checked) { background:var(--color-bg-primary); border-color:var(--color-border-primary); }
312
+ .delivery-options { display:flex; gap:16px; border:0; padding:0; margin:10px 0 4px; }
313
+ .delivery-options legend { font-size:12px; font-weight:600; margin-bottom:6px; }
314
+ .delivery-options label { display:flex; gap:6px; align-items:center; padding:6px 0; cursor:pointer; }
315
+ #zip-download { display:block; padding:8px 0; color:var(--color-text-brand-secondary); }
316
+ </style>
317
+ </head>
318
+ <body>
319
+
320
+ <header class="header">
321
+ <h1>Figma Handoff Kit</h1>
322
+ <label class="language-toggle"><span>VI</span><input id="language-switch" type="checkbox" role="switch" aria-label="Use English"><span class="toggle-track" aria-hidden="true"></span><span>EN</span></label>
323
+ </header>
324
+ <fieldset class="delivery-options"><legend data-i18n="deliveryTitle"></legend><label><input type="radio" name="delivery" value="zip" checked><span data-i18n="deliveryZip"></span></label><label><input type="radio" name="delivery" value="local"><span data-i18n="deliveryLocal"></span></label></fieldset>
325
+ <label id="sync-control"><input type="checkbox" id="allow-sync"> <span data-i18n="allowSync"></span></label>
326
+ <p id="delivery-note" class="option-hint"></p>
327
+ <section id="local-destination" class="destination" aria-labelledby="destination-title">
328
+ <div class="destination-heading"><strong id="destination-title" data-i18n="destination">Export tới</strong><span id="server-badge" class="badge badge-offline" role="status">…</span></div>
329
+ <div id="retry-action" class="actions retry-action" hidden><button id="retry" type="button" class="icon-button" data-icon-label="retry"><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20 7v5h-5M4 17v-5h5"/><path d="M6 8a7 7 0 0 1 11-2l3 6M4 12l3 6a7 7 0 0 0 11-2"/></svg></button></div>
330
+ <strong id="project-name">…</strong>
331
+ <details class="destination-path"><summary data-i18n="pathTitle">Thư mục lưu</summary><code id="output-directory">…</code></details>
332
+ <p id="connection-error" role="status"></p>
333
+ <div class="actions" id="connection-actions" hidden><code>figma-handoff start</code><button id="copy-command" type="button" class="icon-button" data-icon-label="copyCommand"><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="8" y="8" width="12" height="12" rx="2"/><path d="M16 8V4H4v12h4"/></svg></button></div>
334
+ </section>
335
+ <div class="scope-box">
336
+ <div class="scope-label"><span data-i18n="s5">Phạm vi xuất dữ liệu (Export Scope)</span><button type="button" id="options-help-button" class="icon-button help-trigger" data-icon-label="optionsHelp" popovertarget="options-help" aria-controls="options-help" aria-expanded="false"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" aria-hidden="true"><circle cx="12" cy="12" r="9"/><path d="M9.5 9a2.5 2.5 0 0 1 5 .5c0 1.5-2.5 1.7-2.5 3.5M12 16v1"/></svg></button></div>
337
+
338
+ <label class="radio-option">
339
+ <input type="radio" name="export-scope" value="current_page" checked>
340
+ <div>
341
+ <div class="radio-title" id="page-scope-title"><span data-i18n="s6">Toàn bộ Page này</span></div>
342
+ <div class="radio-desc" id="page-scope-desc"><span data-i18n="s7">Tự động duyệt tất cả sections & screens trên page hiện tại</span></div>
343
+ </div>
344
+ </label>
345
+
346
+ <label class="radio-option">
347
+ <input type="radio" name="export-scope" value="selection">
348
+ <div>
349
+ <div class="radio-title" id="sel-scope-title"><span data-i18n="s8">Chỉ mục đang chọn trên Canvas</span></div>
350
+ <div class="radio-desc" id="sel-scope-desc"><span data-i18n="s9">Chưa chọn mục nào</span></div>
351
+ </div>
352
+ </label>
353
+
354
+ <label class="radio-option">
355
+ <input type="radio" name="export-scope" value="all_pages">
356
+ <div>
357
+ <div class="radio-title"><span data-i18n="s10">Tất cả các Pages trong file</span></div>
358
+ <div class="radio-desc" id="all-pages-desc"><span data-i18n="s11">Xuất toàn bộ project (tự động bỏ qua Trash)</span></div>
359
+ </div>
360
+ </label>
361
+ </div>
362
+
363
+ <div class="export-options">
364
+ <fieldset class="scale-options"><legend data-i18n="scaleShort">Độ nét</legend><div class="segments">
365
+ <label><input type="radio" name="scale" value="1"><span>1×</span></label>
366
+ <label><input type="radio" name="scale" value="2" checked><span>2×</span></label>
367
+ <label><input type="radio" name="scale" value="3"><span>3×</span></label>
368
+ </div></fieldset>
369
+
370
+ <label class="force-toggle" id="force-control"><span data-i18n="forceShort">Xuất lại tất cả</span><input type="checkbox" id="force-export" role="switch" aria-describedby="force-hint"><span class="toggle-track" aria-hidden="true"></span></label>
371
+ </div>
372
+ <p class="option-hint" id="force-hint" aria-live="polite"></p>
373
+ <button id="btn-export" class="btn-primary" disabled>
374
+ <span data-i18n="s17">🚀 Bắt đầu xuất sang AI Folder</span>
375
+ </button>
376
+
377
+ <a id="zip-download" hidden download="figma-handoff.zip" data-i18n="downloadReady"></a>
378
+ <p id="progress" role="status" aria-live="polite"></p>
379
+ <section class="log-panel" aria-labelledby="log-title">
380
+ <div class="log-toolbar"><strong id="log-title" data-i18n="logsTitle">Log chi tiết</strong>
381
+ <div class="actions"><button id="copy-log" type="button" class="icon-button" data-icon-label="copyLog"><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="8" y="8" width="12" height="12" rx="2"/><path d="M16 8V4H4v12h4"/></svg></button><button id="clear-log" type="button" class="icon-button" data-icon-label="clearLog"><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 6h18M9 6V3h6v3M6 6l1 15h10l1-15M10 10v7M14 10v7"/></svg></button></div>
382
+ </div>
383
+ <div class="logs-container" id="logs" role="log" aria-label="Export log" tabindex="0"></div>
384
+ </section>
385
+ <details class="help"><summary data-i18n="helpTitle">Kết nối với máy của bạn</summary>
386
+ <p data-i18n="syncHelp"></p><p data-i18n="installTitle"></p><div class="help-command"><code>npm install -g figma-handoff-kit</code><button id="copy-install" class="icon-button" type="button" data-icon-label="copyCommand">⧉</button></div><ol class="help-steps"><li><strong data-i18n="helpRunTitle"></strong><p data-i18n="helpRun"></p><div class="help-command"><code>figma-handoff start</code><button id="copy-help-command" type="button" class="icon-button" data-icon-label="copyCommand"><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="8" y="8" width="12" height="12" rx="2"/><path d="M16 8V4H4v12h4"/></svg></button></div></li><li><strong data-i18n="helpProjectTitle"></strong><p data-i18n="helpProject"></p></li><li><strong data-i18n="helpKeepTitle"></strong><p data-i18n="helpKeep"></p></li></ol>
387
+ <p class="storage-note" data-i18n="helpStorage"></p>
388
+ </details>
389
+ <div id="action-feedback" class="toast" role="status" aria-live="polite" hidden></div>
390
+ <div id="options-help" popover role="dialog" aria-labelledby="options-help-title">
391
+ <header class="popover-header"><strong id="options-help-title" data-i18n="optionsHelp"></strong><button type="button" class="icon-button" data-icon-label="closeCopy" popovertarget="options-help" popovertargetaction="hide"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" aria-hidden="true"><path d="m6 6 12 12M18 6 6 18"/></svg></button></header>
392
+ <section class="explain-section"><h3 data-i18n="s5"></h3><ul class="explain-list"><li><strong data-i18n="scopePageTitle"></strong><span data-i18n="scopePageText"></span></li><li><strong data-i18n="scopeSelectedTitle"></strong><span data-i18n="scopeSelectedText"></span></li><li><strong data-i18n="scopeAllTitle"></strong><span data-i18n="scopeAllText"></span></li></ul></section>
393
+ <section class="explain-section"><h3 data-i18n="scaleShort"></h3><div class="scale-explainer"><div><strong>1×</strong><span data-i18n="scaleOne"></span></div><div><strong>2×</strong><span data-i18n="scaleTwo"></span></div><div><strong>3×</strong><span data-i18n="scaleThree"></span></div></div></section>
394
+ <section class="explain-section"><h3 data-i18n="forceShort"></h3><p data-i18n="forceOff"></p><p class="explain-warning" data-i18n="forceOn"></p></section>
395
+ </div>
396
+ <dialog id="copy-dialog"><h2 data-i18n="manualCopyTitle"></h2><p data-i18n="manualCopyHint"></p><textarea id="manual-copy" readonly aria-label="Content to copy"></textarea><button id="close-copy" type="button" data-i18n="closeCopy"></button></dialog>
397
+
398
+ <script>
399
+ let language = "vi";
400
+ const translations = {"s0": {"vi": "💎 Figma Handoff Kit (Pixel-Perfect 100%)", "en": "💎 Figma Handoff Kit"}, "s1": {"vi": "Bóc tách toàn bộ DOM Tree, CSS chính xác & Reusable Components", "en": "Export design structure, CSS and reusable components"}, "s2": {"vi": "🎯 <strong>Pixel-Perfect (100%):</strong> Trích xuất chuẩn từng dòng CSS, flexbox, gaps, borders, shadows & nhận diện component dùng chung để Agent tái sử dụng thay vì tạo mới.", "en": "🎯 Extract CSS, layout, spacing, borders, shadows and shared components for reuse."}, "s3": {"vi": "Local Bridge Server:", "en": "Local bridge:"}, "s4": {"vi": "🔴 Đang kiểm tra...", "en": "🔴 Checking connection…"}, "s5": {"vi": "Phạm vi xuất dữ liệu (Export Scope)", "en": "Export scope"}, "s6": {"vi": "Toàn bộ Page này", "en": "Current page"}, "s7": {"vi": "Tự động duyệt tất cả sections & screens trên page hiện tại", "en": "Export sections and screens on the current page"}, "s8": {"vi": "Chỉ mục đang chọn trên Canvas", "en": "Selected items only"}, "s9": {"vi": "Chưa chọn mục nào", "en": "Nothing selected"}, "s10": {"vi": "Tất cả các Pages trong file", "en": "All pages in this file"}, "s11": {"vi": "Xuất toàn bộ project (tự động bỏ qua Trash)", "en": "Export all pages (automatically skip Trash)"}, "s12": {"vi": "Độ phân giải ảnh (Screenshot Scale):", "en": "Screenshot scale:"}, "s13": {"vi": "2x Retina (Khuyên dùng - Chuẩn nét cho Vision AI)", "en": "2x Retina (recommended for Vision AI)"}, "s14": {"vi": "1x Standard (Dung lượng nhẹ)", "en": "1x Standard (smaller files)"}, "s15": {"vi": "3x Ultra HD", "en": "3x Ultra HD"}, "s16": {"vi": "Force export (bỏ qua cache)", "en": "Force export (ignore cache)"}, "s17": {"vi": "🚀 Bắt đầu xuất sang AI Folder", "en": "🚀 Export designs"}, "s18": {"vi": "[Ready] Chờ lệnh xuất dữ liệu Pixel-Perfect...", "en": "[Ready] Waiting to export designs…"}, "s19": {"vi": "Chưa kết nối project", "en": "No project connected"}, "s20": {"vi": "Chạy <code>figma-handoff start</code> và chọn project trên cùng máy đang mở Figma Web/Desktop. Giữ Terminal chạy trong lúc export. Dữ liệu lưu local, không tải lên server cloud.", "en": "Run <code>figma-handoff start</code> and select a project on the same computer as Figma Web/Desktop. Keep the terminal running during export. Files stay on your computer; they are not uploaded to a cloud server."}, "s21": {"vi": "Thư mục lưu trên máy này:", "en": "Output directory on this computer:"}, "s22": {"vi": "Đang kết nối bridge…", "en": "Connecting to bridge…"}, "s23": {"vi": "Chưa kết nối — chạy figma-handoff start trên máy này", "en": "Disconnected — run figma-handoff start on this computer"}, "s24": {"vi": "Chưa xác định", "en": "Not available"}, "s25": {"vi": "🟢 Online (Port 3055)", "en": "🟢 Connected (port 3055)"}, "s26": {"vi": "🔴 Offline (Chạy figma-handoff start)", "en": "🔴 Offline (run figma-handoff start)"}, "s27": {"vi": "Chưa chọn mục nào trên canvas", "en": "Nothing selected on the canvas"}, "s28": {"vi": "🎉 Hoàn tất export tới thư mục đã cấu hình.", "en": "🎉 Export completed to the configured directory."}, "s29": {"vi": "Bridge change check failed; reload updated bridge.", "en": "Bridge change check failed; reload updated bridge."}};
401
+ Object.assign(translations, {
402
+ scaleShort:{vi:"Độ nét",en:"Scale"}, forceShort:{vi:"Xuất lại tất cả",en:"Re-export all"},
403
+ advancedTitle:{vi:"Tùy chọn nâng cao",en:"Advanced options"}, pathTitle:{vi:"Thư mục lưu",en:"Output directory"}, destination:{vi:"Export tới",en:"Export destination"}, retry:{vi:"Thử lại",en:"Retry"}, copyCommand:{vi:"Copy lệnh khởi động",en:"Copy start command"},
404
+ logsTitle:{vi:"Log chi tiết",en:"Detailed log"}, copyLog:{vi:"Copy log",en:"Copy log"}, clearLog:{vi:"Xóa log",en:"Clear log"}, helpTitle:{vi:"Cách kết nối và lưu dữ liệu",en:"Connection and storage help"}
405
+ });
406
+ Object.assign(translations, {
407
+ helpRunTitle:{vi:"Khởi động bridge",en:"Start the bridge"},
408
+ helpProjectTitle:{vi:"Chọn nơi lưu",en:"Choose the destination"},
409
+ helpKeepTitle:{vi:"Quay lại Figma và export",en:"Return to Figma and export"},
410
+ helpRun:{vi:"Chạy lệnh này trong Terminal trên máy đang mở Figma:",en:"Run this command in a terminal on this computer:"},
411
+ helpProject:{vi:"Chọn project trong Terminal. Kiểm tra project và thư mục đích ở đầu plugin.",en:"Select a project in the terminal. Confirm the destination at the top of this plugin."},
412
+ helpKeep:{vi:"Chờ trạng thái Đã kết nối rồi bấm Export. Giữ Terminal mở.",en:"Wait for Connected, then export. Keep the terminal open."},
413
+ helpStorage:{vi:"Lưu trên máy này • Trong thư mục đích đã chọn • Không tải lên cloud",en:"Saved locally • In your selected output directory • No cloud upload"},
414
+ manualCopyTitle:{vi:"Copy thủ công",en:"Copy manually"}, manualCopyHint:{vi:"Nội dung đã được chọn. Nhấn ⌘C trên Mac hoặc Ctrl+C trên Windows.",en:"Text is selected. Press ⌘C on Mac or Ctrl+C on Windows."}, closeCopy:{vi:"Đóng",en:"Close"}
415
+ });
416
+ translations.retry = {vi:"Thử kết nối lại với bridge",en:"Retry bridge connection"};
417
+ translations.copyCommand = {vi:"Copy lệnh khởi động bridge",en:"Copy bridge start command"};
418
+ Object.assign(translations, {
419
+ s5:{vi:"Bạn muốn export phần nào?",en:"What would you like to export?"},
420
+ s10:{vi:"Mọi trang trong file Figma",en:"Every page in this Figma file"},
421
+ scaleShort:{vi:"Kích thước ảnh",en:"Screenshot size"},
422
+ scaleHint:{vi:"1×: file nhỏ · 2×: khuyên dùng · 3×: ảnh lớn, export lâu hơn.",en:"1× smaller files · 2× recommended · 3× larger images, slower export."},
423
+ forceShort:{vi:"Xuất lại cả màn hình không đổi",en:"Include unchanged screens"}
424
+ });
425
+ Object.assign(translations, {
426
+ optionsHelp:{vi:"Giải thích tùy chọn export",en:"Export options explained"},
427
+ scopeHelp:{vi:"Trang hiện tại: chỉ trang đang mở. Mục đã chọn: chỉ section hoặc màn hình bạn chọn trên canvas. Mọi trang: toàn file, bỏ qua Trash.",en:"Current page: only the page you have open. Selected items: only sections or screens selected on the canvas. Every page: the whole file, excluding Trash."},
428
+ forceHelp:{vi:"Mặc định chỉ export màn hình mới hoặc thay đổi. Bật switch để xuất lại cả màn hình không đổi, chỉ trong phạm vi đã chọn; thao tác có thể lâu hơn.",en:"By default, only new or changed screens are exported. Turn this on to also re-export unchanged screens within your selected scope; this can take longer."},
429
+ s5:{vi:"Phạm vi export",en:"Export scope"}
430
+ });
431
+ Object.assign(translations, {
432
+ scopePageTitle:{vi:"Trang hiện tại",en:"Current page"}, scopePageText:{vi:"Màn hình trong trang đang mở.",en:"Screens on the page you have open."},
433
+ scopeSelectedTitle:{vi:"Mục đã chọn",en:"Selected items"}, scopeSelectedText:{vi:"Chỉ section hoặc màn hình bạn chọn trên canvas.",en:"Only sections or screens selected on the canvas."},
434
+ scopeAllTitle:{vi:"Mọi trang",en:"Every page"}, scopeAllText:{vi:"Toàn file Figma, bỏ qua Trash.",en:"The entire Figma file, excluding Trash."},
435
+ scaleOne:{vi:"File nhỏ",en:"Smaller files"},scaleTwo:{vi:"Khuyên dùng",en:"Recommended"},scaleThree:{vi:"Ảnh lớn hơn",en:"Larger images"},
436
+ forceOff:{vi:"Tắt: bỏ qua màn hình không thay đổi.",en:"Off: skip screens that have not changed."},
437
+ forceOn:{vi:"Xuất lại mọi màn hình trong phạm vi đã chọn, kể cả không thay đổi.",en:"On: re-export all screens in the selected scope. This can take longer."}
438
+ });
439
+ translations.scaleShort = {vi:"Ảnh",en:"Image"};
440
+ translations.forceShort = {vi:"Xuất lại tất cả",en:"Re-export all"};
441
+ translations.forceOff = {vi:"Tắt: chỉ xuất màn hình mới hoặc thay đổi.",en:"Off: export only new or changed screens."};
442
+ translations.forceOn = {vi:"Bật: xuất lại cả màn hình không đổi trong phạm vi đã chọn.",en:"On: include unchanged screens in the selected scope."};
443
+ Object.assign(translations, {
444
+ deliveryTitle:{vi:"Lưu thiết kế",en:"Save designs"},deliveryZip:{vi:"Tải ZIP",en:"Download ZIP"},deliveryLocal:{vi:"Lưu vào project",en:"Save to project"},
445
+ installTitle:{vi:"Cài CLI một lần (Node.js 20+)",en:"Install the CLI once (Node.js 20+)"}, downloadReady:{vi:"Tải file ZIP",en:"Download ZIP file"}
446
+ });
447
+ translations.syncHelp = {vi:"Để sync từ terminal: bật Cho phép CLI sync, giữ plugin và bridge đang mở rồi chạy figma-handoff sync. Lệnh kiểm tra mọi trang ở 2×, bỏ qua màn hình không đổi. Tắt tùy chọn để ngắt quyền sync; bật lại sau mỗi lần khởi động.",en:"To sync from terminal: enable Allow CLI sync, keep the plugin and bridge open, then run figma-handoff sync. It checks all pages at 2× and skips unchanged screens. Disable the option to revoke sync; enable it again after restarting."};
448
+ translations.allowSync = {vi:"Cho phép CLI sync toàn file này (2×)",en:"Allow CLI sync for this file (all pages, 2×)"};
449
+ translations.helpTitle = {vi:"Kết nối với máy của bạn",en:"Connect to your computer"};
450
+ translations.s17 = {vi:"Export thiết kế",en:"Export designs"};
451
+ const exact = Object.fromEntries(Object.values(translations).map(v => [v.vi, v.en]));
452
+ const logEntries = [];
453
+ function translate(value) {
454
+ if (language === "vi") {
455
+ const errors = {
456
+ "Upload failed or timed out; export stopped.": "Gửi dữ liệu lỗi hoặc quá hạn; đã dừng export.",
457
+ "Notes upload failed or timed out; export stopped.": "Gửi ghi chú lỗi hoặc quá hạn; đã dừng export.",
458
+ "Change check timed out": "Kiểm tra thay đổi quá hạn.",
459
+ "Bridge change check failed; reload updated bridge.": "Không kiểm tra được thay đổi; hãy khởi động lại bridge bản mới."
460
+ };
461
+ return errors[value] || value;
462
+ }
463
+ if (exact[value]) return exact[value];
464
+ const patterns = [
465
+ [/^Toàn bộ Page '(.*)'$/, (_, name) => `Page: ${name}`],
466
+ [/^Gồm ~(\d+) sections và ~(\d+) màn hình$/, (_, sections, screens) => `About ${sections} sections and ${screens} screens`],
467
+ [/^Mục đang chọn: (.*)$/, (_, name) => `Selected: ${name}`],
468
+ [/^Quét toàn bộ (\d+) pages trong dự án$/, (_, count) => `Scan all ${count} pages in this file`],
469
+ [/^📝 Đã lưu notes: (.*)$/, (_, name) => `📝 Notes saved: ${name}`],
470
+ [/^❌ Lỗi lưu notes: (.*)$/, (_, error) => `❌ Could not save notes: ${error}`],
471
+ [/^💾 Đang lưu: (.*?) \((\d+) files:.*$/, (_, name, count) => `💾 Saving: ${name} (${count} files)…`],
472
+ [/^✅ Đã lưu xong (.*)$/, (_, name) => `✅ Saved: ${name}`],
473
+ [/^❌ Server lỗi khi lưu: (.*)$/, (_, name) => `❌ Server could not save: ${name}`],
474
+ [/^❌ Lỗi gửi file: (.*)$/, (_, error) => `❌ Upload failed: ${error}`],
475
+ [/^🚀 Bắt đầu xuất theo chế độ: \[(.*)\].*$/, (_, scope) => `🚀 Starting export: ${scope}. Keep the Figma window open.`],
476
+ [/^⏭ Không đổi: (.*)$/, (_, name) => `⏭ Unchanged: ${name}`],
477
+ [/^📸 Render ảnh 2x Retina & trích xuất SVGs, Images, CSS 100%: (.*)$/, (_, name) => `📸 Rendering screenshot and extracting assets/CSS: ${name}`],
478
+ [/^🚀 Đang quét toàn bộ Page '(.*)'\.\.\.$/, (_, name) => `🚀 Scanning page: ${name}…`],
479
+ [/^📁 Đang xử lý Page: (.*)$/, (_, name) => `📁 Processing page: ${name}`],
480
+ [/^📥 Đang tải tất cả các pages trong document\.\.\.$/, () => '📥 Loading all pages…']
481
+ ];
482
+ for (const [pattern, replacement] of patterns) if (pattern.test(value)) return value.replace(pattern, replacement);
483
+ return value;
484
+ }
485
+ function appendLog(entry) {
486
+ const follow = logs.scrollHeight - logs.scrollTop - logs.clientHeight < 32;
487
+ const div = document.createElement("div");
488
+ div.className = `log-entry log-${entry.type}`;
489
+ div.textContent = translate(entry.value);
490
+ logs.appendChild(div);
491
+ if (logs.children.length > 1000) logs.firstChild.remove();
492
+ if (follow) logs.scrollTop = logs.scrollHeight;
493
+ }
494
+ function renderLogs() {
495
+ const position = logs.scrollTop;
496
+ logs.replaceChildren();
497
+ for (const entry of logEntries) appendLog(entry);
498
+ logs.scrollTop = position;
499
+ }
500
+ const stats = { checked:0, saved:0, skipped:0 };
501
+ let phase = "ready";
502
+ const words = (vi,en) => language === "vi" ? vi : en;
503
+ function renderOptionHint() {
504
+ document.getElementById("force-hint").hidden = delivery !== "local";
505
+ document.getElementById("force-hint").textContent = document.getElementById("force-export").checked
506
+ ? words("Xuất lại mọi màn hình trong phạm vi đã chọn, kể cả không thay đổi.", "Re-exports every screen in the selected scope, including unchanged screens.")
507
+ : words("Tự động bỏ qua màn hình đã export nếu không thay đổi.", "Previously exported screens are automatically skipped if unchanged.");
508
+ }
509
+ function renderProgress() {
510
+ const labels = {ready:words("Sẵn sàng","Ready"),checking:words("Đang kiểm tra…","Checking…"),exporting:words("Đang export…","Exporting…"),done:words("Hoàn tất","Completed"),error:words("Export dừng do lỗi","Export stopped with an error")};
511
+ document.getElementById("progress").hidden = phase === "ready";
512
+ document.getElementById("progress").textContent = `${labels[phase]} · ${stats.checked} ${words("đã kiểm tra","checked")} · ${stats.saved} ${words("đã lưu","saved")} · ${stats.skipped} ${words("bỏ qua","skipped")}`;
513
+ btnExport.textContent = isExporting ? labels[phase] : words("Export thiết kế","Export designs");
514
+ btnExport.setAttribute("aria-busy", String(isExporting));
515
+ }
516
+ function setLanguage(value) {
517
+ language = value === "en" ? "en" : "vi";
518
+ document.documentElement.lang = language;
519
+ document.getElementById("language-switch").checked = language === "en";
520
+ document.querySelectorAll("[data-i18n]").forEach(el => { el.innerHTML = translations[el.dataset.i18n][language]; });
521
+ document.querySelectorAll("[data-icon-label]").forEach(el => {
522
+ const label = translations[el.dataset.iconLabel][language];
523
+ el.removeAttribute("title");
524
+ el.setAttribute("aria-label", label);
525
+ el.dataset.tooltip = label;
526
+ });
527
+ document.getElementById("force-export").setAttribute("aria-label", words("Xuất lại mọi màn hình, kể cả không thay đổi", "Re-export every screen, including unchanged screens"));
528
+ document.querySelector(".force-toggle").title = words("Bật để bỏ qua cache. Mặc định chỉ xuất màn hình mới hoặc thay đổi.", "Enable to ignore cache. By default, only new or changed screens are exported.");
529
+ renderOptionHint();
530
+ if (currentStatus) renderStatus();
531
+ renderLogs();
532
+ renderProgress();
533
+ renderDelivery();
534
+ document.getElementById('sync-control').title = words('Giữ plugin và bridge đang mở. figma-handoff sync xuất toàn bộ trang ở 2×, bỏ qua màn hình không đổi.','Keep the plugin and bridge open. figma-handoff sync exports all pages at 2× and skips unchanged screens.');
535
+ checkServer();
536
+ }
537
+ let syncToken = null, documentId = null, syncJob = null;
538
+ async function syncRequest(route, extra={}) {
539
+ const response = await fetch(BRIDGE_URL+route,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({project_id:projectId,documentId,token:syncToken,...extra}),signal:AbortSignal.timeout(4000)});
540
+ const data = await response.json(); if(!response.ok) throw new Error(data.error || 'Sync failed'); return data;
541
+ }
542
+ async function disableSync() {
543
+ if(syncToken) {
544
+ try { await syncRequest('/sync/unpair'); } catch(error) { toast(error.message); }
545
+ }
546
+ syncToken=null;
547
+ document.getElementById('allow-sync').checked=false;
548
+ }
549
+ async function finishSync(error) {
550
+ if(!syncJob) return;
551
+ const jobId=syncJob;syncJob=null;
552
+ try { await syncRequest('/sync/result',{jobId,error,stats:{...stats}}); } catch(e) {addLog(e.message,'error');}
553
+ }
554
+ let delivery = "zip";
555
+ let exportDelivery = "zip";
556
+ const zipFiles = new Map();
557
+ let zipURL;
558
+ // ZIP STORE: UTF-8 names, CRC32, no compression or external CDN/runtime dependency.
559
+ function makeZip(entries) {
560
+ const encoder = new TextEncoder();
561
+ const locals = [], central = []; let offset = 0;
562
+ const crc32 = data => { let crc = -1; for (const byte of data) { crc ^= byte; for(let i=0;i<8;i++) crc = (crc >>> 1) ^ ((crc & 1) ? 0xedb88320 : 0); } return (crc ^ -1) >>> 0; };
563
+ const header = length => new Uint8Array(length);
564
+ for (const [path,data] of entries) {
565
+ const name = encoder.encode(path); const crc = crc32(data);
566
+ const local = header(30); const l = new DataView(local.buffer);
567
+ l.setUint32(0,0x04034b50,true); l.setUint16(4,20,true); l.setUint16(6,0x800,true); l.setUint16(12,33,true); l.setUint32(14,crc,true); l.setUint32(18,data.length,true); l.setUint32(22,data.length,true); l.setUint16(26,name.length,true);
568
+ const record = header(46); const c = new DataView(record.buffer);
569
+ c.setUint32(0,0x02014b50,true); c.setUint16(4,20,true); c.setUint16(6,20,true); c.setUint16(8,0x800,true); c.setUint16(14,33,true); c.setUint32(16,crc,true); c.setUint32(20,data.length,true); c.setUint32(24,data.length,true); c.setUint16(28,name.length,true); c.setUint32(42,offset,true);
570
+ locals.push(local,name,data); central.push(record,name); offset += local.length + name.length + data.length;
571
+ }
572
+ const centralSize = central.reduce((sum,b)=>sum+b.length,0); const end = header(22);const e = new DataView(end.buffer);
573
+ if(entries.size > 65535 || offset + centralSize > 0xffffffff) throw new Error("ZIP too large; export a smaller selection.");
574
+ e.setUint32(0,0x06054b50,true); e.setUint16(8,entries.size,true); e.setUint16(10,entries.size,true); e.setUint32(12,centralSize,true); e.setUint32(16,offset,true);
575
+ return new Blob([...locals,...central,end],{type:"application/zip"});
576
+ }
577
+ const zipName = value => String(value || "unnamed").replace(/[\\/*?:"<>|]/g,"_").replace(/^\.+$/, "_").trim() || "unnamed";
578
+ function addZipFiles(msg, files) {
579
+ const nodes = msg.node_path.map(n => `${zipName(n.name)}--${zipName(n.id)}`);
580
+ const folder = [zipName(msg.document.name) + "--" + zipName(msg.document.id), ...nodes].join("/");
581
+ for(const file of files) {
582
+ const bytes = file.type === "base64" ? Uint8Array.from(atob(file.content), c=>c.charCodeAt(0)) : new TextEncoder().encode(file.content);
583
+ zipFiles.set(folder + "/" + file.name.split("/").map(zipName).join("/"), bytes);
584
+ }
585
+ }
586
+ function renderDelivery() {
587
+ document.getElementById("sync-control").hidden = delivery !== "local";
588
+ if(delivery !== "local" && syncToken) void disableSync();
589
+ document.getElementById("local-destination").hidden = delivery !== "local";
590
+ document.querySelector(".help").hidden = delivery !== "local";
591
+ document.getElementById("force-control").hidden = delivery !== "local";
592
+ document.getElementById("delivery-note").textContent = delivery === "zip"
593
+ ? words("Không cần CLI. Tải ZIP rồi giải nén vào project. Mỗi lần xuất tạo ZIP mới.","No CLI needed. Download and extract into your project. Each export creates a new ZIP.")
594
+ : words("Cài CLI và chạy bridge trên máy này để lưu trực tiếp, tự bỏ qua màn hình không đổi.","Install the CLI and run the bridge on this computer to save directly and skip unchanged screens.");
595
+ renderOptionHint(); updateButtonState();
596
+ }
597
+ const BRIDGE_URL = "http://localhost:3055";
598
+ let isServerOnline = false;
599
+ let projectId = null;
600
+ let exportProjectId = null;
601
+ let currentStatus = null;
602
+ let isExporting = false;
603
+ let activeRunId = null;
604
+
605
+ const serverBadge = document.getElementById("server-badge");
606
+ const pageScopeTitle = document.getElementById("page-scope-title");
607
+ const pageScopeDesc = document.getElementById("page-scope-desc");
608
+ const selScopeTitle = document.getElementById("sel-scope-title");
609
+ const selScopeDesc = document.getElementById("sel-scope-desc");
610
+ const allPagesDesc = document.getElementById("all-pages-desc");
611
+ const btnExport = document.getElementById("btn-export");
612
+ const logs = document.getElementById("logs");
613
+
614
+
615
+ function getSelectedScope() {
616
+ const radios = document.getElementsByName("export-scope");
617
+ for (const r of radios) {
618
+ if (r.checked) return r.value;
619
+ }
620
+ return "current_page";
621
+ }
622
+
623
+ function addLog(text, type = "info") {
624
+ const entry = { value: text, type };
625
+ logEntries.push(entry);
626
+ if (logEntries.length > 1000) logEntries.shift();
627
+ appendLog(entry);
628
+ }
629
+
630
+ async function checkServer() {
631
+ try {
632
+ const res = await fetch(`${BRIDGE_URL}/health`, { method: "GET", signal: AbortSignal.timeout(4000) });
633
+ if (res.ok) {
634
+ const health = await res.json();
635
+ if (health.protocol_version !== 1) throw new Error("VERSION_MISMATCH");
636
+ projectId = health.project_id;
637
+ document.getElementById("project-name").textContent = translate(`Project: ${health.project_name || health.project_id}`);
638
+ document.getElementById("output-directory").textContent = health.exports_dir;
639
+ document.getElementById("connection-error").textContent = "";
640
+ document.getElementById("connection-actions").hidden = true;
641
+ document.getElementById("retry-action").hidden = true;
642
+ document.getElementById("project-name").hidden = false;
643
+ document.querySelector(".destination-path").hidden = false;
644
+ isServerOnline = true;
645
+ serverBadge.className = "badge badge-online";
646
+ serverBadge.innerText = words("Đã kết nối", "Connected");
647
+ } else {
648
+ throw new Error(`HTTP ${res.status}`);
649
+ }
650
+ } catch (err) {
651
+ document.getElementById("connection-error").textContent = err.message === "VERSION_MISMATCH"
652
+ ? words("Bridge khác phiên bản. Dừng bridge và chạy lại figma-handoff start.","Bridge version mismatch. Stop it and rerun figma-handoff start.")
653
+ : words("Chạy lệnh bên dưới trên máy này để kết nối. Nếu bridge đã chạy, kiểm tra quyền truy cập mạng local.","Start the bridge on this computer using the command below. If it is running, check local-network permissions.") + (err.message.startsWith("HTTP") ? ` (${err.message})` : "");
654
+ document.getElementById("connection-actions").hidden = false;
655
+ document.getElementById("retry-action").hidden = false;
656
+ document.getElementById("project-name").hidden = true;
657
+ document.querySelector(".destination-path").hidden = true;
658
+ isServerOnline = false;
659
+ document.getElementById("project-name").textContent = translate("Chưa kết nối — chạy figma-handoff start trên máy này");
660
+ document.getElementById("output-directory").textContent = translate("Chưa xác định");
661
+ serverBadge.className = "badge badge-offline";
662
+ serverBadge.innerText = words("Chưa kết nối", "Disconnected");
663
+ }
664
+ updateButtonState();
665
+ }
666
+
667
+ function renderStatus() {
668
+ pageScopeTitle.innerText = words(`Trang hiện tại: ${currentStatus.currentPageName}`, `Current page: ${currentStatus.currentPageName}`);
669
+ pageScopeDesc.innerText = translate(`Gồm ~${currentStatus.pageSections} sections và ~${currentStatus.pageScreens} màn hình`);
670
+
671
+ if (currentStatus.hasSelection) {
672
+ selScopeTitle.innerText = words(`Chỉ mục đã chọn: ${currentStatus.selectionName}`, `Selected items only: ${currentStatus.selectionName}`);
673
+ selScopeDesc.innerText = translate(`Gồm ~${currentStatus.selectionSections} sections và ~${currentStatus.selectionScreens} màn hình`);
674
+ } else {
675
+ selScopeTitle.innerText = translate("Chỉ mục đang chọn trên Canvas");
676
+ selScopeDesc.innerText = translate("Chưa chọn mục nào trên canvas");
677
+ }
678
+
679
+ allPagesDesc.innerText = words(`Kiểm tra ${currentStatus.totalPages} trang; bỏ qua Trash. Phạm vi lớn nhất.`, `Check ${currentStatus.totalPages} pages; skip Trash. Largest scope.`);
680
+ }
681
+
682
+ function updateButtonState() {
683
+ const scope = getSelectedScope();
684
+ if (isExporting) { btnExport.disabled = true; return; }
685
+ if (delivery === "local" && !isServerOnline) {
686
+ btnExport.disabled = true;
687
+ return;
688
+ }
689
+ if (scope === "selection" && (!currentStatus || !currentStatus.hasSelection)) {
690
+ btnExport.disabled = true;
691
+ return;
692
+ }
693
+ btnExport.disabled = false;
694
+ }
695
+
696
+ document.querySelectorAll("input[name='export-scope']").forEach(r => {
697
+ r.addEventListener("change", updateButtonState);
698
+ });
699
+
700
+ function setControlsDisabled(disabled) {
701
+ document.querySelectorAll("input[name=delivery], input[name='export-scope'], input[name=scale], #force-export").forEach(el => { el.disabled = disabled; });
702
+ }
703
+ let toastTimer;
704
+ function toast(message) {
705
+ const el = document.getElementById("action-feedback");
706
+ clearTimeout(toastTimer);
707
+ el.textContent = message;
708
+ el.hidden = false;
709
+ toastTimer = setTimeout(() => { el.hidden = true; }, 3000);
710
+ }
711
+ function legacyCopy(value) {
712
+ const previous = document.activeElement;
713
+ const field = document.createElement("textarea");
714
+ field.value = value;
715
+ field.style.cssText = "position:fixed;left:0;top:0;opacity:0;width:1px;height:1px";
716
+ document.body.appendChild(field);
717
+ field.focus(); field.select();
718
+ let copied = false;
719
+ try { copied = document.execCommand("copy"); } catch {}
720
+ field.remove(); previous?.focus();
721
+ return copied;
722
+ }
723
+ async function copyText(value) {
724
+ if (!value) { toast(words("Chưa có log để copy.","No log entries to copy.")); return; }
725
+ // Synchronous fallback preserves the click gesture in Figma's sandboxed iframe.
726
+ let copied = legacyCopy(value);
727
+ if (!copied && navigator.clipboard?.writeText) {
728
+ try { await navigator.clipboard.writeText(value); copied = true; } catch {}
729
+ }
730
+ if (copied) { toast(words("Đã copy vào clipboard.","Copied to clipboard.")); return; }
731
+ const dialog = document.getElementById("copy-dialog");
732
+ const field = document.getElementById("manual-copy");
733
+ field.value = value;
734
+ dialog.showModal(); field.focus(); field.select();
735
+ }
736
+ document.getElementById("close-copy").onclick = () => document.getElementById("copy-dialog").close();
737
+ document.getElementById("options-help").addEventListener("toggle", event => {
738
+ document.getElementById("options-help-button").setAttribute("aria-expanded", String(event.newState === "open"));
739
+ if (event.newState === "closed" && document.activeElement === document.body) document.getElementById("options-help-button").focus();
740
+ });
741
+ document.getElementById("force-export").addEventListener("change", renderOptionHint);
742
+ document.querySelectorAll("input[name=delivery]").forEach(el => el.addEventListener("change", () => { delivery = el.value; renderDelivery(); }));
743
+ document.getElementById("copy-install").onclick = () => copyText("npm install -g figma-handoff-kit");
744
+ document.getElementById("retry").onclick = checkServer;
745
+ document.getElementById("copy-command").onclick = () => copyText("figma-handoff start");
746
+ document.getElementById("copy-help-command").onclick = () => copyText("figma-handoff start");
747
+ document.getElementById("copy-log").onclick = () => copyText(logEntries.map(e => translate(e.value)).join("\n"));
748
+ document.getElementById("clear-log").onclick = () => { logEntries.length = 0; logs.replaceChildren(); };
749
+ document.getElementById("language-switch").addEventListener("change", event => {
750
+ setLanguage(event.target.checked ? "en" : "vi");
751
+ parent.postMessage({ pluginMessage: { type: "SET_LANGUAGE", language } }, "*");
752
+ });
753
+ logEntries.push({ value: "[Ready] Chờ lệnh xuất dữ liệu Pixel-Perfect...", type: "info" });
754
+ setLanguage("vi");
755
+ setInterval(checkServer, 5000);
756
+
757
+ // Reliable upload helper with retry
758
+ async function uploadPayloadWithRetry(endpoint, bodyObj, retries = 2) {
759
+ for (let attempt = 1; attempt <= retries; attempt++) {
760
+ try {
761
+ const res = await fetch(`${BRIDGE_URL}${endpoint}`, {
762
+ method: "POST",
763
+ headers: { "Content-Type": "application/json" },
764
+ signal: AbortSignal.timeout(60000),
765
+ body: JSON.stringify({ ...bodyObj, project_id: exportProjectId })
766
+ });
767
+ if (res.ok) return true;
768
+ const failure = await res.json().catch(() => ({}));
769
+ throw new Error(failure.error || `HTTP ${res.status}`);
770
+ } catch (e) {
771
+ if (attempt === retries) throw e;
772
+ await new Promise(r => setTimeout(r, 1000));
773
+ }
774
+ }
775
+ return false;
776
+ }
777
+
778
+ window.onmessage = async (event) => {
779
+ const msg = event.data.pluginMessage;
780
+ if (!msg) return;
781
+ if (!["LANGUAGE", "STATUS_UPDATE", "DOCUMENT_ID"].includes(msg.type) && (!isExporting || msg.runId !== activeRunId)) return;
782
+
783
+ if (msg.type === "DOCUMENT_ID") { documentId=msg.documentId; return; }
784
+ if (msg.type === "LANGUAGE") { setLanguage(msg.language); }
785
+ else if (msg.type === "CHECK_SCREEN") {
786
+ if (exportDelivery === "zip") {
787
+ stats.checked++; renderProgress();
788
+ parent.postMessage({pluginMessage:{type:"CHECK_RESULT",hash:"",unchanged:false}},"*");
789
+ return;
790
+ }
791
+ phase = "checking"; renderProgress();
792
+ try {
793
+ const canonical = value => Array.isArray(value) ? value.map(canonical) : value && typeof value === "object" ? Object.fromEntries(Object.keys(value).sort().map(key => [key, canonical(value[key])])) : value;
794
+ const snapshot = JSON.stringify(canonical(JSON.parse(msg.snapshot)));
795
+ const response = await fetch(`${BRIDGE_URL}/check`, {
796
+ method: "POST", headers: { "Content-Type": "application/json" },
797
+ body: JSON.stringify({ project_id: exportProjectId, document: msg.document, node_path: msg.node_path, snapshot })
798
+ });
799
+ if (!response.ok) throw new Error("Bridge change check failed; reload updated bridge.");
800
+ const result = await response.json();
801
+ if (!result.hash) throw new Error(words("Cần cập nhật bridge để tính hash. Khởi động lại CLI bản mới.", "Update the bridge to support hashing, then restart the CLI."));
802
+ stats.checked++;
803
+ if (result.unchanged && !document.getElementById("force-export").checked) stats.skipped++;
804
+ renderProgress();
805
+ parent.postMessage({ pluginMessage: { type: "CHECK_RESULT", hash: result.hash, unchanged: result.unchanged } }, "*");
806
+ } catch (error) {
807
+ parent.postMessage({ pluginMessage: { type: "CHECK_RESULT", error: error.message } }, "*");
808
+ }
809
+ }
810
+ else if (msg.type === "STATUS_UPDATE") {
811
+ currentStatus = msg.data;
812
+ renderStatus();
813
+ updateButtonState();
814
+ }
815
+
816
+ else if (msg.type === "PROGRESS_UPDATE") {
817
+ addLog(msg.message, "info");
818
+ }
819
+
820
+ else if (msg.type === "UPLOAD_NOTES") {
821
+ if(exportDelivery === "zip") {
822
+ try { addZipFiles(msg,[{name:"flow_notes.md",content:msg.content}]); parent.postMessage({pluginMessage:{type:"SCREEN_UPLOAD_ACK",success:true}},"*"); }
823
+ catch(error) { addLog(error.message,"error"); parent.postMessage({pluginMessage:{type:"SCREEN_UPLOAD_ACK",success:false}},"*"); }
824
+ return;
825
+ }
826
+ let success = false;
827
+ try {
828
+ success = await uploadPayloadWithRetry("/save-notes", {
829
+ folder_path: msg.folder_path,
830
+ document: msg.document,
831
+ node_path: msg.node_path,
832
+ filename: "flow_notes.md",
833
+ content: msg.content
834
+ });
835
+ if (success) addLog(`📝 Đã lưu notes: ${msg.folder_path.join(" / ")}`, "success");
836
+ } catch (e) {
837
+ addLog(`❌ Lỗi lưu notes: ${e.message}`, "error");
838
+ } finally {
839
+ parent.postMessage({ pluginMessage: { type: "SCREEN_UPLOAD_ACK", success: success } }, "*");
840
+ }
841
+ }
842
+
843
+ else if (msg.type === "UPLOAD_SCREEN_BATCH") {
844
+ if(exportDelivery === "zip") {
845
+ try { addZipFiles(msg,msg.files); stats.saved++; renderProgress(); addLog(`✅ Đã lưu xong ${msg.screen_name}`,"success"); parent.postMessage({pluginMessage:{type:"SCREEN_UPLOAD_ACK",success:true}},"*"); }
846
+ catch(error) { addLog(error.message,"error"); parent.postMessage({pluginMessage:{type:"SCREEN_UPLOAD_ACK",success:false}},"*"); }
847
+ return;
848
+ }
849
+ phase = "exporting"; renderProgress();
850
+ addLog(`💾 Đang lưu: ${msg.screen_name} (${msg.files.length} files: 100% CSS, DOM tree, Tokens, SVGs/PNGs)...`, "info");
851
+ let success = false;
852
+ try {
853
+ const payload = {
854
+ folder_path: msg.folder_path,
855
+ document: msg.document,
856
+ node_path: msg.node_path,
857
+ content_hash: msg.content_hash,
858
+ files: msg.files
859
+ };
860
+
861
+ success = await uploadPayloadWithRetry("/save", payload, 2);
862
+ if (success) {
863
+ stats.saved++; renderProgress();
864
+ addLog(`✅ Đã lưu xong ${msg.screen_name}`, "success");
865
+ } else {
866
+ addLog(`❌ Server lỗi khi lưu: ${msg.screen_name}`, "error");
867
+ }
868
+ } catch (e) {
869
+ addLog(`❌ Lỗi gửi file: ${e.message}`, "error");
870
+ } finally {
871
+ // Always send ACK back to code.js so it can proceed sequentially to the next screen!
872
+ parent.postMessage({ pluginMessage: { type: "SCREEN_UPLOAD_ACK", success: success } }, "*");
873
+ }
874
+ }
875
+
876
+ else if (msg.type === "EXPORT_ERROR") {
877
+ finishSync(msg.message);
878
+ addLog(msg.message, "error");
879
+ isExporting = false;
880
+ phase = msg.type === "EXPORT_ERROR" ? "error" : "done";
881
+ renderProgress();
882
+ setControlsDisabled(false);
883
+ updateButtonState();
884
+ }
885
+
886
+ else if (msg.type === "EXPORT_FINISHED") {
887
+ finishSync();
888
+ if(exportDelivery === "zip") {
889
+ try {
890
+ if (!zipFiles.size) throw new Error(words("Không có màn hình để xuất.","No screens to export."));
891
+ if(zipURL) URL.revokeObjectURL(zipURL);
892
+ zipURL = URL.createObjectURL(makeZip(zipFiles));
893
+ const link = document.getElementById("zip-download"); link.href = zipURL; link.hidden = false; link.click();
894
+ } catch(error) { addLog(error.message,"error"); isExporting=false; phase="error"; setControlsDisabled(false);renderProgress();updateButtonState();return; }
895
+ finally { zipFiles.clear(); }
896
+ }
897
+ addLog(exportDelivery === "zip" ? words("ZIP sẵn sàng. Bấm Tải file ZIP nếu chưa tải tự động.","ZIP ready. Click Download ZIP file if the download did not start.") : "🎉 Hoàn tất export tới thư mục đã cấu hình.", "success");
898
+ isExporting = false;
899
+ phase = msg.type === "EXPORT_ERROR" ? "error" : "done";
900
+ renderProgress();
901
+ setControlsDisabled(false);
902
+ updateButtonState();
903
+ }
904
+ };
905
+
906
+ function startExport(fromSync=false) {
907
+ if (isExporting || (!fromSync && btnExport.disabled)) return;
908
+ // Figma iframe environments may not expose the secure-context randomUUID API.
909
+ activeRunId = `export-${Date.now()}-${Math.random().toString(36).slice(2)}`;
910
+ exportDelivery = delivery;
911
+ zipFiles.clear();
912
+ if (zipURL) { URL.revokeObjectURL(zipURL); zipURL = null; }
913
+ document.getElementById("zip-download").hidden = true;
914
+ isExporting = true;
915
+ stats.checked = stats.saved = stats.skipped = 0;
916
+ phase = "checking";
917
+ renderProgress();
918
+ setControlsDisabled(true);
919
+ btnExport.disabled = true;
920
+ const scope = fromSync ? "all_pages" : getSelectedScope();
921
+ const scale = fromSync ? 2 : Number(document.querySelector("input[name=scale]:checked").value);
922
+ addLog(`🚀 Bắt đầu xuất theo chế độ: [${scope}]... Vui lòng không đóng cửa sổ Figma.`, "info");
923
+ exportProjectId = projectId;
924
+ parent.postMessage({ pluginMessage: { type: "START_EXPORT", runId: activeRunId, scope: scope, scale: scale, force: fromSync ? false : document.getElementById("force-export").checked } }, "*");
925
+ };
926
+ btnExport.onclick = event => { if(event.isTrusted) startExport(); };
927
+ parent.postMessage({pluginMessage:{type:'GET_DOCUMENT'}},'*');
928
+ document.getElementById('allow-sync').onchange = async event => {
929
+ if(!event.target.checked) { await disableSync(); return; }
930
+ try {
931
+ if(!documentId || !isServerOnline || delivery!=='local') throw new Error(words('Chọn lưu vào project và kết nối trước.','Connect to a project first.'));
932
+ const paired=await syncRequest('/sync/pair');syncToken=paired.token;
933
+ } catch(error) {event.target.checked=false;toast(error.message);}
934
+ };
935
+ let syncPolling=false;
936
+ setInterval(async()=>{
937
+ if(!syncToken || syncPolling || delivery!=='local') return;
938
+ syncPolling=true;
939
+ try { const result=await syncRequest('/sync/poll'); if(result.job) { if(isExporting) await syncRequest('/sync/result',{jobId:result.job.id,error:'Plugin is already exporting; retry after it finishes.'}); else {syncJob=result.job.id;startExport(true);} } }
940
+ catch(error) {syncToken=null;document.getElementById('allow-sync').checked=false;toast(error.message);}
941
+ finally {syncPolling=false;}
942
+ },2000);
943
+ </script>
944
+ </body>
945
+ </html>