@ponderdev/justfits 1.2.0 → 1.3.0

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.
@@ -1,13 +1,26 @@
1
1
  'use strict';
2
2
 
3
- /* The window. Holds no logic worth testing: the decisions live in plan.js. */
3
+ /* The window. Holds no logic worth testing: the decisions live in plan.js.
4
+ The start screen, the file row, the run part and the footer come from the
5
+ kit (kit/kit.js); this file fills them with Just Fits' own words. */
4
6
 
5
7
  const MB = 1000 * 1000;
6
8
 
7
9
  const el = (id) => document.getElementById(id);
10
+
11
+ // The strip at the top is room for the Mac's traffic lights, which sit over the
12
+ // page. Windows and Linux have a native title bar of their own, so there it
13
+ // would only be an empty band under it.
8
14
  let chosen = null; // the file being worked on
9
15
  let targetBytes = 10 * MB;
10
16
  let busy = false;
17
+ let made = null; // the file the last run saved, for "Show me the file"
18
+ let batch = null; // several files or a folder, instead of chosen (see take below)
19
+ let runNo = 0; // each press of Compress on a batch, so main picks a folder's results folder once per run
20
+
21
+ // A folder's results go into a new folder beside it ("Holiday (fitted)")
22
+ // unless Save next to the originals instead is ticked (decided 2026-11-20).
23
+ const settings = Kit.store('justfits', { beside: false });
11
24
 
