image-optimizer-webui 1.1.0__py3-none-any.whl

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,3066 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Image Optimizer</title>
7
+ <link rel="icon" href="/favicon.ico">
8
+ <style>
9
+ :root {
10
+ --bg: #f5f2ed;
11
+ --surface: #ffffff;
12
+ --surface2: #f0ece6;
13
+ --border: #d9d3cb;
14
+ --text: #3d3833;
15
+ --text2: #8a8580;
16
+ --accent: #588b8b;
17
+ --accent2: #4a7a7a;
18
+ --green: #7a9e7e;
19
+ --red: #c96b6b;
20
+ --yellow: #d4a85c;
21
+ --radius: 8px;
22
+ --shadow: 0 1px 6px rgba(0,0,0,.08);
23
+ }
24
+ /* Dark palette. green/red/yellow stay identical across themes so the
25
+ status colors read the same; surfaces, text, and accent shift to
26
+ cooler slate tones for better contrast and a less muddy feel.
27
+ Applied via data-theme="dark" (manual toggle) OR, when the user
28
+ hasn't explicitly chosen a theme (no data-theme attribute), via the OS
29
+ prefers-color-scheme media query below. */
30
+ :root[data-theme="dark"] {
31
+ --bg: #1a1d21;
32
+ --surface: #25292e;
33
+ --surface2: #32383e;
34
+ --border: #454c54;
35
+ --text: #eaecf0;
36
+ --text2: #8e95a0;
37
+ --accent: #62a3a3;
38
+ --accent2: #559494;
39
+ --shadow: 0 1px 6px rgba(0,0,0,.35);
40
+ }
41
+ @media (prefers-color-scheme: dark) {
42
+ :root:not([data-theme]) {
43
+ --bg: #1a1d21;
44
+ --surface: #25292e;
45
+ --surface2: #32383e;
46
+ --border: #454c54;
47
+ --text: #eaecf0;
48
+ --text2: #8e95a0;
49
+ --accent: #62a3a3;
50
+ --accent2: #559494;
51
+ --shadow: 0 1px 6px rgba(0,0,0,.35);
52
+ }
53
+ }
54
+ * { margin:0; padding:0; box-sizing:border-box; }
55
+ body {
56
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Noto Sans SC", sans-serif;
57
+ background: var(--bg);
58
+ color: var(--text);
59
+ min-height: 100vh;
60
+ font-size: 14px;
61
+ line-height: 1.5;
62
+ }
63
+ ::-webkit-scrollbar { width: 6px; }
64
+ ::-webkit-scrollbar-track { background: var(--surface); }
65
+ ::-webkit-scrollbar-thumb { background: var(--border); border-radius: 3px; }
66
+
67
+ /* Header */
68
+ header {
69
+ background: var(--surface);
70
+ border-bottom: 1px solid var(--border);
71
+ padding: 16px 24px;
72
+ display: flex;
73
+ align-items: center;
74
+ justify-content: space-between;
75
+ }
76
+ header h1 { font-size: 20px; font-weight: 700; }
77
+ header h1 span { color: var(--accent); }
78
+ .header-right { display: flex; align-items: center; gap: 16px; font-size: 13px; color: var(--text2); }
79
+ .status-dot {
80
+ display: inline-block; width: 8px; height: 8px; border-radius: 50%;
81
+ margin-right: 6px;
82
+ }
83
+ .status-dot.ok { background: var(--green); }
84
+ .status-dot.warn { background: var(--yellow); }
85
+ .status-dot.err { background: var(--red); }
86
+ .theme-toggle {
87
+ background: var(--bg); border: 1px solid var(--border); color: var(--text2);
88
+ border-radius: var(--radius); cursor: pointer; padding: 6px 10px; font-size: 15px;
89
+ line-height: 1; transition: all .15s;
90
+ }
91
+ .theme-toggle:hover { border-color: var(--accent); color: var(--text); }
92
+
93
+ #notice-container {
94
+ position: fixed; top: 16px; right: 16px; z-index: 1000;
95
+ display: flex; flex-direction: column; gap: 8px; max-width: 380px;
96
+ }
97
+ .notice {
98
+ background: var(--surface); border: 1px solid var(--border); border-left: 4px solid var(--text2);
99
+ border-radius: var(--radius); padding: 12px 16px; box-shadow: var(--shadow);
100
+ font-size: 13px; color: var(--text); display: flex; align-items: flex-start; gap: 10px;
101
+ animation: notice-in .2s ease-out;
102
+ }
103
+ .notice.err { border-left-color: var(--red); }
104
+ .notice.ok { border-left-color: var(--green); }
105
+ .notice.info { border-left-color: var(--accent); }
106
+ .notice-msg { flex: 1; }
107
+ .notice-close { cursor: pointer; color: var(--text2); font-size: 16px; line-height: 1; background: none; border: none; padding: 0; }
108
+ .notice-close:hover { color: var(--text); }
109
+ @keyframes notice-in { from { opacity: 0; transform: translateY(-6px); } to { opacity: 1; transform: translateY(0); } }
110
+
111
+ .recent-chips { display: flex; flex-wrap: wrap; gap: 6px; margin: -6px 0 12px; }
112
+ .recent-chips:empty { margin: 0; }
113
+ .recent-chip {
114
+ font-size: 12px; padding: 4px 10px; border-radius: 999px; cursor: pointer;
115
+ background: var(--bg); border: 1px solid var(--border); color: var(--text2);
116
+ max-width: 260px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
117
+ transition: all .15s;
118
+ }
119
+ .recent-chip:hover { border-color: var(--accent); color: var(--text); background: var(--surface); }
120
+
121
+ /* Main Layout */
122
+ .container {
123
+ max-width: 1680px; margin: 0 auto; padding: 20px 24px;
124
+ display: grid; grid-template-columns: 380px 1fr 340px; gap: 20px; align-items: start;
125
+ }
126
+ .app-sidebar {
127
+ display: flex; flex-direction: column; gap: 20px; position: sticky; top: 20px;
128
+ max-height: calc(100vh - 40px); overflow-y: auto;
129
+ }
130
+ .app-main { display: flex; flex-direction: column; gap: 20px; min-width: 0; }
131
+ .app-right {
132
+ display: flex; flex-direction: column; gap: 20px; position: sticky; top: 20px;
133
+ }
134
+ /* Between 1000-1300px there's no room for a true third column, so Watch
135
+ Mode drops to a full-width row under Settings/Files instead of getting
136
+ squeezed into a column that's too narrow for its inputs. */
137
+ @media (max-width: 1300px) {
138
+ .container { grid-template-columns: 380px 1fr; }
139
+ .app-sidebar { position: static; }
140
+ .app-right { grid-column: 1 / -1; position: static; }
141
+ }
142
+ @media (max-width: 1000px) {
143
+ .container { display: flex; flex-direction: column; }
144
+ .app-sidebar, .app-right { position: static; }
145
+ }
146
+
147
+ .card {
148
+ background: var(--surface);
149
+ border: 1px solid var(--border);
150
+ border-radius: var(--radius);
151
+ padding: 20px;
152
+ }
153
+
154
+ .card-title {
155
+ font-size: 13px; font-weight: 600; text-transform: uppercase; letter-spacing: 1px;
156
+ color: var(--text2); margin-bottom: 14px;
157
+ }
158
+
159
+ /* Input Section */
160
+ .input-row { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 14px; }
161
+ .input-row input[type="text"] {
162
+ flex: 1 1 100%; padding: 10px 14px; background: var(--bg); border: 1px solid var(--border);
163
+ border-radius: var(--radius); color: var(--text); font-size: 14px; outline: none;
164
+ transition: border-color .2s;
165
+ }
166
+ .input-row input[type="text"]:focus { border-color: var(--accent); }
167
+ .btn {
168
+ padding: 10px 20px; border: none; border-radius: var(--radius); cursor: pointer;
169
+ font-size: 14px; font-weight: 500; transition: all .2s; white-space: nowrap;
170
+ }
171
+ .btn-primary { background: var(--accent); color: #000; }
172
+ .btn-primary:hover { background: var(--accent2); }
173
+ .btn-primary:disabled { opacity: .4; cursor: not-allowed; }
174
+ .btn-secondary { background: var(--surface2); color: var(--text); border: 1px solid var(--border); }
175
+ .btn-secondary:hover { background: var(--border); }
176
+ .btn-danger { background: var(--red); color: #fff; }
177
+ .btn-danger:hover { opacity: .8; }
178
+
179
+ /* Config */
180
+ .config-grid { display: flex; gap: 24px; flex-wrap: wrap; }
181
+ /* width: 100% is deliberate, not decorative: without it each group is a
182
+ flex item sized by flex-basis:auto, which considers the *max-content*
183
+ width of everything inside it, including any hidden-by-default child
184
+ that later becomes visible (this bit us once already — a conditional
185
+ note inside the Compression Mode group whose un-wrapped text was wider
186
+ than the panel, which pulled the whole group, mode buttons included,
187
+ wider whenever it showed). Pinning the group to 100% of the row gives
188
+ it a definite width up front, so nothing inside it can ever expand it
189
+ again; content just wraps/fits within that fixed width instead. */
190
+ .config-group { display: flex; flex-direction: column; gap: 6px; width: 100%; }
191
+ .config-group label { font-size: 12px; color: var(--text2); text-transform: uppercase; letter-spacing: .5px; }
192
+ .config-group select, .config-group input[type="number"] {
193
+ padding: 8px 12px; background: var(--bg); border: 1px solid var(--border);
194
+ border-radius: var(--radius); color: var(--text); font-size: 14px; outline: none;
195
+ min-width: 140px;
196
+ }
197
+ .config-group select:focus, .config-group input:focus { border-color: var(--accent); }
198
+ /* Same visual language as .config-group select (border/background/color
199
+ all theme-aware) but scaled down for the compact preset-controls row it
200
+ lives in, which isn't itself a .config-group. Without this it fell back
201
+ to the browser's unstyled native <select> appearance — stark white in
202
+ dark mode, and visually inconsistent with every other control either way. */
203
+ .custom-preset-select {
204
+ padding: 4px 8px; background: var(--bg); border: 1px solid var(--border);
205
+ border-radius: var(--radius); color: var(--text); font-size: 12px; outline: none;
206
+ max-width: 180px;
207
+ }
208
+ .custom-preset-select:focus { border-color: var(--accent); }
209
+ .config-group input[type="text"] {
210
+ padding: 8px 12px; background: var(--bg); border: 1px solid var(--border);
211
+ border-radius: var(--radius); color: var(--text); font-size: 14px; outline: none;
212
+ min-width: 180px;
213
+ }
214
+ .config-group.disabled-group, .radio-group.disabled-group { opacity: .45; }
215
+ .radio-group { display: flex; gap: 4px; background: var(--bg); border-radius: var(--radius); padding: 3px; }
216
+ .radio-group label {
217
+ padding: 6px 16px; border-radius: 5px; cursor: pointer; font-size: 13px;
218
+ color: var(--text2); transition: all .2s; user-select: none;
219
+ }
220
+ .radio-group input { display: none; }
221
+ /* Selection is shown by background contrast alone, not font-weight — a
222
+ bolder font is measurably wider than regular weight for the same
223
+ string, so toggling it on :checked shifted layout around it (most
224
+ visibly in #mode-group's 2-column grid below: selecting "Screenshot"
225
+ widened its column and shoved the other pill wider too). Background
226
+ + white text already reads clearly as "selected" without that risk. */
227
+ .radio-group input:checked + label { background: var(--accent); color: #000; }
228
+ /* Compression Mode has 4 options and two of them ("Resize Only",
229
+ "Screenshot") are long enough to overflow a single flex row inside the
230
+ 380px sidebar. Lay it out as a self-contained 2x2 grid instead so it
231
+ never depends on how much space the row happens to have.
232
+ minmax(0, 1fr) (rather than plain 1fr) keeps both columns strictly
233
+ equal-width regardless of label length, instead of a grid column's
234
+ default min-width:auto letting its widest cell's content dictate the
235
+ column's minimum size — belt-and-suspenders against the same class of
236
+ shift the font-weight fix above addresses, e.g. for a future
237
+ translation whose mode names vary more in length than en/zh do. */
238
+ #mode-group {
239
+ display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 6px;
240
+ }
241
+ #mode-group label {
242
+ padding: 8px 10px; text-align: center;
243
+ }
244
+ .check-row {
245
+ display: flex; align-items: center; gap: 6px; font-size: 13px; cursor: pointer;
246
+ user-select: none; padding: 8px 0;
247
+ }
248
+
249
+ /* File List */
250
+ .file-stats { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; font-size: 13px; color: var(--text2); gap: 12px; flex-wrap: wrap; }
251
+ .file-stats select {
252
+ padding: 4px 8px; background: var(--bg); border: 1px solid var(--border);
253
+ border-radius: var(--radius); color: var(--text); font-size: 12px; outline: none;
254
+ }
255
+ .file-stats select:focus { border-color: var(--accent); }
256
+ .file-grid {
257
+ display: grid; grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); gap: 10px;
258
+ max-height: 360px; overflow-y: auto; align-items: start;
259
+ }
260
+ .file-card {
261
+ background: var(--bg); border: 1px solid var(--border); border-radius: var(--radius);
262
+ padding: 8px; cursor: pointer; transition: all .2s;
263
+ }
264
+ .file-card:hover { border-color: var(--accent); }
265
+ .file-card.selected { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent); }
266
+ /* .fc-main wraps everything that isn't the (optional) override panel, and
267
+ is the positioning context for the check/gear/preview-btn overlays —
268
+ scoping them here (instead of to .file-card) means opening the override
269
+ panel below can never cover them, since they're absolutely positioned
270
+ relative to this box, not the taller card. */
271
+ .file-card .fc-main { position: relative; }
272
+ .file-card .thumb {
273
+ width: 100%; aspect-ratio: 16/10; object-fit: cover; border-radius: 4px;
274
+ background: #222; display: block;
275
+ }
276
+ .file-card .fname {
277
+ font-size: 12px; margin-top: 6px; overflow: hidden; text-overflow: ellipsis;
278
+ white-space: nowrap;
279
+ }
280
+ /* fsize + preview-btn share one row so the button can never ride up over
281
+ .fname above it (it did when it was absolutely positioned off the
282
+ bottom of .fc-main, which floated at a fixed offset regardless of how
283
+ tall the content above actually was) — same line, same baseline, always
284
+ bottom-aligned with the size text by construction. */
285
+ .file-card .fmeta { display: flex; align-items: center; justify-content: space-between; gap: 6px; margin-top: 2px; }
286
+ .file-card .fsize {
287
+ font-size: 11px; color: var(--text2); flex: 1; min-width: 0;
288
+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
289
+ }
290
+ .file-card .check {
291
+ position: absolute; top: 4px; right: 4px; width: 18px; height: 18px;
292
+ border-radius: 50%; background: rgba(0,0,0,.6); border: 2px solid rgba(255,255,255,.3);
293
+ display: flex; align-items: center; justify-content: center;
294
+ font-size: 11px; color: transparent; transition: all .2s;
295
+ }
296
+ .file-card.selected .check { background: var(--accent); border-color: var(--accent); color: #000; }
297
+ .file-card .preview-btn {
298
+ font-size: 10px; padding: 2px 6px; border-radius: 4px; flex-shrink: 0;
299
+ border: 1px solid var(--border); background: var(--card); color: var(--text2);
300
+ cursor: pointer; white-space: nowrap; transition: opacity .15s;
301
+ opacity: 0;
302
+ }
303
+ .file-card:hover .preview-btn, .file-card .preview-btn:not(:disabled) { opacity: .9; }
304
+ .file-card .preview-btn:hover { opacity: 1; border-color: var(--accent); color: var(--accent); }
305
+ .file-card .preview-btn:disabled { cursor: default; opacity: .8; }
306
+ .file-card .card-gear {
307
+ position: absolute; top: 4px; left: 4px;
308
+ font-size: 12px; width: 20px; height: 20px; line-height: 18px;
309
+ border-radius: 50%; border: 1px solid var(--border); background: rgba(0,0,0,.5);
310
+ color: var(--text2); cursor: pointer; padding: 0; opacity: 0; transition: opacity .15s;
311
+ }
312
+ .file-card:hover .card-gear { opacity: .85; }
313
+ .file-card .card-gear:hover { opacity: 1; color: var(--accent); border-color: var(--accent); }
314
+ .file-card.has-override .card-gear { opacity: 1; color: var(--accent); border-color: var(--accent); }
315
+ /* Normal-flow block below .fc-main (not an absolute overlay) — opening it
316
+ grows the card's own height instead of covering fsize/preview-btn, which
317
+ both live inside .fc-main above it. */
318
+ .file-card .file-override {
319
+ margin-top: 6px; border-top: 1px solid var(--border);
320
+ padding-top: 4px; font-size: 10px; display: flex; flex-direction: column; gap: 2px;
321
+ }
322
+ /* The panel's own `hidden` attribute must beat the `display:flex` above —
323
+ otherwise the panel is force-shown and the gear toggle can't hide it. */
324
+ .file-card .file-override[hidden] { display: none; }
325
+ .file-card .fo-row { display: flex; align-items: center; gap: 4px; }
326
+ .file-card .fo-label { width: 42px; color: var(--text2); flex-shrink: 0; }
327
+ .file-card .fo-row select, .file-card .fo-row input {
328
+ flex: 1; min-width: 0; font-size: 10px; padding: 1px 2px;
329
+ background: var(--bg); color: var(--text); border: 1px solid var(--border); border-radius: 3px;
330
+ }
331
+ .file-list-empty {
332
+ text-align: center; padding: 30px; color: var(--text2); white-space: nowrap;
333
+ }
334
+
335
+ /* Progress */
336
+ .progress-bar {
337
+ height: 6px; background: var(--bg); border-radius: 3px; overflow: hidden; margin-bottom: 12px;
338
+ }
339
+ .progress-bar-fill {
340
+ height: 100%; background: linear-gradient(90deg, var(--accent), var(--green));
341
+ border-radius: 3px; transition: width .3s; width: 0%;
342
+ }
343
+ .progress-info { display: flex; justify-content: space-between; font-size: 13px; color: var(--text2); margin-bottom: 10px; }
344
+ .log-box {
345
+ background: var(--bg); border-radius: var(--radius); padding: 12px 16px;
346
+ max-height: 240px; overflow-y: auto; font-family: "Cascadia Code", "Fira Code", "JetBrains Mono", monospace;
347
+ font-size: 12px; line-height: 1.7;
348
+ }
349
+ .log-entry { color: var(--text2); }
350
+ .log-entry.ok { color: var(--green); }
351
+ .log-entry.err { color: var(--red); }
352
+ .log-entry.info { color: var(--accent); }
353
+
354
+ /* Results */
355
+ .result-summary {
356
+ display: flex; gap: 24px; margin-bottom: 16px; flex-wrap: wrap;
357
+ }
358
+ .result-toolbar {
359
+ display: flex; gap: 12px; flex-wrap: wrap; align-items: center; margin-bottom: 12px;
360
+ }
361
+ .result-toolbar label { font-size: 12px; color: var(--text2); }
362
+ .result-toolbar select {
363
+ padding: 6px 10px; background: var(--bg); border: 1px solid var(--border);
364
+ border-radius: var(--radius); color: var(--text); font-size: 13px; outline: none;
365
+ }
366
+ .result-toolbar select:focus { border-color: var(--accent); }
367
+ .result-toolbar .count { font-size: 12px; color: var(--text2); margin-left: auto; }
368
+ .result-stat { text-align: center; min-width: 100px; }
369
+ .result-stat .value { font-size: 24px; font-weight: 700; }
370
+ .result-stat .value.green { color: var(--green); }
371
+ .result-stat .value.accent { color: var(--accent); }
372
+ .result-stat .label { font-size: 12px; color: var(--text2); margin-top: 2px; }
373
+
374
+ .result-grid {
375
+ display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 10px;
376
+ max-height: 400px; overflow-y: auto;
377
+ }
378
+ .result-card {
379
+ background: var(--bg); border: 1px solid var(--border); border-radius: var(--radius);
380
+ padding: 10px; transition: all .2s;
381
+ }
382
+ .result-card:hover { border-color: var(--accent); }
383
+ .result-card .thumb {
384
+ width: 100%; aspect-ratio: 16/10; object-fit: cover; border-radius: 4px;
385
+ background: #222; display: block;
386
+ }
387
+ .result-card .rname { font-size: 12px; margin-top: 6px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
388
+ .result-card .rstats { font-size: 11px; color: var(--text2); margin-top: 2px; }
389
+ .result-card .rsaved { font-size: 13px; font-weight: 600; color: var(--green); margin-top: 4px; }
390
+ .result-card .compare-btn {
391
+ display: inline-block; margin-top: 6px; padding: 4px 12px; font-size: 11px;
392
+ background: var(--surface2); color: var(--accent); border: 1px solid var(--border);
393
+ border-radius: 4px; cursor: pointer; text-decoration: none; transition: all .2s;
394
+ }
395
+ .result-card .compare-btn:hover { background: var(--border); }
396
+
397
+ /* Sections visibility */
398
+ .section { display: none; }
399
+ .section.active { display: block; }
400
+
401
+ /* Action bar */
402
+ .action-bar { display: flex; gap: 10px; align-items: center; }
403
+ .action-bar .btn { flex-shrink: 0; }
404
+ .action-bar .spacer { flex: 1; }
405
+
406
+ /* Watch Mode */
407
+ .watch-status { font-size: 13px; color: var(--text2); padding: 4px 0; }
408
+ .watch-log-box {
409
+ background: var(--bg); border-radius: var(--radius); padding: 10px 14px;
410
+ max-height: 180px; overflow-y: auto; font-family: "Cascadia Code", "Fira Code", monospace;
411
+ font-size: 12px; line-height: 1.7; margin-top: 8px;
412
+ }
413
+
414
+ /* Settings panel */
415
+ .settings-btn {
416
+ background: var(--bg); border: 1px solid var(--border); color: var(--text2);
417
+ border-radius: var(--radius); cursor: pointer; padding: 6px 10px; font-size: 15px;
418
+ line-height: 1; transition: all .15s;
419
+ }
420
+ .settings-btn:hover { border-color: var(--accent); color: var(--text); }
421
+ .settings-overlay {
422
+ display: none; position: fixed; inset: 0; background: rgba(0,0,0,.35);
423
+ z-index: 900; align-items: center; justify-content: center;
424
+ }
425
+ .settings-overlay.open { display: flex; }
426
+ .settings-panel {
427
+ background: var(--surface); border-radius: var(--radius); box-shadow: 0 8px 30px rgba(0,0,0,.18);
428
+ width: 420px; max-width: 92vw; max-height: 85vh; overflow-y: auto; padding: 24px;
429
+ }
430
+ .settings-panel h2 { font-size: 16px; font-weight: 700; margin-bottom: 16px; display: flex; align-items: center; justify-content: space-between; }
431
+ .settings-panel h2 button { background: none; border: none; font-size: 18px; cursor: pointer; color: var(--text2); padding: 2px 6px; }
432
+ .settings-panel h2 button:hover { color: var(--text); }
433
+ .settings-field { margin-bottom: 14px; }
434
+ .settings-field label { display: block; font-size: 12px; font-weight: 600; color: var(--text2); margin-bottom: 4px; }
435
+ .settings-field input, .settings-field select {
436
+ width: 100%; padding: 7px 10px; border: 1px solid var(--border); border-radius: var(--radius);
437
+ background: var(--bg); color: var(--text); font-size: 13px; font-family: inherit;
438
+ }
439
+ .settings-field input:focus, .settings-field select:focus { outline: none; border-color: var(--accent); }
440
+ .settings-field .field-hint { font-size: 11px; color: var(--text2); margin-top: 2px; }
441
+ .settings-actions { display: flex; gap: 8px; justify-content: flex-end; margin-top: 18px; }
442
+ .settings-actions .btn { padding: 7px 18px; font-size: 13px; }
443
+
444
+ /* Responsive */
445
+ @media (max-width: 640px) {
446
+ .container { padding: 12px; }
447
+ .input-row { flex-direction: column; }
448
+ .config-grid { flex-direction: column; }
449
+ .file-grid { grid-template-columns: repeat(auto-fill, minmax(100px, 1fr)); }
450
+ }
451
+ </style>
452
+ </head>
453
+ <body>
454
+
455
+ <header>
456
+ <h1 style="display:flex;align-items:center;gap:10px"><svg width="28" height="28" viewBox="0 0 256 256" xmlns="http://www.w3.org/2000/svg"><rect x="20" y="20" width="216" height="216" rx="34" fill="#588b8b"/><path d="M64 176 L118 106 L152 142 L184 96 L216 176 Z" fill="#f5f2ed"/><circle cx="86" cy="80" r="18" fill="#f5f2ed"/></svg><span data-i18n="app.title">Image Optimizer</span></h1>
457
+ <div class="header-right">
458
+ <span id="health-status"><span class="status-dot warn"></span><span id="health-status-text" data-i18n="health.checking">Checking...</span></span>
459
+ <span id="workspace-info"></span>
460
+ <button class="settings-btn" id="settings-btn" data-i18n-title="header.settingsTitle" title="Settings" aria-label="Open settings">&#9881;</button>
461
+ <button class="theme-toggle" id="theme-toggle" data-i18n-title="header.themeToggleTitle" title="Toggle light / dark theme" aria-label="Toggle theme"></button>
462
+ </div>
463
+ </header>
464
+
465
+ <!-- Settings modal -->
466
+ <div class="settings-overlay" id="settings-overlay">
467
+ <div class="settings-panel">
468
+ <h2><span data-i18n="settings.title">Settings</span> <button id="settings-close" aria-label="Close settings">&times;</button></h2>
469
+ <div class="settings-field">
470
+ <label for="setting-language" data-i18n="settings.language">Language</label>
471
+ <select id="setting-language">
472
+ <option value="en">English</option>
473
+ <option value="zh">中文</option>
474
+ </select>
475
+ <div class="field-hint" data-i18n="settings.languageHint">Applies immediately</div>
476
+ </div>
477
+ <div class="settings-field">
478
+ <label for="setting-host" data-i18n="settings.host">Host</label>
479
+ <input type="text" id="setting-host" placeholder="127.0.0.1">
480
+ <div class="field-hint" data-i18n="settings.restartHint">Requires restart to take effect</div>
481
+ </div>
482
+ <div class="settings-field">
483
+ <label for="setting-port" data-i18n="settings.port">Port</label>
484
+ <input type="number" id="setting-port" min="1" max="65535" placeholder="8090">
485
+ <div class="field-hint" data-i18n="settings.restartHint">Requires restart to take effect</div>
486
+ </div>
487
+ <div class="settings-field">
488
+ <label for="setting-concurrent-workers" data-i18n="settings.concurrentWorkers">Concurrent Workers</label>
489
+ <input type="number" id="setting-concurrent-workers" min="1" placeholder="4">
490
+ <div class="field-hint" data-i18n="settings.concurrentWorkersHint">Number of images compressed in parallel. Requires restart</div>
491
+ </div>
492
+ <div class="settings-field">
493
+ <label for="setting-thumbnail-workers" data-i18n="settings.thumbnailWorkers">Thumbnail Workers</label>
494
+ <input type="number" id="setting-thumbnail-workers" min="1" placeholder="4">
495
+ <div class="field-hint" data-i18n="settings.thumbnailWorkersHint">Number of thumbnails generated in parallel. Requires restart</div>
496
+ </div>
497
+ <div class="settings-field">
498
+ <label for="setting-cleanup-delay" data-i18n="settings.cleanupDelay">Workspace Cleanup Delay (seconds)</label>
499
+ <input type="number" id="setting-cleanup-delay" min="0" step="0.5" placeholder="10">
500
+ </div>
501
+ <div class="settings-field">
502
+ <label for="setting-idle-timeout" data-i18n="settings.idleTimeout">Session Idle Timeout (hours)</label>
503
+ <input type="number" id="setting-idle-timeout" min="0" step="0.5" placeholder="4">
504
+ </div>
505
+ <div class="settings-actions">
506
+ <button class="btn" id="settings-cancel" style="background:var(--surface2)" data-i18n="settings.cancel">Cancel</button>
507
+ <button class="btn" id="settings-save" style="background:var(--accent);color:#fff" data-i18n="settings.save">Save</button>
508
+ </div>
509
+ </div>
510
+ </div>
511
+
512
+ <!-- Themed prompt/confirm/alert modal — replaces window.prompt/confirm/alert,
513
+ which render as an unstyled native browser dialog ("127.0.0.1:8090
514
+ says") that doesn't match the app's look. Reuses the exact same
515
+ .settings-overlay/.settings-panel classes as the Settings modal above
516
+ for visual consistency, rather than a one-off style. -->
517
+ <div class="settings-overlay" id="app-dialog-overlay">
518
+ <div class="settings-panel" style="width:340px">
519
+ <h2><span id="app-dialog-title"></span></h2>
520
+ <div class="settings-field" id="app-dialog-input-field" style="display:none">
521
+ <input type="text" id="app-dialog-input">
522
+ </div>
523
+ <div id="app-dialog-message" style="font-size:13px;color:var(--text);margin-bottom:4px;display:none"></div>
524
+ <div class="settings-actions">
525
+ <button class="btn" id="app-dialog-cancel" style="background:var(--surface2)" data-i18n="dialog.cancel">Cancel</button>
526
+ <button class="btn" id="app-dialog-ok" style="background:var(--accent);color:#fff" data-i18n="dialog.ok">OK</button>
527
+ </div>
528
+ </div>
529
+ </div>
530
+
531
+ <div id="notice-container"></div>
532
+
533
+ <!-- Batch resume banner -->
534
+ <div id="batch-resume-banner" style="display:none;background:rgba(230,180,60,0.1);border:1px solid rgba(230,180,60,0.3);color:var(--text);border-radius:8px;padding:12px 20px;margin:0 24px;align-items:center;gap:12px;font-size:14px">
535
+ <span id="batch-resume-text"></span>
536
+ <div style="margin-left:auto;display:flex;gap:8px">
537
+ <button class="btn btn-primary btn-sm" id="batch-resume-btn" style="padding:4px 16px;font-size:13px" data-i18n="common.resume">Resume</button>
538
+ <button class="btn btn-secondary btn-sm" id="batch-dismiss-btn" style="padding:4px 12px;font-size:13px" data-i18n="common.dismiss">Dismiss</button>
539
+ </div>
540
+ </div>
541
+
542
+ <div class="container">
543
+
544
+ <div class="app-sidebar">
545
+
546
+ <!-- Input Section -->
547
+ <div class="card" id="input-section">
548
+ <div class="card-title" data-i18n="input.title">Source Path</div>
549
+ <div class="input-row">
550
+ <input type="text" id="dir-path" data-i18n-placeholder="input.dirPlaceholder" placeholder="Folder path to scan, e.g. D:\screenshots" />
551
+ <button class="btn btn-primary" id="scan-btn" data-i18n="input.scanBtn">Scan Folder</button>
552
+ <button class="btn btn-secondary" id="browse-folder-btn" data-i18n="common.browseFolder">Browse Folder...</button>
553
+ <button class="btn btn-secondary" id="browse-files-btn" data-i18n="input.browseFilesBtn">Browse Files...</button>
554
+ </div>
555
+ <div class="recent-chips" id="recent-scan-dirs"></div>
556
+ <div id="scan-progress-wrap" style="display:none;margin-bottom:12px">
557
+ <div class="progress-bar" style="margin-bottom:6px"><div class="progress-bar-fill" id="scan-progress-fill"></div></div>
558
+ <div style="font-size:12px;color:var(--text2)" id="scan-progress-text"></div>
559
+ </div>
560
+ <div style="margin-bottom:12px;display:flex;align-items:center;gap:8px;font-size:13px">
561
+ <label style="cursor:pointer;user-select:none;display:flex;align-items:center;gap:4px">
562
+ <input type="checkbox" id="recursive-scan" /> <span data-i18n="common.includeSubfolders">Include subfolders</span>
563
+ </label>
564
+ </div>
565
+ <input type="file" id="file-input" accept="image/png,image/jpeg,image/bmp,image/tiff,image/webp" multiple style="display:none" />
566
+ </div>
567
+
568
+ <!-- Target Path -->
569
+ <div class="card" id="output-section">
570
+ <div class="card-title" data-i18n="output.title">Output Path (optional)</div>
571
+ <div class="input-row">
572
+ <input type="text" id="output-dir" data-i18n-placeholder="output.placeholder" placeholder="Type or paste the output folder path, or leave empty for temp folder" />
573
+ <button class="btn btn-secondary" id="output-browse-btn" data-i18n="common.browseFolder">Browse Folder...</button>
574
+ </div>
575
+ <div class="recent-chips" id="recent-output-dirs"></div>
576
+ <label class="check-row" style="margin-top:8px;cursor:pointer;user-select:none;font-size:13px;display:flex;align-items:center;gap:4px"
577
+ data-i18n-title="output.skipExistingTitle"
578
+ title="When re-running against the same output folder, files already optimized there are reused instead of being recompressed. Only applies when an output folder is set.">
579
+ <input type="checkbox" id="skip-existing" /> <span data-i18n="output.skipExisting">Skip files already in the output folder</span>
580
+ </label>
581
+ <label class="check-row" style="margin-top:8px;cursor:pointer;user-select:none;font-size:13px;display:flex;align-items:center;gap:4px"
582
+ data-i18n-title="output.keepExifTitle"
583
+ title="Keep a curated subset of EXIF metadata (camera make/model, date, exposure) in the output. GPS coordinates, Orientation (already baked into the pixels), and bulky MakerNote are dropped. Off by default; turn on only if you need the metadata preserved.">
584
+ <input type="checkbox" id="keep-exif" /> <span data-i18n="output.keepExif">Keep EXIF metadata (camera info, date; GPS stripped)</span>
585
+ </label>
586
+ </div>
587
+
588
+ </div>
589
+
590
+ <div class="app-main">
591
+
592
+ <!-- File List -->
593
+ <div class="card" id="files-section">
594
+ <div class="card-title" data-i18n="files.title">Files</div>
595
+ <div class="file-stats">
596
+ <span id="file-stats-text"></span>
597
+ <span style="display:flex;align-items:center;gap:10px">
598
+ <label for="file-sort" style="font-size:12px" data-i18n="common.sort">Sort</label>
599
+ <select id="file-sort">
600
+ <option value="default" data-i18n="files.sort.default">Scan order</option>
601
+ <option value="mtime_desc" data-i18n="files.sort.mtimeDesc">Modified (newest first)</option>
602
+ <option value="mtime_asc" data-i18n="files.sort.mtimeAsc">Modified (oldest first)</option>
603
+ <option value="ctime_desc" data-i18n="files.sort.ctimeDesc">Created (newest first)</option>
604
+ <option value="ctime_asc" data-i18n="files.sort.ctimeAsc">Created (oldest first)</option>
605
+ <option value="size_desc" data-i18n="files.sort.sizeDesc">Size (large to small)</option>
606
+ <option value="size_asc" data-i18n="files.sort.sizeAsc">Size (small to large)</option>
607
+ </select>
608
+ <label style="font-size:13px;cursor:pointer;user-select:none">
609
+ <input type="checkbox" id="select-all" checked /> <span data-i18n="files.selectAll">Select all</span>
610
+ </label>
611
+ </span>
612
+ </div>
613
+ <div id="files-empty" style="font-size:13px;color:var(--text2);padding:0 0 16px" data-i18n="files.empty">Images will appear here after you scan a folder or add files</div>
614
+ <div class="file-grid" id="file-grid"></div>
615
+ </div>
616
+
617
+ <!-- Progress -->
618
+ <div class="card" id="progress-section">
619
+ <div class="card-title" data-i18n="progress.title">Progress</div>
620
+ <div class="progress-bar"><div class="progress-bar-fill" id="progress-fill"></div></div>
621
+ <div class="progress-info">
622
+ <span id="progress-text" data-i18n="progress.waiting">Waiting...</span>
623
+ <span>
624
+ <button class="btn btn-secondary btn-sm" id="pause-btn" style="display:none;padding:4px 12px;font-size:12px" data-i18n-title="progress.pauseTitle" title="Pause: stop starting new files (in-flight ones finish). Click Resume to continue." data-i18n="common.pause">Pause</button>
625
+ <button class="btn btn-primary btn-sm" id="resume-btn" style="display:none;padding:4px 12px;font-size:12px" data-i18n="common.resume">Resume</button>
626
+ <button class="btn btn-danger btn-sm" id="cancel-btn" style="display:none;padding:4px 12px;font-size:12px" data-i18n="common.cancel">Cancel</button>
627
+ </span>
628
+ </div>
629
+ <div class="log-box" id="log-box"></div>
630
+ </div>
631
+
632
+ <!-- Results -->
633
+ <div class="card" id="results-section">
634
+ <div class="card-title" data-i18n="results.title">Results</div>
635
+ <div id="results-empty" style="font-size:13px;color:var(--text2);padding:0 0 16px" data-i18n="results.empty">No results yet, run Start to see compressed files</div>
636
+ <div class="result-summary" id="result-summary"></div>
637
+ <div class="action-bar" style="margin-bottom:12px">
638
+ <span id="output-path-info" style="font-size:12px;color:var(--text2)"></span>
639
+ <div class="spacer"></div>
640
+ <button class="btn btn-secondary" id="retry-btn" style="display:none" data-i18n="results.retry">Retry Failed</button>
641
+ <button class="btn btn-secondary" id="reveal-dir-btn" style="display:none" data-i18n-title="results.revealTitle" title="Open the output folder in the OS file explorer" data-i18n="results.reveal">Reveal Output Folder</button>
642
+ <button class="btn btn-primary" id="download-btn" style="display:none" data-i18n="results.download">Download All (ZIP)</button>
643
+ <button class="btn btn-secondary" id="reset-btn" data-i18n="common.reset">Reset</button>
644
+ </div>
645
+ <div class="result-toolbar" id="result-toolbar" style="display:none">
646
+ <label for="result-sort" data-i18n="common.sort">Sort</label>
647
+ <select id="result-sort">
648
+ <option value="default" data-i18n="results.sort.default">Completion order</option>
649
+ <option value="savings_desc" data-i18n="results.sort.savingsDesc">Compression % (high to low)</option>
650
+ <option value="savings_asc" data-i18n="results.sort.savingsAsc">Compression % (low to high)</option>
651
+ <option value="size_desc" data-i18n="results.sort.sizeDesc">Compressed size (large to small)</option>
652
+ <option value="saved_desc" data-i18n="results.sort.savedDesc">Bytes saved (most first)</option>
653
+ </select>
654
+ <label for="result-filter" data-i18n="results.show">Show</label>
655
+ <select id="result-filter">
656
+ <option value="all" data-i18n="results.filter.all">All</option>
657
+ <option value="success" data-i18n="results.filter.success">Succeeded only</option>
658
+ <option value="failed" data-i18n="results.filter.failed">Failed only</option>
659
+ </select>
660
+ <span class="count" id="result-count"></span>
661
+ </div>
662
+ <div class="result-grid" id="result-grid"></div>
663
+ </div>
664
+
665
+ </div>
666
+
667
+ <div class="app-right">
668
+
669
+ <!-- Config + Action -->
670
+ <div class="card" id="config-section">
671
+ <div class="card-title" data-i18n="config.title">Settings</div>
672
+ <div id="settings-tip" style="font-size:12px;color:var(--text2);margin-bottom:12px" data-i18n="config.settingsTip">Settings are saved automatically.</div>
673
+ <button class="btn btn-secondary btn-sm" id="screenshot-preset-btn" style="padding:4px 12px;font-size:12px;margin-bottom:12px" data-i18n-title="config.screenshotPresetTitle" title="Sets Quality: High, Max Width: 1920px, Mode: Standard, Dithering: Off. A starting point for compressing software screenshots." data-i18n="config.screenshotPreset">Screenshot preset</button>
674
+ <div style="display:flex;gap:6px;align-items:center;margin-bottom:12px;flex-wrap:wrap">
675
+ <select id="custom-preset-select" class="custom-preset-select">
676
+ <option value="" data-i18n="config.presetsPlaceholder">Custom presets...</option>
677
+ </select>
678
+ <button class="btn btn-secondary btn-sm" id="save-preset-btn" style="padding:4px 10px;font-size:12px" data-i18n-title="config.savePresetTitle" title="Save the current Quality/Max Width/Format/Mode/Dithering/Protect Colors/Keep EXIF settings as a named preset." data-i18n="config.savePreset">Save preset</button>
679
+ <button class="btn btn-secondary btn-sm" id="delete-preset-btn" style="padding:4px 10px;font-size:12px;display:none" data-i18n="config.deletePreset">Delete</button>
680
+ </div>
681
+ <div id="watch-lock-notice" style="display:none;font-size:12px;color:var(--yellow);background:rgba(230,180,60,0.1);border:1px solid rgba(230,180,60,0.3);border-radius:6px;padding:8px 10px;margin-bottom:12px" data-i18n="config.watchLockNotice">
682
+ Locked while Watch Mode is running. It captured these settings when you clicked "Start Watching" and won't pick up changes. Stop Watch Mode to change them, then start again.
683
+ </div>
684
+ <div class="config-grid" style="margin-bottom:16px">
685
+ <div class="config-group">
686
+ <label data-i18n-title="config.qualityTitle" title="Controls how much color detail Standard mode is allowed to sacrifice for size. For UI screenshots with text, High usually costs little extra size since screenshots rarely use many colors to begin with." data-i18n="config.quality">Quality</label>
687
+ <div class="radio-group" id="quality-group">
688
+ <input type="radio" name="quality" id="q-high" value="high"
689
+ title="Controls how much color detail Standard mode is allowed to sacrifice for size. For UI screenshots with text, High usually costs little extra size since screenshots rarely use many colors to begin with.">
690
+ <label for="q-high" data-i18n="config.qualityHigh"
691
+ title="Controls how much color detail Standard mode is allowed to sacrifice for size. For UI screenshots with text, High usually costs little extra size since screenshots rarely use many colors to begin with.">High</label>
692
+ <input type="radio" name="quality" id="q-med" value="medium" checked><label for="q-med" data-i18n="config.qualityMedium">Medium</label>
693
+ <input type="radio" name="quality" id="q-low" value="low"><label for="q-low" data-i18n="config.qualityLow">Low</label>
694
+ </div>
695
+ </div>
696
+ <div class="config-group">
697
+ <label data-i18n-title="config.maxWidthTitle" title="Shrinking dimensions is the one setting that can genuinely blur small text. Screenshots with UI text often look best left at 'No resize' or scaled down only slightly." data-i18n="config.maxWidth">Max Width</label>
698
+ <select id="max-width"
699
+ data-i18n-title="config.maxWidthTitle"
700
+ title="Shrinking dimensions is the one setting that can genuinely blur small text. Screenshots with UI text often look best left at 'No resize' or scaled down only slightly.">
701
+ <option value="0" data-i18n="config.noResize">No resize</option>
702
+ <option value="1920">1920px</option>
703
+ <option value="1500">1500px</option>
704
+ <option value="1200">1200px</option>
705
+ </select>
706
+ </div>
707
+ <div class="config-group">
708
+ <label data-i18n="config.outputFormat">Output Format</label>
709
+ <div class="radio-group" id="format-group">
710
+ <input type="radio" name="format" id="fmt-png" value="png" checked><label for="fmt-png">PNG</label>
711
+ <input type="radio" name="format" id="fmt-jpg" value="jpg"
712
+ title="Re-compresses images with mozjpeg's cjpeg while KEEPING the JPEG format, the way to shrink a batch of JPGs without converting them. Quality applies in Standard mode; 'Lossless' maps to the highest mozjpeg quality (~95) since JPEG is inherently lossy. Requires cjpeg in the bin/ directory.">
713
+ <label for="fmt-jpg" data-i18n-title="config.fmtJpgTitle"
714
+ title="Re-compresses images with mozjpeg's cjpeg while KEEPING the JPEG format, the way to shrink a batch of JPGs without converting them. Quality applies in Standard mode; 'Lossless' maps to the highest mozjpeg quality (~95) since JPEG is inherently lossy. Requires cjpeg in the bin/ directory.">JPG</label>
715
+ <input type="radio" name="format" id="fmt-webp" value="webp"
716
+ title="WebP typically produces smaller files than PNG at similar visual quality. Uses its own encoder (not pngquant/oxipng), so Quality/Protect Colors/Dithering don't apply; only Compression Mode's lossy-vs-lossless choice does.">
717
+ <label for="fmt-webp" data-i18n-title="config.fmtWebpTitle"
718
+ title="WebP typically produces smaller files than PNG at similar visual quality. Uses its own encoder (not pngquant/oxipng), so Quality/Protect Colors/Dithering don't apply; only Compression Mode's lossy-vs-lossless choice does.">WebP</label>
719
+ <input type="radio" name="format" id="fmt-avif" value="avif"
720
+ title="AVIF is a modern codec that typically produces the smallest files at equivalent quality. Slower encoding than PNG/WebP. Requires avifenc in the bin/ directory or PATH.">
721
+ <label for="fmt-avif" data-i18n-title="config.fmtAvifTitle"
722
+ title="AVIF is a modern codec that typically produces the smallest files at equivalent quality. Slower encoding than PNG/WebP. Requires avifenc in the bin/ directory or PATH.">AVIF</label>
723
+ </div>
724
+ </div>
725
+ <div class="config-group">
726
+ <label data-i18n-title="config.modeTitle" title="Choose how compression is achieved." data-i18n="config.compressionMode">Compression Mode</label>
727
+ <div class="radio-group" id="mode-group">
728
+ <input type="radio" name="mode" id="mode-standard" value="standard" checked
729
+ title="Best compression. Reduces the image to a smaller color palette before compressing; may cause slight color shifts on small or unique-colored details.">
730
+ <label for="mode-standard" data-i18n-title="config.modeStandardTitle" data-i18n="config.modeStandard"
731
+ title="Best compression. Reduces the image to a smaller color palette before compressing; may cause slight color shifts on small or unique-colored details.">Standard</label>
732
+ <input type="radio" name="mode" id="mode-lossless" value="lossless"
733
+ title="No color changes at all. Compresses without touching pixel values; larger files than Standard, but pixel-perfect.">
734
+ <label for="mode-lossless" data-i18n-title="config.modeLosslessTitle" data-i18n="config.modeLossless"
735
+ title="No color changes at all. Compresses without touching pixel values; larger files than Standard, but pixel-perfect.">Lossless</label>
736
+ <input type="radio" name="mode" id="mode-resize" value="resize_only"
737
+ title="Shrinks image dimensions (requires Max Width to be set) and compresses losslessly, keeping full original color accuracy at the smaller size.">
738
+ <label for="mode-resize" data-i18n-title="config.modeResizeTitle" data-i18n="config.modeResize"
739
+ title="Shrinks image dimensions (requires Max Width to be set) and compresses losslessly, keeping full original color accuracy at the smaller size.">Resize Only</label>
740
+ <input type="radio" name="mode" id="mode-screenshot" value="screenshot"
741
+ title="Tuned specifically for software/UI screenshots (PNG only): a much tighter color-quality floor than Standard mode, dithering off, no resize. Full resolution and near-zero color deviation, typically ~70-80% smaller. Falls back to Lossless automatically if a particular image is too color-complex (e.g. a screenshot with an embedded photo) to hit that quality floor.">
742
+ <label for="mode-screenshot" data-i18n-title="config.modeScreenshotTitle" data-i18n="config.modeScreenshot"
743
+ title="Tuned specifically for software/UI screenshots (PNG only): a much tighter color-quality floor than Standard mode, dithering off, no resize. Full resolution and near-zero color deviation, typically ~70-80% smaller. Falls back to Lossless automatically if a particular image is too color-complex (e.g. a screenshot with an embedded photo) to hit that quality floor.">Screenshot</label>
744
+ </div>
745
+ </div>
746
+ <div class="config-group" id="protect-colors-group">
747
+ <label data-i18n-title="config.protectColorsTitle" title="Colors listed here are prioritized when building the compressed palette, reducing the chance they get replaced by a similar color. Not a 100% guarantee. Only applies in Standard mode." data-i18n="config.protectColors">Protect Colors</label>
748
+ <input type="text" id="protect-colors" placeholder="#2ecc71, #ff0000"
749
+ data-i18n-title="config.protectColorsInputTitle"
750
+ title="Colors listed here (hex codes, comma-separated) are prioritized when building the compressed palette, reducing the chance they get replaced by a similar color. Not a 100% guarantee; pngquant may still adjust the rest of the palette. Only applies in Standard mode.">
751
+ </div>
752
+ <div class="config-group" id="dithering-group">
753
+ <label data-i18n-title="config.ditheringTitle" title="Smooths color transitions by mixing nearby palette colors in a fine pattern. For screenshots with UI text, turning this off usually keeps text edges cleaner. Only applies in Standard mode." data-i18n="config.dithering">Dithering</label>
754
+ <label class="check-row"
755
+ data-i18n-title="config.ditheringInputTitle"
756
+ title="Smooths color transitions by mixing nearby palette colors in a fine pattern. Usually helps gradients and photos, but can make flat-color graphics and text edges (icons, UI screenshots) look slightly grainy. Turn off for cleaner text and flat colors. Only applies in Standard mode.">
757
+ <input type="checkbox" id="dithering" checked /> <span data-i18n="config.enabled">Enabled</span>
758
+ </label>
759
+ </div>
760
+ </div>
761
+ <div id="mode-hint" style="display:none;font-size:12px;color:var(--red);margin:-8px 0 16px"></div>
762
+ <div id="mode-note" style="display:none;font-size:12px;color:var(--yellow);margin:-8px 0 16px"></div>
763
+ <div class="action-bar">
764
+ <div class="spacer"></div>
765
+ <span style="font-size:13px;color:var(--text2)" id="file-count-info"></span>
766
+ <button class="btn btn-primary" id="start-btn" disabled data-i18n="common.start">Start</button>
767
+ </div>
768
+ </div>
769
+
770
+ <!-- Watch Mode -->
771
+ <div class="card" id="watch-section">
772
+ <div class="card-title" data-i18n="watch.title">Watch Mode</div>
773
+ <div style="font-size:12px;color:var(--text2);margin-bottom:10px" data-i18n="watch.desc">
774
+ Monitor a folder and auto-optimize new or changed images as they appear.
775
+ </div>
776
+ <div class="input-row" style="margin-bottom:8px">
777
+ <button class="btn btn-secondary" id="watch-use-current-paths-btn" style="white-space:nowrap" data-i18n="watch.useCurrentPaths">Use Source / Output paths</button>
778
+ </div>
779
+ <div class="input-row" style="margin-bottom:8px">
780
+ <input type="text" id="watch-dir" data-i18n-placeholder="watch.dirPlaceholder" placeholder="Watch directory" style="flex:1" />
781
+ <button class="btn btn-secondary" id="watch-browse-dir-btn" style="white-space:nowrap" data-i18n="common.browse">Browse...</button>
782
+ </div>
783
+ <div class="input-row" style="margin-bottom:8px">
784
+ <input type="text" id="watch-output-dir" data-i18n-placeholder="watch.outputPlaceholder" placeholder="Output directory (required)" style="flex:1" />
785
+ <button class="btn btn-secondary" id="watch-browse-output-btn" style="white-space:nowrap" data-i18n="common.browse">Browse...</button>
786
+ </div>
787
+ <div style="display:flex;gap:12px;margin-bottom:10px">
788
+ <label style="font-size:13px;cursor:pointer;user-select:none;display:flex;align-items:center;gap:4px">
789
+ <input type="checkbox" id="watch-recursive" checked /> <span data-i18n="common.includeSubfolders">Include subfolders</span>
790
+ </label>
791
+ <label style="font-size:13px;cursor:pointer;user-select:none;display:flex;align-items:center;gap:4px">
792
+ <input type="checkbox" id="watch-process-existing" /> <span data-i18n="watch.processExisting">Process existing files</span>
793
+ </label>
794
+ </div>
795
+ <div class="watch-status" id="watch-status" data-i18n="watch.idle">Idle</div>
796
+ <div class="action-bar" style="margin-top:8px">
797
+ <button class="btn btn-primary" id="watch-start-btn" data-i18n="watch.start">Start Watching</button>
798
+ <button class="btn btn-danger" id="watch-stop-btn" style="display:none" data-i18n="common.stop">Stop</button>
799
+ <div class="spacer"></div>
800
+ <span style="font-size:12px;color:var(--text2)" id="watch-stats"></span>
801
+ </div>
802
+ <div class="watch-log-box" id="watch-log-box" style="display:none"></div>
803
+ </div>
804
+
805
+ </div>
806
+
807
+ </div>
808
+
809
+ <script>
810
+ const STATE = {
811
+ files: [],
812
+ results: [],
813
+ wsName: '',
814
+ isRunning: false,
815
+ isPaused: false,
816
+ pollTimer: null,
817
+ thumbPollTimer: null,
818
+ runStartTime: 0,
819
+ resultSort: 'default',
820
+ resultFilter: 'all',
821
+ fileSort: 'default',
822
+ resultCursor: 0,
823
+ logCursor: 0,
824
+ logLines: [],
825
+ fileOverrides: {},
826
+ watchRunning: false,
827
+ watchProcessed: 0,
828
+ watchErrors: 0,
829
+ watchLogs: [],
830
+ watchLogCursor: 0,
831
+ watchSSE: null,
832
+ watchPollTimer: null,
833
+ };
834
+
835
+ // DOM refs
836
+ const $ = id => document.getElementById(id);
837
+
838
+ // ---------------------------------------------------------------------
839
+ // i18n
840
+ // ---------------------------------------------------------------------
841
+ // Extensible dictionary: add a new language by adding a key to I18N and an
842
+ // <option> in #setting-language. Keys are dot-namespaced by section.
843
+ // Scope: front-end UI text only — server-pushed log lines (Watch Mode
844
+ // activity, per-file progress messages) stay in English regardless of the
845
+ // selected UI language, since those originate from the Python backend.
846
+ const I18N = {
847
+ en: {
848
+ 'app.title': 'Image Optimizer',
849
+ 'health.checking': 'Checking...',
850
+ 'health.connectionFailed': 'Connection failed',
851
+ 'header.settingsTitle': 'Settings',
852
+ 'header.themeToggleTitle': 'Toggle light / dark theme',
853
+ 'settings.title': 'Settings',
854
+ 'settings.language': 'Language',
855
+ 'settings.languageHint': 'Applies immediately',
856
+ 'settings.host': 'Host',
857
+ 'settings.port': 'Port',
858
+ 'settings.restartHint': 'Requires restart to take effect',
859
+ 'settings.concurrentWorkers': 'Concurrent Workers',
860
+ 'settings.concurrentWorkersHint': 'Number of images compressed in parallel. Requires restart',
861
+ 'settings.thumbnailWorkers': 'Thumbnail Workers',
862
+ 'settings.thumbnailWorkersHint': 'Number of thumbnails generated in parallel. Requires restart',
863
+ 'settings.cleanupDelay': 'Workspace Cleanup Delay (seconds)',
864
+ 'settings.idleTimeout': 'Session Idle Timeout (hours)',
865
+ 'settings.cancel': 'Cancel',
866
+ 'dialog.ok': 'OK',
867
+ 'dialog.cancel': 'Cancel',
868
+ 'settings.save': 'Save',
869
+ 'settings.saved': 'Settings saved.',
870
+ 'settings.savedRestartNote': ' Some changes require a restart to take effect.',
871
+ 'settings.saveFailed': 'Failed to save settings',
872
+ 'common.resume': 'Resume',
873
+ 'common.dismiss': 'Dismiss',
874
+ 'batchResume.found': 'Found unfinished batch: {done}/{total} completed ({failed} failed). Resume?',
875
+ 'common.browseFolder': 'Browse Folder...',
876
+ 'common.browse': 'Browse...',
877
+ 'common.includeSubfolders': 'Include subfolders',
878
+ 'common.sort': 'Sort',
879
+ 'common.pause': 'Pause',
880
+ 'common.cancel': 'Cancel',
881
+ 'common.reset': 'Reset',
882
+ 'common.start': 'Start',
883
+ 'common.stop': 'Stop',
884
+ 'common.selecting': 'Selecting...',
885
+ 'common.failed': 'failed',
886
+ 'input.title': 'Source Path',
887
+ 'input.dirPlaceholder': 'Folder path to scan, e.g. D:\\screenshots',
888
+ 'input.scanBtn': 'Scan Folder',
889
+ 'input.scanning': 'Scanning...',
890
+ 'input.findingImages': 'Finding images...',
891
+ 'input.scanningProgress': 'Scanning {current} / {total} images...',
892
+ 'input.browseFilesBtn': 'Browse Files...',
893
+ 'input.clearAll': 'Clear all',
894
+ 'input.noImagesFound': 'No images found',
895
+ 'output.title': 'Target Path (optional)',
896
+ 'output.placeholder': 'Type or paste the output folder path, or leave empty for temp folder',
897
+ 'output.skipExistingTitle': 'When re-running against the same output folder, files already optimized there are reused instead of being recompressed. Only applies when an output folder is set.',
898
+ 'output.skipExisting': 'Skip files already in the output folder',
899
+ 'output.keepExifTitle': 'Keep a curated subset of EXIF metadata (camera make/model, date, exposure) in the output. GPS coordinates, Orientation (already baked into the pixels), and bulky MakerNote are dropped. Off by default; turn on only if you need the metadata preserved.',
900
+ 'output.keepExif': 'Keep EXIF metadata (camera info, date; GPS stripped)',
901
+ 'output.prefix': 'Output: ',
902
+ 'files.title': 'Files',
903
+ 'files.sort.default': 'Scan order',
904
+ 'files.sort.mtimeDesc': 'Modified (newest first)',
905
+ 'files.sort.mtimeAsc': 'Modified (oldest first)',
906
+ 'files.sort.ctimeDesc': 'Created (newest first)',
907
+ 'files.sort.ctimeAsc': 'Created (oldest first)',
908
+ 'files.sort.sizeDesc': 'Size (large to small)',
909
+ 'files.sort.sizeAsc': 'Size (small to large)',
910
+ 'files.selectAll': 'Select all',
911
+ 'files.empty': 'Images will appear here after you scan a folder or add files',
912
+ 'files.stats': '{count} file(s), {size} total',
913
+ 'files.preview': 'Preview',
914
+ 'files.previewTitle': 'Run a single-file dry run with the current settings to project the compressed size. Does not affect results or the download ZIP.',
915
+ 'files.overrideTitle': 'Per-file settings (override the global quality/mode for just this file)',
916
+ 'files.overrideMode': 'Mode',
917
+ 'files.overrideWidth': 'Width',
918
+ 'files.inherit': 'inherit',
919
+ 'progress.title': 'Progress',
920
+ 'progress.waiting': 'Waiting...',
921
+ 'progress.complete': 'Complete',
922
+ 'progress.pauseTitle': 'Pause: stop starting new files (in-flight ones finish). Click Resume to continue.',
923
+ 'results.title': 'Results',
924
+ 'results.empty': 'No results yet, run Start to see compressed files',
925
+ 'results.retry': 'Retry Failed',
926
+ 'results.revealTitle': 'Open the output folder in the OS file explorer',
927
+ 'results.reveal': 'Reveal Output Folder',
928
+ 'results.download': 'Download All (ZIP)',
929
+ 'results.sort.default': 'Completion order',
930
+ 'results.sort.savingsDesc': 'Compression % (high to low)',
931
+ 'results.sort.savingsAsc': 'Compression % (low to high)',
932
+ 'results.sort.sizeDesc': 'Compressed size (large to small)',
933
+ 'results.sort.savedDesc': 'Bytes saved (most first)',
934
+ 'results.show': 'Show',
935
+ 'results.filter.all': 'All',
936
+ 'results.filter.success': 'Succeeded only',
937
+ 'results.filter.failed': 'Failed only',
938
+ 'results.failedLabel': 'Failed',
939
+ 'results.skipped': 'Skipped (already optimized)',
940
+ 'results.saved': 'Saved {pct}%',
941
+ 'results.compare': 'Compare',
942
+ 'results.stat.files': 'Files',
943
+ 'results.stat.compression': 'Compression',
944
+ 'results.stat.original': 'Original',
945
+ 'results.stat.compressed': 'Compressed',
946
+ 'results.stat.saved': 'Saved',
947
+ 'results.countAll': '{total} file(s)',
948
+ 'results.countFiltered': '{shown} of {total} shown',
949
+ 'config.title': 'Settings',
950
+ 'config.watchLockNotice': 'Locked while Watch Mode is running. It captured these settings when you clicked "Start Watching" and won\u2019t pick up changes. Stop Watch Mode to change them, then start again.',
951
+ 'config.settingsTip': 'Settings are saved automatically.',
952
+ 'config.screenshotPreset': 'Screenshot preset',
953
+ 'config.screenshotPresetTitle': 'Sets Quality: High, Max Width: 1920px, Mode: Standard, Dithering: Off. A starting point for compressing software screenshots.',
954
+ 'config.presetsPlaceholder': 'Custom presets...',
955
+ 'config.savePreset': 'Save preset',
956
+ 'config.savePresetTitle': 'Save the current Quality/Max Width/Format/Mode/Dithering/Protect Colors/Keep EXIF settings as a named preset.',
957
+ 'config.deletePreset': 'Delete',
958
+ 'config.presetNamePrompt': 'Preset name:',
959
+ 'config.presetNameEmpty': 'Preset name cannot be empty.',
960
+ 'config.presetOverwriteConfirm': 'A preset named "{name}" already exists. Overwrite it?',
961
+ 'config.presetDeleteConfirm': 'Delete preset "{name}"?',
962
+ 'config.quality': 'Quality',
963
+ 'config.qualityTitle': 'Controls how much color detail Standard mode is allowed to sacrifice for size. For UI screenshots with text, High usually costs little extra size since screenshots rarely use many colors to begin with.',
964
+ 'config.qualityHigh': 'High',
965
+ 'config.qualityMedium': 'Medium',
966
+ 'config.qualityLow': 'Low',
967
+ 'config.maxWidth': 'Max Width',
968
+ 'config.maxWidthTitle': "Shrinking dimensions is the one setting that can genuinely blur small text. Screenshots with UI text often look best left at 'No resize' or scaled down only slightly.",
969
+ 'config.noResize': 'No resize',
970
+ 'config.outputFormat': 'Output Format',
971
+ 'config.fmtJpgTitle': "Re-compresses images with mozjpeg's cjpeg while KEEPING the JPEG format, the way to shrink a batch of JPGs without converting them. Quality applies in Standard mode; 'Lossless' maps to the highest mozjpeg quality (~95) since JPEG is inherently lossy. Requires cjpeg in the bin/ directory.",
972
+ 'config.fmtWebpTitle': "WebP typically produces smaller files than PNG at similar visual quality. Uses its own encoder (not pngquant/oxipng), so Quality/Protect Colors/Dithering don't apply; only Compression Mode's lossy-vs-lossless choice does.",
973
+ 'config.fmtAvifTitle': 'AVIF is a modern codec that typically produces the smallest files at equivalent quality. Slower encoding than PNG/WebP. Requires avifenc in the bin/ directory or PATH.',
974
+ 'config.compressionMode': 'Compression Mode',
975
+ 'config.modeTitle': 'Choose how compression is achieved.',
976
+ 'config.modeStandard': 'Standard',
977
+ 'config.modeStandardTitle': 'Best compression. Reduces the image to a smaller color palette before compressing; may cause slight color shifts on small or unique-colored details.',
978
+ 'config.modeLossless': 'Lossless',
979
+ 'config.modeLosslessTitle': 'No color changes at all. Compresses without touching pixel values; larger files than Standard, but pixel-perfect.',
980
+ 'config.modeResize': 'Resize Only',
981
+ 'config.modeResizeTitle': 'Shrinks image dimensions (requires Max Width to be set) and compresses losslessly, keeping full original color accuracy at the smaller size.',
982
+ 'config.modeScreenshot': 'Screenshot',
983
+ 'config.modeScreenshotTitle': 'Tuned specifically for software/UI screenshots (PNG only): a much tighter color-quality floor than Standard mode, dithering off, no resize. Full resolution and near-zero color deviation, typically ~70-80% smaller. Falls back to Lossless automatically if a particular image is too color-complex (e.g. a screenshot with an embedded photo) to hit that quality floor.',
984
+ 'config.modeNoteJpeg': 'JPEG is inherently lossy, so "Lossless" and "Resize Only" use mozjpeg\u2019s highest quality (~95) with no palette changes.',
985
+ 'config.resizeOnlyHint': 'Resize Only mode needs a Max Width other than "No resize".',
986
+ 'config.protectColors': 'Protect Colors',
987
+ 'config.protectColorsTitle': 'Colors listed here are prioritized when building the compressed palette, reducing the chance they get replaced by a similar color. Not a 100% guarantee. Only applies in Standard mode.',
988
+ 'config.protectColorsInputTitle': 'Colors listed here (hex codes, comma-separated) are prioritized when building the compressed palette, reducing the chance they get replaced by a similar color. Not a 100% guarantee; pngquant may still adjust the rest of the palette. Only applies in Standard mode.',
989
+ 'config.dithering': 'Dithering',
990
+ 'config.ditheringTitle': 'Smooths color transitions by mixing nearby palette colors in a fine pattern. For screenshots with UI text, turning this off usually keeps text edges cleaner. Only applies in Standard mode.',
991
+ 'config.ditheringInputTitle': 'Smooths color transitions by mixing nearby palette colors in a fine pattern. Usually helps gradients and photos, but can make flat-color graphics and text edges (icons, UI screenshots) look slightly grainy. Turn off for cleaner text and flat colors. Only applies in Standard mode.',
992
+ 'config.enabled': 'Enabled',
993
+ 'watch.title': 'Watch Mode',
994
+ 'watch.desc': 'Monitor a folder and auto-optimize new or changed images as they appear.',
995
+ 'watch.useCurrentPaths': 'Use Source Path / Target Path settings',
996
+ 'watch.dirPlaceholder': 'Watch directory',
997
+ 'watch.outputPlaceholder': 'Output directory (required)',
998
+ 'watch.processExisting': 'Process existing files',
999
+ 'watch.idle': 'Idle',
1000
+ 'watch.watching': 'Watching\u2026',
1001
+ 'watch.start': 'Start Watching',
1002
+ 'notice.enterFolderPath': 'Please enter a folder path',
1003
+ 'notice.folderPickerUnavailable': 'Folder picker unavailable: {error}. Type the path manually instead.',
1004
+ 'notice.folderPickerFailed': 'Folder picker failed: {error}',
1005
+ 'notice.scanFailedPrefix': 'Scan failed: ',
1006
+ 'notice.lostConnectionScanning': 'Lost connection while scanning: {error}',
1007
+ 'notice.uploadFailed': 'Upload failed: {error}',
1008
+ 'notice.waitForCurrentRun': 'Wait for the current run to finish before previewing.',
1009
+ 'notice.previewFailed': 'Preview failed',
1010
+ 'notice.startFailedPrefix': 'Start failed: ',
1011
+ 'notice.retryFailedPrefix': 'Retry failed: ',
1012
+ 'notice.noFailedFiles': 'No failed files to retry',
1013
+ 'notice.explorerOpenFailed': 'Could not open file explorer: {error}',
1014
+ 'notice.enterWatchDir': 'Please enter a watch directory',
1015
+ 'notice.enterOutputDir': 'Please enter an output directory',
1016
+ 'notice.watchStartFailedPrefix': 'Watch start failed: ',
1017
+ 'notice.pathsBothEmpty': 'Source Path and Target Path are both empty. Set them above first.',
1018
+ 'notice.watchOutputStillEmpty': 'Copied the folder to watch, but Output path is empty there too. Watch Mode needs an output folder (no temp-folder option), so set one before starting.',
1019
+ 'notice.resumeFailed': 'Resume failed',
1020
+ 'notice.resumeFailedPrefix': 'Resume failed: ',
1021
+ },
1022
+ zh: {
1023
+ 'app.title': '图片优化工具',
1024
+ 'health.checking': '检测中...',
1025
+ 'health.connectionFailed': '连接失败',
1026
+ 'header.settingsTitle': '设置',
1027
+ 'header.themeToggleTitle': '切换浅色/深色主题',
1028
+ 'settings.title': '设置',
1029
+ 'settings.language': '语言',
1030
+ 'settings.languageHint': '立即生效',
1031
+ 'settings.host': '主机地址',
1032
+ 'settings.port': '端口',
1033
+ 'settings.restartHint': '需要重启后生效',
1034
+ 'settings.concurrentWorkers': '并发处理数',
1035
+ 'settings.concurrentWorkersHint': '并行压缩的图片数量,需要重启后生效',
1036
+ 'settings.thumbnailWorkers': '缩略图并发数',
1037
+ 'settings.thumbnailWorkersHint': '并行生成缩略图的数量,需要重启后生效',
1038
+ 'settings.cleanupDelay': '工作区清理延迟(秒)',
1039
+ 'settings.idleTimeout': '会话空闲超时(小时)',
1040
+ 'settings.cancel': '取消',
1041
+ 'dialog.ok': '确定',
1042
+ 'dialog.cancel': '取消',
1043
+ 'settings.save': '保存',
1044
+ 'settings.saved': '设置已保存。',
1045
+ 'settings.savedRestartNote': '部分改动需要重启后才能生效。',
1046
+ 'settings.saveFailed': '保存设置失败',
1047
+ 'common.resume': '继续',
1048
+ 'common.dismiss': '关闭',
1049
+ 'batchResume.found': '发现未完成的批次:已完成 {done}/{total}(失败 {failed} 个)。是否继续?',
1050
+ 'common.browseFolder': '浏览文件夹...',
1051
+ 'common.browse': '浏览...',
1052
+ 'common.includeSubfolders': '包含子文件夹',
1053
+ 'common.sort': '排序',
1054
+ 'common.pause': '暂停',
1055
+ 'common.cancel': '取消',
1056
+ 'common.reset': '重置',
1057
+ 'common.start': '开始',
1058
+ 'common.stop': '停止',
1059
+ 'common.selecting': '选择中...',
1060
+ 'common.failed': '失败',
1061
+ 'input.title': '源路径',
1062
+ 'input.dirPlaceholder': '要扫描的文件夹路径,例如 D:\\screenshots',
1063
+ 'input.scanBtn': '扫描文件夹',
1064
+ 'input.scanning': '扫描中...',
1065
+ 'input.findingImages': '正在查找图片...',
1066
+ 'input.scanningProgress': '正在扫描 {current} / {total} 张图片...',
1067
+ 'input.browseFilesBtn': '浏览文件...',
1068
+ 'input.clearAll': '全部清除',
1069
+ 'input.noImagesFound': '未找到图片',
1070
+ 'output.title': '目标路径(可选)',
1071
+ 'output.placeholder': '输入或粘贴输出文件夹路径,留空则使用临时文件夹',
1072
+ 'output.skipExistingTitle': '再次对同一输出文件夹运行时,已经优化过的文件会被直接复用,而不是重新压缩。仅在设置了输出文件夹时生效。',
1073
+ 'output.skipExisting': '跳过输出文件夹中已存在的文件',
1074
+ 'output.keepExifTitle': '在输出文件中保留一部分精选的 EXIF 元数据(相机型号、日期、曝光参数)。GPS 坐标、方向信息(已经烘焙进像素中)以及体积较大的 MakerNote 会被丢弃。默认关闭,只有确实需要保留这些元数据时才开启。',
1075
+ 'output.keepExif': '保留 EXIF 元数据(相机信息、日期;GPS 已剥离)',
1076
+ 'output.prefix': '输出路径:',
1077
+ 'files.title': '文件',
1078
+ 'files.sort.default': '扫描顺序',
1079
+ 'files.sort.mtimeDesc': '修改时间(最新优先)',
1080
+ 'files.sort.mtimeAsc': '修改时间(最早优先)',
1081
+ 'files.sort.ctimeDesc': '创建时间(最新优先)',
1082
+ 'files.sort.ctimeAsc': '创建时间(最早优先)',
1083
+ 'files.sort.sizeDesc': '大小(从大到小)',
1084
+ 'files.sort.sizeAsc': '大小(从小到大)',
1085
+ 'files.selectAll': '全选',
1086
+ 'files.empty': '扫描文件夹或添加文件后,图片会显示在这里',
1087
+ 'files.stats': '{count} 个文件,共 {size}',
1088
+ 'files.preview': '预览',
1089
+ 'files.previewTitle': '使用当前设置对单个文件进行试运行,预估压缩后的大小。不影响最终结果或下载的 ZIP。',
1090
+ 'files.overrideTitle': '单文件设置(仅为这个文件覆盖全局的质量/模式设置)',
1091
+ 'files.overrideMode': '模式',
1092
+ 'files.overrideWidth': '宽度',
1093
+ 'files.inherit': '继承',
1094
+ 'progress.title': '进度',
1095
+ 'progress.waiting': '等待中...',
1096
+ 'progress.complete': '已完成',
1097
+ 'progress.pauseTitle': '暂停:不再开始处理新文件(正在处理的文件会完成)。点击继续可恢复。',
1098
+ 'results.title': '结果',
1099
+ 'results.empty': '暂无结果,点击开始以查看压缩后的文件',
1100
+ 'results.retry': '重试失败项',
1101
+ 'results.revealTitle': '在系统文件管理器中打开输出文件夹',
1102
+ 'results.reveal': '打开输出文件夹',
1103
+ 'results.download': '下载全部(ZIP)',
1104
+ 'results.sort.default': '完成顺序',
1105
+ 'results.sort.savingsDesc': '压缩率(从高到低)',
1106
+ 'results.sort.savingsAsc': '压缩率(从低到高)',
1107
+ 'results.sort.sizeDesc': '压缩后大小(从大到小)',
1108
+ 'results.sort.savedDesc': '节省字节数(从多到少)',
1109
+ 'results.show': '筛选',
1110
+ 'results.filter.all': '全部',
1111
+ 'results.filter.success': '仅成功',
1112
+ 'results.filter.failed': '仅失败',
1113
+ 'results.failedLabel': '失败',
1114
+ 'results.skipped': '已跳过(已优化过)',
1115
+ 'results.saved': '节省 {pct}%',
1116
+ 'results.compare': '对比',
1117
+ 'results.stat.files': '文件数',
1118
+ 'results.stat.compression': '压缩率',
1119
+ 'results.stat.original': '原始大小',
1120
+ 'results.stat.compressed': '压缩后大小',
1121
+ 'results.stat.saved': '节省',
1122
+ 'results.countAll': '共 {total} 个文件',
1123
+ 'results.countFiltered': '显示 {shown} / {total} 个',
1124
+ 'config.title': '设置',
1125
+ 'config.watchLockNotice': 'Watch Mode 运行期间这些设置被锁定,点击【开始监控】时的设置已被记录,不会再跟随改动。请先停止 Watch Mode 再修改,然后重新开始。',
1126
+ 'config.settingsTip': '设置将自动保存。',
1127
+ 'config.screenshotPreset': '软件截图预设',
1128
+ 'config.screenshotPresetTitle': '一键设置 Quality: High、Max Width: 1920px、Mode: Standard、Dithering: Off,适合压缩软件截图的起点。',
1129
+ 'config.presetsPlaceholder': '自定义预设...',
1130
+ 'config.savePreset': '保存预设',
1131
+ 'config.savePresetTitle': '将当前的 Quality/Max Width/Format/Mode/Dithering/Protect Colors/Keep EXIF 设置保存为一个命名预设。',
1132
+ 'config.deletePreset': '删除',
1133
+ 'config.presetNamePrompt': '预设名称:',
1134
+ 'config.presetNameEmpty': '预设名称不能为空。',
1135
+ 'config.presetOverwriteConfirm': '已存在名为“{name}”的预设,是否覆盖?',
1136
+ 'config.presetDeleteConfirm': '删除预设“{name}”?',
1137
+ 'config.quality': '质量',
1138
+ 'config.qualityTitle': '控制 Standard 模式允许牺牲多少色彩细节来换取体积。对于带文字的 UI 截图,选择 High 通常不会增加太多体积,因为截图本身颜色数就不多。',
1139
+ 'config.qualityHigh': '高',
1140
+ 'config.qualityMedium': '中',
1141
+ 'config.qualityLow': '低',
1142
+ 'config.maxWidth': '最大宽度',
1143
+ 'config.maxWidthTitle': "缩小尺寸是唯一真正可能让小字变模糊的设置,带 UI 文字的截图通常保持【不缩放】或只轻微缩小效果最好。",
1144
+ 'config.noResize': '不缩放',
1145
+ 'config.outputFormat': '输出格式',
1146
+ 'config.fmtJpgTitle': '使用 mozjpeg 的 cjpeg 重新压缩图片,同时保持 JPEG 格式,在不转换格式的前提下压缩一批 JPG 图片。Quality 设置在 Standard 模式下生效;Lossless 对应 mozjpeg 的最高质量(约 95),因为 JPEG 本身是有损格式。需要在 bin/ 目录下提供 cjpeg。',
1147
+ 'config.fmtWebpTitle': 'WebP 在视觉质量相近的情况下通常比 PNG 文件更小。使用独立的编码器(非 pngquant/oxipng),Quality/Protect Colors/Dithering 不生效,只有 Compression Mode 的有损/无损选择会影响结果。',
1148
+ 'config.fmtAvifTitle': 'AVIF 是一种现代编码格式,同等质量下通常能生成体积最小的文件。编码速度比 PNG/WebP 慢。需要在 bin/ 目录或 PATH 中提供 avifenc。',
1149
+ 'config.compressionMode': '压缩模式',
1150
+ 'config.modeTitle': '选择压缩的实现方式。',
1151
+ 'config.modeStandard': '标准',
1152
+ 'config.modeStandardTitle': '压缩效果最好。压缩前先把图片缩减到更小的调色板,可能导致细小或特殊颜色区域出现轻微色差。',
1153
+ 'config.modeLossless': '无损',
1154
+ 'config.modeLosslessTitle': '完全不改变颜色。压缩时不触碰像素值,文件比 Standard 模式大,但像素级精确无损。',
1155
+ 'config.modeResize': '仅缩放',
1156
+ 'config.modeResizeTitle': '缩小图片尺寸(需要设置 Max Width)并做无损压缩,在更小的尺寸下保留完整的原始色彩精度。',
1157
+ 'config.modeScreenshot': '截图模式',
1158
+ 'config.modeScreenshotTitle': '专为软件/UI 截图调优(仅支持 PNG):色彩质量下限比 Standard 模式严格得多,关闭抖动、不缩放,保持全分辨率且色彩偏差趋近于零,通常能缩小约 70-80%。如果某张图片颜色过于复杂(比如截图里嵌了一张照片)而无法达到该质量下限,会自动改用 Lossless 模式的行为。',
1159
+ 'config.modeNoteJpeg': 'JPEG 本身是有损格式,【无损】和【仅缩放】会使用 mozjpeg 的最高质量(约 95),不改变调色板。',
1160
+ 'config.resizeOnlyHint': '【仅缩放】模式需要将 Max Width 设置为【不缩放】以外的值。',
1161
+ 'config.protectColors': '保护颜色',
1162
+ 'config.protectColorsTitle': '这里列出的颜色在构建压缩调色板时会被优先保留,降低被相近颜色替换的概率。不是 100% 保证。仅在 Standard 模式下生效。',
1163
+ 'config.protectColorsInputTitle': '这里列出的颜色(十六进制色号,用逗号分隔)在构建压缩调色板时会被优先保留,降低被相近颜色替换的概率。不是 100% 保证,pngquant 仍可能调整调色板的其余部分。仅在 Standard 模式下生效。',
1164
+ 'config.dithering': '抖动',
1165
+ 'config.ditheringTitle': '通过在细微图案中混合相邻调色板颜色来平滑色彩过渡。对于带 UI 文字的截图,关闭此项通常能让文字边缘更清晰。仅在 Standard 模式下生效。',
1166
+ 'config.ditheringInputTitle': '通过在细微图案中混合相邻调色板颜色来平滑色彩过渡。通常对渐变和照片有帮助,但可能让纯色图形和文字边缘(图标、UI 截图)显得略微粗糙。关闭可让文字和纯色区域更清晰。仅在 Standard 模式下生效。',
1167
+ 'config.enabled': '已启用',
1168
+ 'watch.title': 'Watch Mode',
1169
+ 'watch.desc': '监控一个文件夹,自动优化新出现或发生变化的图片。',
1170
+ 'watch.useCurrentPaths': '使用【源路径】/【目标路径】中的设置',
1171
+ 'watch.dirPlaceholder': '监控目录',
1172
+ 'watch.outputPlaceholder': '输出目录(必填)',
1173
+ 'watch.processExisting': '处理已有文件',
1174
+ 'watch.idle': '空闲',
1175
+ 'watch.watching': '监控中\u2026',
1176
+ 'watch.start': '开始监控',
1177
+ 'notice.enterFolderPath': '请输入文件夹路径',
1178
+ 'notice.folderPickerUnavailable': '文件夹选择器不可用:{error}。请手动输入路径。',
1179
+ 'notice.folderPickerFailed': '文件夹选择失败:{error}',
1180
+ 'notice.scanFailedPrefix': '扫描失败:',
1181
+ 'notice.lostConnectionScanning': '扫描过程中连接中断:{error}',
1182
+ 'notice.uploadFailed': '上传失败:{error}',
1183
+ 'notice.waitForCurrentRun': '请等待当前任务完成后再进行预览。',
1184
+ 'notice.previewFailed': '预览失败',
1185
+ 'notice.startFailedPrefix': '启动失败:',
1186
+ 'notice.retryFailedPrefix': '重试失败:',
1187
+ 'notice.noFailedFiles': '没有需要重试的失败文件',
1188
+ 'notice.explorerOpenFailed': '无法打开文件管理器:{error}',
1189
+ 'notice.enterWatchDir': '请输入要监控的目录',
1190
+ 'notice.enterOutputDir': '请输入输出目录',
1191
+ 'notice.watchStartFailedPrefix': '启动监控失败:',
1192
+ 'notice.pathsBothEmpty': '【源路径】和【目标路径】都是空的,请先在上方设置好。',
1193
+ 'notice.watchOutputStillEmpty': '已复制监控目录,但那边的输出路径也是空的,Watch Mode 需要一个输出文件夹(没有临时文件夹选项),请先设置好再开始。',
1194
+ 'notice.resumeFailed': '恢复失败',
1195
+ 'notice.resumeFailedPrefix': '恢复失败:',
1196
+ },
1197
+ };
1198
+
1199
+ // Best-effort mapping from browser locale to a supported I18N key. Only
1200
+ // 'zh'/'en' exist today; anything else (or no match) falls back to 'en'.
1201
+ // Extend this alongside I18N when a new language is added.
1202
+ function detectBrowserLang() {
1203
+ const candidates = (navigator.languages && navigator.languages.length)
1204
+ ? navigator.languages
1205
+ : [navigator.language || navigator.userLanguage || 'en'];
1206
+ for (const l of candidates) {
1207
+ const base = String(l).toLowerCase();
1208
+ if (base.startsWith('zh')) return 'zh';
1209
+ if (base.startsWith('en')) return 'en';
1210
+ }
1211
+ return 'en';
1212
+ }
1213
+
1214
+ // Explicit choice (Settings > Language) always wins and persists. With
1215
+ // nothing stored yet, the browser's language is used as the initial
1216
+ // default — recomputed live rather than cached, so it isn't "sticky" the
1217
+ // way an explicit choice is.
1218
+ function currentLang() {
1219
+ const stored = localStorage.getItem('imgopt.lang');
1220
+ if (stored && I18N[stored]) return stored;
1221
+ return detectBrowserLang();
1222
+ }
1223
+
1224
+ // t(key, vars?) — looks up `key` in the current language, falling back to
1225
+ // English then to the key itself so a missing translation never renders as
1226
+ // blank. `vars` does simple {name} interpolation for values that come from
1227
+ // the app itself (never raw user/server text, which stays untranslated on
1228
+ // purpose — see the i18n scope note above).
1229
+ function t(key, vars) {
1230
+ const lang = currentLang();
1231
+ let str = (I18N[lang] && I18N[lang][key]) || I18N.en[key] || key;
1232
+ if (vars) {
1233
+ for (const k in vars) str = str.split(`{${k}}`).join(vars[k]);
1234
+ }
1235
+ return str;
1236
+ }
1237
+
1238
+ // Applies the current language to every element carrying a data-i18n*
1239
+ // attribute. Safe to call repeatedly (e.g. right after a language change).
1240
+ function applyI18n() {
1241
+ document.documentElement.lang = currentLang() === 'zh' ? 'zh-CN' : 'en';
1242
+ document.querySelectorAll('[data-i18n]').forEach(el => {
1243
+ el.textContent = t(el.getAttribute('data-i18n'));
1244
+ });
1245
+ document.querySelectorAll('[data-i18n-placeholder]').forEach(el => {
1246
+ el.placeholder = t(el.getAttribute('data-i18n-placeholder'));
1247
+ });
1248
+ document.querySelectorAll('[data-i18n-title]').forEach(el => {
1249
+ el.title = t(el.getAttribute('data-i18n-title'));
1250
+ });
1251
+ }
1252
+
1253
+ // Applies the stored language, then re-renders whatever dynamic (JS
1254
+ // generated) content is already on screen so a mid-session language switch
1255
+ // doesn't leave stale English behind in file/result cards, watch status,
1256
+ // etc. Each call is guarded — these renderers are idempotent over current
1257
+ // STATE, safe to call again even if nothing has been scanned/run yet.
1258
+ function applyStoredLang() {
1259
+ applyI18n();
1260
+ if (typeof renderFileGrid === 'function' && STATE.files.length) renderFileGrid(STATE.files);
1261
+ if (typeof renderResultGrid === 'function' && STATE.results.length) renderResultGrid();
1262
+ if (typeof updateModeDependentControls === 'function') updateModeDependentControls();
1263
+ if (typeof updateStartButtonState === 'function') updateStartButtonState();
1264
+ // The preset dropdown's placeholder <option> is built via innerHTML, not
1265
+ // a static [data-i18n] element, so it's outside applyI18n()'s sweep above
1266
+ // and needs its own refresh here.
1267
+ if (typeof renderPresetDropdown === 'function' && $('custom-preset-select')) {
1268
+ renderPresetDropdown($('custom-preset-select').value);
1269
+ }
1270
+ }
1271
+
1272
+ // Wraps fetch() to attach the per-session app token (see APP_TOKEN in the
1273
+ // page <head>) as a custom header. Only needed for state-changing/sensitive
1274
+ // endpoints — image-serving endpoints (thumb/result/source-file/download)
1275
+ // are loaded via plain <img src>/<a href> and can't carry custom headers
1276
+ // anyway, and don't need this protection (see the backend comment on
1277
+ // require_token for why the header itself is the actual defense).
1278
+ function apiFetch(url, options) {
1279
+ options = options || {};
1280
+ options.headers = Object.assign({}, options.headers, { 'X-App-Token': window.APP_TOKEN || '' });
1281
+ return fetch(url, options);
1282
+ }
1283
+
1284
+
1285
+ // Lightweight toast notification. type: 'err' | 'ok' | 'info'.
1286
+ // (This was called in 8 places without ever being defined — every error
1287
+ // path in the app was throwing an uncaught ReferenceError instead of
1288
+ // telling the user anything went wrong.)
1289
+ const noticeContainer = $('notice-container');
1290
+ let persistentNoticeEl = null;
1291
+
1292
+ function showNotice(message, type) {
1293
+ type = type || 'info';
1294
+ const el = document.createElement('div');
1295
+ el.className = `notice ${type}`;
1296
+ el.innerHTML = `<span class="notice-msg"></span><button class="notice-close" aria-label="${t('common.dismiss')}">&times;</button>`;
1297
+ el.querySelector('.notice-msg').textContent = message;
1298
+ const remove = () => el.remove();
1299
+ el.querySelector('.notice-close').addEventListener('click', remove);
1300
+ noticeContainer.appendChild(el);
1301
+ setTimeout(remove, 5000);
1302
+ }
1303
+
1304
+ function showPersistentNotice(message, type) {
1305
+ dismissPersistentNotice();
1306
+ const el = document.createElement('div');
1307
+ el.className = `notice ${type || 'info'}`;
1308
+ el.innerHTML = `<span class="notice-msg"></span><button class="notice-close" aria-label="${t('common.dismiss')}">&times;</button>`;
1309
+ el.querySelector('.notice-msg').textContent = message;
1310
+ el.querySelector('.notice-close').addEventListener('click', () => dismissPersistentNotice());
1311
+ noticeContainer.appendChild(el);
1312
+ persistentNoticeEl = el;
1313
+ }
1314
+
1315
+ function dismissPersistentNotice() {
1316
+ if (persistentNoticeEl) {
1317
+ persistentNoticeEl.remove();
1318
+ persistentNoticeEl = null;
1319
+ }
1320
+ }
1321
+
1322
+ const dirPath = $('dir-path'),
1323
+ scanBtn = $('scan-btn'),
1324
+ fileInput = $('file-input'),
1325
+ outputDir = $('output-dir'),
1326
+ outputBrowseBtn = $('output-browse-btn'),
1327
+ fileGrid = $('file-grid'),
1328
+ fileStatsText = $('file-stats-text'),
1329
+ fileSortSel = $('file-sort'),
1330
+ selectAll = $('select-all'),
1331
+ fileCountInfo = $('file-count-info'),
1332
+ startBtn = $('start-btn'),
1333
+ progressSection = $('progress-section'),
1334
+ progressFill = $('progress-fill'),
1335
+ progressText = $('progress-text'),
1336
+ cancelBtn = $('cancel-btn'),
1337
+ pauseBtn = $('pause-btn'),
1338
+ resumeBtn = $('resume-btn'),
1339
+ escHtml = s => s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;'),
1340
+ logBox = $('log-box'),
1341
+ resultsSection = $('results-section'),
1342
+ resultsEmpty = $('results-empty'),
1343
+ filesEmpty = $('files-empty'),
1344
+ resultSummary = $('result-summary'),
1345
+ resultGrid = $('result-grid'),
1346
+ downloadBtn = $('download-btn'),
1347
+ revealDirBtn = $('reveal-dir-btn'),
1348
+ resetBtn = $('reset-btn'),
1349
+ healthStatus = $('health-status'),
1350
+ configSection = $('config-section'),
1351
+ filesSection = $('files-section'),
1352
+ protectColorsInput = $('protect-colors'),
1353
+ protectColorsGroup = $('protect-colors-group'),
1354
+ ditheringInput = $('dithering'),
1355
+ ditheringGroup = $('dithering-group'),
1356
+ modeHint = $('mode-hint'),
1357
+ retryBtn = $('retry-btn'),
1358
+ resultToolbar = $('result-toolbar'),
1359
+ resultSortSel = $('result-sort'),
1360
+ resultFilterSel = $('result-filter'),
1361
+ resultCountEl = $('result-count'),
1362
+ themeToggle = $('theme-toggle');
1363
+
1364
+ // Utility
1365
+ function fmtSize(bytes) {
1366
+ if (bytes < 1024) return bytes + ' B';
1367
+ if (bytes < 1048576) return (bytes / 1024).toFixed(1) + ' KB';
1368
+ return (bytes / 1048576).toFixed(2) + ' MB';
1369
+ }
1370
+
1371
+ // Format a duration in seconds as "mm:ss" (or "h:mm:ss" past an hour).
1372
+ function fmtDuration(sec) {
1373
+ sec = Math.max(0, Math.round(sec));
1374
+ const h = Math.floor(sec / 3600), m = Math.floor((sec % 3600) / 60), s = sec % 60;
1375
+ const pad = n => String(n).padStart(2, '0');
1376
+ return h > 0 ? `${h}:${pad(m)}:${pad(s)}` : `${m}:${pad(s)}`;
1377
+ }
1378
+
1379
+ // Theme: 'light' | 'dark' persisted in localStorage. When nothing is stored
1380
+ // we leave the data-theme attribute off entirely so the prefers-color-scheme
1381
+ // media query decides (follow the OS). The toggle always writes an explicit
1382
+ // choice, which from then on overrides the OS setting.
1383
+ function currentTheme() {
1384
+ const stored = localStorage.getItem('imgopt.theme');
1385
+ if (stored === 'light' || stored === 'dark') return stored;
1386
+ return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
1387
+ }
1388
+ function applyStoredTheme() {
1389
+ const stored = localStorage.getItem('imgopt.theme');
1390
+ if (stored === 'light' || stored === 'dark') {
1391
+ document.documentElement.setAttribute('data-theme', stored);
1392
+ } else {
1393
+ document.documentElement.removeAttribute('data-theme');
1394
+ }
1395
+ themeToggle.textContent = currentTheme() === 'dark' ? '\u2600' : '\u263e'; // sun when dark (click->light), moon when light
1396
+ }
1397
+ themeToggle.addEventListener('click', () => {
1398
+ const next = currentTheme() === 'dark' ? 'light' : 'dark';
1399
+ localStorage.setItem('imgopt.theme', next);
1400
+ applyStoredTheme();
1401
+ });
1402
+
1403
+ // Config memory: persist the last-used settings so a page refresh doesn't
1404
+ // reset Quality/Format/Mode/etc. back to the HTML defaults. Stored under one
1405
+ // key as a plain object; missing/corrupt storage falls back to the HTML
1406
+ // defaults (the hardcoded `checked` attributes) untouched.
1407
+ function saveConfig() {
1408
+ try {
1409
+ const cfg = {
1410
+ quality: (document.querySelector('input[name="quality"]:checked') || {}).value,
1411
+ maxWidth: $('max-width').value,
1412
+ format: (document.querySelector('input[name="format"]:checked') || {}).value,
1413
+ mode: (document.querySelector('input[name="mode"]:checked') || {}).value,
1414
+ dithering: ditheringInput.checked,
1415
+ protectColors: protectColorsInput.value,
1416
+ recursive: $('recursive-scan').checked,
1417
+ skipExisting: $('skip-existing').checked,
1418
+ keepExif: $('keep-exif').checked,
1419
+ };
1420
+ localStorage.setItem('imgopt.config', JSON.stringify(cfg));
1421
+ } catch (e) { /* storage unavailable/full — non-critical */ }
1422
+ }
1423
+ function loadConfig() {
1424
+ let cfg;
1425
+ try { cfg = JSON.parse(localStorage.getItem('imgopt.config') || 'null'); }
1426
+ catch (e) { cfg = null; }
1427
+ if (!cfg) return;
1428
+ const setRadio = (name, val) => {
1429
+ if (val == null) return;
1430
+ const el = document.querySelector(`input[name="${name}"][value="${val}"]`);
1431
+ if (el) el.checked = true;
1432
+ };
1433
+ setRadio('quality', cfg.quality);
1434
+ setRadio('format', cfg.format);
1435
+ setRadio('mode', cfg.mode);
1436
+ if (cfg.maxWidth != null && $('max-width').querySelector(`option[value="${cfg.maxWidth}"]`)) {
1437
+ $('max-width').value = cfg.maxWidth;
1438
+ }
1439
+ if (typeof cfg.dithering === 'boolean') ditheringInput.checked = cfg.dithering;
1440
+ if (typeof cfg.protectColors === 'string') protectColorsInput.value = cfg.protectColors;
1441
+ if (typeof cfg.recursive === 'boolean') $('recursive-scan').checked = cfg.recursive;
1442
+ if (typeof cfg.skipExisting === 'boolean') $('skip-existing').checked = cfg.skipExisting;
1443
+ if (typeof cfg.keepExif === 'boolean') $('keep-exif').checked = cfg.keepExif;
1444
+ }
1445
+ // Screenshot preset: one click to Quality High + Max Width 1920px + Mode
1446
+ // Standard + Dithering Off — the combo settled on for screenshots meant to
1447
+ // software screenshots (see config.screenshotPresetTitle for the
1448
+ // rationale). Dispatches 'change' on each control after setting it so the
1449
+ // existing per-control listeners (saveConfig, updateModeDependentControls,
1450
+ // updateStartButtonState) fire exactly as if the user had clicked each one.
1451
+ function applyScreenshotPreset() {
1452
+ const setRadio = (name, val) => {
1453
+ const el = document.querySelector(`input[name="${name}"][value="${val}"]`);
1454
+ if (el && !el.disabled) { el.checked = true; el.dispatchEvent(new Event('change', { bubbles: true })); }
1455
+ };
1456
+ setRadio('quality', 'high');
1457
+ setRadio('mode', 'standard');
1458
+ if (!$('max-width').disabled) {
1459
+ $('max-width').value = '1920';
1460
+ $('max-width').dispatchEvent(new Event('change', { bubbles: true }));
1461
+ }
1462
+ if (!ditheringInput.disabled) {
1463
+ ditheringInput.checked = false;
1464
+ ditheringInput.dispatchEvent(new Event('change', { bubbles: true }));
1465
+ }
1466
+ }
1467
+ $('screenshot-preset-btn').addEventListener('click', applyScreenshotPreset);
1468
+
1469
+ // Custom presets: user-named snapshots of the "compression recipe" fields
1470
+ // (quality/maxWidth/format/mode/dithering/protectColors/keepExif) —
1471
+ // deliberately NOT recursive/skipExisting, which are properties of how a
1472
+ // given batch run is scoped, not of the image-processing recipe itself, so
1473
+ // applying a preset shouldn't unexpectedly flip those on/off underneath the
1474
+ // current run. Stored as one object under 'imgopt.presets', same
1475
+ // try/except-and-fall-back-to-empty shape as loadConfig/saveConfig above —
1476
+ // corrupt/unavailable storage degrades to "no presets" rather than breaking
1477
+ // the page.
1478
+ const PRESET_FIELDS = ['quality', 'maxWidth', 'format', 'mode', 'dithering', 'protectColors', 'keepExif'];
1479
+
1480
+ function getSavedPresets() {
1481
+ try {
1482
+ const raw = JSON.parse(localStorage.getItem('imgopt.presets') || 'null');
1483
+ return (raw && typeof raw === 'object') ? raw : {};
1484
+ } catch (e) { return {}; }
1485
+ }
1486
+ function setSavedPresets(presets) {
1487
+ try { localStorage.setItem('imgopt.presets', JSON.stringify(presets)); }
1488
+ catch (e) { /* storage unavailable/full — non-critical, same as saveConfig */ }
1489
+ }
1490
+ function captureCurrentSettingsForPreset() {
1491
+ return {
1492
+ quality: (document.querySelector('input[name="quality"]:checked') || {}).value,
1493
+ maxWidth: $('max-width').value,
1494
+ format: (document.querySelector('input[name="format"]:checked') || {}).value,
1495
+ mode: (document.querySelector('input[name="mode"]:checked') || {}).value,
1496
+ dithering: ditheringInput.checked,
1497
+ protectColors: protectColorsInput.value,
1498
+ keepExif: $('keep-exif').checked,
1499
+ };
1500
+ }
1501
+ function applyPresetValues(preset) {
1502
+ const setRadio = (name, val) => {
1503
+ if (val == null) return;
1504
+ const el = document.querySelector(`input[name="${name}"][value="${val}"]`);
1505
+ if (el && !el.disabled) { el.checked = true; el.dispatchEvent(new Event('change', { bubbles: true })); }
1506
+ };
1507
+ setRadio('quality', preset.quality);
1508
+ setRadio('format', preset.format);
1509
+ setRadio('mode', preset.mode);
1510
+ if (preset.maxWidth != null && !$('max-width').disabled
1511
+ && $('max-width').querySelector(`option[value="${preset.maxWidth}"]`)) {
1512
+ $('max-width').value = preset.maxWidth;
1513
+ $('max-width').dispatchEvent(new Event('change', { bubbles: true }));
1514
+ }
1515
+ if (typeof preset.dithering === 'boolean' && !ditheringInput.disabled) {
1516
+ ditheringInput.checked = preset.dithering;
1517
+ ditheringInput.dispatchEvent(new Event('change', { bubbles: true }));
1518
+ }
1519
+ if (typeof preset.protectColors === 'string' && !protectColorsInput.disabled) {
1520
+ protectColorsInput.value = preset.protectColors;
1521
+ protectColorsInput.dispatchEvent(new Event('change', { bubbles: true }));
1522
+ }
1523
+ if (typeof preset.keepExif === 'boolean' && !$('keep-exif').disabled) {
1524
+ $('keep-exif').checked = preset.keepExif;
1525
+ $('keep-exif').dispatchEvent(new Event('change', { bubbles: true }));
1526
+ }
1527
+ }
1528
+ function renderPresetDropdown(selectName) {
1529
+ const presets = getSavedPresets();
1530
+ const select = $('custom-preset-select');
1531
+ const names = Object.keys(presets).sort((a, b) => a.localeCompare(b));
1532
+ select.innerHTML = `<option value="">${t('config.presetsPlaceholder')}</option>`
1533
+ + names.map(n => `<option value="${n.replace(/"/g, '&quot;')}">${n}</option>`).join('');
1534
+ select.value = (selectName && names.includes(selectName)) ? selectName : '';
1535
+ $('delete-preset-btn').style.display = select.value ? '' : 'none';
1536
+ }
1537
+ $('custom-preset-select').addEventListener('change', () => {
1538
+ const name = $('custom-preset-select').value;
1539
+ $('delete-preset-btn').style.display = name ? '' : 'none';
1540
+ if (!name) return;
1541
+ const presets = getSavedPresets();
1542
+ if (presets[name]) applyPresetValues(presets[name]);
1543
+ });
1544
+ // Themed replacement for window.prompt/confirm/alert (see the
1545
+ // #app-dialog-overlay markup above) — same Promise-based call shape so the
1546
+ // call sites below just gain an `await`, nothing else changes structurally.
1547
+ function showAppDialog({ title, message, showInput, inputValue, okOnly }) {
1548
+ return new Promise(resolve => {
1549
+ const overlay = $('app-dialog-overlay');
1550
+ const inputField = $('app-dialog-input-field');
1551
+ const messageEl = $('app-dialog-message');
1552
+ const inputEl = $('app-dialog-input');
1553
+ const okBtn = $('app-dialog-ok');
1554
+ const cancelBtn = $('app-dialog-cancel');
1555
+
1556
+ $('app-dialog-title').textContent = title || '';
1557
+ if (message) { messageEl.textContent = message; messageEl.style.display = ''; }
1558
+ else { messageEl.style.display = 'none'; }
1559
+ if (showInput) { inputField.style.display = ''; inputEl.value = inputValue || ''; }
1560
+ else { inputField.style.display = 'none'; }
1561
+ cancelBtn.style.display = okOnly ? 'none' : '';
1562
+
1563
+ overlay.classList.add('open');
1564
+ if (showInput) { inputEl.focus(); inputEl.select(); }
1565
+
1566
+ function cleanup(result) {
1567
+ overlay.classList.remove('open');
1568
+ okBtn.removeEventListener('click', onOk);
1569
+ cancelBtn.removeEventListener('click', onCancel);
1570
+ inputEl.removeEventListener('keydown', onKeydown);
1571
+ resolve(result);
1572
+ }
1573
+ function onOk() { cleanup(showInput ? inputEl.value : true); }
1574
+ function onCancel() { cleanup(showInput ? null : false); }
1575
+ function onKeydown(e) {
1576
+ if (e.key === 'Enter') onOk();
1577
+ else if (e.key === 'Escape') onCancel();
1578
+ }
1579
+ okBtn.addEventListener('click', onOk);
1580
+ cancelBtn.addEventListener('click', onCancel);
1581
+ if (showInput) inputEl.addEventListener('keydown', onKeydown);
1582
+ });
1583
+ }
1584
+ function appPrompt(title, defaultValue) {
1585
+ return showAppDialog({ title, showInput: true, inputValue: defaultValue });
1586
+ }
1587
+ function appConfirm(title, message) {
1588
+ return showAppDialog({ title, message, showInput: false });
1589
+ }
1590
+ function appAlert(title, message) {
1591
+ return showAppDialog({ title, message, showInput: false, okOnly: true });
1592
+ }
1593
+
1594
+ $('save-preset-btn').addEventListener('click', async () => {
1595
+ let name = await appPrompt(t('config.presetNamePrompt'), $('custom-preset-select').value || '');
1596
+ if (name == null) return; // cancelled
1597
+ name = name.trim().slice(0, 60);
1598
+ if (!name) { await appAlert(t('config.presetNameEmpty')); return; }
1599
+ const presets = getSavedPresets();
1600
+ if (presets[name] && !(await appConfirm(t('config.presetOverwriteConfirm', { name })))) return;
1601
+ presets[name] = captureCurrentSettingsForPreset();
1602
+ setSavedPresets(presets);
1603
+ renderPresetDropdown(name);
1604
+ });
1605
+ $('delete-preset-btn').addEventListener('click', async () => {
1606
+ const name = $('custom-preset-select').value;
1607
+ if (!name) return;
1608
+ if (!(await appConfirm(t('config.presetDeleteConfirm', { name })))) return;
1609
+ const presets = getSavedPresets();
1610
+ delete presets[name];
1611
+ setSavedPresets(presets);
1612
+ renderPresetDropdown();
1613
+ });
1614
+ renderPresetDropdown();
1615
+
1616
+ // Save on any config change. updateModeDependentControls (bound separately
1617
+ // for format/mode) also recomputes disabled states; saveConfig is additive.
1618
+ ['quality', 'format', 'mode'].forEach(name =>
1619
+ document.querySelectorAll(`input[name="${name}"]`).forEach(r => r.addEventListener('change', saveConfig)));
1620
+ $('max-width').addEventListener('change', saveConfig);
1621
+ ditheringInput.addEventListener('change', saveConfig);
1622
+ protectColorsInput.addEventListener('input', saveConfig);
1623
+ $('recursive-scan').addEventListener('change', saveConfig);
1624
+ $('skip-existing').addEventListener('change', saveConfig);
1625
+ $('keep-exif').addEventListener('change', saveConfig);
1626
+
1627
+ // Health check
1628
+ async function checkHealth() {
1629
+ try {
1630
+ const r = await fetch('/api/health');
1631
+ const d = await r.json();
1632
+ const tools = [];
1633
+ if (d.pngquant) tools.push('pngquant ✓');
1634
+ else tools.push('pngquant ✗');
1635
+ if (d.oxipng) tools.push('oxipng ✓');
1636
+ else tools.push('oxipng ✗');
1637
+ if (d.cjpeg) tools.push('cjpeg ✓');
1638
+ else tools.push('cjpeg ✗');
1639
+ if (d.avifenc) tools.push('avifenc ✓');
1640
+ else tools.push('avifenc ✗');
1641
+ const allOk = d.pngquant && d.oxipng && d.cjpeg;
1642
+ healthStatus.innerHTML =
1643
+ `<span class="status-dot ${allOk ? 'ok' : 'warn'}"></span>${tools.join(' ')}`;
1644
+ // NOTE: deliberately no startBtn touching here — missing binaries only
1645
+ // degrade compression (see available_modes server-side), they don't
1646
+ // make Start invalid. updateStartButtonState() owns that button.
1647
+ return allOk;
1648
+ } catch(e) {
1649
+ healthStatus.innerHTML = '<span class="status-dot err"></span>' + t('health.connectionFailed');
1650
+ return false;
1651
+ }
1652
+ }
1653
+
1654
+ // Scan directory
1655
+ const scanProgressWrap = $('scan-progress-wrap'),
1656
+ scanProgressFill = $('scan-progress-fill'),
1657
+ scanProgressText = $('scan-progress-text');
1658
+ let scanPollTimer = null;
1659
+
1660
+ async function scanPath(path) {
1661
+ dismissPersistentNotice();
1662
+ const recursive = $('recursive-scan').checked;
1663
+ scanBtn.disabled = true;
1664
+ scanBtn.textContent = t('input.scanning');
1665
+ scanProgressWrap.style.display = 'block';
1666
+ scanProgressFill.style.width = '0%';
1667
+ scanProgressText.textContent = t('input.findingImages');
1668
+ try {
1669
+ const r = await apiFetch('/api/scan', {
1670
+ method: 'POST',
1671
+ headers: { 'Content-Type': 'application/json' },
1672
+ body: JSON.stringify({ directory: path, recursive }),
1673
+ });
1674
+ const d = await r.json();
1675
+ if (d.error) { showNotice(d.error, 'err'); resetScanUI(); return; }
1676
+ scanPollTimer = setInterval(pollScanProgress, 250);
1677
+ } catch(e) {
1678
+ showNotice(t('notice.scanFailedPrefix') + e.message, 'err');
1679
+ resetScanUI();
1680
+ }
1681
+ }
1682
+
1683
+ function resetScanUI() {
1684
+ scanBtn.disabled = false;
1685
+ scanBtn.textContent = t('input.scanBtn');
1686
+ scanProgressWrap.style.display = 'none';
1687
+ if (scanPollTimer) { clearInterval(scanPollTimer); scanPollTimer = null; }
1688
+ }
1689
+
1690
+ async function pollScanProgress() {
1691
+ try {
1692
+ const r = await apiFetch('/api/scan-progress');
1693
+ const d = await r.json();
1694
+ if (d.total > 0) {
1695
+ const pct = Math.round((d.current / d.total) * 100);
1696
+ scanProgressFill.style.width = pct + '%';
1697
+ scanProgressText.textContent = t('input.scanningProgress', { current: d.current, total: d.total });
1698
+ } else {
1699
+ scanProgressText.textContent = t('input.findingImages');
1700
+ }
1701
+ if (!d.running) {
1702
+ resetScanUI();
1703
+ if (d.error) { showNotice(t('notice.scanFailedPrefix') + d.error, 'err'); return; }
1704
+ STATE.files = d.files;
1705
+ STATE.wsName = d.files[0]?.thumbnail?.split('/')[3] || '';
1706
+ renderFiles();
1707
+ showConfigSection();
1708
+ loadRecentPaths();
1709
+ }
1710
+ } catch(e) {
1711
+ resetScanUI();
1712
+ showNotice(t('notice.lostConnectionScanning', { error: e.message }), 'err');
1713
+ }
1714
+ }
1715
+
1716
+ // Recently used folders (like FocusOCR) — click a chip to reuse it instead
1717
+ // of browsing again. Persisted server-side so it survives restarts.
1718
+ const recentScanEl = $('recent-scan-dirs'), recentOutputEl = $('recent-output-dirs');
1719
+ function renderRecentChips(container, paths, onPick, onRemove, onClearAll) {
1720
+ container.innerHTML = '';
1721
+ for (const p of paths) {
1722
+ const chip = document.createElement('span');
1723
+ chip.className = 'recent-chip';
1724
+ chip.title = p;
1725
+ const text = document.createElement('span');
1726
+ text.textContent = p;
1727
+ text.style.cursor = 'pointer';
1728
+ text.addEventListener('click', () => onPick(p));
1729
+ chip.appendChild(text);
1730
+ const del = document.createElement('span');
1731
+ del.textContent = '×';
1732
+ del.style.cssText = 'margin-left:4px;cursor:pointer;font-size:14px;line-height:1;color:var(--text2);opacity:.5';
1733
+ del.addEventListener('click', (e) => { e.stopPropagation(); onRemove(p); });
1734
+ chip.appendChild(del);
1735
+ container.appendChild(chip);
1736
+ }
1737
+ if (paths.length > 1) {
1738
+ const clearAll = document.createElement('span');
1739
+ clearAll.className = 'recent-chip';
1740
+ clearAll.textContent = t('input.clearAll');
1741
+ clearAll.style.cssText = 'font-size:12px;color:var(--text2);cursor:pointer';
1742
+ clearAll.addEventListener('click', onClearAll);
1743
+ container.appendChild(clearAll);
1744
+ }
1745
+ }
1746
+ async function loadRecentPaths() {
1747
+ try {
1748
+ const r = await apiFetch('/api/recent');
1749
+ const d = await r.json();
1750
+ renderRecentChips(recentScanEl, d.scan_dirs || [],
1751
+ (p) => { dirPath.value = p; scanPath(p); },
1752
+ async (p) => { await apiFetch('/api/recent/remove', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ key: 'scan_dirs', value: p }) }); loadRecentPaths(); },
1753
+ async () => { await apiFetch('/api/recent/clear', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ key: 'scan_dirs' }) }); loadRecentPaths(); },
1754
+ );
1755
+ renderRecentChips(recentOutputEl, d.output_dirs || [],
1756
+ (p) => { outputDir.value = p; },
1757
+ async (p) => { await apiFetch('/api/recent/remove', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ key: 'output_dirs', value: p }) }); loadRecentPaths(); },
1758
+ async () => { await apiFetch('/api/recent/clear', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ key: 'output_dirs' }) }); loadRecentPaths(); },
1759
+ );
1760
+ } catch(e) {
1761
+ // Non-critical — just skip showing the recent-folder chips.
1762
+ }
1763
+ }
1764
+
1765
+ scanBtn.addEventListener('click', () => {
1766
+ const path = dirPath.value.trim();
1767
+ if (!path) { showNotice(t('notice.enterFolderPath'), 'err'); return; }
1768
+ scanPath(path);
1769
+ });
1770
+
1771
+ // Opens the OS native folder picker via the server (tkinter on Windows).
1772
+ // The browser doesn't expose real filesystem paths for security, so we
1773
+ // can't use webkitdirectory for output path — the server-side dialog is
1774
+ // the only reliable way to get a real writable path. The dialog shows
1775
+ // Python's icon (not Chrome's) because it's a server-side window, not
1776
+ // something the browser is opening.
1777
+ async function pickFolder() {
1778
+ try {
1779
+ const r = await apiFetch('/api/browse-folder');
1780
+ const d = await r.json();
1781
+ if (d.error) {
1782
+ showNotice(t('notice.folderPickerUnavailable', { error: d.error }), 'err');
1783
+ return '';
1784
+ }
1785
+ return d.path || ''; // '' also covers the user simply cancelling the dialog
1786
+ } catch(e) {
1787
+ showNotice(t('notice.folderPickerFailed', { error: e.message }), 'err');
1788
+ return '';
1789
+ }
1790
+ }
1791
+
1792
+ // Output path: text field is the source of truth; the server-side picker
1793
+ // fills it in. No webkitdirectory here — the browser can't give us the
1794
+ // real path we need to write files to.
1795
+ outputBrowseBtn.addEventListener('click', async () => {
1796
+ outputBrowseBtn.disabled = true;
1797
+ outputBrowseBtn.textContent = t('common.selecting');
1798
+ try {
1799
+ const path = await pickFolder();
1800
+ if (path) outputDir.value = path;
1801
+ // No path = user cancelled; do nothing.
1802
+ } catch(e) {
1803
+ // ignore — user can still type a path manually
1804
+ } finally {
1805
+ outputBrowseBtn.disabled = false;
1806
+ outputBrowseBtn.textContent = t('common.browseFolder');
1807
+ }
1808
+ });
1809
+
1810
+ // Browse Folder (Source Path): pick a folder path → auto-scan it.
1811
+ // This is a local tool — no uploading, just reads files by path.
1812
+ const browseFolderBtn = $('browse-folder-btn');
1813
+ browseFolderBtn.addEventListener('click', async () => {
1814
+ browseFolderBtn.disabled = true;
1815
+ browseFolderBtn.textContent = t('common.selecting');
1816
+ try {
1817
+ const path = await pickFolder();
1818
+ if (path) {
1819
+ dirPath.value = path;
1820
+ await scanPath(path);
1821
+ }
1822
+ } catch(e) {
1823
+ showNotice(t('notice.folderPickerFailed', { error: e.message }), 'err');
1824
+ } finally {
1825
+ browseFolderBtn.disabled = false;
1826
+ browseFolderBtn.textContent = t('common.browseFolder');
1827
+ }
1828
+ });
1829
+
1830
+ $('browse-files-btn').addEventListener('click', () => fileInput.click());
1831
+ fileInput.addEventListener('change', async (e) => {
1832
+ const files = e.target.files;
1833
+ if (!files.length) return;
1834
+ await uploadFiles(files);
1835
+ });
1836
+
1837
+ async function uploadFiles(files) {
1838
+ dismissPersistentNotice();
1839
+ const formData = new FormData();
1840
+ for (const f of files) formData.append('files', f);
1841
+
1842
+ try {
1843
+ const r = await apiFetch('/api/upload', { method: 'POST', body: formData });
1844
+ const d = await r.json();
1845
+ if (d.error) { showNotice(d.error, 'err'); return; }
1846
+ STATE.files = d.files;
1847
+ STATE.wsName = d.files[0]?.thumbnail?.split('/')[3] || '';
1848
+ renderFiles();
1849
+ showConfigSection();
1850
+ } catch(e) {
1851
+ showNotice(t('notice.uploadFailed', { error: e.message }), 'err');
1852
+ }
1853
+ }
1854
+
1855
+ // Render file grid
1856
+ function renderFiles() {
1857
+ // Sort a copy — STATE.files must keep its stable scan order (ids are
1858
+ // positional and runOptimize sends file_ids from it untouched); the
1859
+ // dropdown only changes the display order.
1860
+ const files = sortFileList(STATE.files);
1861
+ // Drop override entries for ids no longer present (e.g. after a re-scan
1862
+ // of a different folder). Keeps STATE.fileOverrides in sync with the
1863
+ // current file set without wiping the user's per-file edits on a mere
1864
+ // re-render (same ids are preserved).
1865
+ const ids = new Set(files.map(f => f.id));
1866
+ for (const k of Object.keys(STATE.fileOverrides)) {
1867
+ if (!ids.has(k)) delete STATE.fileOverrides[k];
1868
+ }
1869
+ if (!files.length) {
1870
+ fileGrid.innerHTML = '';
1871
+ filesEmpty.textContent = t('input.noImagesFound');
1872
+ filesEmpty.style.display = '';
1873
+ fileStatsText.textContent = '';
1874
+ selectAll.checked = true;
1875
+ return;
1876
+ }
1877
+ filesEmpty.style.display = 'none';
1878
+ // Remember which cards the user deselected so a re-render triggered by
1879
+ // the Sort dropdown doesn't silently re-select everything.
1880
+ const unselected = new Set(
1881
+ [...fileGrid.querySelectorAll('.file-card:not(.selected)')].map(el => el.dataset.id)
1882
+ );
1883
+ let html = '';
1884
+ for (const f of files) {
1885
+ const selClass = unselected.has(f.id) ? '' : ' selected';
1886
+ html += `
1887
+ <div class="file-card${selClass}" data-id="${f.id}" onclick="toggleFile('${f.id}')">
1888
+ <div class="fc-main">
1889
+ <img class="thumb" src="${f.thumbnail}" alt="${escHtml(f.name)}" loading="lazy" />
1890
+ <div class="fname" title="${escHtml(f.name)}">${escHtml(f.name)}</div>
1891
+ <div class="fmeta">
1892
+ <span class="fsize" title="${fmtSize(f.size)}">${fmtSize(f.size)}</span>
1893
+ <button class="preview-btn" type="button"
1894
+ title="${t('files.previewTitle')}"
1895
+ onclick="event.stopPropagation(); previewFile('${f.id}', this)">${t('files.preview')}</button>
1896
+ </div>
1897
+ <div class="check">✓</div>
1898
+ <button class="card-gear" type="button" title="${t('files.overrideTitle')}"
1899
+ onclick="event.stopPropagation(); toggleFileOverride('${f.id}', this)">⚙</button>
1900
+ </div>
1901
+ <div class="file-override" data-id="${f.id}" hidden onclick="event.stopPropagation()">
1902
+ <div class="fo-row">
1903
+ <span class="fo-label">${t('config.quality')}</span>
1904
+ <select data-field="quality" onchange="setFileOverride('${f.id}')">
1905
+ <option value="">${t('files.inherit')}</option><option value="high">${t('config.qualityHigh')}</option><option value="medium">${t('config.qualityMedium')}</option><option value="low">${t('config.qualityLow')}</option>
1906
+ </select>
1907
+ </div>
1908
+ <div class="fo-row">
1909
+ <span class="fo-label">${t('files.overrideMode')}</span>
1910
+ <select data-field="compression_mode" onchange="setFileOverride('${f.id}')">
1911
+ <option value="">${t('files.inherit')}</option><option value="standard">${t('config.modeStandard')}</option><option value="lossless">${t('config.modeLossless')}</option><option value="resize_only">${t('config.modeResize')}</option>
1912
+ </select>
1913
+ </div>
1914
+ <div class="fo-row">
1915
+ <span class="fo-label">${t('files.overrideWidth')}</span>
1916
+ <input type="number" min="0" data-field="max_width" placeholder="${t('files.inherit')}" oninput="setFileOverride('${f.id}')">
1917
+ </div>
1918
+ <div class="fo-row">
1919
+ <span class="fo-label">${t('config.outputFormat')}</span>
1920
+ <select data-field="output_format" onchange="setFileOverride('${f.id}')">
1921
+ <option value="">${t('files.inherit')}</option><option value="png">PNG</option><option value="webp">WebP</option><option value="jpg">JPG</option>
1922
+ </select>
1923
+ </div>
1924
+ </div>
1925
+ </div>
1926
+ `;
1927
+ }
1928
+ fileGrid.innerHTML = html;
1929
+ const total = files.reduce((s, f) => s + f.size, 0);
1930
+ fileStatsText.textContent = t('files.stats', { count: files.length, size: fmtSize(total) });
1931
+ selectAll.checked = !fileGrid.querySelector('.file-card:not(.selected)');
1932
+ }
1933
+
1934
+ // Files-grid Sort dropdown: display-order only (see renderFiles). mtime =
1935
+ // last modified, ctime = creation time (Windows); both come from the scan
1936
+ // result entries. Missing timestamps (corrupt-file entries) sort as oldest.
1937
+ function sortFileList(files) {
1938
+ const arr = files.slice();
1939
+ switch (STATE.fileSort) {
1940
+ case 'mtime_desc': arr.sort((a, b) => (b.mtime || 0) - (a.mtime || 0)); break;
1941
+ case 'mtime_asc': arr.sort((a, b) => (a.mtime || 0) - (b.mtime || 0)); break;
1942
+ case 'ctime_desc': arr.sort((a, b) => (b.ctime || 0) - (a.ctime || 0)); break;
1943
+ case 'ctime_asc': arr.sort((a, b) => (a.ctime || 0) - (b.ctime || 0)); break;
1944
+ case 'size_desc': arr.sort((a, b) => (b.size || 0) - (a.size || 0)); break;
1945
+ case 'size_asc': arr.sort((a, b) => (a.size || 0) - (b.size || 0)); break;
1946
+ default: break; // 'default' keeps scan order
1947
+ }
1948
+ return arr;
1949
+ }
1950
+
1951
+ fileSortSel.addEventListener('change', () => { STATE.fileSort = fileSortSel.value; renderFiles(); });
1952
+
1953
+ function toggleFile(id) {
1954
+ const el = fileGrid.querySelector(`[data-id="${id}"]`);
1955
+ if (!el) return;
1956
+ el.classList.toggle('selected');
1957
+ const all = fileGrid.querySelectorAll('.file-card');
1958
+ const sel = fileGrid.querySelectorAll('.file-card.selected');
1959
+ selectAll.checked = all.length === sel.length;
1960
+ }
1961
+
1962
+ // Single-file dry run: projects the compressed size of one file under the
1963
+ // current settings WITHOUT touching the results list or the download ZIP
1964
+ // (server-side it writes to ws/preview, not ws/output, then deletes it).
1965
+ // Reads the same controls runOptimize uses so the projection matches what
1966
+ // a real run would produce for this file.
1967
+ async function previewFile(id, btn) {
1968
+ if (STATE.isRunning) { showNotice(t('notice.waitForCurrentRun'), 'err'); return; }
1969
+ const quality = document.querySelector('input[name="quality"]:checked').value;
1970
+ const maxWidth = parseInt($('max-width').value);
1971
+ const format = document.querySelector('input[name="format"]:checked').value;
1972
+ const compressionMode = document.querySelector('input[name="mode"]:checked').value;
1973
+ const protectedColors = protectColorsInput.value.split(',').map(s => s.trim()).filter(Boolean);
1974
+ const dithering = ditheringInput.checked;
1975
+ const keepExif = $('keep-exif').checked;
1976
+ const prevText = btn.textContent;
1977
+ btn.disabled = true;
1978
+ btn.textContent = '...';
1979
+ try {
1980
+ const r = await apiFetch('/api/preview-optimize', {
1981
+ method: 'POST',
1982
+ headers: { 'Content-Type': 'application/json' },
1983
+ body: JSON.stringify({
1984
+ file_id: id, quality, max_width: maxWidth, output_format: format,
1985
+ compression_mode: compressionMode, protected_colors: protectedColors,
1986
+ dithering, keep_exif: keepExif,
1987
+ }),
1988
+ });
1989
+ const d = await r.json();
1990
+ if (!r.ok || d.error) {
1991
+ btn.textContent = t('common.failed');
1992
+ showNotice(d.error || t('notice.previewFailed'), 'err');
1993
+ } else {
1994
+ // Show projected size + savings; reverts after a few seconds.
1995
+ btn.textContent = `${fmtSize(d.compressed_size)} (-${d.savings_percent}%)`;
1996
+ }
1997
+ } catch (e) {
1998
+ btn.textContent = t('common.failed');
1999
+ } finally {
2000
+ btn.disabled = false;
2001
+ setTimeout(() => { if (btn.textContent !== t('files.preview')) btn.textContent = t('files.preview'); }, 4000);
2002
+ }
2003
+ }
2004
+
2005
+ // Per-file override UI: clicking the gear toggles a small panel where the
2006
+ // user sets quality/mode/width for just this file. Empty/"inherit" values
2007
+ // are dropped, so STATE.fileOverrides only holds files with at least one
2008
+ // non-default field — exactly the "only override files the user manually
2009
+ // expanded" rule from the review. The whole map is sent on Start; the
2010
+ // server ignores entries for unselected ids.
2011
+ function toggleFileOverride(id, gearBtn) {
2012
+ const card = fileGrid.querySelector(`.file-card[data-id="${id}"]`);
2013
+ if (!card) return;
2014
+ const panel = card.querySelector('.file-override');
2015
+ const willShow = panel.hasAttribute('hidden');
2016
+ if (willShow) panel.removeAttribute('hidden'); else panel.setAttribute('hidden', '');
2017
+ // Pre-fill the panel from any existing override for this file.
2018
+ const ov = STATE.fileOverrides[id] || {};
2019
+ card.querySelectorAll('.file-override [data-field]').forEach(el => {
2020
+ el.value = ov[el.dataset.field] != null ? ov[el.dataset.field] : '';
2021
+ });
2022
+ }
2023
+ function setFileOverride(id) {
2024
+ const card = fileGrid.querySelector(`.file-card[data-id="${id}"]`);
2025
+ if (!card) return;
2026
+ const ov = {};
2027
+ card.querySelectorAll('.file-override [data-field]').forEach(el => {
2028
+ const v = el.value.trim();
2029
+ if (v !== '') ov[el.dataset.field] = el.dataset.field === 'max_width' ? parseInt(v) : v;
2030
+ });
2031
+ if (Object.keys(ov).length) {
2032
+ STATE.fileOverrides[id] = ov;
2033
+ card.classList.add('has-override');
2034
+ } else {
2035
+ delete STATE.fileOverrides[id];
2036
+ card.classList.remove('has-override');
2037
+ }
2038
+ }
2039
+
2040
+ selectAll.addEventListener('change', () => {
2041
+ const checked = selectAll.checked;
2042
+ fileGrid.querySelectorAll('.file-card').forEach(el => el.classList.toggle('selected', checked));
2043
+ });
2044
+
2045
+ // Show config and files sections
2046
+ function showConfigSection() {
2047
+ configSection.classList.add('active');
2048
+ filesSection.classList.add('active');
2049
+ const files = STATE.files;
2050
+ fileCountInfo.textContent = files.length ? `${files.length} files ready` : 'No files found';
2051
+ updateStartButtonState();
2052
+ }
2053
+
2054
+ // Compression Mode: controls which settings are relevant.
2055
+ function updateModeDependentControls() {
2056
+ const mode = document.querySelector('input[name="mode"]:checked').value;
2057
+ const isScreenshot = mode === 'screenshot';
2058
+
2059
+ // Screenshot mode is PNG-only (it's a tuned pngquant pass, not a general
2060
+ // codec setting) — lock the format to PNG and disable the others so the
2061
+ // user can't land on a combination the backend would 400 on. Re-enabling
2062
+ // happens naturally below since this whole block re-runs on every mode
2063
+ // change, including switching away from Screenshot.
2064
+ if (isScreenshot) {
2065
+ document.getElementById('fmt-png').checked = true;
2066
+ }
2067
+ document.querySelectorAll('input[name="format"]').forEach(r => {
2068
+ r.disabled = isScreenshot && r.value !== 'png';
2069
+ });
2070
+
2071
+ const format = document.querySelector('input[name="format"]:checked').value;
2072
+ const isStandard = mode === 'standard';
2073
+ const isPng = format === 'png';
2074
+
2075
+ // Protect Colors / Dithering: pngquant-specific — only apply in Standard
2076
+ // mode AND when the output format is PNG (WebP uses its own encoder and
2077
+ // never touches pngquant, regardless of compression mode). Screenshot
2078
+ // mode uses pngquant too, but with hardcoded internal settings (a much
2079
+ // tighter quality floor, dithering forced off) — these controls don't
2080
+ // apply to it either, same as every other non-Standard mode.
2081
+ const pngquantApplies = isStandard && isPng;
2082
+ protectColorsInput.disabled = !pngquantApplies;
2083
+ ditheringInput.disabled = !pngquantApplies;
2084
+ protectColorsGroup.classList.toggle('disabled-group', !pngquantApplies);
2085
+ ditheringGroup.classList.toggle('disabled-group', !pngquantApplies);
2086
+
2087
+ // Quality: relevant for Standard-mode PNG (pngquant target), Standard-mode
2088
+ // WebP/AVIF (Pillow's/avifenc's own quality parameter), and Standard-mode
2089
+ // JPEG (cjpeg -quality) — only meaningless when compression mode isn't
2090
+ // Standard (Lossless/Resize Only/Screenshot skip quality entirely).
2091
+ document.querySelectorAll('input[name="quality"]').forEach(r => r.disabled = !isStandard);
2092
+ document.getElementById('quality-group').classList.toggle('disabled-group', !isStandard);
2093
+
2094
+ // Max Width is intentionally NOT tied to compression mode or format in
2095
+ // general — resizing is orthogonal to how colors/encoding are handled,
2096
+ // so it stays enabled for Standard/Lossless/Resize Only. Screenshot mode
2097
+ // is the one exception: it never resizes (the whole point is keeping UI
2098
+ // text pixel-sharp at full resolution — see optimizer.py), and silently
2099
+ // ignores max_width server-side, so leaving the control enabled here
2100
+ // would let the user set a value that quietly does nothing.
2101
+ $('max-width').disabled = isScreenshot;
2102
+ $('max-width').closest('.config-group')?.classList.toggle('disabled-group', isScreenshot);
2103
+
2104
+ // JPEG is an inherently lossy codec — there's no true lossless pass, so
2105
+ // 'Lossless'/'Resize Only' for JPG just encodes at mozjpeg's highest
2106
+ // quality (~95) with no palette change. Tell the user that up front
2107
+ // instead of implying pixel-perfect output.
2108
+ const modeNote = $('mode-note');
2109
+ if (format === 'jpg' && !isStandard && !isScreenshot) {
2110
+ modeNote.textContent = t('config.modeNoteJpeg');
2111
+ modeNote.style.display = 'block';
2112
+ } else {
2113
+ modeNote.style.display = 'none';
2114
+ }
2115
+
2116
+ updateStartButtonState();
2117
+ }
2118
+ document.querySelectorAll('input[name="format"]').forEach(r => r.addEventListener('change', updateModeDependentControls));
2119
+ document.querySelectorAll('input[name="mode"]').forEach(r => r.addEventListener('change', updateModeDependentControls));
2120
+ $('max-width').addEventListener('change', updateStartButtonState);
2121
+
2122
+ // Central place that decides whether Start can be clicked: needs at least
2123
+ // one file, and Resize Only mode specifically needs a Max Width > 0 (it has
2124
+ // nothing else to do otherwise).
2125
+ function updateStartButtonState() {
2126
+ const hasFiles = STATE.files.length > 0;
2127
+ const mode = document.querySelector('input[name="mode"]:checked').value;
2128
+ const maxWidth = parseInt($('max-width').value);
2129
+ const resizeOnlyNeedsWidth = mode === 'resize_only' && maxWidth <= 0;
2130
+ if (resizeOnlyNeedsWidth) {
2131
+ modeHint.textContent = t('config.resizeOnlyHint');
2132
+ modeHint.style.display = 'block';
2133
+ } else {
2134
+ modeHint.style.display = 'none';
2135
+ }
2136
+ startBtn.disabled = STATE.isRunning || !hasFiles || resizeOnlyNeedsWidth;
2137
+ }
2138
+
2139
+ // Start optimization. Shared by the Start button (full/selected run) and the
2140
+ // Retry Failed button (retry=true re-runs only the given ids server-side
2141
+ // without wiping earlier successful outputs).
2142
+ async function runOptimize(ids, opts) {
2143
+ opts = opts || {};
2144
+ const retry = !!opts.retry;
2145
+
2146
+ const quality = document.querySelector('input[name="quality"]:checked').value;
2147
+ const maxWidth = parseInt($('max-width').value);
2148
+ const format = document.querySelector('input[name="format"]:checked').value;
2149
+ const outputDir = $('output-dir').value.trim();
2150
+ const compressionMode = document.querySelector('input[name="mode"]:checked').value;
2151
+ const protectedColors = protectColorsInput.value.split(',').map(s => s.trim()).filter(Boolean);
2152
+ const dithering = ditheringInput.checked;
2153
+
2154
+ STATE.isRunning = true;
2155
+ STATE.runStartTime = Date.now();
2156
+ STATE.total = ids.length;
2157
+ if (!retry) STATE.results = [];
2158
+ // Incremental-poll cursors always restart at 0 for a new run: the server's
2159
+ // state.results is the source of truth (on retry it already holds the
2160
+ // preserved successes), so a from-zero first poll re-syncs the full set,
2161
+ // then subsequent polls only carry the tail.
2162
+ STATE.resultCursor = 0;
2163
+ STATE.logCursor = 0;
2164
+ STATE.logLines = [];
2165
+ STATE.isPaused = false;
2166
+ // Clean up any transport left over from a previous run before starting fresh.
2167
+ if (STATE.pollTimer) { clearInterval(STATE.pollTimer); STATE.pollTimer = null; }
2168
+ stopSSE();
2169
+
2170
+ dismissPersistentNotice();
2171
+
2172
+ // Show progress section
2173
+ progressSection.classList.add('active');
2174
+ resultsSection.classList.remove('active');
2175
+ cancelBtn.style.display = '';
2176
+ pauseBtn.style.display = '';
2177
+ resumeBtn.style.display = 'none';
2178
+ logBox.innerHTML = '';
2179
+ progressFill.style.width = '0%';
2180
+ progressText.textContent = retry ? 'Retrying...' : 'Starting...';
2181
+ startBtn.disabled = true;
2182
+ retryBtn.disabled = true;
2183
+
2184
+ try {
2185
+ const r = await apiFetch('/api/optimize', {
2186
+ method: 'POST',
2187
+ headers: { 'Content-Type': 'application/json' },
2188
+ body: JSON.stringify({
2189
+ file_ids: ids, quality, max_width: maxWidth, output_format: format, output_dir: outputDir,
2190
+ compression_mode: compressionMode, protected_colors: protectedColors, dithering, retry,
2191
+ skip_existing: $('skip-existing').checked,
2192
+ keep_exif: $('keep-exif').checked,
2193
+ overrides: STATE.fileOverrides,
2194
+ }),
2195
+ });
2196
+ const d = await r.json();
2197
+ if (d.error) {
2198
+ showNotice(d.error, 'err');
2199
+ STATE.isRunning = false;
2200
+ cancelBtn.style.display = 'none';
2201
+ pauseBtn.style.display = 'none';
2202
+ resumeBtn.style.display = 'none';
2203
+ retryBtn.disabled = false;
2204
+ updateStartButtonState();
2205
+ return;
2206
+ }
2207
+ if (d.warning) showNotice(d.warning, 'info');
2208
+
2209
+ // Stream progress over SSE (primary); falls back to polling
2210
+ // automatically on connect failure or sustained silence.
2211
+ startSSE();
2212
+ loadRecentPaths();
2213
+ } catch(e) {
2214
+ showNotice((retry ? t('notice.retryFailedPrefix') : t('notice.startFailedPrefix')) + e.message, 'err');
2215
+ STATE.isRunning = false;
2216
+ cancelBtn.style.display = 'none';
2217
+ pauseBtn.style.display = 'none';
2218
+ resumeBtn.style.display = 'none';
2219
+ retryBtn.disabled = false;
2220
+ updateStartButtonState();
2221
+ }
2222
+ }
2223
+
2224
+ startBtn.addEventListener('click', () => {
2225
+ const selected = fileGrid.querySelectorAll('.file-card.selected');
2226
+ const ids = Array.from(selected).map(el => el.dataset.id);
2227
+ runOptimize(ids, { retry: false });
2228
+ });
2229
+
2230
+ retryBtn.addEventListener('click', () => {
2231
+ const failedIds = STATE.results.filter(r => !r.success).map(r => r.id).filter(id => id != null);
2232
+ if (!failedIds.length) { showNotice(t('notice.noFailedFiles'), 'info'); return; }
2233
+ runOptimize(failedIds, { retry: true });
2234
+ });
2235
+
2236
+ async function pollProgress() {
2237
+ try {
2238
+ const r = await fetch(`/api/progress?since_result=${STATE.resultCursor}&since_log=${STATE.logCursor}`);
2239
+ const d = await r.json();
2240
+
2241
+ STATE.isRunning = d.running;
2242
+ STATE.isPaused = !!d.paused;
2243
+ setRunButtons(d.running, d.paused);
2244
+
2245
+ // Accumulate the incremental results tail. When the cursor is 0 (first
2246
+ // poll of a run, or a reattach) we replace; afterwards we append only the
2247
+ // new entries the server sent. STATE.results stays the full set either way.
2248
+ if (d.results && d.results.length) {
2249
+ if (STATE.resultCursor === 0) STATE.results = d.results.slice();
2250
+ else for (const item of d.results) STATE.results.push(item);
2251
+ }
2252
+ if (typeof d.result_total === 'number') STATE.resultCursor = d.result_total;
2253
+
2254
+ renderProgressBar(d.running, d.paused, d.current, d.total);
2255
+ if (d.logs && d.logs.length) {
2256
+ for (const l of d.logs) STATE.logLines.push(l);
2257
+ renderLogs();
2258
+ }
2259
+ if (typeof d.log_total === 'number') STATE.logCursor = d.log_total;
2260
+
2261
+ if (!d.running) {
2262
+ finalizeRun();
2263
+ }
2264
+ } catch(e) {
2265
+ // ignore poll errors
2266
+ }
2267
+ }
2268
+
2269
+ // --- SSE transport (primary) with polling fallback ---
2270
+ // EventSource streams result/log/done events; if it errors or goes silent
2271
+ // for several seconds (proxy buffering, paused run), we drop to the polling
2272
+ // path above automatically. Both read the same server state, so the user
2273
+ // sees consistent progress either way. See OPTIMIZATION_PLAN.md §5.
2274
+ let sseSource = null, sseWatchdog = null, sseLastMsg = 0, usingSSE = false;
2275
+ const SSE_SILENCE_MS = 8000;
2276
+
2277
+ function startSSE() {
2278
+ usingSSE = true;
2279
+ sseLastMsg = Date.now();
2280
+ try {
2281
+ sseSource = new EventSource('/api/events');
2282
+ } catch (e) {
2283
+ fallbackToPolling();
2284
+ return;
2285
+ }
2286
+ sseSource.addEventListener('status', e => {
2287
+ sseLastMsg = Date.now();
2288
+ let d = {};
2289
+ try { d = JSON.parse(e.data); } catch (_) {}
2290
+ STATE.isPaused = !!d.paused;
2291
+ setRunButtons(true, STATE.isPaused);
2292
+ renderProgressBar(true, STATE.isPaused, d.current != null ? d.current : STATE.results.length, d.total != null ? d.total : STATE.total);
2293
+ });
2294
+ sseSource.addEventListener('result', e => {
2295
+ sseLastMsg = Date.now();
2296
+ try { STATE.results.push(JSON.parse(e.data)); } catch (_) {}
2297
+ // A result can arrive just after Pause was clicked — it's a file that
2298
+ // was already mid-compression when the run paused, finishing up on its
2299
+ // own (see /api/pause docstring). Keep reflecting the real paused state
2300
+ // here rather than assuming "a result came in, so we must be running
2301
+ // normally" — that assumption is what made Pause look broken.
2302
+ setRunButtons(true, STATE.isPaused);
2303
+ renderProgressBar(true, STATE.isPaused, STATE.results.length, STATE.total);
2304
+ });
2305
+ sseSource.addEventListener('log', e => {
2306
+ sseLastMsg = Date.now();
2307
+ try { STATE.logLines.push(JSON.parse(e.data).line); } catch (_) {}
2308
+ renderLogs();
2309
+ });
2310
+ sseSource.addEventListener('done', e => {
2311
+ sseLastMsg = Date.now();
2312
+ let d = {};
2313
+ try { d = JSON.parse(e.data); } catch (_) {}
2314
+ STATE.isRunning = false;
2315
+ stopSSE();
2316
+ renderProgressBar(false, false, d.current != null ? d.current : STATE.results.length, d.total != null ? d.total : STATE.total);
2317
+ finalizeRun();
2318
+ });
2319
+ sseSource.onerror = () => { fallbackToPolling(); };
2320
+ // Watchdog: silent too long → a proxy may be buffering the stream, or the
2321
+ // run is paused (SSE sends only heartbeats then). Polling reports the full
2322
+ // state (including paused) so fall back rather than look frozen.
2323
+ sseWatchdog = setInterval(() => {
2324
+ if (usingSSE && Date.now() - sseLastMsg > SSE_SILENCE_MS) fallbackToPolling();
2325
+ }, 2000);
2326
+ }
2327
+
2328
+ function stopSSE() {
2329
+ usingSSE = false;
2330
+ if (sseSource) { sseSource.close(); sseSource = null; }
2331
+ if (sseWatchdog) { clearInterval(sseWatchdog); sseWatchdog = null; }
2332
+ }
2333
+
2334
+ function fallbackToPolling() {
2335
+ stopSSE();
2336
+ if (!STATE.pollTimer && STATE.isRunning) {
2337
+ STATE.pollTimer = setInterval(pollProgress, 400);
2338
+ }
2339
+ }
2340
+
2341
+ // Shared render helpers used by both the SSE path and the polling fallback.
2342
+ function setRunButtons(running, paused) {
2343
+ if (running) {
2344
+ cancelBtn.style.display = '';
2345
+ pauseBtn.style.display = paused ? 'none' : '';
2346
+ resumeBtn.style.display = paused ? '' : 'none';
2347
+ } else {
2348
+ cancelBtn.style.display = 'none';
2349
+ pauseBtn.style.display = 'none';
2350
+ resumeBtn.style.display = 'none';
2351
+ }
2352
+ }
2353
+
2354
+ function renderProgressBar(running, paused, current, total) {
2355
+ const pct = total > 0 ? Math.round(current / total * 100) : 0;
2356
+ progressFill.style.width = pct + '%';
2357
+ let txt = running ? (paused ? `Paused ${current}/${total}` : `Processing ${current}/${total}`) : `${current}/${total}`;
2358
+ if (running && !paused && current > 0 && STATE.runStartTime) {
2359
+ const elapsed = (Date.now() - STATE.runStartTime) / 1000;
2360
+ if (elapsed > 0) {
2361
+ const rate = current / elapsed;
2362
+ const remaining = Math.max(0, total - current);
2363
+ const eta = rate > 0 ? remaining / rate : 0;
2364
+ txt += ` \u00b7 ${rate.toFixed(1)} img/s \u00b7 ~${fmtDuration(eta)} left`;
2365
+ }
2366
+ }
2367
+ progressText.textContent = txt;
2368
+ }
2369
+
2370
+ function renderLogs() {
2371
+ if (STATE.logLines.length > 500) STATE.logLines = STATE.logLines.slice(-500);
2372
+ // escHtml on every line: log lines embed file names, and a name like
2373
+ // "<img src=x onerror=...>.png" (legal on Linux) must render as text.
2374
+ logBox.innerHTML = STATE.logLines.map(l => {
2375
+ let c = 'log-entry';
2376
+ if (l.indexOf('OK ') !== -1 || l.indexOf('\u2713') !== -1) c += ' ok';
2377
+ else if (l.indexOf('FAILED') !== -1 || l.indexOf('\u2717') !== -1) c += ' err';
2378
+ else if (l.startsWith(' ')) c += ' info';
2379
+ return `<div class="${c}">${escHtml(l)}</div>`;
2380
+ }).join('');
2381
+ logBox.scrollTop = logBox.scrollHeight;
2382
+ }
2383
+
2384
+ function finalizeRun() {
2385
+ if (STATE.pollTimer) { clearInterval(STATE.pollTimer); STATE.pollTimer = null; }
2386
+ if (STATE.thumbPollTimer) { clearInterval(STATE.thumbPollTimer); STATE.thumbPollTimer = null; }
2387
+ stopSSE();
2388
+ setRunButtons(false, false);
2389
+ if (STATE.results.length > 0) {
2390
+ // Don't clobber a wsName that's already correct (e.g. set by
2391
+ // restoreState() after a resume) — this thumbnail-based derivation
2392
+ // gives '' for files rebuilt on resume, since those never get a
2393
+ // regenerated thumbnail.
2394
+ if (!STATE.wsName) STATE.wsName = STATE.files[0]?.thumbnail?.split('/')[3] || '';
2395
+ showResults();
2396
+ showPersistentNotice(`Compression complete! ${STATE.results.filter(r => r.success).length}/${STATE.results.length} files optimized.`, 'ok');
2397
+ } else {
2398
+ // e.g. cancelled before any file finished — nothing to show, but
2399
+ // Start still needs to become clickable again.
2400
+ updateStartButtonState();
2401
+ }
2402
+ }
2403
+
2404
+ // Cancel
2405
+ cancelBtn.addEventListener('click', async () => {
2406
+ await apiFetch('/api/cancel', { method: 'POST' });
2407
+ });
2408
+
2409
+ // Pause / Resume (soft pause: new files stop scheduling, in-flight finish)
2410
+ pauseBtn.addEventListener('click', async () => {
2411
+ await apiFetch('/api/pause', { method: 'POST' });
2412
+ });
2413
+ resumeBtn.addEventListener('click', async () => {
2414
+ await apiFetch('/api/resume', { method: 'POST' });
2415
+ });
2416
+
2417
+ // Show results
2418
+ function showResults() {
2419
+ resultsSection.classList.add('active');
2420
+ resultsEmpty.style.display = 'none';
2421
+ const results = STATE.results;
2422
+ const success = results.filter(r => r.success);
2423
+ const failed = results.filter(r => !r.success);
2424
+
2425
+ // Summary
2426
+ const totalOrig = success.reduce((s, r) => s + r.original_size, 0);
2427
+ const totalComp = success.reduce((s, r) => s + r.compressed_size, 0);
2428
+ const saved = totalOrig - totalComp;
2429
+ const pct = totalOrig > 0 ? (saved / totalOrig * 100).toFixed(1) : 0;
2430
+ resultSummary.innerHTML = `
2431
+ <div class="result-stat">
2432
+ <div class="value accent">${results.length}</div>
2433
+ <div class="label">${t('results.stat.files')}</div>
2434
+ </div>
2435
+ <div class="result-stat">
2436
+ <div class="value green">${pct}%</div>
2437
+ <div class="label">${t('results.stat.compression')}</div>
2438
+ </div>
2439
+ <div class="result-stat">
2440
+ <div class="value accent">${fmtSize(totalOrig)}</div>
2441
+ <div class="label">${t('results.stat.original')}</div>
2442
+ </div>
2443
+ <div class="result-stat">
2444
+ <div class="value green">${fmtSize(totalComp)}</div>
2445
+ <div class="label">${t('results.stat.compressed')}</div>
2446
+ </div>
2447
+ <div class="result-stat">
2448
+ <div class="value accent">${fmtSize(saved)}</div>
2449
+ <div class="label">${t('results.stat.saved')}</div>
2450
+ </div>
2451
+ `;
2452
+
2453
+ // Sort/filter toolbar is only useful once there's something to sort.
2454
+ resultToolbar.style.display = results.length ? 'flex' : 'none';
2455
+ renderResultGrid();
2456
+
2457
+ // Show output path info
2458
+ const outputDir = $('output-dir').value.trim();
2459
+ if (outputDir) {
2460
+ $('output-path-info').textContent = t('output.prefix') + outputDir;
2461
+ } else {
2462
+ $('output-path-info').textContent = '';
2463
+ }
2464
+
2465
+ // Enable download (any success), Reveal Output Folder (any result that
2466
+ // actually landed in a persistent output dir — final_output_path is only
2467
+ // set then, see process_one) and Retry Failed (any failure).
2468
+ downloadBtn.style.display = success.length > 0 ? 'inline-block' : 'none';
2469
+ revealDirBtn.style.display = success.some(r => r.final_output_path) ? 'inline-block' : 'none';
2470
+ retryBtn.style.display = failed.length > 0 ? 'inline-block' : 'none';
2471
+ retryBtn.disabled = false;
2472
+ updateStartButtonState();
2473
+ progressText.textContent = t('progress.complete');
2474
+ }
2475
+
2476
+ // Render the result cards applying the current filter then sort. Reads from
2477
+ // STATE.results (never mutates it — default order must survive), so the
2478
+ // toolbar can re-render instantly without re-fetching.
2479
+ function renderResultGrid() {
2480
+ let rows = STATE.results.slice();
2481
+ if (STATE.resultFilter === 'success') rows = rows.filter(r => r.success);
2482
+ else if (STATE.resultFilter === 'failed') rows = rows.filter(r => !r.success);
2483
+
2484
+ const savedBytes = r => (r.original_size || 0) - (r.compressed_size || 0);
2485
+ switch (STATE.resultSort) {
2486
+ case 'savings_desc': rows.sort((a, b) => (b.savings_percent || 0) - (a.savings_percent || 0)); break;
2487
+ case 'savings_asc': rows.sort((a, b) => (a.savings_percent || 0) - (b.savings_percent || 0)); break;
2488
+ case 'size_desc': rows.sort((a, b) => (b.compressed_size || 0) - (a.compressed_size || 0)); break;
2489
+ case 'saved_desc': rows.sort((a, b) => savedBytes(b) - savedBytes(a)); break;
2490
+ default: break; // 'default' keeps completion order
2491
+ }
2492
+
2493
+ let html = '';
2494
+ for (const r of rows) {
2495
+ if (!r.success) {
2496
+ html += `
2497
+ <div class="result-card" style="opacity:.5">
2498
+ <div class="rname" title="${escHtml(r.name || '')}">✗ ${escHtml(r.name || '')}</div>
2499
+ <div class="rstats">${escHtml(r.error) || t('results.failedLabel')}</div>
2500
+ </div>`;
2501
+ continue;
2502
+ }
2503
+ const previewUrl = `/api/preview/${STATE.wsName}/${r.id}?lang=${encodeURIComponent(currentLang())}`;
2504
+ const savedLine = r.skipped
2505
+ ? `<div class="rsaved">${t('results.skipped')}</div>`
2506
+ : `<div class="rsaved">${t('results.saved', { pct: r.savings_percent })}</div>`;
2507
+ html += `
2508
+ <div class="result-card">
2509
+ <div class="rname" title="${escHtml(r.name)}">${escHtml(r.name)}</div>
2510
+ <div class="rstats">${fmtSize(r.original_size)} → ${fmtSize(r.compressed_size)}</div>
2511
+ ${savedLine}
2512
+ <a class="compare-btn" href="${previewUrl}" target="_blank">${t('results.compare')}</a>
2513
+ </div>`;
2514
+ }
2515
+ resultGrid.innerHTML = html;
2516
+
2517
+ const total = STATE.results.length, shown = rows.length;
2518
+ resultCountEl.textContent = shown === total ? t('results.countAll', { total }) : t('results.countFiltered', { shown, total });
2519
+ }
2520
+
2521
+ // Reveal the run's output folder in the OS file explorer. One button for
2522
+ // the whole folder instead of one per image — there's only ever one
2523
+ // output_dir per run. The client sends no path at all: the backend opens
2524
+ // the output_dir it recorded itself (state.output_dir), so there is
2525
+ // nothing to spoof.
2526
+ revealDirBtn.addEventListener('click', async () => {
2527
+ try {
2528
+ const r = await apiFetch('/api/reveal', {
2529
+ method: 'POST',
2530
+ headers: { 'Content-Type': 'application/json' },
2531
+ body: JSON.stringify({ path: '' }),
2532
+ });
2533
+ const d = await r.json();
2534
+ if (d.error) showNotice(d.error, 'err');
2535
+ } catch (err) {
2536
+ showNotice(t('notice.explorerOpenFailed', { error: err.message }), 'err');
2537
+ }
2538
+ });
2539
+
2540
+ resultSortSel.addEventListener('change', () => { STATE.resultSort = resultSortSel.value; renderResultGrid(); });
2541
+ resultFilterSel.addEventListener('change', () => { STATE.resultFilter = resultFilterSel.value; renderResultGrid(); });
2542
+
2543
+ // Download
2544
+ downloadBtn.addEventListener('click', async () => {
2545
+ const wsName = STATE.wsName;
2546
+ if (!wsName) return;
2547
+ const a = document.createElement('a');
2548
+ a.href = `/api/download/${wsName}`;
2549
+ a.download = 'optimized_images.zip';
2550
+ a.click();
2551
+ });
2552
+
2553
+ // Reset
2554
+ resetBtn.addEventListener('click', async () => {
2555
+ dismissPersistentNotice();
2556
+ resetScanUI();
2557
+ // Clear the server-side session too — otherwise the files/results stay
2558
+ // alive on the server and a page refresh (restoreState) resurrects them.
2559
+ try { await apiFetch('/api/reset', { method: 'POST' }); } catch(e) { /* best-effort */ }
2560
+ STATE.files = [];
2561
+ STATE.results = [];
2562
+ STATE.wsName = '';
2563
+ fileGrid.innerHTML = '';
2564
+ filesEmpty.textContent = t('files.empty');
2565
+ filesEmpty.style.display = '';
2566
+ resultGrid.innerHTML = '';
2567
+ resultSummary.innerHTML = '';
2568
+ resultsEmpty.style.display = '';
2569
+ fileStatsText.textContent = '';
2570
+ startBtn.disabled = true;
2571
+ fileCountInfo.textContent = '';
2572
+ downloadBtn.style.display = 'none';
2573
+ revealDirBtn.style.display = 'none';
2574
+ retryBtn.style.display = 'none';
2575
+ resultToolbar.style.display = 'none';
2576
+ resultCountEl.textContent = '';
2577
+ STATE.runStartTime = 0;
2578
+ STATE.resultCursor = 0;
2579
+ STATE.logCursor = 0;
2580
+ STATE.logLines = [];
2581
+ $('output-path-info').textContent = '';
2582
+ logBox.innerHTML = '';
2583
+ progressFill.style.width = '0%';
2584
+ progressText.textContent = t('progress.waiting');
2585
+ });
2586
+
2587
+ // Restore server-side session state after a page refresh — the server
2588
+ // keeps files/results per session, but the UI used to come back blank
2589
+ // (and /api/state sat unused). Also reattaches to a still-running batch.
2590
+ // Backfills STATE.files' thumbnails after a resume reattach (see the call
2591
+ // site in restoreState()) by re-polling /api/state until every file has
2592
+ // one, merging by id rather than replacing STATE.files wholesale so it
2593
+ // can't clobber anything else concurrent code touches on that array.
2594
+ // Bounded and self-clearing: stops on completion, on run end, or after a
2595
+ // generous cap — same "never outlive the run" discipline as STATE.pollTimer,
2596
+ // after the orphaned-task issues this project has hit before.
2597
+ function pollThumbnailsUntilReady() {
2598
+ if (STATE.thumbPollTimer) return;
2599
+ let attempts = 0;
2600
+ const MAX_ATTEMPTS = 60; // ~60s at 1/s — plenty for thumbnailing a batch
2601
+ STATE.thumbPollTimer = setInterval(async () => {
2602
+ attempts++;
2603
+ if (!STATE.isRunning || attempts > MAX_ATTEMPTS) {
2604
+ clearInterval(STATE.thumbPollTimer);
2605
+ STATE.thumbPollTimer = null;
2606
+ return;
2607
+ }
2608
+ try {
2609
+ const r = await fetch('/api/state');
2610
+ const d = await r.json();
2611
+ const byId = new Map(d.files.map(f => [f.id, f.thumbnail]));
2612
+ let changed = false;
2613
+ for (const f of STATE.files) {
2614
+ const t = byId.get(f.id);
2615
+ if (t && t !== f.thumbnail) { f.thumbnail = t; changed = true; }
2616
+ }
2617
+ if (changed) renderFiles();
2618
+ if (STATE.files.every(f => f.thumbnail)) {
2619
+ clearInterval(STATE.thumbPollTimer);
2620
+ STATE.thumbPollTimer = null;
2621
+ }
2622
+ } catch (e) {
2623
+ // Transient fetch error — leave the timer running, try again next
2624
+ // tick; MAX_ATTEMPTS is the backstop if this keeps failing.
2625
+ }
2626
+ }, 1000);
2627
+ }
2628
+
2629
+ async function restoreState() {
2630
+ try {
2631
+ const r = await fetch('/api/state');
2632
+ const d = await r.json();
2633
+ if (!d.files || !d.files.length) return;
2634
+ STATE.files = d.files;
2635
+ // Prefer the explicit field — thumbnails for files rebuilt on resume
2636
+ // fill in asynchronously (see _backfill_resume_thumbnails on the
2637
+ // backend), so files[0].thumbnail is still "" right when this often
2638
+ // runs. Keep the old derivation only as a fallback for older server
2639
+ // versions.
2640
+ STATE.wsName = d.ws_name || (d.files[0]?.thumbnail?.split('/')[3] || '');
2641
+ if (d.input_dir) dirPath.value = d.input_dir;
2642
+ renderFiles();
2643
+ showConfigSection();
2644
+ if (d.is_running) {
2645
+ STATE.isRunning = true;
2646
+ STATE.isPaused = !!d.paused;
2647
+ // total/current weren't set anywhere on this path — renderProgressBar
2648
+ // falls back to STATE.total whenever an SSE event doesn't carry its
2649
+ // own total, so it silently showed "Processing N/undefined" here.
2650
+ STATE.total = d.total;
2651
+ // We didn't see this run start, so treat "now" as t0 for ETA. The
2652
+ // estimate will be rough until a few more files complete under our
2653
+ // own timing, then converge — good enough for a reattach.
2654
+ STATE.runStartTime = Date.now();
2655
+ // Reattaching mid-run: pull from the start so the first poll re-syncs
2656
+ // whatever results/logs already accumulated, then go incremental.
2657
+ STATE.resultCursor = 0;
2658
+ STATE.logCursor = 0;
2659
+ STATE.logLines = [];
2660
+ // Same section/button setup as starting a fresh run (see the top of
2661
+ // the optimize click handler) — restoreState() only ever synced
2662
+ // data, never made the progress card itself visible, so a reattach
2663
+ // (resume, or a page refresh mid-run) left it hidden the whole time.
2664
+ progressSection.classList.add('active');
2665
+ resultsSection.classList.remove('active');
2666
+ setRunButtons(true, STATE.isPaused);
2667
+ renderProgressBar(true, STATE.isPaused, d.current || 0, d.total || 0);
2668
+ updateStartButtonState();
2669
+ // Reattach via SSE (primary): a fresh EventSource replays from r0:l0
2670
+ // so the client re-syncs everything accumulated so far, then continues
2671
+ // live. Falls back to polling on failure/silence.
2672
+ startSSE();
2673
+ // Files rebuilt on resume start with thumbnail: "" and fill in on the
2674
+ // server asynchronously (_backfill_resume_thumbnails) — nothing else
2675
+ // re-fetches state.files after this point, so without this the grid
2676
+ // would just stay blank until the next full page load, even though
2677
+ // the thumbnails were sitting there ready on the server the whole
2678
+ // time. Normal (non-resume) reattaches already have real thumbnails
2679
+ // from scan, so this is a no-op for them.
2680
+ if (d.files.some(f => !f.thumbnail)) pollThumbnailsUntilReady();
2681
+ } else if (d.results && d.results.length) {
2682
+ STATE.results = d.results;
2683
+ showResults();
2684
+ }
2685
+ } catch(e) {
2686
+ // Fresh session or server unreachable — nothing to restore.
2687
+ }
2688
+ }
2689
+
2690
+ // --- Watch mode ---
2691
+ const watchDir = $('watch-dir'),
2692
+ watchOutputDir = $('watch-output-dir'),
2693
+ watchRecursive = $('watch-recursive'),
2694
+ watchProcessExisting = $('watch-process-existing'),
2695
+ watchStartBtn = $('watch-start-btn'),
2696
+ watchStopBtn = $('watch-stop-btn'),
2697
+ watchStatusEl = $('watch-status'),
2698
+ watchLogBox = $('watch-log-box'),
2699
+ watchStatsEl = $('watch-stats');
2700
+
2701
+ async function startWatch() {
2702
+ const dir = watchDir.value.trim();
2703
+ const outputDir = watchOutputDir.value.trim();
2704
+ if (!dir) { showNotice(t('notice.enterWatchDir'), 'err'); return; }
2705
+ if (!outputDir) { showNotice(t('notice.enterOutputDir'), 'err'); return; }
2706
+
2707
+ const quality = document.querySelector('input[name="quality"]:checked').value;
2708
+ const maxWidth = parseInt($('max-width').value);
2709
+ const format = document.querySelector('input[name="format"]:checked').value;
2710
+ const compressionMode = document.querySelector('input[name="mode"]:checked').value;
2711
+ const protectedColors = protectColorsInput.value.split(',').map(s => s.trim()).filter(Boolean);
2712
+ const dithering = ditheringInput.checked;
2713
+ const keepExif = $('keep-exif').checked;
2714
+
2715
+ try {
2716
+ const r = await apiFetch('/api/watch/start', {
2717
+ method: 'POST',
2718
+ headers: { 'Content-Type': 'application/json' },
2719
+ body: JSON.stringify({
2720
+ directory: dir, recursive: watchRecursive.checked,
2721
+ process_existing: watchProcessExisting.checked,
2722
+ quality, max_width: maxWidth, output_format: format,
2723
+ compression_mode: compressionMode, protected_colors: protectedColors,
2724
+ dithering, keep_exif: keepExif, output_dir: outputDir,
2725
+ }),
2726
+ });
2727
+ const d = await r.json();
2728
+ if (d.error) { showNotice(d.error, 'err'); return; }
2729
+ if (d.warning) showNotice(d.warning, 'info');
2730
+ STATE.watchRunning = true;
2731
+ STATE.watchLogs = [];
2732
+ STATE.watchLogCursor = 0;
2733
+ updateWatchUI();
2734
+ startWatchSSE();
2735
+ } catch(e) {
2736
+ showNotice(t('notice.watchStartFailedPrefix') + e.message, 'err');
2737
+ }
2738
+ }
2739
+
2740
+ async function stopWatch() {
2741
+ try {
2742
+ const r = await apiFetch('/api/watch/stop', { method: 'POST' });
2743
+ const d = await r.json();
2744
+ if (d.error) showNotice(d.error, 'err');
2745
+ } catch(e) { /* best-effort */ }
2746
+ STATE.watchRunning = false;
2747
+ stopWatchSSE();
2748
+ updateWatchUI();
2749
+ }
2750
+
2751
+ let watchSSESource = null, watchSSEWatchdog = null, watchSSELastMsg = 0;
2752
+ const WATCH_SSE_SILENCE_MS = 10000;
2753
+
2754
+ function startWatchSSE() {
2755
+ watchSSELastMsg = Date.now();
2756
+ try {
2757
+ watchSSESource = new EventSource('/api/watch/events');
2758
+ } catch (e) { fallbackWatchToPolling(); return; }
2759
+ watchSSESource.addEventListener('watch_log', e => {
2760
+ watchSSELastMsg = Date.now();
2761
+ try { STATE.watchLogs.push(JSON.parse(e.data).line); } catch (_) {}
2762
+ renderWatchLog();
2763
+ });
2764
+ watchSSESource.addEventListener('watch_status', e => {
2765
+ watchSSELastMsg = Date.now();
2766
+ try {
2767
+ const d = JSON.parse(e.data);
2768
+ STATE.watchRunning = d.running;
2769
+ STATE.watchProcessed = d.processed;
2770
+ STATE.watchErrors = d.errors;
2771
+ } catch (_) {}
2772
+ updateWatchUI();
2773
+ if (!STATE.watchRunning) stopWatchSSE();
2774
+ });
2775
+ watchSSESource.onerror = () => { fallbackWatchToPolling(); };
2776
+ watchSSEWatchdog = setInterval(() => {
2777
+ if (watchSSESource && Date.now() - watchSSELastMsg > WATCH_SSE_SILENCE_MS) fallbackWatchToPolling();
2778
+ }, 3000);
2779
+ }
2780
+
2781
+ function stopWatchSSE() {
2782
+ if (watchSSESource) { watchSSESource.close(); watchSSESource = null; }
2783
+ if (watchSSEWatchdog) { clearInterval(watchSSEWatchdog); watchSSEWatchdog = null; }
2784
+ if (STATE.watchPollTimer) { clearInterval(STATE.watchPollTimer); STATE.watchPollTimer = null; }
2785
+ }
2786
+
2787
+ function fallbackWatchToPolling() {
2788
+ stopWatchSSE();
2789
+ if (!STATE.watchPollTimer && STATE.watchRunning) {
2790
+ STATE.watchPollTimer = setInterval(pollWatchStatus, 2000);
2791
+ }
2792
+ }
2793
+
2794
+ async function pollWatchStatus() {
2795
+ try {
2796
+ const r = await fetch('/api/watch/status');
2797
+ const d = await r.json();
2798
+ STATE.watchRunning = d.running;
2799
+ STATE.watchProcessed = d.processed;
2800
+ STATE.watchErrors = d.errors;
2801
+ if (d.logs && d.logs.length > STATE.watchLogCursor) {
2802
+ for (let i = STATE.watchLogCursor; i < d.logs.length; i++) STATE.watchLogs.push(d.logs[i]);
2803
+ STATE.watchLogCursor = d.logs.length;
2804
+ renderWatchLog();
2805
+ }
2806
+ updateWatchUI();
2807
+ if (!STATE.watchRunning) stopWatchSSE();
2808
+ } catch(e) { /* ignore */ }
2809
+ }
2810
+
2811
+ // Shared Settings controls (quality/format/mode/max-width/protect-colors/
2812
+ // dithering/keep-exif) double as Watch Mode's config — startWatch() reads
2813
+ // them once at click time and the backend freezes them for the life of
2814
+ // that watch run (see _watch_loop). Nothing here re-reads them, so leaving
2815
+ // these interactive while Watch Mode is running would silently mislead
2816
+ // anyone who changes format/quality mid-watch expecting it to take effect.
2817
+ // Lock them visibly instead, and restore the normal mode-dependent
2818
+ // disabled state (via updateModeDependentControls) once Watch Mode stops.
2819
+ function applyWatchLock(locked) {
2820
+ const notice = $('watch-lock-notice');
2821
+ notice.style.display = locked ? '' : 'none';
2822
+ const inputs = [
2823
+ ...document.querySelectorAll('input[name="quality"]'),
2824
+ ...document.querySelectorAll('input[name="format"]'),
2825
+ ...document.querySelectorAll('input[name="mode"]'),
2826
+ $('max-width'), $('protect-colors'), $('dithering'), $('keep-exif'),
2827
+ $('screenshot-preset-btn'), $('custom-preset-select'), $('save-preset-btn'), $('delete-preset-btn'),
2828
+ ];
2829
+ if (locked) {
2830
+ inputs.forEach(el => { el.disabled = true; });
2831
+ } else {
2832
+ inputs.forEach(el => { el.disabled = false; });
2833
+ updateModeDependentControls(); // reapply the fine-grained mode/format rules
2834
+ }
2835
+ }
2836
+
2837
+ function updateWatchUI() {
2838
+ if (STATE.watchRunning) {
2839
+ watchStartBtn.style.display = 'none';
2840
+ watchStopBtn.style.display = '';
2841
+ watchStatusEl.innerHTML = '<span class="status-dot ok"></span>' + t('watch.watching');
2842
+ watchLogBox.style.display = '';
2843
+ } else {
2844
+ watchStartBtn.style.display = '';
2845
+ watchStopBtn.style.display = 'none';
2846
+ watchStatusEl.textContent = t('watch.idle');
2847
+ watchLogBox.style.display = 'none';
2848
+ }
2849
+ applyWatchLock(STATE.watchRunning);
2850
+ watchStatsEl.textContent = STATE.watchProcessed || STATE.watchErrors
2851
+ ? `Processed: ${STATE.watchProcessed} | Errors: ${STATE.watchErrors}`
2852
+ : '';
2853
+ }
2854
+
2855
+ function renderWatchLog() {
2856
+ if (STATE.watchLogs.length > 300) STATE.watchLogs = STATE.watchLogs.slice(-300);
2857
+ watchLogBox.innerHTML = STATE.watchLogs.map(l => {
2858
+ let c = 'log-entry';
2859
+ if (l.indexOf('OK ') !== -1) c += ' ok';
2860
+ else if (l.indexOf('FAIL') !== -1 || l.indexOf('ERROR') !== -1) c += ' err';
2861
+ else if (l.startsWith(' ')) c += ' info';
2862
+ return `<div class="${c}">${escHtml(l)}</div>`;
2863
+ }).join('');
2864
+ watchLogBox.scrollTop = watchLogBox.scrollHeight;
2865
+ }
2866
+
2867
+ watchStartBtn.addEventListener('click', startWatch);
2868
+ watchStopBtn.addEventListener('click', stopWatch);
2869
+ $('watch-use-current-paths-btn').addEventListener('click', () => {
2870
+ const src = dirPath.value.trim();
2871
+ const out = outputDir.value.trim();
2872
+ if (!src && !out) {
2873
+ showNotice(t('notice.pathsBothEmpty'), 'err');
2874
+ return;
2875
+ }
2876
+ if (src) watchDir.value = src;
2877
+ if (out) {
2878
+ watchOutputDir.value = out;
2879
+ } else {
2880
+ showNotice(t('notice.watchOutputStillEmpty'), 'err');
2881
+ }
2882
+ });
2883
+ $('watch-browse-dir-btn').addEventListener('click', async () => {
2884
+ const path = await pickFolder();
2885
+ if (path) watchDir.value = path;
2886
+ });
2887
+ $('watch-browse-output-btn').addEventListener('click', async () => {
2888
+ const path = await pickFolder();
2889
+ if (path) watchOutputDir.value = path;
2890
+ });
2891
+
2892
+ async function checkWatchStatus() {
2893
+ try {
2894
+ const r = await fetch('/api/watch/status');
2895
+ const d = await r.json();
2896
+ if (d.running) {
2897
+ STATE.watchRunning = true;
2898
+ STATE.watchProcessed = d.processed;
2899
+ STATE.watchErrors = d.errors;
2900
+ STATE.watchLogs = d.logs || [];
2901
+ STATE.watchLogCursor = STATE.watchLogs.length;
2902
+ updateWatchUI();
2903
+ renderWatchLog();
2904
+ startWatchSSE();
2905
+ }
2906
+ } catch(e) { /* fresh session or server unreachable */ }
2907
+ }
2908
+
2909
+ // --- Batch resume ---
2910
+ const resumeBanner = $('batch-resume-banner');
2911
+ const resumeText = $('batch-resume-text');
2912
+ const batchResumeBtn = $('batch-resume-btn');
2913
+ const batchDismissBtn = $('batch-dismiss-btn');
2914
+ let _savedBatchState = null; // remember params from the banner to send on Resume
2915
+
2916
+ async function checkBatchState() {
2917
+ try {
2918
+ const r = await fetch('/api/batch-state');
2919
+ const d = await r.json();
2920
+ if (!d.has_batch) return;
2921
+ _savedBatchState = d;
2922
+ resumeText.textContent = t('batchResume.found', { done: d.done, total: d.total, failed: d.failed });
2923
+ resumeBanner.style.display = 'flex';
2924
+ } catch(e) { /* no batch or server error */ }
2925
+ }
2926
+
2927
+ batchResumeBtn.addEventListener('click', async () => {
2928
+ if (!_savedBatchState) return;
2929
+ resumeBanner.style.display = 'none';
2930
+ // Pre-fill the output dir from the saved batch so the UI is consistent
2931
+ if (_savedBatchState.output_dir) {
2932
+ outputDir.value = _savedBatchState.output_dir;
2933
+ }
2934
+ try {
2935
+ const r = await apiFetch('/api/optimize', {
2936
+ method: 'POST',
2937
+ headers: { 'Content-Type': 'application/json' },
2938
+ body: JSON.stringify({
2939
+ resume: true,
2940
+ output_dir: _savedBatchState.output_dir,
2941
+ output_format: _savedBatchState.output_format,
2942
+ quality: _savedBatchState.quality,
2943
+ compression_mode: _savedBatchState.compression_mode,
2944
+ }),
2945
+ });
2946
+ const d = await r.json();
2947
+ if (!r.ok) { showNotice(d.error || t('notice.resumeFailed'), 'err'); return; }
2948
+ // /api/optimize only kicks the run off — it doesn't hand back this
2949
+ // session's files/input_dir/ws_name. Pull those from /api/state (the
2950
+ // same call used to reattach after a page refresh) so the source-path
2951
+ // field and compare/preview links are correct right away, instead of
2952
+ // sitting blank/broken until finalizeRun() re-derives them at the end.
2953
+ // restoreState() also starts SSE itself when the run is in progress,
2954
+ // so it replaces the manual isRunning/startSSE setup below.
2955
+ await restoreState();
2956
+ } catch(e) {
2957
+ showNotice(t('notice.resumeFailedPrefix') + e.message, 'err');
2958
+ }
2959
+ });
2960
+
2961
+ batchDismissBtn.addEventListener('click', () => {
2962
+ resumeBanner.style.display = 'none';
2963
+ _savedBatchState = null;
2964
+ });
2965
+
2966
+ // --- Settings panel ---
2967
+ const settingsOverlay = $('settings-overlay');
2968
+ const settingsBtn = $('settings-btn');
2969
+ const settingsClose = $('settings-close');
2970
+ const settingsCancel = $('settings-cancel');
2971
+ const settingsSave = $('settings-save');
2972
+ const settingHost = $('setting-host');
2973
+ const settingPort = $('setting-port');
2974
+ const settingConcurrentWorkers = $('setting-concurrent-workers');
2975
+ const settingThumbnailWorkers = $('setting-thumbnail-workers');
2976
+ const settingCleanupDelay = $('setting-cleanup-delay');
2977
+ const settingIdleTimeout = $('setting-idle-timeout');
2978
+ const settingLanguage = $('setting-language');
2979
+
2980
+ // Language is a pure client-side preference, so it applies immediately on
2981
+ // change rather than waiting for the Settings panel's Save button (which
2982
+ // only covers server-side config like host/port).
2983
+ settingLanguage.addEventListener('change', () => {
2984
+ localStorage.setItem('imgopt.lang', settingLanguage.value);
2985
+ applyStoredLang();
2986
+ });
2987
+
2988
+ function openSettings() {
2989
+ settingsOverlay.classList.add('open');
2990
+ settingLanguage.value = currentLang();
2991
+ // Load current values
2992
+ apiFetch('/api/settings').then(r => r.json()).then(data => {
2993
+ const s = data.settings || {};
2994
+ settingHost.value = s.host || '';
2995
+ settingPort.value = s.port || '';
2996
+ settingConcurrentWorkers.value = s.concurrent_workers || '';
2997
+ settingThumbnailWorkers.value = s.thumbnail_workers || '';
2998
+ settingCleanupDelay.value = s.workspace_cleanup_delay || '';
2999
+ settingIdleTimeout.value = s.session_idle_timeout_hours || '';
3000
+ }).catch(() => {});
3001
+ }
3002
+
3003
+ function closeSettings() {
3004
+ settingsOverlay.classList.remove('open');
3005
+ }
3006
+
3007
+ settingsBtn.addEventListener('click', openSettings);
3008
+ settingsClose.addEventListener('click', closeSettings);
3009
+ settingsCancel.addEventListener('click', closeSettings);
3010
+ settingsOverlay.addEventListener('click', (e) => {
3011
+ if (e.target === settingsOverlay) closeSettings();
3012
+ });
3013
+
3014
+ settingsSave.addEventListener('click', async () => {
3015
+ const payload = {
3016
+ host: settingHost.value.trim(),
3017
+ port: settingPort.value,
3018
+ concurrent_workers: settingConcurrentWorkers.value,
3019
+ thumbnail_workers: settingThumbnailWorkers.value,
3020
+ workspace_cleanup_delay: settingCleanupDelay.value,
3021
+ session_idle_timeout_hours: settingIdleTimeout.value,
3022
+ };
3023
+ try {
3024
+ const r = await apiFetch('/api/settings', {
3025
+ method: 'PUT',
3026
+ headers: { 'Content-Type': 'application/json' },
3027
+ body: JSON.stringify(payload),
3028
+ });
3029
+ const data = await r.json();
3030
+ if (!r.ok) {
3031
+ showNotice(data.error || t('settings.saveFailed'), 'err');
3032
+ return;
3033
+ }
3034
+ let msg = t('settings.saved');
3035
+ if (data.requires_restart && data.requires_restart.length > 0) {
3036
+ msg += t('settings.savedRestartNote');
3037
+ }
3038
+ showNotice(msg, 'ok');
3039
+ closeSettings();
3040
+ } catch (e) {
3041
+ showNotice(t('settings.saveFailed') + ': ' + e.message, 'err');
3042
+ }
3043
+ });
3044
+
3045
+ // Init
3046
+ applyStoredTheme();
3047
+ applyStoredLang();
3048
+ loadConfig();
3049
+ checkHealth();
3050
+ loadRecentPaths();
3051
+ updateModeDependentControls();
3052
+
3053
+ // Auto-scan from URL params
3054
+ const params = new URLSearchParams(window.location.search);
3055
+ const autoDir = params.get('dir');
3056
+ if (autoDir) {
3057
+ dirPath.value = autoDir;
3058
+ scanBtn.click();
3059
+ } else {
3060
+ restoreState();
3061
+ }
3062
+ checkWatchStatus();
3063
+ checkBatchState();
3064
+ </script>
3065
+ </body>
3066
+ </html>