@ponderdev/justfits 1.2.0 → 1.4.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,49 @@
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.
6
+
7
+ Every word it shows goes through the kit's language (Kit.t and Kit.tn, the
8
+ English sentence as the key), and what it hands the kit's parts is already
9
+ translated: the kit does not translate what it is given. What main sends
10
+ (the targets, a probe's reason, the progress stage, a length note) comes
11
+ translated from main, which has the same language. ffmpeg's own lines are
12
+ shown as ffmpeg wrote them. Sizes (10 MB, 1.5 GB), a frame size (1280x720)
13
+ and a frame rate (30fps) are left as they are. */
4
14
 
5
15
  const MB = 1000 * 1000;
6
16
 
7
17
  const el = (id) => document.getElementById(id);
18
+
19
+ // The language first, before anything shows a word: main is told it, so what
20
+ // it sends the window is in it too.
21
+ Kit.languages({ tell: window.fits.language, mistake: window.fits.translationMistake, busy: () => busy, reload: window.fits.reloadWindow, keep: () => keepForSwitch() });
22
+ const { t, tn } = Kit;
23
+
24
+ // A whole percent, written the way the window's language writes one ("50 %"
25
+ // in French, "50%" in English).
26
+ const percent = (fraction) => Kit.num(Math.round(fraction * 100) / 100, { style: 'percent' });
27
+
28
+ // The strip at the top is room for the Mac's traffic lights, which sit over the
29
+ // page. Windows and Linux have a native title bar of their own, so there it
30
+ // would only be an empty band under it.
8
31
  let chosen = null; // the file being worked on
9
32
  let targetBytes = 10 * MB;
10
33
  let busy = false;
34
+ let made = null; // the file the last run saved, for "Show me the file"
35
+ let batch = null; // several files or a folder, instead of chosen (see take below)
36
+ let runNo = 0; // each press of Compress on a batch, so main picks a folder's results folder once per run
37
+
38
+ // A folder's results go into a new folder beside it ("Holiday (fitted)")
39
+ // unless Save next to the originals instead is ticked (decided 2026-11-20).
40
+ const settings = Kit.store('justfits', { beside: false, carry: {} });
41
+
42
+ // What is on screen, as plain data: the paths that came in, the last result
43
+ // card drawn (shown), and the paths as they were taken (taken). Kept across a
44
+ // language switch (see the end of this file), where the page is rebuilt.
45
+ let taken = null;
46
+ let shown = null;
11
47
 
12
48
  function human(bytes) {
13
49
  if (bytes >= 1000 * MB) return trim(bytes / 1000 / MB) + ' GB';
@@ -25,6 +61,94 @@ function clock(seconds) {
25
61
  return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
26
62
  }
27
63
 
64
+ /* --- the parts ---------------------------------------------------------- */
65
+
66
+ async function choose() {
67
+ const picked = await window.fits.pickFile();
68
+ if (picked && picked.length) intake(picked);
69
+ }
70
+
71
+ // Windows and Linux pickers take files or folders, never both in one, so
72
+ // there a folder has a button of its own. A Mac's picker takes either.
73
+ async function chooseFolder() {
74
+ const picked = await window.fits.pickFolder();
75
+ if (picked && picked.length) intake(picked);
76
+ }
77
+
78
+ // Option A: nothing but the drop zone until a file is in.
79
+ const start = Kit.start(el('start'), {
80
+ name: 'Just Fits',
81
+ version: window.fits.version,
82
+ line: t('Makes a file small enough to send.'),
83
+ icon: 'video',
84
+ say: t('Drop videos, pictures, sound or a folder here'),
85
+ choose: t('Choose a file'),
86
+ takes: t('A video, picture or sound file, or several, or a folder of them'),
87
+ onChoose: choose,
88
+ also: window.fits.folderButton ? { label: t('Choose a folder'), onClick: chooseFolder, change: t('Change folder') } : null,
89
+ // Copy skill puts the app's own SKILL.md on the clipboard; What's this?
90
+ // says what a skill is, with How it works opening the page through main.
91
+ skill: {
92
+ copy: () => window.fits.skillText(),
93
+ about: () => window.fits.openHowItWorks(),
94
+ },
95
+ // No onDrop here: the veil takes a drop anywhere in the window, the drop
96
+ // zone included, so a drop on the zone is not taken twice.
97
+ });
98
+ start.buttons.choose.id = 'browse';
99
+ start.buttons.change.id = 'change';
100
+ if (start.buttons.also) start.buttons.also.id = 'browse-folder';
101
+ if (start.buttons.changeAlso) start.buttons.changeAlso.id = 'change-folder';
102
+
103
+ const run = Kit.run(el('run'), {
104
+ onCancel: () => cancel(),
105
+ onReveal: () => { if (made) window.fits.reveal(made); },
106
+ onAgain: () => again(),
107
+ onRetry: () => (batch ? compressMany() : compress()),
108
+ });
109
+ run.buttons.cancel.id = 'cancel';
110
+ run.buttons.reveal.id = 'reveal';
111
+ run.buttons.again.id = 'again';
112
+ run.buttons.retry.id = 'retry';
113
+
114
+ const veil = Kit.veil({
115
+ say: t('Drop videos, pictures, sound or a folder'),
116
+ icon: 'video',
117
+ // While a file is being fitted a drop is refused: no veil, and the pointer
118
+ // shows it will not be taken, rather than a drop that does nothing.
119
+ when: () => !busy,
120
+ onDrop: (files) => {
121
+ if (files.length) intake(files.map((f) => (window.fits.pathFor ? window.fits.pathFor(f) : f.path)));
122
+ },
123
+ });
124
+ // Without a veil handler of its own, a drop outside the page's own targets
125
+ // would have the window navigate to the file.
126
+ document.addEventListener('dragover', (e) => e.preventDefault());
127
+ document.addEventListener('drop', (e) => e.preventDefault());
128
+
129
+ Kit.footer(el('footer'), {
130
+ onSite: () => window.fits.openSite(),
131
+ onLicences: () => window.fits.openLicences(),
132
+ });
133
+
134
+ // A sibling tool for what Just Fits does not do: Just Zip for files
135
+ // it cannot shrink, Just JPEG for a HEIC picture. One line, never in the way.
136
+ const familyHint = Kit.hint(el('family-hint'), { open: (id) => window.fits.openSibling(id) });
137
+ const MEDIA = ['video', 'picture', 'heic', 'audio'];
138
+ const notMedia = (name) => !MEDIA.includes(Kit.kindOf(name));
139
+
140
+ const runState = () => el('run').dataset.state;
141
+
142
+ // The estimate above the main button is for before a run; once the button is
143
+ // pressed the run part says what is happening instead.
144
+ function note() {
145
+ el('aim').textContent = runState() === 'idle' ? t('Aiming for {size}', { size: human(targetBytes) }) : '';
146
+ }
147
+
148
+ function veilSay() {
149
+ veil.say(batch ? t('Drop to use these instead') : chosen ? t('Drop to use this file instead') : t('Drop videos, pictures, sound or a folder'));
150
+ }
151
+
28
152
  /* --- target picking ----------------------------------------------------- */
29
153
 
30
154
  let TARGETS = [];
@@ -32,33 +156,44 @@ let TARGETS = [];
32
156
  async function drawTargets() {
33
157
  TARGETS = await window.fits.targets();
34
158
  const select = el('target');
35
- let html = '';
159
+ // Built as elements rather than HTML: the labels come in the window's
160
+ // language, and a translation may hold a character HTML would read.
161
+ select.replaceChildren();
36
162
  let group = null;
37
- for (const t of TARGETS) {
38
- if (t.group !== group) {
39
- if (group !== null) html += '</optgroup>';
40
- group = t.group;
41
- html += `<optgroup label="${group}">`;
163
+ for (const target of TARGETS) {
164
+ if (!group || group.label !== target.group) {
165
+ group = document.createElement('optgroup');
166
+ group.label = target.group;
167
+ select.append(group);
42
168
  }
43
- const size = t.bytes >= 1000 * MB ? `${t.bytes / 1000 / MB}GB` : `${Math.round(t.bytes / MB)}MB`;
44
- html += `<option value="${t.id}">${t.label} &middot; ${size}</option>`;
169
+ const size = target.bytes >= 1000 * MB ? `${target.bytes / 1000 / MB}GB` : `${Math.round(target.bytes / MB)}MB`;
170
+ const option = document.createElement('option');
171
+ option.value = target.id;
172
+ option.textContent = `${target.label} \u00b7 ${size}`;
173
+ group.append(option);
45
174
  }
46
- select.innerHTML = html + '</optgroup>';
47
175
  select.value = TARGETS[0].id;
48
176
  useTarget(TARGETS[0]);
49
177
  }
50
178
 
51
- function useTarget(t) {
52
- targetBytes = t.bytes;
53
- el('aim').textContent = `aiming for ${human(t.bytes)}`;
54
- el('why').textContent = t.note || '';
179
+ // The done card was for the old limit, and kept saying so beside the new one.
180
+ // A failed card goes the same way: its reason belonged to the old limit.
181
+ function dropDone() {
182
+ if (!busy && (runState() === 'done' || runState() === 'failed')) run.reset();
183
+ }
184
+
185
+ function useTarget(target) {
186
+ dropDone();
187
+ targetBytes = target.bytes;
188
+ el('why').textContent = target.note || '';
189
+ note();
55
190
  }
56
191
 
57
192
  el('target').addEventListener('change', (e) => {
58
- const t = TARGETS.find((x) => x.id === e.target.value);
59
- if (!t || busy) return;
193
+ const target = TARGETS.find((x) => x.id === e.target.value);
194
+ if (!target || busy) return;
60
195
  el('custom').value = '';
61
- useTarget(t);
196
+ useTarget(target);
62
197
  });
63
198
 
64
199
  el('custom').addEventListener('input', (e) => {
@@ -66,86 +201,184 @@ el('custom').addEventListener('input', (e) => {
66
201
  if (!(mb > 0)) {
67
202
  // Cleared or nonsense: fall back to what the dropdown shows, rather than
68
203
  // quietly keeping the last custom size while the dropdown says otherwise.
69
- const t = TARGETS.find((x) => x.id === el('target').value);
70
- if (t) useTarget(t);
204
+ const target = TARGETS.find((x) => x.id === el('target').value);
205
+ if (target) useTarget(target);
71
206
  return;
72
207
  }
208
+ dropDone();
73
209
  targetBytes = mb * MB;
74
- el('aim').textContent = `aiming for ${human(targetBytes)}`;
75
210
  el('why').textContent = '';
211
+ note();
76
212
  });
77
213
 
78
214
  /* --- picking a file ----------------------------------------------------- */
79
215
 
216
+ // Whatever came in, by the picker or a drop: one file goes the way it always
217
+ // has (take), and several files or a folder become a batch (takeMany).
218
+ async function intake(paths) {
219
+ if (busy) return;
220
+ paths = paths.filter(Boolean);
221
+ // No path at all (a drop from somewhere that is not a file on disk): take
222
+ // says so in its own words.
223
+ if (!paths.length) return take('');
224
+ const g = await window.fits.gather(paths);
225
+ taken = paths;
226
+ if (g.single) return take(paths[0]);
227
+ return takeMany(paths, g);
228
+ }
229
+
80
230
  async function take(filePath) {
81
231
  if (busy) return;
82
- hide('error');
83
- hide('done');
232
+ start.error('');
233
+ familyHint.clear();
234
+ run.reset();
235
+ made = null;
236
+ batch = null;
237
+ whereField(null);
84
238
 
85
239
  // A drop that carries no path (dragged from somewhere that is not a real
86
240
  // file on disk) would otherwise surface ffprobe's ": No such file" with no name.
87
241
  const r = filePath
88
242
  ? await window.fits.probe(filePath)
89
- : { ok: false, message: 'Could not tell where that file is. Try "choose a file" instead.' };
243
+ : { ok: false, message: t('Could not tell where that file is. Try "Choose a file" instead.') };
90
244
  if (!r.ok) {
91
245
  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);
246
+ taken = null;
247
+ // Back to the start, so the previous file's name is not left beside an
248
+ // error about another; the reason goes under the drop zone.
249
+ start.reset();
250
+ note();
251
+ veilSay();
252
+ start.error(r.message);
253
+ // Read but not a video or picture (a PDF, a document, anything else): Just
254
+ // Zip sends it as it is. Not for a file that is gone or cannot be opened.
255
+ if (r.code === 'unreadable' && notMedia(filePath)) {
256
+ familyHint.show('justzip', t('Just Fits shrinks videos, pictures and sound. To send this as it is, Just Zip packs it into one file.'));
257
+ }
258
+ el('start').scrollIntoView({ block: 'nearest', behavior: 'smooth' });
96
259
  return;
97
260
  }
98
261
 
99
262
  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;
263
+ // A HEIC fits like any picture; this only says Just JPEG is there for one.
264
+ if (Kit.kindOf(filePath) === 'heic') familyHint.show('justjpeg', t('Need it as a JPEG instead?'));
265
+ start.landed({
266
+ name: filePath.split(/[\\/]/).pop(),
267
+ icon: r.info.kind === 'image' ? 'photo' : r.info.kind === 'audio' ? 'audio' : 'video',
268
+ facts: [
269
+ human(r.info.bytes),
270
+ r.info.width && `${r.info.width}x${r.info.height}`,
271
+ (r.info.kind === 'video' || r.info.kind === 'audio') && r.info.durationSec && clock(r.info.durationSec),
272
+ r.info.kind === 'video' && `${Math.round(r.info.fps)}fps`,
273
+ r.info.kind === 'video' && (r.info.hasAudio ? t('with sound') : t('silent')),
274
+ ].filter(Boolean).join(' · '),
275
+ });
110
276
  el('go').disabled = false;
277
+ note();
278
+ veilSay();
111
279
  }
112
280
 
113
- const drop = el('drop');
114
- for (const type of ['dragenter', 'dragover']) {
115
- drop.addEventListener(type, (e) => { e.preventDefault(); drop.classList.add('over'); });
281
+ // Several files or a folder. Each is probed first, so the file row can say
282
+ // what came in and the run knows which ones it cannot read before it starts.
283
+ async function takeMany(paths, g) {
284
+ if (busy) return;
285
+ start.error('');
286
+ familyHint.clear();
287
+ run.reset();
288
+ made = null;
289
+ chosen = null;
290
+ batch = null;
291
+ whereField(null);
292
+ const label = paths.length === 1 && g.folders === 1 ? paths[0].replace(/[\\/]+$/, '').split(/[\\/]/).pop() : tn(g.files.length, '{n} file', '{n} files');
293
+ // Some of them are not videos or pictures (in a folder, or named): the media
294
+ // ones are fitted as ever, and Just Zip sends the lot as one file.
295
+ const zipHint = () => familyHint.show('justzip', t('To send them as one file, try Just Zip.'));
296
+ if (!g.files.length) {
297
+ taken = null;
298
+ start.reset();
299
+ note();
300
+ veilSay();
301
+ start.error(g.missing.length
302
+ ? t('Could not find {name}. It may have been moved or deleted.', { name: g.missing[0].split(/[\\/]/).pop() })
303
+ : t('There are no videos or pictures in {name}.', { name: label }));
304
+ if (g.others) zipHint();
305
+ return;
306
+ }
307
+
308
+ // A few at a time: a folder of hundreds should not wait on each in turn.
309
+ const items = g.files.map((f) => ({ path: f.path, name: f.name, bytes: f.bytes, from: f.from, info: null, message: '', code: '' }));
310
+ for (let i = 0; i < items.length; i += 4) {
311
+ await Promise.all(items.slice(i, i + 4).map(async (it) => {
312
+ const r = await window.fits.probe(it.path);
313
+ if (r.ok) it.info = r.info; else { it.message = r.message; it.code = r.code || ''; }
314
+ }));
315
+ }
316
+ if (busy) return;
317
+
318
+ const videos = items.filter((it) => it.info && it.info.kind === 'video').length;
319
+ const pictures = items.filter((it) => it.info && it.info.kind === 'image').length;
320
+ const sounds = items.filter((it) => it.info && it.info.kind === 'audio').length;
321
+ const unreadable = items.length - videos - pictures - sounds;
322
+ const kinds = [
323
+ videos && tn(videos, '{n} video', '{n} videos'),
324
+ pictures && tn(pictures, '{n} picture', '{n} pictures'),
325
+ sounds && tn(sounds, '{n} sound file', '{n} sound files'),
326
+ unreadable && tn(unreadable, '{n} it cannot read', '{n} it cannot read'),
327
+ ].filter(Boolean);
328
+ batch = { label, items };
329
+ if (g.others || items.some((it) => notMedia(it.name))) zipHint();
330
+ whereField(items.find((it) => it.from));
331
+ start.landed({
332
+ name: label,
333
+ icon: g.folders ? 'folder' : videos ? 'video' : sounds && !pictures ? 'audio' : 'photos',
334
+ facts: `${kinds.join(', ')} · ${human(items.reduce((n, it) => n + it.bytes, 0))}`,
335
+ });
336
+ el('go').disabled = false;
337
+ note();
338
+ veilSay();
116
339
  }
117
- for (const type of ['dragleave', 'drop']) {
118
- drop.addEventListener(type, () => drop.classList.remove('over'));
340
+
341
+ // Save next to the originals instead: shown only with a folder in, with a
342
+ // line saying where the results go otherwise (the first folder's name).
343
+ function whereField(fromFolder) {
344
+ el('where-field').hidden = !fromFolder;
345
+ if (!fromFolder) return;
346
+ const name = fromFolder.from.replace(/[\\/]+$/, '').split(/[\\/]/).pop();
347
+ el('beside').checked = settings.get('beside');
348
+ el('where-hint').textContent = el('beside').checked
349
+ ? t('Each one is saved beside its original, as name-fits.')
350
+ // The results folder's real name on disk, which is always "(fitted)".
351
+ : t('Otherwise they go in a new folder beside it, {folder}, and the folder itself is left as it is.', { folder: `${name} (fitted)` });
119
352
  }
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);
353
+ el('beside').addEventListener('change', () => {
354
+ settings.set('beside', el('beside').checked);
355
+ whereField(batch && batch.items.find((it) => it.from));
124
356
  });
125
- document.addEventListener('dragover', (e) => e.preventDefault());
126
- document.addEventListener('drop', (e) => e.preventDefault());
127
357
 
128
- el('browse').addEventListener('click', async () => {
129
- const f = await window.fits.pickFile();
130
- if (f) take(f);
131
- });
358
+ // Start again: back to the drop zone, with the target left as it was.
359
+ function again() {
360
+ if (busy) return;
361
+ familyHint.clear();
362
+ chosen = null;
363
+ batch = null;
364
+ taken = null;
365
+ whereField(null);
366
+ made = null;
367
+ start.error('');
368
+ run.reset();
369
+ start.reset();
370
+ note();
371
+ veilSay();
372
+ }
132
373
 
133
374
  /* --- the work ----------------------------------------------------------- */
134
375
 
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
376
  // 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
377
+ // all land below the fold, and a grayed button alone looks the same as nothing
144
378
  // happening. So whatever the user is now waiting on, or has just got, scrolls
145
379
  // into view.
146
- function showInView(id, text) {
147
- show(id, text);
148
- el(id).scrollIntoView({ block: 'nearest', behavior: 'smooth' });
380
+ function inView() {
381
+ el('run').scrollIntoView({ block: 'nearest', behavior: 'smooth' });
149
382
  }
150
383
 
151
384
  // The output goes beside the original with no Save window, so the Done card
@@ -156,71 +389,462 @@ function whereText(file) {
156
389
  const name = file.slice(cut + 1);
157
390
  // A file at the top of a drive or the root keeps its separator: C:\ and /.
158
391
  const folder = cut > 0 && !/:$/.test(file.slice(0, cut)) ? file.slice(0, cut) : file.slice(0, cut + 1);
159
- return folder ? `Saved as ${name}, next to the original in ${folder}` : `Saved as ${name}`;
392
+ return folder ? t('Saved as {name}, next to the original in {folder}', { name, folder }) : t('Saved as {name}', { name });
393
+ }
394
+
395
+ // The time left, from how fast this attempt has gone so far. Each attempt
396
+ // starts its progress again, so the clock starts again with it.
397
+ let pace = null;
398
+ function timeLeft(p) {
399
+ const now = Date.now();
400
+ if (!pace || pace.attempt !== p.attempt || p.progress < pace.from) pace = { attempt: p.attempt, from: p.progress, at: now };
401
+ const done = p.progress - pace.from;
402
+ const spent = (now - pace.at) / 1000;
403
+ if (spent < 2 || done < 0.02) return '';
404
+ return aboutLeft(spent / done * (1 - p.progress));
405
+ }
406
+
407
+ // "About 9 seconds left", whole, in the window's language.
408
+ function aboutLeft(seconds) {
409
+ const s = Math.max(1, Math.round(seconds));
410
+ if (s < 60) return tn(s, 'About {n} second left', 'About {n} seconds left');
411
+ return tn(Math.round(s / 60), 'About {n} minute left', 'About {n} minutes left');
160
412
  }
161
413
 
162
414
  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` : '';
415
+ if (!busy) return;
416
+ if (batch) return manyProgress(p);
417
+ run.working({
418
+ // The stage comes from main in the window's language.
419
+ what: p.attempt > 0 ? t('{stage}, attempt {n}, aiming lower', { stage: p.stage, n: p.attempt + 1 }) : p.stage,
420
+ // Until ffmpeg says how far it is (a slow machine's first pass can take
421
+ // a while to say anything, and a picture says nothing), the bar sweeps.
422
+ count: p.progress > 0 ? percent(p.progress) : '',
423
+ fraction: p.progress,
424
+ unknown: !(p.progress > 0),
425
+ file: chosen ? chosen.path.split(/[\\/]/).pop() : '',
426
+ left: timeLeft(p),
427
+ });
167
428
  });
168
429
 
169
- el('go').addEventListener('click', async () => {
430
+ function finished({ title, detail = '', where = '', file = null, folder = false, over = false }) {
431
+ made = file;
432
+ run.done({ title, detail, where, reveal: Boolean(file), revealLabel: folder ? t('Show me the folder') : t('Show me the file'), tone: over ? 'over' : '' });
433
+ note();
434
+ inView();
435
+ }
436
+
437
+ async function compress() {
170
438
  if (!chosen || busy) return;
171
439
 
172
440
  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');
441
+ showSingle({ k: 'fits', size: chosen.info.bytes, limit: targetBytes });
179
442
  return;
180
443
  }
181
444
 
182
445
  busy = true;
446
+ pace = null;
183
447
  el('go').disabled = true;
184
- hide('error');
185
- hide('done');
186
- el('fill').style.width = '0%';
187
- showInView('working');
448
+ veilSay();
449
+ run.working({ what: t('Working'), unknown: true, file: chosen.path.split(/[\\/]/).pop() });
450
+ note();
451
+ inView();
188
452
 
189
453
  const r = await window.fits.fit(chosen.path, targetBytes);
190
454
 
191
455
  busy = false;
192
456
  el('go').disabled = false;
193
- hide('working');
457
+ veilSay();
194
458
 
195
459
  if (!r.ok) {
196
- if (!r.cancelled) showInView('error', r.message);
460
+ // Cancelled: say so, or the window just goes back to how it was.
461
+ showSingle(r.cancelled ? { k: 'stopped' } : { k: 'failed', message: r.message });
197
462
  return;
198
463
  }
199
464
 
200
- 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
203
- ? `Got it to ${human(r.bytes)}, still over the line.`
204
- : `Done. ${human(r.before)} to ${human(r.bytes)}, ${saved}% smaller.`;
465
+ showSingle({
466
+ k: 'done',
467
+ before: r.before, bytes: r.bytes, over: Boolean(r.over), kind: r.kind, path: r.path, attempts: r.attempts, note: r.note || '', duration: r.durationSec || 0,
468
+ plan: r.plan ? { width: r.plan.width, height: r.plan.height, fps: r.plan.fps, videoKbps: r.plan.videoKbps, audioKbps: r.plan.audioKbps } : null,
469
+ });
470
+ }
471
+
472
+ // A single file's result card, drawn from plain data so it can be drawn again
473
+ // in another language after a switch (what main said in its own words, the
474
+ // length note and a failure's message, stays as it was).
475
+ function showSingle(res) {
476
+ shown = { single: res };
477
+ if (res.k === 'fits') {
478
+ finished({
479
+ title: t('That already fits.'),
480
+ detail: t('{size}, under the {limit} limit. Nothing to do.', { size: human(res.size), limit: human(res.limit) }),
481
+ });
482
+ return;
483
+ }
484
+ if (res.k === 'failed') {
485
+ run.failed(res.message);
486
+ note();
487
+ inView();
488
+ return;
489
+ }
490
+ if (res.k === 'stopped') {
491
+ finished({ title: t('Stopped.'), detail: t('Nothing was saved, and the original is untouched.') });
492
+ return;
493
+ }
494
+
495
+ const saved = Math.round((1 - res.bytes / res.before) * 100);
496
+ const title = res.over
497
+ ? t('Got it to {size}, still over the line.', { size: human(res.bytes) })
498
+ : t('Done. {before} to {after}, {percent}% smaller.', { before: human(res.before), after: human(res.bytes), percent: saved });
205
499
 
206
500
  const bits = [];
207
- if (r.plan && r.kind === 'video') {
208
- bits.push(`${r.plan.width}x${r.plan.height}`);
209
- bits.push(`${Math.round(r.plan.fps)}fps`);
210
- bits.push(`${r.plan.videoKbps}k video`);
211
- if (r.plan.audioKbps) bits.push(`${r.plan.audioKbps}k audio`);
212
- }
213
- if (r.attempts > 1) bits.push(`${r.attempts} attempts`);
214
- el('detail').textContent = bits.join(' · ');
215
-
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
- });
501
+ if (res.plan && res.kind === 'video') {
502
+ bits.push(`${res.plan.width}x${res.plan.height}`);
503
+ bits.push(`${Math.round(res.plan.fps)}fps`);
504
+ bits.push(t('{kbps}k video', { kbps: res.plan.videoKbps }));
505
+ if (res.plan.audioKbps) bits.push(t('{kbps}k audio', { kbps: res.plan.audioKbps }));
506
+ }
507
+ // Sound has no frame to describe: how long it is and what it was made at.
508
+ if (res.plan && res.kind === 'audio') {
509
+ if (res.duration) bits.push(clock(res.duration));
510
+ if (res.plan.audioKbps) bits.push(t('{kbps}k audio', { kbps: res.plan.audioKbps }));
511
+ }
512
+ if (res.attempts > 1) bits.push(tn(res.attempts, '{n} attempt', '{n} attempts'));
513
+ // The plan knew when the target was too small for the length; say it here
514
+ // too, so a soft picture is explained rather than a surprise. The sentence
515
+ // is the command line's, from plan.lengthNote through main.
516
+ const rough = res.note || '';
517
+
518
+ // the facts stay a facts line; the plain-words warning leads the line under it
519
+ finished({ title, detail: bits.join(' · '), where: (rough ? rough + ' ' : '') + whereText(res.path), file: res.path, over: res.over });
520
+ }
521
+
522
+ /* --- several files ------------------------------------------------------ */
523
+
524
+ // Cancel stops at once, in a batch too: the file being fitted is stopped and
525
+ // its half-written result removed (the engine does that), and no more start.
526
+ // Files already fitted stay fitted.
527
+ let stopping = false;
528
+ function cancel() {
529
+ if (batch) {
530
+ stopping = true;
531
+ if (manyAt) manyProgress(manyAt.last);
532
+ }
533
+ window.fits.cancel();
534
+ }
535
+
536
+ let manyAt = null; // where a batch run is: which file, since when
537
+
538
+ // What the queue says beside a file, from what happened to it, so it can be
539
+ // said again in another language after a switch.
540
+ function noteOf(it) {
541
+ if (it.mark === 'part') return t('Stopped part way, nothing kept');
542
+ if (it.mark === 'unstarted') return t('Not started');
543
+ if (it.result === 'failed') return shortReason(it.message, it.code);
544
+ if (it.result === 'skipped') return it.copied ? t('Already small enough, copied in') : t('Already small enough');
545
+ if (it.result === 'over') return t('Could not get under {limit}, got to {size}', { limit: human(it.limit), size: human(it.after) });
546
+ if (it.result === 'fitted') return t('{before} to {after}', { before: human(it.before), after: human(it.after) });
547
+ return '';
548
+ }
549
+
550
+ function rows() {
551
+ return batch.items.map((it) => ({ name: it.name, state: it.state || 'waiting', note: noteOf(it) }));
552
+ }
553
+
554
+ // The queue shows every file, so the one being fitted is kept in sight in it.
555
+ function showQueue() {
556
+ run.queue(rows());
557
+ const box = el('run').querySelector('.k-run-queue');
558
+ const now = box && box.querySelector('li[data-q="working"]');
559
+ if (now) box.scrollTop = Math.max(0, now.offsetTop - box.clientHeight / 2);
560
+ }
561
+
562
+ function manyProgress(p) {
563
+ if (!manyAt) return;
564
+ manyAt.last = p;
565
+ const n = batch.items.length;
566
+ // Weighed by size, not by count: a video among photos is most of the work,
567
+ // and counting files said "3 seconds left" as it started on it.
568
+ const items = batch.items;
569
+ const total = items.reduce((t, it) => t + it.bytes, 0) || 1;
570
+ const before = items.slice(0, manyAt.index).reduce((t, it) => t + it.bytes, 0);
571
+ const overall = Math.min(1, (before + items[manyAt.index].bytes * (p ? p.progress : 0)) / total);
572
+ const spent = (Date.now() - manyAt.started) / 1000;
573
+ const left = spent > 3 && overall > 0.02 ? aboutLeft(spent / overall * (1 - overall)) : '';
574
+ const at = { at: manyAt.index + 1, total: n };
575
+ run.working({
576
+ what: stopping ? t('Stopping')
577
+ : p && p.attempt > 0 ? t('Fitting {at} of {total}, attempt {n}', { ...at, n: p.attempt + 1 })
578
+ : t('Fitting {at} of {total}', at),
579
+ count: overall > 0 ? percent(overall) : '',
580
+ fraction: overall,
581
+ unknown: !(overall > 0),
582
+ file: batch.items[manyAt.index].name,
583
+ left,
584
+ });
585
+ }
221
586
 
222
- el('cancel').addEventListener('click', () => window.fits.cancel());
223
- el('site').addEventListener('click', () => window.fits.openSite());
224
- el('licences').addEventListener('click', () => window.fits.openLicences());
587
+ // A short reason for the queue; the whole sentence is in the probe's message.
588
+ // Told by the probe's code, not its words, which are in the window's language.
589
+ function shortReason(message, code) {
590
+ if (code === 'unreadable') return t('Not a video, picture or sound file Just Fits can read');
591
+ if (code === 'animated-webp') return t('An animated WebP, which it cannot shrink');
592
+ if (code === 'missing') return t('It was moved or deleted');
593
+ return String(message || t('Failed')).split('\n')[0];
594
+ }
595
+
596
+ async function compressMany() {
597
+ if (!batch || busy) return;
598
+ const items = batch.items;
599
+ for (const it of items) { it.state = 'waiting'; it.mark = ''; it.out = null; it.folder = null; it.copied = false; it.result = null; }
600
+ const run1 = ++runNo;
601
+ const beside = settings.get('beside');
602
+
603
+ busy = true;
604
+ stopping = false;
605
+ made = null;
606
+ el('go').disabled = true;
607
+ veilSay();
608
+ manyAt = { index: 0, started: Date.now(), last: null };
609
+ manyProgress(null);
610
+ showQueue();
611
+ note();
612
+ inView();
613
+
614
+ const target = targetBytes;
615
+ let stoppedAt = null;
616
+ for (let i = 0; i < items.length; i++) {
617
+ if (stopping) { stoppedAt = i; break; }
618
+ const it = items[i];
619
+ manyAt.index = i;
620
+ manyAt.last = null;
621
+ it.state = 'working';
622
+ manyProgress(null);
623
+ showQueue();
624
+
625
+ if (!it.info) {
626
+ it.result = 'failed';
627
+ it.state = 'failed';
628
+ } else if (it.info.bytes <= target && (beside || !it.from)) {
629
+ it.result = 'skipped';
630
+ it.state = 'done';
631
+ } else {
632
+ const r = await window.fits.fit(it.path, target, { beside, run: run1 });
633
+ if (r.cancelled) {
634
+ // stopped part way: nothing of it was kept, and the queue says so
635
+ it.state = 'waiting';
636
+ it.mark = 'part';
637
+ stoppedAt = i;
638
+ break;
639
+ } else if (!r.ok) {
640
+ it.result = 'failed';
641
+ it.state = 'failed';
642
+ it.message = r.message || '';
643
+ it.code = r.code || '';
644
+ } else if (r.copied) {
645
+ // already small enough, copied into the results folder as it is
646
+ it.result = 'skipped';
647
+ it.state = 'done';
648
+ it.out = r.path;
649
+ it.folder = r.folder;
650
+ it.copied = true;
651
+ } else {
652
+ it.out = r.path;
653
+ it.folder = r.folder || null;
654
+ it.before = r.before;
655
+ it.after = r.bytes;
656
+ if (!made) made = r.path;
657
+ if (r.over) {
658
+ it.result = 'over';
659
+ it.state = 'failed';
660
+ it.limit = target;
661
+ } else {
662
+ it.result = 'fitted';
663
+ it.state = 'done';
664
+ }
665
+ }
666
+ }
667
+ }
668
+ const seconds = (Date.now() - manyAt.started) / 1000;
669
+ manyAt = null;
670
+ busy = false;
671
+ el('go').disabled = false;
672
+ veilSay();
673
+ for (const it of items) if (it.state === 'waiting' && stoppedAt !== null && !it.mark) it.mark = 'unstarted';
674
+ showMany({ seconds, stoppedAt, target });
675
+ }
676
+
677
+ // A batch's result card and queue, from what happened to each file, so they
678
+ // can be drawn again in another language after a switch.
679
+ function showMany({ seconds, stoppedAt, target }) {
680
+ const items = batch.items;
681
+ shown = { many: { seconds, stoppedAt, target } };
682
+ showQueue();
683
+
684
+ const tally = (k) => items.filter((it) => it.result === k).length;
685
+ const fitted = tally('fitted');
686
+ const skipped = tally('skipped');
687
+ const over = tally('over');
688
+ const failed = tally('failed');
689
+ const tried = fitted + skipped + over + failed;
690
+
691
+ if (stoppedAt === null && failed === items.length) {
692
+ run.failed(tn(items.length, 'The file could not be fitted. The list says why.', 'None of the {n} files could be fitted. The list says why for each.'));
693
+ note();
694
+ inView();
695
+ return;
696
+ }
697
+
698
+ // Each count is a whole phrase of its own; the list of them goes into the
699
+ // title as one slot.
700
+ const parts = [];
701
+ if (fitted || (!skipped && !over && !failed)) parts.push(tn(fitted, '{n} fitted', '{n} fitted'));
702
+ if (skipped) parts.push(tn(skipped, '{n} already small enough', '{n} already small enough'));
703
+ if (over) parts.push(tn(over, '{n} could not get under {limit}', '{n} could not get under {limit}', { limit: human(target) }));
704
+ if (failed) parts.push(tn(failed, '{n} could not be read or fitted', '{n} could not be read or fitted'));
705
+ const results = parts.join(', ');
706
+ let title;
707
+ if (stoppedAt !== null && !tried) title = tn(items.length, 'Stopped. The file was not changed.', 'Stopped. None of the {n} files were changed.');
708
+ else if (stoppedAt !== null) title = t('Stopped after {done} of {total}. {results}.', { done: tried, total: items.length, results });
709
+ else if (skipped === items.length) title = tn(items.length, 'It already fits under {limit}.', 'All {n} already fit under {limit}.', { limit: human(target) });
710
+ else title = t('Done. {results}.', { results });
711
+ title = title.charAt(0).toUpperCase() + title.slice(1);
712
+
713
+ const changed = items.filter((it) => it.out && !it.copied);
714
+ const written = items.filter((it) => it.out);
715
+ const before = changed.reduce((n, it) => n + it.before, 0);
716
+ const after = changed.reduce((n, it) => n + it.after, 0);
717
+ const took = Math.max(1, Math.round(seconds));
718
+ const sizes = { before: human(before), after: human(after) };
719
+ const detail = !changed.length ? ''
720
+ : took < 60 ? tn(took, '{before} to {after} in {n} second', '{before} to {after} in {n} seconds', sizes)
721
+ : tn(Math.round(took / 60), '{before} to {after} in {n} minute', '{before} to {after} in {n} minutes', sizes);
722
+ const folders = [...new Set(written.map((it) => it.folder).filter(Boolean))];
723
+ const besideCount = written.filter((it) => !it.folder).length;
724
+ const nameOf = (p) => p.split(/[\\/]/).pop();
725
+ let where = '';
726
+ if (folders.length === 1 && !besideCount) where = tn(written.length, 'Saved {n} file in {folder}', 'Saved {n} files in {folder}', { folder: nameOf(folders[0]) });
727
+ else if (folders.length > 1 && !besideCount) where = tn(written.length, 'Saved {n} file in {count} new folders beside the originals', 'Saved {n} files in {count} new folders beside the originals', { count: folders.length });
728
+ else if (folders.length) {
729
+ // Two counts in one sentence: the folders and the files beside their
730
+ // originals are each said whole and go into the files' sentence as slots.
731
+ where = tn(written.length - besideCount, 'Saved {n} file in {folder}, {beside}', 'Saved {n} files in {folder}, {beside}', {
732
+ folder: folders.length === 1 ? nameOf(folders[0]) : tn(folders.length, '{n} new folder', '{n} new folders'),
733
+ beside: tn(besideCount, '{n} next to its original', '{n} next to their originals'),
734
+ });
735
+ } else if (written.length) where = t('Saved next to each original');
736
+ if (where && stoppedAt !== null) where = t('{saved}. The rest were left as they were.', { saved: where });
737
+ finished({
738
+ title,
739
+ detail,
740
+ where,
741
+ // Show me the file: the results folder when they all went into one.
742
+ file: folders.length === 1 && !besideCount ? folders[0] : made,
743
+ folder: folders.length === 1 && !besideCount,
744
+ over: over > 0,
745
+ });
746
+ }
747
+
748
+ el('go').addEventListener('click', () => (batch ? compressMany() : compress()));
749
+
750
+ /* --- across a language switch -------------------------------------------- */
751
+
752
+ /*
753
+ * Picking another language reloads the window, which would drop what is on
754
+ * screen. Told just before, this keeps a plain description of it (the paths
755
+ * that came in, the target and custom size, and a finished, stopped or failed
756
+ * result) once, for the page that loads next to put back in the new language.
757
+ * The files come back through intake, the way a drop does, so main's checks
758
+ * all apply; a file that has gone is left out. Save next to the originals is
759
+ * already kept by its own setting.
760
+ */
761
+ const KEPT_FOR = 60 * 1000;
762
+ const PICK = ['fitted', 'skipped', 'over', 'failed'];
763
+
764
+ function keepForSwitch() {
765
+ const carry = { at: Date.now(), runNo };
766
+ const state = runState();
767
+ if (taken && (chosen || batch)) {
768
+ carry.paths = taken;
769
+ carry.target = el('target').value;
770
+ carry.custom = el('custom').value;
771
+ if (!busy && (state === 'done' || state === 'failed') && shown) {
772
+ if (shown.single) carry.single = shown.single;
773
+ else if (shown.many && batch) {
774
+ carry.many = {
775
+ ...shown.many,
776
+ made,
777
+ items: batch.items.map((it) => ({
778
+ path: it.path, state: it.state, result: it.result, mark: it.mark, message: it.message, code: it.code, limit: it.limit,
779
+ before: it.before, after: it.after, out: it.out, folder: it.folder, copied: it.copied,
780
+ })),
781
+ };
782
+ }
783
+ }
784
+ }
785
+ settings.set('carry', carry);
786
+ }
787
+
788
+ // Only what is the right shape goes back, and nothing here throws: on any
789
+ // doubt the start screen is what the person sees.
790
+ const text = (v) => (typeof v === 'string' ? v : '');
791
+ const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : 0);
792
+
793
+ async function restore() {
794
+ const carry = settings.get('carry');
795
+ settings.set('carry', {});
796
+ await drawTargets();
797
+ try {
798
+ if (carry && Number.isInteger(carry.runNo) && carry.runNo > runNo) runNo = carry.runNo;
799
+ if (!carry || !Array.isArray(carry.paths) || !carry.paths.length || !(Date.now() - carry.at < KEPT_FOR)) return;
800
+ const target = TARGETS.find((x) => x.id === carry.target);
801
+ if (target) {
802
+ el('target').value = target.id;
803
+ useTarget(target);
804
+ }
805
+ const mb = Number(carry.custom);
806
+ if (carry.custom && mb > 0) {
807
+ el('custom').value = String(carry.custom);
808
+ el('custom').dispatchEvent(new Event('input', { bubbles: true }));
809
+ }
810
+ await intake(carry.paths.map(String));
811
+ if (!chosen && !batch) {
812
+ // Nothing came back (the file has gone): no error from a file the
813
+ // person did not just pick.
814
+ start.error('');
815
+ familyHint.clear();
816
+ return;
817
+ }
818
+ if (busy) return;
819
+ if (carry.single && chosen) {
820
+ const s = carry.single;
821
+ if (s.k === 'fits') showSingle({ k: 'fits', size: num(s.size), limit: num(s.limit) });
822
+ else if (s.k === 'stopped') showSingle({ k: 'stopped' });
823
+ else if (s.k === 'failed') showSingle({ k: 'failed', message: text(s.message) });
824
+ else if (s.k === 'done') {
825
+ showSingle({
826
+ k: 'done', before: num(s.before), bytes: num(s.bytes), over: Boolean(s.over), kind: text(s.kind), path: text(s.path),
827
+ attempts: num(s.attempts), note: text(s.note), duration: num(s.duration),
828
+ plan: s.plan ? { width: num(s.plan.width), height: num(s.plan.height), fps: num(s.plan.fps), videoKbps: num(s.plan.videoKbps), audioKbps: num(s.plan.audioKbps) } : null,
829
+ });
830
+ made = text(s.path) || null;
831
+ }
832
+ } else if (carry.many && batch) {
833
+ const m = carry.many;
834
+ const saved = Array.isArray(m.items) ? m.items : [];
835
+ // The same files, in the same order, or the result is not put back: it
836
+ // would describe a different set.
837
+ if (saved.length !== batch.items.length || !saved.every((x, i) => x && x.path === batch.items[i].path)) return;
838
+ saved.forEach((x, i) => {
839
+ const it = batch.items[i];
840
+ it.state = text(x.state); it.result = PICK.includes(x.result) ? x.result : null; it.mark = text(x.mark);
841
+ it.message = text(x.message); it.code = text(x.code); it.limit = num(x.limit);
842
+ it.before = num(x.before); it.after = num(x.after); it.out = text(x.out) || null; it.folder = text(x.folder) || null; it.copied = Boolean(x.copied);
843
+ });
844
+ made = text(m.made) || null;
845
+ showMany({ seconds: num(m.seconds), stoppedAt: Number.isInteger(m.stoppedAt) ? m.stoppedAt : null, target: num(m.target) });
846
+ }
847
+ } catch (err) { /* nothing to put back; the start screen is there */ }
848
+ }
225
849
 
226
- drawTargets();
850
+ restore();