12
25
  function human(bytes) {
13
26
  if (bytes >= 1000 * MB) return trim(bytes / 1000 / MB) + ' GB';
@@ -25,6 +38,88 @@ function clock(seconds) {
25
38
  return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
26
39
  }
27
40
 
41
+ /* --- the parts ---------------------------------------------------------- */
42
+
43
+ async function choose() {
44
+ const picked = await window.fits.pickFile();
45
+ if (picked && picked.length) intake(picked);
46
+ }
47
+
48
+ // Windows and Linux pickers take files or folders, never both in one, so
49
+ // there a folder has a button of its own. A Mac's picker takes either.
50
+ async function chooseFolder() {
51
+ const picked = await window.fits.pickFolder();
52
+ if (picked && picked.length) intake(picked);
53
+ }
54
+
55
+ // Option A: nothing but the drop zone until a file is in.
56
+ const start = Kit.start(el('start'), {
57
+ name: 'Just Fits',
58
+ version: window.fits.version,
59
+ line: 'Makes a file small enough to send.',
60
+ icon: 'video',
61
+ say: 'Drop videos, pictures or a folder here',
62
+ choose: 'Choose a file',
63
+ takes: 'A video or picture, or several, or a folder of them',
64
+ onChoose: choose,
65
+ also: window.fits.folderButton ? { label: 'Choose a folder', onClick: chooseFolder, change: 'Change folder' } : null,
66
+ // Copy skill puts the app's own SKILL.md on the clipboard; What's this?
67
+ // says what a skill is, with How it works opening the page through main.
68
+ skill: {
69
+ copy: () => window.fits.skillText(),
70
+ about: () => window.fits.openHowItWorks(),
71
+ },
72
+ // No onDrop here: the veil takes a drop anywhere in the window, the drop
73
+ // zone included, so a drop on the zone is not taken twice.
74
+ });
75
+ start.buttons.choose.id = 'browse';
76
+ start.buttons.change.id = 'change';
77
+ if (start.buttons.also) start.buttons.also.id = 'browse-folder';
78
+ if (start.buttons.changeAlso) start.buttons.changeAlso.id = 'change-folder';
79
+
80
+ const run = Kit.run(el('run'), {
81
+ onCancel: () => cancel(),
82
+ onReveal: () => { if (made) window.fits.reveal(made); },
83
+ onAgain: () => again(),
84
+ onRetry: () => (batch ? compressMany() : compress()),
85
+ });
86
+ run.buttons.cancel.id = 'cancel';
87
+ run.buttons.reveal.id = 'reveal';
88
+ run.buttons.again.id = 'again';
89
+ run.buttons.retry.id = 'retry';
90
+
91
+ const veil = Kit.veil({
92
+ say: 'Drop videos, pictures or a folder',
93
+ icon: 'video',
94
+ // While a file is being fitted a drop is refused: no veil, and the pointer
95
+ // shows it will not be taken, rather than a drop that does nothing.
96
+ when: () => !busy,
97
+ onDrop: (files) => {
98
+ if (files.length) intake(files.map((f) => (window.fits.pathFor ? window.fits.pathFor(f) : f.path)));
99
+ },
100
+ });
101
+ // Without a veil handler of its own, a drop outside the page's own targets
102
+ // would have the window navigate to the file.
103
+ document.addEventListener('dragover', (e) => e.preventDefault());
104
+ document.addEventListener('drop', (e) => e.preventDefault());
105
+
106
+ Kit.footer(el('footer'), {
107
+ onSite: () => window.fits.openSite(),
108
+ onLicences: () => window.fits.openLicences(),
109
+ });
110
+
111
+ const runState = () => el('run').dataset.state;
112
+
113
+ // The estimate above the main button is for before a run; once the button is
114
+ // pressed the run part says what is happening instead.
115
+ function note() {
116
+ el('aim').textContent = runState() === 'idle' ? `Aiming for ${human(targetBytes)}` : '';
117
+ }
118
+
119
+ function veilSay() {
120
+ veil.say(batch ? 'Drop to use these instead' : chosen ? 'Drop to use this file instead' : 'Drop videos, pictures or a folder');
121
+ }
122
+
28
123
  /* --- target picking ----------------------------------------------------- */
29
124
 
30
125
  let TARGETS = [];
@@ -48,10 +143,17 @@ async function drawTargets() {
48
143
  useTarget(TARGETS[0]);
49
144
  }
50
145
 
146
+ // The done card was for the old limit, and kept saying so beside the new one.
147
+ // A failed card goes the same way: its reason belonged to the old limit.
148
+ function dropDone() {
149
+ if (!busy && (runState() === 'done' || runState() === 'failed')) run.reset();
150
+ }
151
+
51
152
  function useTarget(t) {
153
+ dropDone();
52
154
  targetBytes = t.bytes;
53
- el('aim').textContent = `aiming for ${human(t.bytes)}`;
54
155
  el('why').textContent = t.note || '';
156
+ note();
55
157
  }
56
158
 
57
159
  el('target').addEventListener('change', (e) => {
@@ -70,82 +172,153 @@ el('custom').addEventListener('input', (e) => {
70
172
  if (t) useTarget(t);
71
173
  return;
72
174
  }
175
+ dropDone();
73
176
  targetBytes = mb * MB;
74
- el('aim').textContent = `aiming for ${human(targetBytes)}`;
75
177
  el('why').textContent = '';
178
+ note();
76
179
  });
77
180
 
78
181
  /* --- picking a file ----------------------------------------------------- */
79
182
 
183
+ // Whatever came in, by the picker or a drop: one file goes the way it always
184
+ // has (take), and several files or a folder become a batch (takeMany).
185
+ async function intake(paths) {
186
+ if (busy) return;
187
+ paths = paths.filter(Boolean);
188
+ // No path at all (a drop from somewhere that is not a file on disk): take
189
+ // says so in its own words.
190
+ if (!paths.length) return take('');
191
+ const g = await window.fits.gather(paths);
192
+ if (g.single) return take(paths[0]);
193
+ return takeMany(paths, g);
194
+ }
195
+
80
196
  async function take(filePath) {
81
197
  if (busy) return;
82
- hide('error');
83
- hide('done');
198
+ start.error('');
199
+ run.reset();
200
+ made = null;
201
+ batch = null;
202
+ whereField(null);
84
203
 
85
204
  // A drop that carries no path (dragged from somewhere that is not a real
86
205
  // file on disk) would otherwise surface ffprobe's ": No such file" with no name.
87
206
  const r = filePath
88
207
  ? await window.fits.probe(filePath)
89
- : { ok: false, message: 'Could not tell where that file is. Try "choose a file" instead.' };
208
+ : { ok: false, message: 'Could not tell where that file is. Try "Choose a file" instead.' };
90
209
  if (!r.ok) {
91
210
  chosen = null;
92
- el('go').disabled = true;
93
- // Hide the previous file, so its name is not left beside an error about another.
94
- el('file').hidden = true;
95
- showInView('error', r.message);
211
+ // Back to the start, so the previous file's name is not left beside an
212
+ // error about another; the reason goes under the drop zone.
213
+ start.reset();
214
+ note();
215
+ veilSay();
216
+ start.error(r.message);
217
+ el('start').scrollIntoView({ block: 'nearest', behavior: 'smooth' });
96
218
  return;
97
219
  }
98
220
 
99
221
  chosen = { path: filePath, info: r.info };
100
- el('name').textContent = filePath.split(/[\\/]/).pop();
101
- el('facts').textContent = [
102
- human(r.info.bytes),
103
- r.info.width && `${r.info.width}x${r.info.height}`,
104
- r.info.kind === 'video' && r.info.durationSec && clock(r.info.durationSec),
105
- r.info.kind === 'video' && `${Math.round(r.info.fps)}fps`,
106
- r.info.kind === 'video' && (r.info.hasAudio ? 'with sound' : 'silent'),
107
- ].filter(Boolean).join(' · ');
108
-
109
- el('file').hidden = false;
222
+ start.landed({
223
+ name: filePath.split(/[\\/]/).pop(),
224
+ icon: r.info.kind === 'image' ? 'photo' : 'video',
225
+ facts: [
226
+ human(r.info.bytes),
227
+ r.info.width && `${r.info.width}x${r.info.height}`,
228
+ r.info.kind === 'video' && r.info.durationSec && clock(r.info.durationSec),
229
+ r.info.kind === 'video' && `${Math.round(r.info.fps)}fps`,
230
+ r.info.kind === 'video' && (r.info.hasAudio ? 'with sound' : 'silent'),
231
+ ].filter(Boolean).join(' · '),
232
+ });
110
233
  el('go').disabled = false;
234
+ note();
235
+ veilSay();
111
236
  }
112
237
 
113
- const drop = el('drop');
114
- for (const type of ['dragenter', 'dragover']) {
115
- drop.addEventListener(type, (e) => { e.preventDefault(); drop.classList.add('over'); });
238
+ // Several files or a folder. Each is probed first, so the file row can say
239
+ // what came in and the run knows which ones it cannot read before it starts.
240
+ async function takeMany(paths, g) {
241
+ if (busy) return;
242
+ start.error('');
243
+ run.reset();
244
+ made = null;
245
+ chosen = null;
246
+ batch = null;
247
+ whereField(null);
248
+ const label = paths.length === 1 && g.folders === 1 ? paths[0].replace(/[\\/]+$/, '').split(/[\\/]/).pop() : `${g.files.length} files`;
249
+ if (!g.files.length) {
250
+ start.reset();
251
+ note();
252
+ veilSay();
253
+ start.error(g.missing.length ? `Could not find ${g.missing[0].split(/[\\/]/).pop()}. It may have been moved or deleted.` : `There are no videos or pictures in ${label}.`);
254
+ return;
255
+ }
256
+
257
+ // A few at a time: a folder of hundreds should not wait on each in turn.
258
+ const items = g.files.map((f) => ({ path: f.path, name: f.name, bytes: f.bytes, from: f.from, info: null, message: '' }));
259
+ for (let i = 0; i < items.length; i += 4) {
260
+ await Promise.all(items.slice(i, i + 4).map(async (it) => {
261
+ const r = await window.fits.probe(it.path);
262
+ if (r.ok) it.info = r.info; else it.message = r.message;
263
+ }));
264
+ }
265
+ if (busy) return;
266
+
267
+ const videos = items.filter((it) => it.info && it.info.kind === 'video').length;
268
+ const pictures = items.filter((it) => it.info && it.info.kind === 'image').length;
269
+ const unreadable = items.length - videos - pictures;
270
+ const count = (n, one, many) => `${n} ${n === 1 ? one : many}`;
271
+ const kinds = [videos && count(videos, 'video', 'videos'), pictures && count(pictures, 'picture', 'pictures'), unreadable && `${unreadable} it cannot read`].filter(Boolean);
272
+ batch = { label, items };
273
+ whereField(items.find((it) => it.from));
274
+ start.landed({
275
+ name: label,
276
+ icon: g.folders ? 'folder' : videos ? 'video' : 'photos',
277
+ facts: `${kinds.join(', ')} · ${human(items.reduce((n, it) => n + it.bytes, 0))}`,
278
+ });
279
+ el('go').disabled = false;
280
+ note();
281
+ veilSay();
116
282
  }
117
- for (const type of ['dragleave', 'drop']) {
118
- drop.addEventListener(type, () => drop.classList.remove('over'));
283
+
284
+ // Save next to the originals instead: shown only with a folder in, with a
285
+ // line saying where the results go otherwise (the first folder's name).
286
+ function whereField(fromFolder) {
287
+ el('where-field').hidden = !fromFolder;
288
+ if (!fromFolder) return;
289
+ const name = fromFolder.from.replace(/[\\/]+$/, '').split(/[\\/]/).pop();
290
+ el('beside').checked = settings.get('beside');
291
+ el('where-hint').textContent = el('beside').checked
292
+ ? 'Each one is saved beside its original, as name-fits.'
293
+ : `Otherwise they go in a new folder beside it, ${name} (fitted), and the folder itself is left as it is.`;
119
294
  }
120
- drop.addEventListener('drop', (e) => {
121
- e.preventDefault();
122
- const f = e.dataTransfer.files[0];
123
- if (f) take(window.fits.pathFor ? window.fits.pathFor(f) : f.path);
295
+ el('beside').addEventListener('change', () => {
296
+ settings.set('beside', el('beside').checked);
297
+ whereField(batch && batch.items.find((it) => it.from));
124
298
  });
125
- document.addEventListener('dragover', (e) => e.preventDefault());
126
- document.addEventListener('drop', (e) => e.preventDefault());
127
299
 
128
- el('browse').addEventListener('click', async () => {
129
- const f = await window.fits.pickFile();
130
- if (f) take(f);
131
- });
300
+ // Start again: back to the drop zone, with the target left as it was.
301
+ function again() {
302
+ if (busy) return;
303
+ chosen = null;
304
+ batch = null;
305
+ whereField(null);
306
+ made = null;
307
+ start.error('');
308
+ run.reset();
309
+ start.reset();
310
+ note();
311
+ veilSay();
312
+ }
132
313
 
133
314
  /* --- the work ----------------------------------------------------------- */
134
315
 
135
- function show(id, text) {
136
- const node = el(id);
137
- if (text !== undefined) node.textContent = text;
138
- node.hidden = false;
139
- }
140
- function hide(id) { el(id).hidden = true; }
141
-
142
316
  // At 800x600 the window is short enough that progress, the result and errors
143
- // all land below the fold, and a greyed button alone looks the same as nothing
317
+ // all land below the fold, and a grayed button alone looks the same as nothing
144
318
  // happening. So whatever the user is now waiting on, or has just got, scrolls
145
319
  // into view.
146
- function showInView(id, text) {
147
- show(id, text);
148
- el(id).scrollIntoView({ block: 'nearest', behavior: 'smooth' });
320
+ function inView() {
321
+ el('run').scrollIntoView({ block: 'nearest', behavior: 'smooth' });
149
322
  }
150
323
 
151
324
  // The output goes beside the original with no Save window, so the Done card
@@ -159,47 +332,83 @@ function whereText(file) {
159
332
  return folder ? `Saved as ${name}, next to the original in ${folder}` : `Saved as ${name}`;
160
333
  }
161
334
 
335
+ // The time left, from how fast this attempt has gone so far. Each attempt
336
+ // starts its progress again, so the clock starts again with it.
337
+ let pace = null;
338
+ function timeLeft(p) {
339
+ const now = Date.now();
340
+ if (!pace || pace.attempt !== p.attempt || p.progress < pace.from) pace = { attempt: p.attempt, from: p.progress, at: now };
341
+ const done = p.progress - pace.from;
342
+ const spent = (now - pace.at) / 1000;
343
+ if (spent < 2 || done < 0.02) return '';
344
+ const s = Math.max(1, Math.round(spent / done * (1 - p.progress)));
345
+ if (s < 60) return `About ${s} second${s === 1 ? '' : 's'} left`;
346
+ const m = Math.round(s / 60);
347
+ return `About ${m} minute${m === 1 ? '' : 's'} left`;
348
+ }
349
+
162
350
  window.fits.onProgress((p) => {
163
- el('fill').style.width = Math.round(p.progress * 100) + '%';
164
- el('stage').textContent = p.stage;
165
- el('pct').textContent = Math.round(p.progress * 100) + '%';
166
- el('attempt').textContent = p.attempt > 0 ? `attempt ${p.attempt + 1}, aiming lower` : '';
351
+ if (!busy) return;
352
+ if (batch) return manyProgress(p);
353
+ const pct = Math.round(p.progress * 100);
354
+ run.working({
355
+ what: p.stage + (p.attempt > 0 ? `, attempt ${p.attempt + 1}, aiming lower` : ''),
356
+ // Until ffmpeg says how far it is (a slow machine's first pass can take
357
+ // a while to say anything, and a picture says nothing), the bar sweeps.
358
+ count: p.progress > 0 ? pct + '%' : '',
359
+ fraction: p.progress,
360
+ unknown: !(p.progress > 0),
361
+ file: chosen ? chosen.path.split(/[\\/]/).pop() : '',
362
+ left: timeLeft(p),
363
+ });
167
364
  });
168
365
 
169
- el('go').addEventListener('click', async () => {
366
+ function finished({ title, detail = '', where = '', file = null, folder = false, over = false }) {
367
+ made = file;
368
+ run.done({ title, detail, where, reveal: Boolean(file), revealLabel: folder ? 'Show me the folder' : 'Show me the file', tone: over ? 'over' : '' });
369
+ note();
370
+ inView();
371
+ }
372
+
373
+ async function compress() {
170
374
  if (!chosen || busy) return;
171
375
 
172
376
  if (chosen.info.bytes <= targetBytes) {
173
- el('result').textContent = 'That already fits.';
174
- el('result').classList.remove('over');
175
- el('detail').textContent = `${human(chosen.info.bytes)}, under the ${human(targetBytes)} limit. Nothing to do.`;
176
- el('reveal').hidden = true;
177
- el('where').textContent = '';
178
- showInView('done');
377
+ finished({
378
+ title: 'That already fits.',
379
+ detail: `${human(chosen.info.bytes)}, under the ${human(targetBytes)} limit. Nothing to do.`,
380
+ });
179
381
  return;
180
382
  }
181
383
 
182
384
  busy = true;
385
+ pace = null;
183
386
  el('go').disabled = true;
184
- hide('error');
185
- hide('done');
186
- el('fill').style.width = '0%';
187
- showInView('working');
387
+ veilSay();
388
+ run.working({ what: 'Working', unknown: true, file: chosen.path.split(/[\\/]/).pop() });
389
+ note();
390
+ inView();
188
391
 
189
392
  const r = await window.fits.fit(chosen.path, targetBytes);
190
393
 
191
394
  busy = false;
192
395
  el('go').disabled = false;
193
- hide('working');
396
+ veilSay();
194
397
 
195
398
  if (!r.ok) {
196
- if (!r.cancelled) showInView('error', r.message);
399
+ if (!r.cancelled) {
400
+ run.failed(r.message);
401
+ note();
402
+ inView();
403
+ return;
404
+ }
405
+ // Cancelled: say so, or the window just goes back to how it was.
406
+ finished({ title: 'Stopped.', detail: 'Nothing was saved, and the original is untouched.' });
197
407
  return;
198
408
  }
199
409
 
200
410
  const saved = Math.round((1 - r.bytes / r.before) * 100);
201
- el('done').classList.toggle('over', Boolean(r.over));
202
- el('result').textContent = r.over
411
+ const title = r.over
203
412
  ? `Got it to ${human(r.bytes)}, still over the line.`
204
413
  : `Done. ${human(r.before)} to ${human(r.bytes)}, ${saved}% smaller.`;
205
414
 
@@ -211,16 +420,216 @@ el('go').addEventListener('click', async () => {
211
420
  if (r.plan.audioKbps) bits.push(`${r.plan.audioKbps}k audio`);
212
421
  }
213
422
  if (r.attempts > 1) bits.push(`${r.attempts} attempts`);
214
- el('detail').textContent = bits.join(' · ');
423
+ // The plan knew when the target was too small for the length; say it here
424
+ // too, so a soft picture is explained rather than a surprise. The sentence
425
+ // is the command line's, from plan.lengthNote through main.
426
+ const rough = r.note || '';
215
427
 
216
- el('where').textContent = whereText(r.path);
217
- el('reveal').hidden = false;
218
- el('reveal').onclick = () => window.fits.reveal(r.path);
219
- showInView('done');
220
- });
428
+ // the facts stay a facts line; the plain-words warning leads the line under it
429
+ finished({ title, detail: bits.join(' · '), where: (rough ? rough + ' ' : '') + whereText(r.path), file: r.path, over: Boolean(r.over) });
430
+ }
431
+
432
+ /* --- several files ------------------------------------------------------ */
433
+
434
+ // Cancel stops at once, in a batch too: the file being fitted is stopped and
435
+ // its half-written result removed (the engine does that), and no more start.
436
+ // Files already fitted stay fitted.
437
+ let stopping = false;
438
+ function cancel() {
439
+ if (batch) {
440
+ stopping = true;
441
+ if (manyAt) manyProgress(manyAt.last);
442
+ }
443
+ window.fits.cancel();
444
+ }
445
+
446
+ let manyAt = null; // where a batch run is: which file, since when
447
+
448
+ function rows() {
449
+ return batch.items.map((it) => ({ name: it.name, state: it.state || 'waiting', note: it.note || '' }));
450
+ }
451
+
452
+ // The queue shows every file, so the one being fitted is kept in sight in it.
453
+ function showQueue() {
454
+ run.queue(rows());
455
+ const box = el('run').querySelector('.k-run-queue');
456
+ const now = box && box.querySelector('li[data-q="working"]');
457
+ if (now) box.scrollTop = Math.max(0, now.offsetTop - box.clientHeight / 2);
458
+ }
459
+
460
+ function inWords(seconds) {
461
+ const s = Math.max(1, Math.round(seconds));
462
+ if (s < 60) return `${s} second${s === 1 ? '' : 's'}`;
463
+ const m = Math.round(s / 60);
464
+ return `${m} minute${m === 1 ? '' : 's'}`;
465
+ }
466
+
467
+ function manyProgress(p) {
468
+ if (!manyAt) return;
469
+ manyAt.last = p;
470
+ const n = batch.items.length;
471
+ // Weighed by size, not by count: a video among photos is most of the work,
472
+ // and counting files said "3 seconds left" as it started on it.
473
+ const items = batch.items;
474
+ const total = items.reduce((t, it) => t + it.bytes, 0) || 1;
475
+ const before = items.slice(0, manyAt.index).reduce((t, it) => t + it.bytes, 0);
476
+ const overall = Math.min(1, (before + items[manyAt.index].bytes * (p ? p.progress : 0)) / total);
477
+ const spent = (Date.now() - manyAt.started) / 1000;
478
+ const left = spent > 3 && overall > 0.02 ? `About ${inWords(spent / overall * (1 - overall))} left` : '';
479
+ const retry = p && p.attempt > 0 ? `, attempt ${p.attempt + 1}` : '';
480
+ run.working({
481
+ what: stopping ? 'Stopping' : `Fitting ${manyAt.index + 1} of ${n}${retry}`,
482
+ count: overall > 0 ? Math.round(overall * 100) + '%' : '',
483
+ fraction: overall,
484
+ unknown: !(overall > 0),
485
+ file: batch.items[manyAt.index].name,
486
+ left,
487
+ });
488
+ }
489
+
490
+ // A short reason for the queue; the whole sentence is in the probe's message.
491
+ function shortReason(message) {
492
+ if (/is not a video or picture/.test(message)) return 'Not a video or picture Just Fits can read';
493
+ if (/animated WebP/.test(message)) return 'An animated WebP, which it cannot shrink';
494
+ if (/Could not find/.test(message)) return 'It was moved or deleted';
495
+ return String(message || 'Failed').split('\n')[0];
496
+ }
497
+
498
+ async function compressMany() {
499
+ if (!batch || busy) return;
500
+ const items = batch.items;
501
+ for (const it of items) { it.state = 'waiting'; it.note = ''; it.out = null; it.folder = null; it.copied = false; it.result = null; }
502
+ const run1 = ++runNo;
503
+ const beside = settings.get('beside');
504
+
505
+ busy = true;
506
+ stopping = false;
507
+ made = null;
508
+ el('go').disabled = true;
509
+ veilSay();
510
+ manyAt = { index: 0, started: Date.now(), last: null };
511
+ manyProgress(null);
512
+ showQueue();
513
+ note();
514
+ inView();
515
+
516
+ const target = targetBytes;
517
+ let stoppedAt = null;
518
+ for (let i = 0; i < items.length; i++) {
519
+ if (stopping) { stoppedAt = i; break; }
520
+ const it = items[i];
521
+ manyAt.index = i;
522
+ manyAt.last = null;
523
+ it.state = 'working';
524
+ manyProgress(null);
525
+ showQueue();
526
+
527
+ if (!it.info) {
528
+ it.result = 'failed';
529
+ it.state = 'failed';
530
+ it.note = shortReason(it.message);
531
+ } else if (it.info.bytes <= target && (beside || !it.from)) {
532
+ it.result = 'skipped';
533
+ it.state = 'done';
534
+ it.note = 'Already small enough';
535
+ } else {
536
+ const r = await window.fits.fit(it.path, target, { beside, run: run1 });
537
+ if (r.cancelled) {
538
+ // stopped part way: nothing of it was kept, and the queue says so
539
+ it.state = 'waiting';
540
+ it.note = 'Stopped part way, nothing kept';
541
+ stoppedAt = i;
542
+ break;
543
+ } else if (!r.ok) {
544
+ it.result = 'failed';
545
+ it.state = 'failed';
546
+ it.note = shortReason(r.message);
547
+ } else if (r.copied) {
548
+ // already small enough, copied into the results folder as it is
549
+ it.result = 'skipped';
550
+ it.state = 'done';
551
+ it.note = 'Already small enough, copied in';
552
+ it.out = r.path;
553
+ it.folder = r.folder;
554
+ it.copied = true;
555
+ } else {
556
+ it.out = r.path;
557
+ it.folder = r.folder || null;
558
+ it.before = r.before;
559
+ it.after = r.bytes;
560
+ if (!made) made = r.path;
561
+ if (r.over) {
562
+ it.result = 'over';
563
+ it.state = 'failed';
564
+ it.note = `Could not get under ${human(target)}, got to ${human(r.bytes)}`;
565
+ } else {
566
+ it.result = 'fitted';
567
+ it.state = 'done';
568
+ it.note = `${human(r.before)} to ${human(r.bytes)}`;
569
+ }
570
+ }
571
+ }
572
+ }
573
+ const seconds = (Date.now() - manyAt.started) / 1000;
574
+ manyAt = null;
575
+ busy = false;
576
+ el('go').disabled = false;
577
+ veilSay();
578
+ for (const it of items) if (it.state === 'waiting' && stoppedAt !== null && !it.note) it.note = 'Not started';
579
+ showQueue();
580
+
581
+ const tally = (k) => items.filter((it) => it.result === k).length;
582
+ const fitted = tally('fitted');
583
+ const skipped = tally('skipped');
584
+ const over = tally('over');
585
+ const failed = tally('failed');
586
+ const tried = fitted + skipped + over + failed;
587
+
588
+ if (stoppedAt === null && failed === items.length) {
589
+ run.failed(`None of the ${items.length} files could be fitted. The list says why for each.`);
590
+ note();
591
+ inView();
592
+ return;
593
+ }
594
+
595
+ const parts = [];
596
+ if (fitted || (!skipped && !over && !failed)) parts.push(`${fitted} fitted`);
597
+ if (skipped) parts.push(`${skipped} already small enough`);
598
+ if (over) parts.push(`${over} could not get under ${human(target)}`);
599
+ if (failed) parts.push(`${failed} could not be read or fitted`);
600
+ let title;
601
+ if (stoppedAt !== null && !tried) title = `Stopped. None of the ${items.length} files were changed.`;
602
+ else if (stoppedAt !== null) title = `Stopped after ${tried} of ${items.length}. ${parts.join(', ')}.`;
603
+ else if (skipped === items.length) title = `All ${items.length} already fit under ${human(target)}.`;
604
+ else title = `Done. ${parts.join(', ')}.`;
605
+ title = title.charAt(0).toUpperCase() + title.slice(1);
606
+
607
+ const changed = items.filter((it) => it.out && !it.copied);
608
+ const written = items.filter((it) => it.out);
609
+ const before = changed.reduce((n, it) => n + it.before, 0);
610
+ const after = changed.reduce((n, it) => n + it.after, 0);
611
+ const detail = changed.length ? `${human(before)} to ${human(after)} in ${inWords(seconds)}` : '';
612
+ const folders = [...new Set(written.map((it) => it.folder).filter(Boolean))];
613
+ const besideCount = written.filter((it) => !it.folder).length;
614
+ const nameOf = (p) => p.split(/[\\/]/).pop();
615
+ const files = (n) => `${n} ${n === 1 ? 'file' : 'files'}`;
616
+ let where = '';
617
+ if (folders.length === 1 && !besideCount) where = `Saved ${files(written.length)} in ${nameOf(folders[0])}`;
618
+ else if (folders.length > 1 && !besideCount) where = `Saved ${files(written.length)} in ${folders.length} new folders beside the originals`;
619
+ else if (folders.length) where = `Saved ${files(written.length - besideCount)} in ${folders.length === 1 ? nameOf(folders[0]) : `${folders.length} new folders`}, ${besideCount} next to ${besideCount === 1 ? 'its original' : 'their originals'}`;
620
+ else if (written.length) where = 'Saved next to each original';
621
+ if (where && stoppedAt !== null) where += '. The rest were left as they were.';
622
+ finished({
623
+ title,
624
+ detail,
625
+ where,
626
+ // Show me the file: the results folder when they all went into one.
627
+ file: folders.length === 1 && !besideCount ? folders[0] : made,
628
+ folder: folders.length === 1 && !besideCount,
629
+ over: over > 0,
630
+ });
631
+ }
221
632
 
222
- el('cancel').addEventListener('click', () => window.fits.cancel());
223
- el('site').addEventListener('click', () => window.fits.openSite());
224
- el('licences').addEventListener('click', () => window.fits.openLicences());
633
+ el('go').addEventListener('click', () => (batch ? compressMany() : compress()));
225
634
 
226
635
  drawTargets();