forge-terminal 0.1.0 → 0.2.1
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.
- package/README.md +333 -24
- package/dist/chunks/adm-zip-SQKLKBDP.js +3 -0
- package/dist/chunks/available-HEUREG6L.js +3 -0
- package/dist/chunks/boot-BUGERSEB.js +3 -0
- package/dist/chunks/catalog-NTACQH5V.js +3 -0
- package/dist/chunks/cfb-V6M2PYOD.js +13 -0
- package/dist/chunks/chunk-2WYHI73Y.js +3 -0
- package/dist/chunks/chunk-4YCO7S4K.js +3 -0
- package/dist/chunks/chunk-5B7WODWH.js +3 -0
- package/dist/chunks/chunk-C2WYXNRM.js +4 -0
- package/dist/chunks/chunk-C7OOWUMU.js +3 -0
- package/dist/chunks/chunk-EOYBXOCV.js +4 -0
- package/dist/chunks/chunk-G2D6BKOS.js +4 -0
- package/dist/chunks/chunk-HUAEVW2A.js +3 -0
- package/dist/chunks/chunk-J7FLFHQJ.js +3 -0
- package/dist/chunks/chunk-L76Q54MB.js +3 -0
- package/dist/chunks/chunk-LFE3WRU4.js +3 -0
- package/dist/chunks/chunk-PBIS2ONZ.js +3 -0
- package/dist/chunks/chunk-PD5DFBCU.js +3 -0
- package/dist/chunks/chunk-PN73WK2S.js +3 -0
- package/dist/chunks/chunk-QVACE4IE.js +3 -0
- package/dist/chunks/chunk-TEGB7JRM.js +3 -0
- package/dist/chunks/chunk-TMUK2DD3.js +3 -0
- package/dist/chunks/chunk-UNVHKJW4.js +41 -0
- package/dist/chunks/chunk-VH5RWPGZ.js +10 -0
- package/dist/chunks/chunk-XFEHJ4C7.js +3 -0
- package/dist/chunks/chunk-YXDEOLNA.js +3 -0
- package/dist/chunks/colour-DE6N6AZO.js +3 -0
- package/dist/chunks/config-command-SQXRTBRO.js +3 -0
- package/dist/chunks/dist-J2V6ITHG.js +29 -0
- package/dist/chunks/es-T2U7NBLD.js +3 -0
- package/dist/chunks/execute-M3C3TTWB.js +3 -0
- package/dist/chunks/extensions-command-HJDBUBYO.js +3 -0
- package/dist/chunks/image-GYUUMS6H.js +3 -0
- package/dist/chunks/launch-WBUFRVQ7.js +65 -0
- package/dist/chunks/lib-TPEJ5CJJ.js +46 -0
- package/dist/chunks/lock-XD4L3WFM.js +3 -0
- package/dist/chunks/manager-KBJTXZ27.js +4 -0
- package/dist/chunks/paths-JUM6GKQU.js +3 -0
- package/dist/chunks/pdf-compress-IMRFBLZF.js +3 -0
- package/dist/chunks/react-devtools-core-UM4FS6CU.js +3 -0
- package/dist/chunks/run-RXVQD4DZ.js +4 -0
- package/dist/chunks/server-DU7QWDAH.js +73 -0
- package/dist/chunks/theme-DESCJOCE.js +3 -0
- package/dist/chunks/word-OGQ2KZAJ.js +24 -0
- package/dist/index.js +67 -95
- package/dist/third-party-licenses.txt +2856 -0
- package/package.json +28 -21
- package/skills/forge/SKILL.md +149 -0
- package/dist/cli/args.js +0 -278
- package/dist/cli/args.js.map +0 -1
- package/dist/cli/config-command.js +0 -55
- package/dist/cli/config-command.js.map +0 -1
- package/dist/cli/execute.js +0 -377
- package/dist/cli/execute.js.map +0 -1
- package/dist/cli/report.js +0 -123
- package/dist/cli/report.js.map +0 -1
- package/dist/cli/spinner.js +0 -60
- package/dist/cli/spinner.js.map +0 -1
- package/dist/cli/stdin.js +0 -47
- package/dist/cli/stdin.js.map +0 -1
- package/dist/config/preferences.js +0 -143
- package/dist/config/preferences.js.map +0 -1
- package/dist/core/actions/compress.js +0 -157
- package/dist/core/actions/compress.js.map +0 -1
- package/dist/core/actions/convert.js +0 -270
- package/dist/core/actions/convert.js.map +0 -1
- package/dist/core/actions/extract.js +0 -94
- package/dist/core/actions/extract.js.map +0 -1
- package/dist/core/actions/index.js +0 -23
- package/dist/core/actions/index.js.map +0 -1
- package/dist/core/actions/merge.js +0 -16
- package/dist/core/actions/merge.js.map +0 -1
- package/dist/core/actions/rotate.js +0 -36
- package/dist/core/actions/rotate.js.map +0 -1
- package/dist/core/actions/split.js +0 -65
- package/dist/core/actions/split.js.map +0 -1
- package/dist/core/atomic.js +0 -61
- package/dist/core/atomic.js.map +0 -1
- package/dist/core/capabilities.js +0 -59
- package/dist/core/capabilities.js.map +0 -1
- package/dist/core/compress.js +0 -76
- package/dist/core/compress.js.map +0 -1
- package/dist/core/describe.js +0 -49
- package/dist/core/describe.js.map +0 -1
- package/dist/core/errors.js +0 -469
- package/dist/core/errors.js.map +0 -1
- package/dist/core/execute-jobs.js +0 -122
- package/dist/core/execute-jobs.js.map +0 -1
- package/dist/core/formats.js +0 -108
- package/dist/core/formats.js.map +0 -1
- package/dist/core/order.js +0 -44
- package/dist/core/order.js.map +0 -1
- package/dist/core/output-path.js +0 -176
- package/dist/core/output-path.js.map +0 -1
- package/dist/core/pages.js +0 -107
- package/dist/core/pages.js.map +0 -1
- package/dist/core/pdf-compress.js +0 -206
- package/dist/core/pdf-compress.js.map +0 -1
- package/dist/core/plan.js +0 -42
- package/dist/core/plan.js.map +0 -1
- package/dist/core/resolve.js +0 -115
- package/dist/core/resolve.js.map +0 -1
- package/dist/core/run.js +0 -66
- package/dist/core/run.js.map +0 -1
- package/dist/core/suggest.js +0 -50
- package/dist/core/suggest.js.map +0 -1
- package/dist/core/types.js +0 -2
- package/dist/core/types.js.map +0 -1
- package/dist/core/units.js +0 -94
- package/dist/core/units.js.map +0 -1
- package/dist/core/write-safety.js +0 -128
- package/dist/core/write-safety.js.map +0 -1
- package/dist/engines/heic.js +0 -166
- package/dist/engines/heic.js.map +0 -1
- package/dist/engines/image.js +0 -342
- package/dist/engines/image.js.map +0 -1
- package/dist/engines/pdf.js +0 -444
- package/dist/engines/pdf.js.map +0 -1
- package/dist/engines/pdfium.js +0 -161
- package/dist/engines/pdfium.js.map +0 -1
- package/dist/engines/registry.js +0 -65
- package/dist/engines/registry.js.map +0 -1
- package/dist/engines/types.js +0 -2
- package/dist/engines/types.js.map +0 -1
- package/dist/engines/word.js +0 -385
- package/dist/engines/word.js.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/shell/App.js +0 -1972
- package/dist/shell/App.js.map +0 -1
- package/dist/shell/ClickTargets.js +0 -183
- package/dist/shell/ClickTargets.js.map +0 -1
- package/dist/shell/ThemeContext.js +0 -21
- package/dist/shell/ThemeContext.js.map +0 -1
- package/dist/shell/blocks.js +0 -160
- package/dist/shell/blocks.js.map +0 -1
- package/dist/shell/clipboard.js +0 -64
- package/dist/shell/clipboard.js.map +0 -1
- package/dist/shell/commands.js +0 -51
- package/dist/shell/commands.js.map +0 -1
- package/dist/shell/components/Banner.js +0 -73
- package/dist/shell/components/Banner.js.map +0 -1
- package/dist/shell/components/CommandPalette.js +0 -37
- package/dist/shell/components/CommandPalette.js.map +0 -1
- package/dist/shell/components/FileCard.js +0 -59
- package/dist/shell/components/FileCard.js.map +0 -1
- package/dist/shell/components/HintBar.js +0 -18
- package/dist/shell/components/HintBar.js.map +0 -1
- package/dist/shell/components/Hints.js +0 -21
- package/dist/shell/components/Hints.js.map +0 -1
- package/dist/shell/components/MergeList.js +0 -268
- package/dist/shell/components/MergeList.js.map +0 -1
- package/dist/shell/components/ModeHeader.js +0 -21
- package/dist/shell/components/ModeHeader.js.map +0 -1
- package/dist/shell/components/PageGrid.js +0 -324
- package/dist/shell/components/PageGrid.js.map +0 -1
- package/dist/shell/components/PathInput.js +0 -147
- package/dist/shell/components/PathInput.js.map +0 -1
- package/dist/shell/components/Progress.js +0 -43
- package/dist/shell/components/Progress.js.map +0 -1
- package/dist/shell/components/Prompt.js +0 -667
- package/dist/shell/components/Prompt.js.map +0 -1
- package/dist/shell/components/ResultLinks.js +0 -26
- package/dist/shell/components/ResultLinks.js.map +0 -1
- package/dist/shell/components/Select.js +0 -152
- package/dist/shell/components/Select.js.map +0 -1
- package/dist/shell/components/Slider.js +0 -48
- package/dist/shell/components/Slider.js.map +0 -1
- package/dist/shell/components/StagedFiles.js +0 -92
- package/dist/shell/components/StagedFiles.js.map +0 -1
- package/dist/shell/components/ThemePicker.js +0 -18
- package/dist/shell/components/ThemePicker.js.map +0 -1
- package/dist/shell/components/UnitRow.js +0 -30
- package/dist/shell/components/UnitRow.js.map +0 -1
- package/dist/shell/flows/pdf.js +0 -424
- package/dist/shell/flows/pdf.js.map +0 -1
- package/dist/shell/frame-geometry.js +0 -56
- package/dist/shell/frame-geometry.js.map +0 -1
- package/dist/shell/hyperlink.js +0 -27
- package/dist/shell/hyperlink.js.map +0 -1
- package/dist/shell/intro.js +0 -101
- package/dist/shell/intro.js.map +0 -1
- package/dist/shell/launch.js +0 -75
- package/dist/shell/launch.js.map +0 -1
- package/dist/shell/mark.js +0 -134
- package/dist/shell/mark.js.map +0 -1
- package/dist/shell/mouse.js +0 -209
- package/dist/shell/mouse.js.map +0 -1
- package/dist/shell/redraw.js +0 -36
- package/dist/shell/redraw.js.map +0 -1
- package/dist/shell/reveal.js +0 -24
- package/dist/shell/reveal.js.map +0 -1
- package/dist/shell/stage.js +0 -34
- package/dist/shell/stage.js.map +0 -1
- package/dist/shell/terminal-write.js +0 -16
- package/dist/shell/terminal-write.js.map +0 -1
- package/dist/shell/theme.js +0 -178
- package/dist/shell/theme.js.map +0 -1
- package/dist/shell/useFrameOrigin.js +0 -175
- package/dist/shell/useFrameOrigin.js.map +0 -1
- package/dist/shell/useKeys.js +0 -28
- package/dist/shell/useKeys.js.map +0 -1
- package/dist/shell/useMouse.js +0 -150
- package/dist/shell/useMouse.js.map +0 -1
- package/dist/shell/useMouseRouting.js +0 -69
- package/dist/shell/useMouseRouting.js.map +0 -1
- package/dist/shell/width.js +0 -62
- package/dist/shell/width.js.map +0 -1
- package/dist/utils/display-path.js +0 -31
- package/dist/utils/display-path.js.map +0 -1
- package/dist/utils/unescape-path.js +0 -68
- package/dist/utils/unescape-path.js.map +0 -1
package/dist/shell/App.js
DELETED
|
@@ -1,1972 +0,0 @@
|
|
|
1
|
-
import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
-
import { stat } from 'node:fs/promises';
|
|
3
|
-
import { basename } from 'node:path';
|
|
4
|
-
import { Box, Static, Text, useStdout } from 'ink';
|
|
5
|
-
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
|
6
|
-
import { DEFAULT_PREFERENCES, expandTilde, savePreferences, } from '../config/preferences.js';
|
|
7
|
-
import { compressAction, convertAction } from '../core/actions/index.js';
|
|
8
|
-
import { describeResult } from '../core/describe.js';
|
|
9
|
-
import { isForgeError, unexpectedError, unsupportedCompress, unsupportedPdf, } from '../core/errors.js';
|
|
10
|
-
import { runPlan } from '../core/execute-jobs.js';
|
|
11
|
-
import { FORMATS, primaryExtension } from '../core/formats.js';
|
|
12
|
-
import { uniqueOutputPath } from '../core/output-path.js';
|
|
13
|
-
import { resolveDirectory } from '../core/resolve.js';
|
|
14
|
-
import { suggestFormat } from '../core/suggest.js';
|
|
15
|
-
import { describeSize, formatBytes, parseSize } from '../core/units.js';
|
|
16
|
-
import { checkWriteSafety } from '../core/write-safety.js';
|
|
17
|
-
import { encodeToBuffer } from '../engines/image.js';
|
|
18
|
-
import { pdfiumEngine } from '../engines/pdfium.js';
|
|
19
|
-
import { probe } from '../engines/registry.js';
|
|
20
|
-
import { splitPastedPaths, unescapePath } from '../utils/unescape-path.js';
|
|
21
|
-
import { HistoryEntry } from './blocks.js';
|
|
22
|
-
import { ClickTargetProvider } from './ClickTargets.js';
|
|
23
|
-
import { COMMANDS, isCommandBuffer, matchCommands, parseCommand } from './commands.js';
|
|
24
|
-
import { CommandPalette } from './components/CommandPalette.js';
|
|
25
|
-
import { HintBar } from './components/HintBar.js';
|
|
26
|
-
import { Hints } from './components/Hints.js';
|
|
27
|
-
import { PageGrid } from './components/PageGrid.js';
|
|
28
|
-
import { PathInput } from './components/PathInput.js';
|
|
29
|
-
import { Progress } from './components/Progress.js';
|
|
30
|
-
import { Prompt } from './components/Prompt.js';
|
|
31
|
-
import { ResultLinks } from './components/ResultLinks.js';
|
|
32
|
-
import { Select } from './components/Select.js';
|
|
33
|
-
import { Slider } from './components/Slider.js';
|
|
34
|
-
import { StagedFiles } from './components/StagedFiles.js';
|
|
35
|
-
import { ThemePicker } from './components/ThemePicker.js';
|
|
36
|
-
import { SIZE_UNIT_IDS, UnitRow } from './components/UnitRow.js';
|
|
37
|
-
import { HUB_ACTIONS, PdfFlow } from './flows/pdf.js';
|
|
38
|
-
import { mouseSupported } from './mouse.js';
|
|
39
|
-
import { CLEAR_SCREEN, historyForRedraw } from './redraw.js';
|
|
40
|
-
import { openPath, revealLabel, revealPath } from './reveal.js';
|
|
41
|
-
import { addToStage, clearStage, emptyStage } from './stage.js';
|
|
42
|
-
import { ThemeProvider } from './ThemeContext.js';
|
|
43
|
-
import { writeToTerminal } from './terminal-write.js';
|
|
44
|
-
import { colourProp, paletteFor, SYMBOLS } from './theme.js';
|
|
45
|
-
import { useKeys } from './useKeys.js';
|
|
46
|
-
import { useMouseRouting } from './useMouseRouting.js';
|
|
47
|
-
import { bandFor, middleEllipsis } from './width.js';
|
|
48
|
-
let blockSeq = 0;
|
|
49
|
-
const nextId = () => `b${++blockSeq}`;
|
|
50
|
-
/**
|
|
51
|
-
* One line for the history, once a page-operation job has actually run.
|
|
52
|
-
* `HistoryEntry`'s `result` block is built around a `convert` job's
|
|
53
|
-
* one-source-to-one-target shape (spec: "A page operation's result gets its
|
|
54
|
-
* own rendering once one exists") — until it does, a `note` block says what
|
|
55
|
-
* happened in plain words rather than the shell crashing trying to draw a
|
|
56
|
-
* before/after pair for a job that has neither.
|
|
57
|
-
*/
|
|
58
|
-
function describePdfResult(result) {
|
|
59
|
-
const { job } = result;
|
|
60
|
-
const outputs = job.outputs.map((o) => basename(o));
|
|
61
|
-
const first = outputs[0] ?? '';
|
|
62
|
-
switch (job.op) {
|
|
63
|
-
/**
|
|
64
|
-
* The case this switch used to lack.
|
|
65
|
-
*
|
|
66
|
-
* A rasterisation writes one file per page, and falling through to the old
|
|
67
|
-
* `done — ${first}` default reported one filename for however many were
|
|
68
|
-
* written. The count comes from `describeResult` rather than being worked
|
|
69
|
-
* out again here — that is the module which owns what a result means.
|
|
70
|
-
*/
|
|
71
|
-
case 'convert': {
|
|
72
|
-
const view = describeResult(result);
|
|
73
|
-
return view.outputs.length === 1
|
|
74
|
-
? `${view.verb} — ${first}`
|
|
75
|
-
: `${view.verb} into ${view.outputs.length} files`;
|
|
76
|
-
}
|
|
77
|
-
case 'merge':
|
|
78
|
-
return `merged ${job.sources.length} files into ${first}`;
|
|
79
|
-
case 'split':
|
|
80
|
-
return `split into ${outputs.length} files`;
|
|
81
|
-
case 'extract':
|
|
82
|
-
return job.separate
|
|
83
|
-
? `extracted ${job.pages.length} pages into ${outputs.length} files`
|
|
84
|
-
: `extracted ${job.pages.length} pages into ${first}`;
|
|
85
|
-
case 'delete':
|
|
86
|
-
return `removed ${job.pages.length} pages — ${first}`;
|
|
87
|
-
case 'rotate':
|
|
88
|
-
return `rotated ${job.turns * 90}° — ${first}`;
|
|
89
|
-
default: {
|
|
90
|
-
/**
|
|
91
|
-
* No silent default. The old one swallowed `convert` and reported a
|
|
92
|
-
* wrong-but-plausible sentence; a new op must fail to compile instead.
|
|
93
|
-
*/
|
|
94
|
-
const unhandled = job;
|
|
95
|
-
throw new Error(`describePdfResult has no wording for ${JSON.stringify(unhandled)}`);
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
/**
|
|
100
|
-
* The verb painted beside `pageProgress`'s running count, derived from
|
|
101
|
-
* whichever job actually reported it — never a flag threaded down by hand,
|
|
102
|
-
* so it can never say something is rendering when it is really copying
|
|
103
|
-
* pages. `merge`, `delete` and `rotate` report phases only (see
|
|
104
|
-
* `engines/pdf.ts`), so `pageProgress` never carries their `op` and this
|
|
105
|
-
* never runs for them; `default` exists only as a defensive fallback if a
|
|
106
|
-
* future op starts reporting page progress without a label of its own.
|
|
107
|
-
*/
|
|
108
|
-
function pageProgressLabel(op) {
|
|
109
|
-
switch (op) {
|
|
110
|
-
case 'convert':
|
|
111
|
-
return 'RENDERING';
|
|
112
|
-
case 'split':
|
|
113
|
-
return 'SPLITTING';
|
|
114
|
-
case 'extract':
|
|
115
|
-
return 'EXTRACTING';
|
|
116
|
-
default:
|
|
117
|
-
return 'PROCESSING';
|
|
118
|
-
}
|
|
119
|
-
}
|
|
120
|
-
/**
|
|
121
|
-
* The fallback for callers that do not supply preferences — tests, and any
|
|
122
|
-
* direct render. It carries a theme on purpose: an absent theme is the
|
|
123
|
-
* first-run signal, and defaulting to it would put the theme picker in front
|
|
124
|
-
* of every test that only wanted to convert a file.
|
|
125
|
-
*
|
|
126
|
-
* The production path never uses this. `launchShell` always passes what
|
|
127
|
-
* `loadPreferences` returned, where a genuinely absent theme does raise the
|
|
128
|
-
* picker — which is what `theme-picker.test.tsx` exercises by passing
|
|
129
|
-
* `DEFAULT_PREFERENCES` explicitly.
|
|
130
|
-
*/
|
|
131
|
-
const APP_DEFAULT_PREFS = { ...DEFAULT_PREFERENCES, theme: 'dark' };
|
|
132
|
-
/**
|
|
133
|
-
* Routes mouse events into the frame. Renders nothing.
|
|
134
|
-
*
|
|
135
|
-
* A component rather than a `useMouseRouting` call in `App`'s own body, for a
|
|
136
|
-
* reason that is invisible until the whole thing is assembled and is easy to
|
|
137
|
-
* reintroduce: `useContext` only sees providers *above* the component that
|
|
138
|
-
* calls it. `App` renders `ClickTargetProvider` as its own child, so a routing
|
|
139
|
-
* hook in `App`'s body reads the inert fallback registry — the one that
|
|
140
|
-
* hit-tests to nothing — while every clickable component below registers into
|
|
141
|
-
* the real one. Two registries that never meet: no click can land, and hover
|
|
142
|
-
* can never switch the terminal into motion reporting. Routing has to be
|
|
143
|
-
* *inside* the provider, which is the whole job of this component.
|
|
144
|
-
*
|
|
145
|
-
* Rendered as the root Box's first child so its subscription is in place
|
|
146
|
-
* before any sibling registers a target. That is belt-and-braces — the
|
|
147
|
-
* registry defers its notifications for exactly this reason — but it costs
|
|
148
|
-
* nothing and removes the ordering question entirely.
|
|
149
|
-
*/
|
|
150
|
-
function MouseRouter({ rootRef, revision, }) {
|
|
151
|
-
useMouseRouting(rootRef, revision);
|
|
152
|
-
return null;
|
|
153
|
-
}
|
|
154
|
-
/** Sentinel `Select` value for the convert-target picker's row into `/pdf`. */
|
|
155
|
-
const GOTO_PDF = '__goto-pdf__';
|
|
156
|
-
/** The `/pdf` command, looked up once rather than re-found on every render. */
|
|
157
|
-
const pdfCommand = COMMANDS.find((c) => c.name === 'pdf');
|
|
158
|
-
export function App({ initialWidth, initialHeight, prefs = APP_DEFAULT_PREFS, configWarning, introShown = false, }) {
|
|
159
|
-
const { stdout } = useStdout();
|
|
160
|
-
const [measured, setMeasured] = useState(initialWidth ?? stdout?.columns ?? 80);
|
|
161
|
-
/** Only `PdfFlow`'s page grid needs this — see `gridLayout`. */
|
|
162
|
-
const [measuredHeight, setMeasuredHeight] = useState(initialHeight ?? stdout?.rows ?? 24);
|
|
163
|
-
/**
|
|
164
|
-
* Bumped to remount `<Static>`, which replays every history block. See
|
|
165
|
-
* `redraw.ts` for why a width change has to clear the screen and redraw.
|
|
166
|
-
*/
|
|
167
|
-
const [staticGeneration, setStaticGeneration] = useState(0);
|
|
168
|
-
/** Whether `playIntro`'s banner is still only on screen, not in history. */
|
|
169
|
-
const introPending = useRef(introShown);
|
|
170
|
-
/** For the intro banner's redraw — the default output can change mid-session. */
|
|
171
|
-
const defaultOutputRef = useRef(prefs.defaultOutput);
|
|
172
|
-
useEffect(() => {
|
|
173
|
-
if (initialWidth !== undefined || !stdout)
|
|
174
|
-
return;
|
|
175
|
-
let drawnAt = stdout.columns ?? 80;
|
|
176
|
-
const onResize = () => {
|
|
177
|
-
const columns = stdout.columns ?? 80;
|
|
178
|
-
// Height alone reflows nothing, so only a width change pays for a redraw.
|
|
179
|
-
if (columns !== drawnAt) {
|
|
180
|
-
drawnAt = columns;
|
|
181
|
-
writeToTerminal(CLEAR_SCREEN, stdout);
|
|
182
|
-
const intro = introPending.current
|
|
183
|
-
? {
|
|
184
|
-
kind: 'banner',
|
|
185
|
-
id: nextId(),
|
|
186
|
-
width: columns,
|
|
187
|
-
defaultOutput: defaultOutputRef.current,
|
|
188
|
-
}
|
|
189
|
-
: undefined;
|
|
190
|
-
introPending.current = false;
|
|
191
|
-
setHistory((h) => historyForRedraw(h, columns, intro));
|
|
192
|
-
setStaticGeneration((g) => g + 1);
|
|
193
|
-
}
|
|
194
|
-
setMeasured(columns);
|
|
195
|
-
};
|
|
196
|
-
stdout.on('resize', onResize);
|
|
197
|
-
return () => {
|
|
198
|
-
stdout.off('resize', onResize);
|
|
199
|
-
};
|
|
200
|
-
}, [initialWidth, stdout]);
|
|
201
|
-
useEffect(() => {
|
|
202
|
-
if (initialHeight !== undefined || !stdout)
|
|
203
|
-
return;
|
|
204
|
-
const onResize = () => setMeasuredHeight(stdout.rows ?? 24);
|
|
205
|
-
stdout.on('resize', onResize);
|
|
206
|
-
return () => {
|
|
207
|
-
stdout.off('resize', onResize);
|
|
208
|
-
};
|
|
209
|
-
}, [initialHeight, stdout]);
|
|
210
|
-
const width = measured;
|
|
211
|
-
const height = measuredHeight;
|
|
212
|
-
const band = bandFor(width);
|
|
213
|
-
/**
|
|
214
|
-
* Seeded with the banner rather than having an effect push it, so it is
|
|
215
|
-
* `<Static>` item zero from the very first frame. Ink flushes static output
|
|
216
|
-
* above everything that re-renders, so this is what pins the banner to the
|
|
217
|
-
* top of the session — it scrolls up as history grows, exactly as Claude
|
|
218
|
-
* Code's does, instead of being redrawn below the scrollback on every
|
|
219
|
-
* update, which is how it ended up in the middle of the screen.
|
|
220
|
-
*
|
|
221
|
-
* Skipped when no theme has been chosen: the first-run picker owns the
|
|
222
|
-
* screen until it is answered, and the banner is pushed once it is.
|
|
223
|
-
*/
|
|
224
|
-
/**
|
|
225
|
-
* Seeded with the banner so it is `<Static>` item zero from the first
|
|
226
|
-
* frame, which is what pins it to the top: Ink flushes static output above
|
|
227
|
-
* everything that re-renders.
|
|
228
|
-
*
|
|
229
|
-
* An animated version of this existed briefly and was removed. Animation
|
|
230
|
-
* cannot live in `<Static>` — static output is written once and never
|
|
231
|
-
* redrawn — so it had to run in the live region and then settle into
|
|
232
|
-
* history. That height change left earlier lines on screen: the rendered
|
|
233
|
-
* frame was correct, and the terminal showed a stack of stale rules
|
|
234
|
-
* underneath it. A still mark costs nothing and cannot do that.
|
|
235
|
-
*/
|
|
236
|
-
/**
|
|
237
|
-
* Empty. The banner is drawn by `playIntro` before Ink mounts, so by the
|
|
238
|
-
* time this renders it is already on screen as ordinary scrollback — see
|
|
239
|
-
* intro.ts. The one exception is first run, where the theme picker owned
|
|
240
|
-
* the screen and there was no palette to draw it in; `chooseTheme` pushes
|
|
241
|
-
* one then.
|
|
242
|
-
*/
|
|
243
|
-
const [history, setHistory] = useState([]);
|
|
244
|
-
/**
|
|
245
|
-
* Held in state, not read straight from `prefs`, so `/theme` re-themes the
|
|
246
|
-
* running session rather than only the next launch.
|
|
247
|
-
*/
|
|
248
|
-
const [theme, setTheme] = useState(prefs.theme);
|
|
249
|
-
/**
|
|
250
|
-
* Derived straight from `theme`, not read from context: this component is
|
|
251
|
-
* the one that renders `<ThemeProvider palette={paletteFor(theme)}>` a few
|
|
252
|
-
* hundred lines down, and a component can never consume a context value
|
|
253
|
-
* from a provider it renders as its own descendant — that provider's value
|
|
254
|
-
* only reaches components further down the tree. Reading `useTheme()` here
|
|
255
|
-
* instead resolved against whatever wraps `<App>` from the outside
|
|
256
|
-
* (launch.tsx's provider, frozen at the palette computed once at launch),
|
|
257
|
-
* so this file's own top-level elements — the mode header background among
|
|
258
|
-
* them — never picked up a theme chosen or changed mid-session.
|
|
259
|
-
*/
|
|
260
|
-
const palette = paletteFor(theme);
|
|
261
|
-
/**
|
|
262
|
-
* Preferences as they stand *now*, seeded from what was loaded at launch.
|
|
263
|
-
* `d` changes the default output mid-session, and the banner, the preset
|
|
264
|
-
* list and the `default` tag must all follow it without waiting for a
|
|
265
|
-
* relaunch — so they all read this, never the `prefs` prop.
|
|
266
|
-
*/
|
|
267
|
-
const [livePrefs, setLivePrefs] = useState(prefs);
|
|
268
|
-
defaultOutputRef.current = livePrefs.defaultOutput;
|
|
269
|
-
const [step, setStep] = useState(prefs.theme === undefined ? 'theme' : 'idle');
|
|
270
|
-
/**
|
|
271
|
-
* Which action the staged file is being put through. Dropping a file means
|
|
272
|
-
* convert; `/compress` switches it. The action layer already supports more
|
|
273
|
-
* than one action — `actionsFor` has existed since 0.1 and never been
|
|
274
|
-
* called, because until now there was nothing to choose between.
|
|
275
|
-
*/
|
|
276
|
-
const [mode, setMode] = useState('convert');
|
|
277
|
-
const action = mode === 'compress' ? compressAction : convertAction;
|
|
278
|
-
/**
|
|
279
|
-
* The mode banner's colours. `/pdf` has no `action` of its own — it opens
|
|
280
|
-
* `PdfFlow` directly rather than walking `convertAction`/`compressAction`'s
|
|
281
|
-
* option-spec wizard — so this is keyed off `mode` again rather than
|
|
282
|
-
* derived from `action`, the same reason the banner text itself already
|
|
283
|
-
* reads `mode` and not `action.id`.
|
|
284
|
-
*/
|
|
285
|
-
const modeBg = mode === 'compress'
|
|
286
|
-
? palette.modeCompressBg
|
|
287
|
-
: mode === 'pdf'
|
|
288
|
-
? palette.modePdfBg
|
|
289
|
-
: palette.modeConvertBg;
|
|
290
|
-
const modeColour = mode === 'compress'
|
|
291
|
-
? palette.modeCompress
|
|
292
|
-
: mode === 'pdf'
|
|
293
|
-
? palette.modePdf
|
|
294
|
-
: palette.modeConvert;
|
|
295
|
-
/** Where the target-size search has got to, for an honest counter. */
|
|
296
|
-
/**
|
|
297
|
-
* `dpi` names the rung a document search is on. Without it, a search
|
|
298
|
-
* dropping from 150 to 120 dpi looks like the counter restarting for no
|
|
299
|
-
* reason — the CLI learned this the same way.
|
|
300
|
-
*/
|
|
301
|
-
const [attempt, setAttempt] = useState(undefined);
|
|
302
|
-
/**
|
|
303
|
-
* Aborts the target-size search that is running right now, if one is.
|
|
304
|
-
*
|
|
305
|
-
* A ref rather than state: esc is delivered to a synchronous `useKeys`
|
|
306
|
-
* handler, which must abort the controller the in-flight `runPlan` was
|
|
307
|
-
* actually given — not whichever one the last render happened to close
|
|
308
|
-
* over. Same reasoning as `Select`'s `indexRef`.
|
|
309
|
-
*/
|
|
310
|
-
const searchAbort = useRef(undefined);
|
|
311
|
-
/**
|
|
312
|
-
* The target-size field's unit, and whether tab has moved focus onto it.
|
|
313
|
-
*
|
|
314
|
-
* The typed text stays the source of truth for the *amount* only — a unit
|
|
315
|
-
* typed directly (`2mb`) still wins, so the picker is a convenience rather
|
|
316
|
-
* than a second way of saying the same thing that could disagree with the
|
|
317
|
-
* first. `kb` rests as the default because it is the unit a target size is
|
|
318
|
-
* usually written in.
|
|
319
|
-
*/
|
|
320
|
-
const [sizeUnit, setSizeUnit] = useState('kb');
|
|
321
|
-
const [unitFocused, setUnitFocused] = useState(false);
|
|
322
|
-
/**
|
|
323
|
-
* The latest `{ phase: 'page' }` event `runJobs` reported, or `null` until
|
|
324
|
-
* one actually arrives. `null` is the whole point, not just an initial
|
|
325
|
-
* value: invariant 7 forbids a fabricated percentage, and an operation
|
|
326
|
-
* that only ever reports the phases-only variant (`reading`/`decoding`/
|
|
327
|
-
* `encoding`/`writing`) must never mount `<Progress>` — gating on "a page
|
|
328
|
-
* event has been seen" rather than "a job is running" is what keeps a
|
|
329
|
-
* single-file, single-phase conversion from growing a bar it has no real
|
|
330
|
-
* position to show on.
|
|
331
|
-
*/
|
|
332
|
-
const [pageProgress, setPageProgress] = useState(null);
|
|
333
|
-
/** Why a typed size was rejected, shown against the field rather than later. */
|
|
334
|
-
const [sizeError, setSizeError] = useState(undefined);
|
|
335
|
-
/** A measured alternative worth offering after a compression. */
|
|
336
|
-
const [suggestion, setSuggestion] = useState(undefined);
|
|
337
|
-
/**
|
|
338
|
-
* How many `target: 'pdf'` conversions have written a file this session.
|
|
339
|
-
* Unlike `suggestion` (recomputed fresh from one result), the merge offer
|
|
340
|
-
* below only makes sense once a *second* single-image PDF exists to
|
|
341
|
-
* combine the first one with — so this has to survive across separate
|
|
342
|
-
* conversions rather than being derived from the latest result alone. A
|
|
343
|
-
* ref, not state: the count itself is never rendered, only whether it has
|
|
344
|
-
* crossed one, which `mergeOffer` below tracks.
|
|
345
|
-
*/
|
|
346
|
-
const pdfOutputsThisSession = useRef(0);
|
|
347
|
-
/**
|
|
348
|
-
* Set once a `target: 'pdf'` conversion brings `pdfOutputsThisSession`
|
|
349
|
-
* above one. Several single-image PDFs are exactly what phase 3's
|
|
350
|
-
* `mergeAction` combines, and once they exist as separate files nothing
|
|
351
|
-
* else in the wizard points at that — so this offers it, the same way the
|
|
352
|
-
* compress flow offers a stronger format. See the render below for why
|
|
353
|
-
* acting on it is left to `/pdf` rather than a dedicated key.
|
|
354
|
-
*/
|
|
355
|
-
const [mergeOffer, setMergeOffer] = useState(undefined);
|
|
356
|
-
const [text, setText] = useState('');
|
|
357
|
-
/**
|
|
358
|
-
* The staged list. What was one file (`SourceInfo | null`) is now a list
|
|
359
|
-
* with two drops accumulating into it — merge needs several files at once,
|
|
360
|
-
* and `resolve.ts`/`run.ts` already speak in lists; the shell was the only
|
|
361
|
-
* place still narrowed to one.
|
|
362
|
-
*
|
|
363
|
-
* The wizard below (target, quality, destination) still walks a single
|
|
364
|
-
* representative file — `source`, derived just below — because picking a
|
|
365
|
-
* target format is one choice for the whole batch, not a per-file one.
|
|
366
|
-
* Only the run itself, and what is drawn on screen, need the full list.
|
|
367
|
-
*/
|
|
368
|
-
const [stage, setStage] = useState(emptyStage());
|
|
369
|
-
/**
|
|
370
|
-
* The first staged file, standing in for "the" file everywhere the wizard
|
|
371
|
-
* only ever needed one — computing option specs, planning a filename
|
|
372
|
-
* preview, and so on. `?? null` keeps the exact `SourceInfo | null` shape
|
|
373
|
-
* this used to be, so none of that logic has to change.
|
|
374
|
-
*/
|
|
375
|
-
const source = stage.sources[0] ?? null;
|
|
376
|
-
/**
|
|
377
|
-
* Whether converting or compressing right now would silently act on only
|
|
378
|
-
* the first of several staged files. Batch convert/compress is deferred —
|
|
379
|
-
* see the note above `convert()` — so this is what keeps that deferral
|
|
380
|
-
* from being a silent one: `/convert` and `/compress`, and a drop that
|
|
381
|
-
* would otherwise advance straight into the wizard, all check this first
|
|
382
|
-
* and refuse instead of quietly picking `stage.sources[0]` for the user.
|
|
383
|
-
*/
|
|
384
|
-
const stagedBatch = stage.sources.length > 1;
|
|
385
|
-
/**
|
|
386
|
-
* The banner's actual content, with no Box of its own — split out so it
|
|
387
|
-
* can sit inside two different containers: the highlighted bar shown at
|
|
388
|
-
* the top of every other step, and (for `result`) a plain row stacked
|
|
389
|
-
* with the keyboard hints instead. Kept as one function so the two never
|
|
390
|
-
* drift apart on what the banner actually says.
|
|
391
|
-
*
|
|
392
|
-
* `showHint` is false only for `result`: typing `/` there does nothing —
|
|
393
|
-
* the idle prompt that opens the command palette isn't mounted, and
|
|
394
|
-
* `result`'s own keys are `↵`/`o`/`s`/`q`, none of which gets back to it —
|
|
395
|
-
* so "use / to change mode" would be pointing at a door that isn't there.
|
|
396
|
-
*/
|
|
397
|
-
const modeLine = (showHint) => (_jsxs(_Fragment, { children: [_jsx(Text, { color: colourProp(modeColour), bold: true, children: band === 'compact' ? `${mode}` : `current mode: ${mode}` }), step === 'idle' && source && !stagedBatch ? (_jsx(Text, { color: colourProp(palette.fg), bold: true, children: ` ${basename(source.path)}` })) : null, showHint ? (_jsx(Text, { color: colourProp(palette.dim), children: band === 'compact' ? ' / to change' : ' use / to change mode' })) : null] }));
|
|
398
|
-
/**
|
|
399
|
-
* Whether `CommandPalette`'s `<Select>` is currently mounted and
|
|
400
|
-
* interactive — that is, whether the typed fragment has at least one
|
|
401
|
-
* match. `isCommandBuffer` alone is not enough: it is true the instant
|
|
402
|
-
* text starts with `/` and has no further `/` or space, which includes
|
|
403
|
-
* fragments like `/U` that match nothing. `CommandPalette` renders a
|
|
404
|
-
* plain, non-interactive "no command matches" `<Text>` in that state — no
|
|
405
|
-
* `<Select>`, no `useInput` — so nothing would be left to consume escape
|
|
406
|
-
* if the stage hook below were gated on `isCommandBuffer` alone. Calling
|
|
407
|
-
* the same `matchCommands` that `CommandPalette` itself calls to choose
|
|
408
|
-
* between `<Select>` and that message is what keeps this from drifting
|
|
409
|
-
* out of sync with what actually mounts, the way `isCommandBuffer` did.
|
|
410
|
-
*
|
|
411
|
-
* Also handed to `Prompt` as `disableSubmit`: while `Select` is mounted it
|
|
412
|
-
* owns Enter the same way it owns escape, for the same reason — see
|
|
413
|
-
* `disableSubmit`'s own doc comment for what the two of them racing on one
|
|
414
|
-
* keystroke actually did.
|
|
415
|
-
*/
|
|
416
|
-
const paletteOwnsEscape = isCommandBuffer(text) && matchCommands(text.slice(1)).length > 0;
|
|
417
|
-
const [values, setValues] = useState({});
|
|
418
|
-
const [lastResult, setLastResult] = useState(null);
|
|
419
|
-
const [pending, setPending] = useState(null);
|
|
420
|
-
/** Destination and proposed stem while the rename field is open. */
|
|
421
|
-
const [renaming, setRenaming] = useState(null);
|
|
422
|
-
/** Set only while `step === 'pdf-blocked'` — what a refused `/pdf` run can still do. */
|
|
423
|
-
const [pdfBlocked, setPdfBlocked] = useState(null);
|
|
424
|
-
/** Set only while `step === 'size-unreachable'` — see `PendingSizeUnreachable`. */
|
|
425
|
-
const [sizeUnreachable, setSizeUnreachable] = useState(null);
|
|
426
|
-
/**
|
|
427
|
-
* Mirrors `text` for the completion callback, for the same reason
|
|
428
|
-
* `Prompt` mirrors its own buffer: reading a directory is async, and by the
|
|
429
|
-
* time it resolves the user may have typed on. Comparing against the ref
|
|
430
|
-
* is what lets a superseded completion be dropped instead of overwriting
|
|
431
|
-
* what they typed — the same rule `requestId` applies to probes.
|
|
432
|
-
*/
|
|
433
|
-
const textRef = useRef('');
|
|
434
|
-
textRef.current = text;
|
|
435
|
-
const push = useCallback((block) => {
|
|
436
|
-
setHistory((h) => [...h, block]);
|
|
437
|
-
}, []);
|
|
438
|
-
/**
|
|
439
|
-
* Rules a dashed line under whatever is already on screen, so a change of
|
|
440
|
-
* flow reads as a new operation rather than a continuation of the last one.
|
|
441
|
-
*
|
|
442
|
-
* A compress refusal used to sit directly above `/pdf`'s operation list,
|
|
443
|
-
* close enough to read as part of that menu — the user took a message about
|
|
444
|
-
* compression as an explanation of the PDF screen they were now looking at.
|
|
445
|
-
* The same rule already separates finished results (see the `lastResult`
|
|
446
|
-
* handler); entering a different flow earns it for the same reason.
|
|
447
|
-
*
|
|
448
|
-
* Functional update rather than reading `history`: this runs from input
|
|
449
|
-
* callbacks whose closures would otherwise capture a stale array. No rule
|
|
450
|
-
* on an empty session, and never two in a row.
|
|
451
|
-
*/
|
|
452
|
-
const fenceOff = useCallback(() => {
|
|
453
|
-
setHistory((h) => {
|
|
454
|
-
if (h.length === 0)
|
|
455
|
-
return h;
|
|
456
|
-
if (h[h.length - 1]?.kind === 'separator')
|
|
457
|
-
return h;
|
|
458
|
-
return [...h, { kind: 'separator', id: nextId(), width }];
|
|
459
|
-
});
|
|
460
|
-
}, [width]);
|
|
461
|
-
/**
|
|
462
|
-
* A config that could not be read is told to the user once, as history,
|
|
463
|
-
* and never again. The ref — not state — is what makes "once" true: this
|
|
464
|
-
* effect reruns on every render that changes its deps, and a state flag
|
|
465
|
-
* would not be visible to the run that scheduled it.
|
|
466
|
-
*/
|
|
467
|
-
/**
|
|
468
|
-
* Pushed once, before anything else can reach history, so the banner is the
|
|
469
|
-
* first thing `<Static>` flushes and stays at the top of the session.
|
|
470
|
-
*/
|
|
471
|
-
const warned = useRef(false);
|
|
472
|
-
useEffect(() => {
|
|
473
|
-
if (warned.current || configWarning === undefined)
|
|
474
|
-
return;
|
|
475
|
-
warned.current = true;
|
|
476
|
-
push({ kind: 'note', id: nextId(), text: `${SYMBOLS.warn} ${configWarning}` });
|
|
477
|
-
}, [configWarning, push]);
|
|
478
|
-
/**
|
|
479
|
-
* The one way anything in this file reports a failure. Whatever was thrown
|
|
480
|
-
* — a `ForgeError`, or something nothing anticipated — becomes a history
|
|
481
|
-
* block the user can actually read, never a raw stack trace (spec §11).
|
|
482
|
-
*/
|
|
483
|
-
const showError = useCallback((e) => {
|
|
484
|
-
push({ kind: 'error', id: nextId(), error: isForgeError(e) ? e : unexpectedError(e) });
|
|
485
|
-
}, [push]);
|
|
486
|
-
/**
|
|
487
|
-
* Refuses to convert or compress a staged batch rather than silently
|
|
488
|
-
* acting on the first file in it. Refusing beats converting-the-first-
|
|
489
|
-
* loudly: a partial action on an ambiguous request is worse than no
|
|
490
|
-
* action, because the user can clear the stage and drop one file in a
|
|
491
|
-
* second, but they cannot un-convert a file they never meant to touch —
|
|
492
|
-
* the same "a change nobody asked for is a surprise" reasoning the phase-2
|
|
493
|
-
* compress design doc uses for why compress never changes the format.
|
|
494
|
-
*
|
|
495
|
-
* A `note` block, not a new one: this is a plain history line, the same
|
|
496
|
-
* shape `/help` and the config-warning banner already use, with the warn
|
|
497
|
-
* symbol paired with words so the reason survives a monochrome terminal.
|
|
498
|
-
*/
|
|
499
|
-
const refuseBatch = useCallback(() => {
|
|
500
|
-
push({
|
|
501
|
-
kind: 'note',
|
|
502
|
-
id: nextId(),
|
|
503
|
-
text: `${SYMBOLS.warn} Converting several files at once isn't supported yet. Drop a single file, or esc to clear the list.`,
|
|
504
|
-
});
|
|
505
|
-
}, [push]);
|
|
506
|
-
/**
|
|
507
|
-
* Refuses a drop that would stage several files nothing can act on
|
|
508
|
-
* together, *before* staging it — so no card is drawn for a batch the
|
|
509
|
-
* shell is about to turn down. Only a merge consumes several staged files,
|
|
510
|
-
* and merge takes PDFs; staging two images used to probe both, draw a rich
|
|
511
|
-
* card, and refuse only once the user tried to go on (UX audit #6).
|
|
512
|
-
*
|
|
513
|
-
* Says what did happen (nothing was staged), why, and what to do instead:
|
|
514
|
-
* clear what is already staged, or convert several files from the flag
|
|
515
|
-
* CLI, which is where spec §10 puts batch conversion until the shell has
|
|
516
|
-
* it.
|
|
517
|
-
*/
|
|
518
|
-
const refuseUnstageable = useCallback((dropped, staged) => {
|
|
519
|
-
const names = (list) => list.map((s) => basename(s.path)).join(', ');
|
|
520
|
-
const what = dropped.length === 1
|
|
521
|
-
? `${names(dropped)} was not staged`
|
|
522
|
-
: `${dropped.length} files were not staged`;
|
|
523
|
-
const next = staged.length > 0
|
|
524
|
-
? `${names(staged)} is still staged — esc clears it.`
|
|
525
|
-
: 'To convert several files at once, use the command line: forge <files> --to <format>.';
|
|
526
|
-
push({
|
|
527
|
-
kind: 'note',
|
|
528
|
-
id: nextId(),
|
|
529
|
-
text: `${SYMBOLS.warn} ${what}: only PDFs can be staged together, to merge with /pdf. ${next}`,
|
|
530
|
-
});
|
|
531
|
-
}, [push]);
|
|
532
|
-
/**
|
|
533
|
-
* Whether `convertAction` actually has somewhere to send this source.
|
|
534
|
-
* `convertAction.appliesTo` only checks `sources.length >= 1` — that was
|
|
535
|
-
* never enough on its own to guarantee a real choice: before a
|
|
536
|
-
* rasterisation engine arrived, a PDF's only writable format was PDF
|
|
537
|
-
* itself, which
|
|
538
|
-
* `targetSelect` (in `core/actions/convert.ts`) deliberately filters out
|
|
539
|
-
* as a no-op conversion, leaving its target list genuinely empty. A PDF
|
|
540
|
-
* now has real targets (jpeg, png — see `engines/pdfium.ts`), so this
|
|
541
|
-
* returns `true` for one; the check stays because nothing guarantees
|
|
542
|
-
* every future source kind will have somewhere to go.
|
|
543
|
-
*
|
|
544
|
-
* Without this check, a source with no real target would open the
|
|
545
|
-
* `target` step with a `Select` that has nothing to move a cursor onto —
|
|
546
|
-
* and critically, `Select` no-ops on *every* key, including escape, when
|
|
547
|
-
* its item list is empty (see `Select.tsx`). That was a dead end a
|
|
548
|
-
* person could not back out of short of quitting the process; it is why
|
|
549
|
-
* this exists at all, even though no source reaches that empty case
|
|
550
|
-
* today.
|
|
551
|
-
*/
|
|
552
|
-
const hasConvertTarget = useCallback((candidate) => convertAction
|
|
553
|
-
.options([candidate], {}, livePrefs)
|
|
554
|
-
.some((s) => s.kind === 'select' && s.id === 'target' && s.choices.length > 0), [livePrefs]);
|
|
555
|
-
/**
|
|
556
|
-
* Whether *any* of the five page operations `PdfFlow`'s hub lists applies
|
|
557
|
-
* to what is staged — the same question `/convert` asks via
|
|
558
|
-
* `hasConvertTarget` and `/compress` asks via `compressAction.appliesTo`,
|
|
559
|
-
* asked here so `/pdf` agrees with its two siblings in this file about
|
|
560
|
-
* checking applicability before opening anything.
|
|
561
|
-
*
|
|
562
|
-
* Without this, staging a non-PDF (or a mix that satisfies none of the
|
|
563
|
-
* five actions — see each action's own `appliesTo`) and running `/pdf`
|
|
564
|
-
* mounted the hub anyway: every row came back `disabled`, `Select`'s
|
|
565
|
-
* `firstEnabled` fell back to index 0 regardless, and `selected` was
|
|
566
|
-
* false for every row — no visible cursor, arrows doing nothing, Enter
|
|
567
|
-
* submitting nothing. Not the same unrecoverable lock the empty-list case
|
|
568
|
-
* was (`items.length` is 5, so Escape still works), but a confusing,
|
|
569
|
-
* silent screen all the same.
|
|
570
|
-
*/
|
|
571
|
-
const pdfActionsApply = useCallback((sources) => HUB_ACTIONS.some((a) => a.appliesTo(sources)), []);
|
|
572
|
-
// Gated on `step === 'result'`: Ink delivers input to every mounted
|
|
573
|
-
// `useInput` hook regardless of what else is on screen, so an ungated
|
|
574
|
-
// handler here would steal `f`/`o`/`q` from the target/quality/destination
|
|
575
|
-
// stages the moment they happen to share a letter.
|
|
576
|
-
// esc on the name step returns to the location step — but only once the
|
|
577
|
-
// field is already empty. `Prompt` claims escape itself first (see
|
|
578
|
-
// Prompt.tsx) and clears whatever was typed; this hook is what the
|
|
579
|
-
// keystroke falls through to once there is nothing left to clear.
|
|
580
|
-
useKeys((_input, key) => {
|
|
581
|
-
if (key.escape && text === '')
|
|
582
|
-
cancelRename();
|
|
583
|
-
}, { isActive: step === 'rename' });
|
|
584
|
-
// esc on the size field goes back to the mode choice, once `Prompt` has
|
|
585
|
-
// nothing left in the field to clear — same "clear first, then back"
|
|
586
|
-
// split as the rename step above.
|
|
587
|
-
useKeys((_input, key) => {
|
|
588
|
-
if (!key.escape || text !== '')
|
|
589
|
-
return;
|
|
590
|
-
setSizeError(undefined);
|
|
591
|
-
setUnitFocused(false);
|
|
592
|
-
setStep('mode');
|
|
593
|
-
}, { isActive: step === 'size' });
|
|
594
|
-
/**
|
|
595
|
-
* Tab moves between the amount and the unit row; left/right walk the units
|
|
596
|
-
* once it has focus, and enter confirms the field from either half.
|
|
597
|
-
*
|
|
598
|
-
* Left/right and enter are claimed only while the row is focused, so the
|
|
599
|
-
* caret keys and submit `Prompt` needs keep working in the amount — Ink
|
|
600
|
-
* hands every keystroke to both hooks, so anything this one swallows
|
|
601
|
-
* unconditionally would be taken away from the field beside it, and enter
|
|
602
|
-
* in particular would submit twice.
|
|
603
|
-
*
|
|
604
|
-
* Enter is here because the unit row is one half of a single answer rather
|
|
605
|
-
* than a step of its own: the amount and its unit are the same question,
|
|
606
|
-
* and having to tab back onto the amount to say yes to them made the row a
|
|
607
|
-
* dead end — the hint bar names `↵ confirm` first, and it was the one key
|
|
608
|
-
* there that did nothing.
|
|
609
|
-
*/
|
|
610
|
-
useKeys((_input, key) => {
|
|
611
|
-
if (key.tab) {
|
|
612
|
-
setUnitFocused((focused) => !focused);
|
|
613
|
-
return;
|
|
614
|
-
}
|
|
615
|
-
if (!unitFocused)
|
|
616
|
-
return;
|
|
617
|
-
if (key.return) {
|
|
618
|
-
submitSize(text);
|
|
619
|
-
return;
|
|
620
|
-
}
|
|
621
|
-
const delta = key.rightArrow ? 1 : key.leftArrow ? -1 : 0;
|
|
622
|
-
if (delta === 0)
|
|
623
|
-
return;
|
|
624
|
-
setSizeUnit((current) => {
|
|
625
|
-
const next = SIZE_UNIT_IDS.indexOf(current) + delta;
|
|
626
|
-
return SIZE_UNIT_IDS[Math.min(SIZE_UNIT_IDS.length - 1, Math.max(0, next))] ?? current;
|
|
627
|
-
});
|
|
628
|
-
}, { isActive: step === 'size' });
|
|
629
|
-
/**
|
|
630
|
-
* esc while a target-size search is running: stop it and step back one, the
|
|
631
|
-
* way esc does everywhere else. Nothing has been written at this point — a
|
|
632
|
-
* search only measures — so there is nothing to undo, and the staged file
|
|
633
|
-
* stays staged.
|
|
634
|
-
*
|
|
635
|
-
* Only meaningful while a search is actually in flight (`searchAbort` set);
|
|
636
|
-
* an ordinary conversion has no interruptible phase, so esc there is left
|
|
637
|
-
* alone rather than given a cancel that would silently do nothing.
|
|
638
|
-
*/
|
|
639
|
-
useKeys((_input, key) => {
|
|
640
|
-
if (!key.escape || !searchAbort.current)
|
|
641
|
-
return;
|
|
642
|
-
searchAbort.current.abort();
|
|
643
|
-
/**
|
|
644
|
-
* Moved here rather than waiting for `runPlan` to return, because an
|
|
645
|
-
* abort can only take effect *between* encodes — the one already in
|
|
646
|
-
* flight still has to finish, and a 300-dpi scan's encode is seconds
|
|
647
|
-
* long. Waiting for it would leave esc looking as dead as the screen
|
|
648
|
-
* this fixes. Nothing is written during a search, so leaving early
|
|
649
|
-
* costs nothing; the search unwinds behind the screen the user is
|
|
650
|
-
* already back on.
|
|
651
|
-
*
|
|
652
|
-
* Safe against the race where the search settles in the same moment:
|
|
653
|
-
* `finishConversion` returns early only when the outcome really came
|
|
654
|
-
* back cancelled, and otherwise carries on to the result (or the
|
|
655
|
-
* unreachable question) exactly as it would have, moving the step off
|
|
656
|
-
* this one again. The user is never told nothing happened when a file
|
|
657
|
-
* was in fact written.
|
|
658
|
-
*/
|
|
659
|
-
searchAbort.current = undefined;
|
|
660
|
-
setAttempt(undefined);
|
|
661
|
-
setStep('size');
|
|
662
|
-
}, { isActive: step === 'converting' });
|
|
663
|
-
// esc at the prompt clears whatever is typed first (mirroring every other
|
|
664
|
-
// text field), and only once that field is empty does it fall through to
|
|
665
|
-
// clearing a leftover stage — reachable when a PDF backed out of the
|
|
666
|
-
// convert picker kept its place for `/pdf` or a merge list. Empty stages
|
|
667
|
-
// are the common case and cost nothing extra to check.
|
|
668
|
-
//
|
|
669
|
-
// Gated on the command buffer being closed, for the same reason the
|
|
670
|
-
// `step === 'result'` hook above is gated on `step`: Ink delivers input
|
|
671
|
-
// to every mounted `useInput` regardless of what else is on screen.
|
|
672
|
-
// `CommandPalette`'s `Select` (`isActive` default `true`) already owns
|
|
673
|
-
// escape while `/convert` or similar is being typed — its `onCancel`
|
|
674
|
-
// clears the text buffer — so an ungated hook here would fire on the very
|
|
675
|
-
// same keystroke and silently discard the stage as a side effect of
|
|
676
|
-
// someone backing out of a half-typed command, not asking to clear
|
|
677
|
-
// anything.
|
|
678
|
-
useKeys((_input, key) => {
|
|
679
|
-
if (!key.escape)
|
|
680
|
-
return;
|
|
681
|
-
if (text !== '') {
|
|
682
|
-
setText('');
|
|
683
|
-
return;
|
|
684
|
-
}
|
|
685
|
-
if (stage.sources.length === 0 && stage.failures.length === 0)
|
|
686
|
-
return;
|
|
687
|
-
setStage(clearStage());
|
|
688
|
-
}, { isActive: step === 'idle' && !paletteOwnsEscape });
|
|
689
|
-
/**
|
|
690
|
-
* Ctrl+N: abandon whatever is in progress and start over, from any step.
|
|
691
|
-
* A harder reset than any single step's own "back" — it drops the staged
|
|
692
|
-
* source(s), every answer collected so far, and any pending confirmation,
|
|
693
|
-
* landing back on the idle prompt exactly as if the app had just started.
|
|
694
|
-
*
|
|
695
|
-
* Excluded while a job is actually running: there is nothing sound to do
|
|
696
|
-
* with a `runJobs` promise already in flight once the state it was
|
|
697
|
-
* closed over has been reset out from under it.
|
|
698
|
-
*/
|
|
699
|
-
const startNewSession = () => {
|
|
700
|
-
setStage(clearStage());
|
|
701
|
-
setValues({});
|
|
702
|
-
setLastResult(null);
|
|
703
|
-
setPending(null);
|
|
704
|
-
setRenaming(null);
|
|
705
|
-
setPdfBlocked(null);
|
|
706
|
-
setSizeUnreachable(null);
|
|
707
|
-
setSuggestion(undefined);
|
|
708
|
-
setSizeError(undefined);
|
|
709
|
-
setText('');
|
|
710
|
-
setMode('convert');
|
|
711
|
-
setStep('idle');
|
|
712
|
-
};
|
|
713
|
-
useKeys((input, key) => {
|
|
714
|
-
if (key.ctrl && input === 'n')
|
|
715
|
-
startNewSession();
|
|
716
|
-
}, { isActive: step !== 'theme' && step !== 'converting' && step !== 'pdf-running' });
|
|
717
|
-
/**
|
|
718
|
-
* `.catch`, not `void`: `reveal.ts` promisifies `execFile`, so `open`
|
|
719
|
-
* exiting non-zero — which is exactly what it does when the file has
|
|
720
|
-
* since been moved, renamed, or its volume unmounted — rejects. A
|
|
721
|
-
* `void`ed rejection is an unhandled rejection, and Node terminates
|
|
722
|
-
* the process and prints the stack. Result blocks live in `<Static>`
|
|
723
|
-
* scrollback for the rest of the session, so `o` and `s` (and the
|
|
724
|
-
* result links, which call the same two functions) stay pressable
|
|
725
|
-
* long after the file they point at has gone.
|
|
726
|
-
*
|
|
727
|
-
* Shared by the `o`/`s` keys and by clicking the result links. One
|
|
728
|
-
* function per action, not two copies that can drift — the `.catch`
|
|
729
|
-
* above is easy to omit from a second copy.
|
|
730
|
-
*/
|
|
731
|
-
const openLastResult = () => {
|
|
732
|
-
if (!lastResult)
|
|
733
|
-
return;
|
|
734
|
-
openPath(lastResult.job.outputs[0]).catch(showError);
|
|
735
|
-
};
|
|
736
|
-
const revealLastResult = () => {
|
|
737
|
-
if (!lastResult)
|
|
738
|
-
return;
|
|
739
|
-
revealPath(lastResult.job.outputs[0]).catch(showError);
|
|
740
|
-
};
|
|
741
|
-
useKeys((input, key) => {
|
|
742
|
-
if (!lastResult)
|
|
743
|
-
return;
|
|
744
|
-
if (key.return) {
|
|
745
|
-
// A dashed rule and a blank line either side, so a long session reads
|
|
746
|
-
// as a sequence of separate operations rather than one wall of text.
|
|
747
|
-
push({ kind: 'separator', id: nextId(), width });
|
|
748
|
-
setStage(clearStage());
|
|
749
|
-
setValues({});
|
|
750
|
-
setLastResult(null);
|
|
751
|
-
setStep('idle');
|
|
752
|
-
return;
|
|
753
|
-
}
|
|
754
|
-
if (input === 'o')
|
|
755
|
-
openLastResult();
|
|
756
|
-
if (input === 's')
|
|
757
|
-
revealLastResult();
|
|
758
|
-
// Acts on the measured suggestion: re-enters convert with that target
|
|
759
|
-
// already chosen, so the offer is one keystroke from being taken.
|
|
760
|
-
if (input === 'c' && suggestion && lastResult) {
|
|
761
|
-
setSuggestion(undefined);
|
|
762
|
-
setMode('convert');
|
|
763
|
-
setValues({ target: suggestion.target });
|
|
764
|
-
setStage(addToStage(emptyStage(), [lastResult.job.sources[0]], []));
|
|
765
|
-
setStep('destination');
|
|
766
|
-
}
|
|
767
|
-
}, { isActive: step === 'result' });
|
|
768
|
-
// The picker never hardcodes a format list: it renders whatever
|
|
769
|
-
// convertAction.options() returns for the probed source and the answers
|
|
770
|
-
// collected so far (e.g. the quality step only appears once a lossy
|
|
771
|
-
// target is chosen).
|
|
772
|
-
const specs = useMemo(() => (source ? action.options([source], values, livePrefs) : []), [source, values, livePrefs, action]);
|
|
773
|
-
const specFor = useCallback((id) => specs.find((s) => s.id === id), [specs]);
|
|
774
|
-
/**
|
|
775
|
-
* `probe()` is genuinely I/O-bound (`stat`, `access`, then sharp reading
|
|
776
|
-
* the file's header), and nothing moves `step` off `'idle'` until it
|
|
777
|
-
* resolves — the Prompt stays mounted and interactive for the whole
|
|
778
|
-
* `await` by design (disabling it mid-probe, e.g. via `isActive`, is a UX
|
|
779
|
-
* decision this file doesn't get to make on its own). So a user can submit
|
|
780
|
-
* a second, different path before the first probe settles, and the two
|
|
781
|
-
* probes genuinely race.
|
|
782
|
-
*
|
|
783
|
-
* `requestId` is a ref, not state, for the same reason `Select.tsx` and
|
|
784
|
-
* `Prompt.tsx` use one: `useInput` handlers are synchronous but `setState`
|
|
785
|
-
* is not, so a second submission arriving before React re-renders must
|
|
786
|
-
* still see the true current id, not a stale closed-over value. Each call
|
|
787
|
-
* claims the next id the instant it starts, so the *latest* submission
|
|
788
|
-
* always wins ownership — and a probe's result, success or failure, is
|
|
789
|
-
* only applied if its id is still the current one by the time it settles.
|
|
790
|
-
* A superseded (stale) result — an earlier submission that is still
|
|
791
|
-
* finishing after a newer one has already started — is dropped on the
|
|
792
|
-
* floor rather than clobbering whatever the newer submission produced.
|
|
793
|
-
*/
|
|
794
|
-
const requestId = useRef(0);
|
|
795
|
-
/**
|
|
796
|
-
* Runs a command chosen from the palette or typed in full.
|
|
797
|
-
*
|
|
798
|
-
* `needsSource` decides what a command does with a file already on the
|
|
799
|
-
* bench: `/compress` switches it into the compress flow, `/theme` ignores
|
|
800
|
-
* it entirely.
|
|
801
|
-
*/
|
|
802
|
-
const runCommand = useCallback((command) => {
|
|
803
|
-
setText('');
|
|
804
|
-
if (command.name === 'theme') {
|
|
805
|
-
setStep('theme');
|
|
806
|
-
return;
|
|
807
|
-
}
|
|
808
|
-
if (command.name === 'help') {
|
|
809
|
-
push({
|
|
810
|
-
kind: 'note',
|
|
811
|
-
id: nextId(),
|
|
812
|
-
text: COMMANDS.map((c) => ` /${c.name.padEnd(10)} ${c.description}`).join('\n'),
|
|
813
|
-
});
|
|
814
|
-
return;
|
|
815
|
-
}
|
|
816
|
-
if (command.name === 'convert') {
|
|
817
|
-
if (stagedBatch) {
|
|
818
|
-
refuseBatch();
|
|
819
|
-
return;
|
|
820
|
-
}
|
|
821
|
-
setMode('convert');
|
|
822
|
-
setValues({});
|
|
823
|
-
// A source with nowhere to convert to would stay at idle rather
|
|
824
|
-
// than opening a target picker with nothing in it — see
|
|
825
|
-
// `hasConvertTarget`. No source reaches that today; a staged PDF
|
|
826
|
-
// now opens the real picker like anything else, with a way back to
|
|
827
|
-
// `/pdf` from there — see the `target` step's own signpost.
|
|
828
|
-
setStep(source && hasConvertTarget(source) ? 'target' : 'idle');
|
|
829
|
-
return;
|
|
830
|
-
}
|
|
831
|
-
if (command.name === 'compress') {
|
|
832
|
-
if (stagedBatch) {
|
|
833
|
-
refuseBatch();
|
|
834
|
-
return;
|
|
835
|
-
}
|
|
836
|
-
if (source && !compressAction.appliesTo([source])) {
|
|
837
|
-
push({ kind: 'error', id: nextId(), error: unsupportedCompress(source) });
|
|
838
|
-
return;
|
|
839
|
-
}
|
|
840
|
-
fenceOff();
|
|
841
|
-
setMode('compress');
|
|
842
|
-
setValues({});
|
|
843
|
-
setStep(source ? 'mode' : 'idle');
|
|
844
|
-
return;
|
|
845
|
-
}
|
|
846
|
-
/**
|
|
847
|
-
* Deliberately does not consult `stagedBatch`/`refuseBatch` — those
|
|
848
|
-
* exist to stop convert/compress from silently acting on only the
|
|
849
|
-
* first of several staged files (see the note above `convert()`),
|
|
850
|
-
* and `/pdf`'s whole point is the opposite: merge is defined by
|
|
851
|
-
* having several files staged, and the hub itself dims whatever the
|
|
852
|
-
* current stage can't do, with a reason, rather than the shell
|
|
853
|
-
* refusing to even open it.
|
|
854
|
-
*
|
|
855
|
-
* With no source at all, this arms `mode` and stays at idle — the same
|
|
856
|
-
* shape `/compress` already has a few lines up, for the same reason:
|
|
857
|
-
* `/pdf` has nothing to open yet (the hub has no files to show
|
|
858
|
-
* operations for), but the choice of what happens to the *next*
|
|
859
|
-
* dropped file is real and worth remembering, same as compress's own
|
|
860
|
-
* pre-armed mode. `submitPath`'s single-file success path is where
|
|
861
|
-
* that arming actually takes effect once something lands.
|
|
862
|
-
*/
|
|
863
|
-
if (command.name === 'pdf') {
|
|
864
|
-
if (!source) {
|
|
865
|
-
setMode('pdf');
|
|
866
|
-
setStep('idle');
|
|
867
|
-
return;
|
|
868
|
-
}
|
|
869
|
-
// With a source, "dims what doesn't apply" only works once the hub
|
|
870
|
-
// is open — it is not a substitute for checking whether *anything*
|
|
871
|
-
// applies before opening it at all. `/convert` has `hasConvertTarget`
|
|
872
|
-
// and `/compress` has `compressAction.appliesTo` for exactly this, a
|
|
873
|
-
// few lines up; `pdfActionsApply` is `/pdf`'s version of the same
|
|
874
|
-
// check, so all three commands in this file agree on the rule.
|
|
875
|
-
if (!pdfActionsApply(stage.sources)) {
|
|
876
|
-
push({
|
|
877
|
-
kind: 'note',
|
|
878
|
-
id: nextId(),
|
|
879
|
-
text: `${SYMBOLS.warn} /pdf needs the staged files to be PDFs.`,
|
|
880
|
-
});
|
|
881
|
-
return;
|
|
882
|
-
}
|
|
883
|
-
setMode('pdf');
|
|
884
|
-
fenceOff();
|
|
885
|
-
setStep('pdf');
|
|
886
|
-
}
|
|
887
|
-
}, [
|
|
888
|
-
push,
|
|
889
|
-
fenceOff,
|
|
890
|
-
source,
|
|
891
|
-
stage.sources,
|
|
892
|
-
stagedBatch,
|
|
893
|
-
refuseBatch,
|
|
894
|
-
hasConvertTarget,
|
|
895
|
-
pdfActionsApply,
|
|
896
|
-
]);
|
|
897
|
-
/**
|
|
898
|
-
* Stages what a multi-path drop or a folder resolved to — or refuses it
|
|
899
|
-
* before staging, when it would leave several files nothing can act on
|
|
900
|
-
* together (see `refuseUnstageable`). Failures ride along on the stage and
|
|
901
|
-
* are listed beside the card. One file goes to its target picker the way a
|
|
902
|
-
* single drop does; several make a merge list and wait at the prompt.
|
|
903
|
-
*/
|
|
904
|
-
const stageSeveral = useCallback((infos, failures) => {
|
|
905
|
-
const next = addToStage(stage, infos, failures);
|
|
906
|
-
if (next.sources.length > 1 && !pdfActionsApply(next.sources)) {
|
|
907
|
-
refuseUnstageable(infos, stage.sources);
|
|
908
|
-
return;
|
|
909
|
-
}
|
|
910
|
-
setStage(next);
|
|
911
|
-
setValues({});
|
|
912
|
-
if (next.sources.length > 1) {
|
|
913
|
-
setStep('idle');
|
|
914
|
-
return;
|
|
915
|
-
}
|
|
916
|
-
setStep(next.sources[0] && hasConvertTarget(next.sources[0]) ? 'target' : 'idle');
|
|
917
|
-
}, [stage, pdfActionsApply, refuseUnstageable, hasConvertTarget]);
|
|
918
|
-
const submitPath = useCallback(async (raw) => {
|
|
919
|
-
const trimmed = raw.trim();
|
|
920
|
-
if (!trimmed)
|
|
921
|
-
return;
|
|
922
|
-
/**
|
|
923
|
-
* A command, not a path. Checked before probing, because otherwise
|
|
924
|
-
* `/compress` is looked up as a file and reported missing — which is
|
|
925
|
-
* exactly what happened before this branch existed.
|
|
926
|
-
*/
|
|
927
|
-
if (isCommandBuffer(trimmed)) {
|
|
928
|
-
const command = parseCommand(trimmed);
|
|
929
|
-
setText('');
|
|
930
|
-
if (command) {
|
|
931
|
-
runCommand(command);
|
|
932
|
-
}
|
|
933
|
-
else {
|
|
934
|
-
push({
|
|
935
|
-
kind: 'note',
|
|
936
|
-
id: nextId(),
|
|
937
|
-
text: `no command matches ${trimmed} — try /help`,
|
|
938
|
-
});
|
|
939
|
-
}
|
|
940
|
-
return;
|
|
941
|
-
}
|
|
942
|
-
const id = ++requestId.current;
|
|
943
|
-
setText('');
|
|
944
|
-
/**
|
|
945
|
-
* Tried whole and unescaped, before anything is split on whitespace.
|
|
946
|
-
* A single dropped file is the overwhelmingly common case, and a
|
|
947
|
-
* terminal's own escaping of it can be *incomplete* rather than
|
|
948
|
-
* absent: Terminal.app leaves the space before "AM.png"/"PM.png"
|
|
949
|
-
* unescaped in a macOS screenshot's filename (confirmed against the
|
|
950
|
-
* literal bytes it pastes), so splitting on whitespace first — the
|
|
951
|
-
* previous order here — read one dropped screenshot as two
|
|
952
|
-
* nonexistent fragments ("…52" and "AM.png") and never resolved the
|
|
953
|
-
* real file at all.
|
|
954
|
-
*
|
|
955
|
-
* `unescapePath` strips every backslash wherever one appears,
|
|
956
|
-
* regardless of which spaces the terminal did or didn't escape, so it
|
|
957
|
-
* reconstructs the true filename either way. A genuine multi-file drop
|
|
958
|
-
* still reaches the split branch below: two or more real, distinct
|
|
959
|
-
* paths joined by the space between them essentially never match
|
|
960
|
-
* anything on disk as one combined string, so this attempt fails
|
|
961
|
-
* harmlessly and falls through to `splitPastedPaths` exactly as
|
|
962
|
-
* before.
|
|
963
|
-
*/
|
|
964
|
-
let info;
|
|
965
|
-
let wholeError;
|
|
966
|
-
try {
|
|
967
|
-
info = await probe(unescapePath(trimmed));
|
|
968
|
-
}
|
|
969
|
-
catch (e) {
|
|
970
|
-
wholeError = e;
|
|
971
|
-
}
|
|
972
|
-
if (!info) {
|
|
973
|
-
// A real OS drag of several files pastes every escaped path on one
|
|
974
|
-
// line, space-separated — the mechanism `splitPastedPaths` was
|
|
975
|
-
// written and tested for, but left unwired while the shell was
|
|
976
|
-
// single-file only (see the design spec's "one path per drop"
|
|
977
|
-
// section). It runs here rather than `Prompt`'s own `unescapePath`
|
|
978
|
-
// (this is the one `Prompt` passed `rawOnSubmit`, precisely so the
|
|
979
|
-
// escaping survives this far): unescaping first would turn "a\ b.pdf
|
|
980
|
-
// c\ d.pdf" into "a b.pdf c d.pdf", and nothing left could tell an
|
|
981
|
-
// escaped space inside a filename apart from the plain one
|
|
982
|
-
// separating two paths.
|
|
983
|
-
const paths = splitPastedPaths(trimmed);
|
|
984
|
-
if (paths.length > 1) {
|
|
985
|
-
const infos = [];
|
|
986
|
-
const failures = [];
|
|
987
|
-
for (const path of paths) {
|
|
988
|
-
try {
|
|
989
|
-
infos.push(await probe(path));
|
|
990
|
-
}
|
|
991
|
-
catch (e) {
|
|
992
|
-
failures.push({ path, error: isForgeError(e) ? e : unexpectedError(e) });
|
|
993
|
-
}
|
|
994
|
-
}
|
|
995
|
-
if (requestId.current !== id)
|
|
996
|
-
return; // superseded by a later submission
|
|
997
|
-
stageSeveral(infos, failures);
|
|
998
|
-
return;
|
|
999
|
-
}
|
|
1000
|
-
}
|
|
1001
|
-
/**
|
|
1002
|
-
* A folder. Phase 3 §4 has the prompt accept one the way the CLI does,
|
|
1003
|
-
* through `resolve.ts`; probed whole as a file instead, it was refused
|
|
1004
|
-
* as "Not a file" under a CLI hint recommending a directory of images
|
|
1005
|
-
* (UX audit #11). Non-recursive, as the CLI is without `--recursive`.
|
|
1006
|
-
* One file inside is treated as that file dropped on its own, so the
|
|
1007
|
-
* armed mode still decides where it goes; several go through the same
|
|
1008
|
-
* rule as a multi-path drop.
|
|
1009
|
-
*/
|
|
1010
|
-
if (!info && isForgeError(wholeError) && wholeError.code === 'not-a-file') {
|
|
1011
|
-
const dir = unescapePath(trimmed);
|
|
1012
|
-
const isDirectory = await stat(dir).then((s) => s.isDirectory(), () => false);
|
|
1013
|
-
if (isDirectory) {
|
|
1014
|
-
const found = await resolveDirectory(dir, { recursive: false });
|
|
1015
|
-
if (requestId.current !== id)
|
|
1016
|
-
return; // superseded by a later submission
|
|
1017
|
-
if (found.sources.length === 0) {
|
|
1018
|
-
for (const failure of found.failures)
|
|
1019
|
-
showError(failure.error);
|
|
1020
|
-
return;
|
|
1021
|
-
}
|
|
1022
|
-
if (found.sources.length > 1 || found.failures.length > 0) {
|
|
1023
|
-
stageSeveral(found.sources, found.failures);
|
|
1024
|
-
return;
|
|
1025
|
-
}
|
|
1026
|
-
info = found.sources[0];
|
|
1027
|
-
}
|
|
1028
|
-
}
|
|
1029
|
-
try {
|
|
1030
|
-
if (!info)
|
|
1031
|
-
throw wholeError;
|
|
1032
|
-
if (requestId.current !== id)
|
|
1033
|
-
return; // superseded by a later submission
|
|
1034
|
-
// Drops accumulate rather than replace — dropping a second file onto
|
|
1035
|
-
// a prompt that already has one staged (a PDF kept for `/pdf`, say)
|
|
1036
|
-
// builds a batch instead of losing the first file — but only a
|
|
1037
|
-
// batch something can act on (see `refuseUnstageable`). `addToStage`
|
|
1038
|
-
// also drops an exact repeat of a path already staged. Computed
|
|
1039
|
-
// once, synchronously, rather than via the `setStage(s => ...)`
|
|
1040
|
-
// updater form this used before: the guards just below need to know
|
|
1041
|
-
// the resulting list *now*, to decide whether to stage it at all.
|
|
1042
|
-
const next = addToStage(stage, [info], []);
|
|
1043
|
-
if (next.sources.length > 1 && !pdfActionsApply(next.sources)) {
|
|
1044
|
-
refuseUnstageable([info], stage.sources);
|
|
1045
|
-
return;
|
|
1046
|
-
}
|
|
1047
|
-
setStage(next);
|
|
1048
|
-
setValues({});
|
|
1049
|
-
if (next.sources.length > 1) {
|
|
1050
|
-
// `refuseBatch` was written when nothing consumed several files at
|
|
1051
|
-
// once, so a multi-file stage could only mean an unsupported batch
|
|
1052
|
-
// convert. Merge ordering made staging several files the *point*,
|
|
1053
|
-
// and left the message contradicting the `/pdf` signpost two lines
|
|
1054
|
-
// below it — "drop a single file, or esc to clear the list" about a
|
|
1055
|
-
// list the user was deliberately building. A batch the page
|
|
1056
|
-
// operations cannot use is now refused before it is staged, just
|
|
1057
|
-
// above; what reaches here is a merge list, and the staged card
|
|
1058
|
-
// (rendered at idle from two files up — see the gate in the JSX
|
|
1059
|
-
// below) says what is staged while the existing signpost says
|
|
1060
|
-
// where to take it.
|
|
1061
|
-
setStep('idle');
|
|
1062
|
-
return;
|
|
1063
|
-
}
|
|
1064
|
-
// Deliberately *not* pushed to history here. A block committed to
|
|
1065
|
-
// <Static> can never be taken back, and until a conversion actually
|
|
1066
|
-
// happens the dropped file is a choice the user is still making —
|
|
1067
|
-
// esc has to be able to undo it. The result block records the file
|
|
1068
|
-
// once there is something worth recording.
|
|
1069
|
-
//
|
|
1070
|
-
// Which step comes next depends on the mode: `/compress` before
|
|
1071
|
-
// dropping a file means the file lands in the compress flow, and
|
|
1072
|
-
// compressing something lossless is refused here rather than after
|
|
1073
|
-
// the user has answered three more questions about it.
|
|
1074
|
-
if (mode === 'compress') {
|
|
1075
|
-
if (!compressAction.appliesTo([info])) {
|
|
1076
|
-
push({ kind: 'error', id: nextId(), error: unsupportedCompress(info) });
|
|
1077
|
-
setMode('convert');
|
|
1078
|
-
// `compressAction.appliesTo` only accepts a lossy image, so
|
|
1079
|
-
// nothing reaches this branch without a real convert target
|
|
1080
|
-
// either — but check anyway, via `hasConvertTarget`, rather
|
|
1081
|
-
// than assume: falling back to the target step for a source
|
|
1082
|
-
// that turned out to have nothing to convert to would trade
|
|
1083
|
-
// one dead end for another.
|
|
1084
|
-
setStep(hasConvertTarget(info) ? 'target' : 'idle');
|
|
1085
|
-
return;
|
|
1086
|
-
}
|
|
1087
|
-
setStep('mode');
|
|
1088
|
-
return;
|
|
1089
|
-
}
|
|
1090
|
-
// `/pdf` armed with nothing staged yet (see `runCommand`) — the same
|
|
1091
|
-
// shape as the `compress` branch above: a source the hub has
|
|
1092
|
-
// nothing to do with falls back to convert, one it can act on opens
|
|
1093
|
-
// the hub directly, with no need to type `/pdf` a second time now
|
|
1094
|
-
// that a file actually exists for it to open on.
|
|
1095
|
-
if (mode === 'pdf') {
|
|
1096
|
-
if (!pdfActionsApply([info])) {
|
|
1097
|
-
push({ kind: 'error', id: nextId(), error: unsupportedPdf(info) });
|
|
1098
|
-
setMode('convert');
|
|
1099
|
-
setStep(hasConvertTarget(info) ? 'target' : 'idle');
|
|
1100
|
-
return;
|
|
1101
|
-
}
|
|
1102
|
-
fenceOff();
|
|
1103
|
-
setStep('pdf');
|
|
1104
|
-
return;
|
|
1105
|
-
}
|
|
1106
|
-
// A source with a real convert target — every image, and now a PDF
|
|
1107
|
-
// too — goes straight to the target picker. One without a target
|
|
1108
|
-
// would stay at idle, staged and ready for `/pdf` or another
|
|
1109
|
-
// command, rather than opening a picker with nothing in it — see
|
|
1110
|
-
// `hasConvertTarget`.
|
|
1111
|
-
setStep(hasConvertTarget(info) ? 'target' : 'idle');
|
|
1112
|
-
}
|
|
1113
|
-
catch (e) {
|
|
1114
|
-
if (requestId.current !== id)
|
|
1115
|
-
return; // superseded by a later submission
|
|
1116
|
-
// A rethrow here would become an unhandled rejection: submitPath is
|
|
1117
|
-
// fired from Prompt's synchronous useInput handler, and nothing
|
|
1118
|
-
// awaits or catches the promise it returns. Whatever this is —
|
|
1119
|
-
// a ForgeError, or anything else probe() didn't anticipate — the
|
|
1120
|
-
// shell must render it, not silently do nothing forever.
|
|
1121
|
-
showError(e);
|
|
1122
|
-
setStep('idle');
|
|
1123
|
-
}
|
|
1124
|
-
},
|
|
1125
|
-
// `mode` matters: without it this closure keeps the value it had when the
|
|
1126
|
-
// callback was created, and a file dropped after /compress would be
|
|
1127
|
-
// routed to the convert flow anyway. `stage` matters for the same
|
|
1128
|
-
// reason: reading it straight (rather than through the `setStage`
|
|
1129
|
-
// updater form) is what lets the batch guard above decide off the
|
|
1130
|
-
// current list, not a stale one.
|
|
1131
|
-
[
|
|
1132
|
-
showError,
|
|
1133
|
-
push,
|
|
1134
|
-
runCommand,
|
|
1135
|
-
mode,
|
|
1136
|
-
stage,
|
|
1137
|
-
stageSeveral,
|
|
1138
|
-
refuseUnstageable,
|
|
1139
|
-
hasConvertTarget,
|
|
1140
|
-
pdfActionsApply,
|
|
1141
|
-
fenceOff,
|
|
1142
|
-
]);
|
|
1143
|
-
// Takes `currentSource` as a parameter, rather than closing over `source`
|
|
1144
|
-
// (which is `SourceInfo | null`) and asserting it non-null: the caller
|
|
1145
|
-
// below only reaches this from a branch already narrowed on `source`
|
|
1146
|
-
// being set, so the non-null-ness is a real invariant, not a suppression.
|
|
1147
|
-
/**
|
|
1148
|
-
* Takes the whole staged batch back off the bench and returns to the
|
|
1149
|
-
* prompt. Right for a source whose only path forward *was* the target
|
|
1150
|
-
* picker — an image has nothing else to do with a staged file, so
|
|
1151
|
-
* backing out means abandoning it. See `backToPromptKeepingStage` for the
|
|
1152
|
-
* other case.
|
|
1153
|
-
*
|
|
1154
|
-
* Also how a run that failed, was refused, or was abandoned at the
|
|
1155
|
-
* "can't get that small" question ends. Phase 3's rule is that completing
|
|
1156
|
-
* an action clears the stage, and a failure completes it as surely as a
|
|
1157
|
-
* result does: leaving the file staged meant the natural recovery — drop it
|
|
1158
|
-
* again, or drop another — appended to it instead, building a batch the
|
|
1159
|
-
* convert flow then refused (UX audit #7).
|
|
1160
|
-
*/
|
|
1161
|
-
const clearSource = () => {
|
|
1162
|
-
setStage(clearStage());
|
|
1163
|
-
setValues({});
|
|
1164
|
-
setStep('idle');
|
|
1165
|
-
};
|
|
1166
|
-
/**
|
|
1167
|
-
* Backs out of the target picker without discarding what is staged.
|
|
1168
|
-
*
|
|
1169
|
-
* A staged PDF has somewhere else to go besides conversion: `/pdf`'s five
|
|
1170
|
-
* page operations, and — by dropping a second PDF once back at the
|
|
1171
|
-
* prompt — a merge stage. `clearSource` would cost the user both just for
|
|
1172
|
-
* escaping the question "convert it to what", so a document keeps its
|
|
1173
|
-
* place on the bench; only the in-progress target choice is dropped.
|
|
1174
|
-
* Wired up only where the staged source is a document (see the `target`
|
|
1175
|
-
* step below) — an image still uses `clearSource`, unchanged.
|
|
1176
|
-
*/
|
|
1177
|
-
const backToPromptKeepingStage = () => {
|
|
1178
|
-
setValues({});
|
|
1179
|
-
setStep('idle');
|
|
1180
|
-
};
|
|
1181
|
-
const chooseTarget = (currentSource, target) => {
|
|
1182
|
-
setValues((v) => ({ ...v, target }));
|
|
1183
|
-
const next = action.options([currentSource], { target }, livePrefs);
|
|
1184
|
-
// `action.options()` only includes a pages spec when the chosen target
|
|
1185
|
-
// actually rasterises the source (jpeg/png via pdfium) — a pdf/docx/doc
|
|
1186
|
-
// target skips straight to quality or destination, having no pages or
|
|
1187
|
-
// resolution concept at all.
|
|
1188
|
-
if (next.some((s) => s.id === 'pages')) {
|
|
1189
|
-
setStep('pages');
|
|
1190
|
-
return;
|
|
1191
|
-
}
|
|
1192
|
-
setStep(next.some((s) => s.id === 'quality') ? 'quality' : 'destination');
|
|
1193
|
-
};
|
|
1194
|
-
/**
|
|
1195
|
-
* `'all'`/`'first'` advance straight to resolution; `'choose'` hands off to
|
|
1196
|
-
* `PageGrid` (`page-picker`) rather than storing itself as the answer —
|
|
1197
|
-
* `convertAction.plan()` only knows how to turn `'all'`, `'first'`, a typed
|
|
1198
|
-
* range, or an explicit array into pages, not the literal string `'choose'`.
|
|
1199
|
-
*/
|
|
1200
|
-
const choosePages = (value) => {
|
|
1201
|
-
setValues((v) => ({ ...v, pages: value }));
|
|
1202
|
-
setStep(value === 'choose' ? 'page-picker' : 'dpi');
|
|
1203
|
-
};
|
|
1204
|
-
/** `PageGrid`'s own selection, already 0-based — `convertAction.plan()` still runs it through `normalisePages`. */
|
|
1205
|
-
const submitPagePicker = (pages) => {
|
|
1206
|
-
setValues((v) => ({ ...v, pages }));
|
|
1207
|
-
setStep('dpi');
|
|
1208
|
-
};
|
|
1209
|
-
const chooseDpi = (currentSource, dpi) => {
|
|
1210
|
-
setValues((v) => ({ ...v, dpi }));
|
|
1211
|
-
const next = action.options([currentSource], { ...values, target: values.target, dpi }, livePrefs);
|
|
1212
|
-
setStep(next.some((s) => s.id === 'quality') ? 'quality' : 'destination');
|
|
1213
|
-
};
|
|
1214
|
-
/**
|
|
1215
|
-
* `.catch`, not `void`: this runs from Select's synchronous useInput
|
|
1216
|
-
* handler and nothing awaits the promise, so a rejected write would be an
|
|
1217
|
-
* unhandled rejection and Node would take the process down. A theme that
|
|
1218
|
-
* fails to persist is worth telling the user about; it must never cost
|
|
1219
|
-
* them the session.
|
|
1220
|
-
*/
|
|
1221
|
-
const chooseTheme = (next) => {
|
|
1222
|
-
setTheme(next);
|
|
1223
|
-
setStep('idle');
|
|
1224
|
-
// The picker owned the screen until now.
|
|
1225
|
-
push({ kind: 'banner', id: nextId(), width, defaultOutput: livePrefs.defaultOutput });
|
|
1226
|
-
savePreferences({ theme: next }).catch(showError);
|
|
1227
|
-
};
|
|
1228
|
-
/**
|
|
1229
|
-
* Writes the folder to config and says so, without advancing the flow —
|
|
1230
|
-
* the user is still choosing where *this* conversion goes. `.catch` for
|
|
1231
|
-
* the same reason as chooseTheme: nothing awaits this promise.
|
|
1232
|
-
*/
|
|
1233
|
-
const makeDefault = (path) => {
|
|
1234
|
-
setLivePrefs((p) => ({ ...p, defaultOutput: path }));
|
|
1235
|
-
push({ kind: 'note', id: nextId(), text: `${SYMBOLS.ok} default output is now ${path}` });
|
|
1236
|
-
savePreferences({ defaultOutput: path }).catch(showError);
|
|
1237
|
-
};
|
|
1238
|
-
/**
|
|
1239
|
-
* Opens the rename field for the highlighted destination. The extension is
|
|
1240
|
-
* not editable and not shown here — it is decided by the target format, and
|
|
1241
|
-
* letting someone type `.png` onto a WebP would produce a file that lies
|
|
1242
|
-
* about itself.
|
|
1243
|
-
*/
|
|
1244
|
-
/**
|
|
1245
|
-
* Opens the name field, pre-filled from the name the action would have
|
|
1246
|
-
* chosen.
|
|
1247
|
-
*
|
|
1248
|
-
* The proposal comes from `plan()` rather than being rebuilt here: the
|
|
1249
|
-
* action knows the extension (compress keeps the source's, convert uses the
|
|
1250
|
-
* target's) and any suffix it needs to avoid landing on the input. Deriving
|
|
1251
|
-
* it a second time in the shell is how the field ended up offering a name
|
|
1252
|
-
* with no extension at all for compression.
|
|
1253
|
-
*/
|
|
1254
|
-
const startRename = (destination) => {
|
|
1255
|
-
if (!source)
|
|
1256
|
-
return;
|
|
1257
|
-
const planned = action.plan([source], { ...values, destination })[0];
|
|
1258
|
-
const proposed = (planned?.outputs[0] ?? source.path).split('/').pop() ?? 'file';
|
|
1259
|
-
const dot = proposed.lastIndexOf('.');
|
|
1260
|
-
const stem = dot > 0 ? proposed.slice(0, dot) : proposed;
|
|
1261
|
-
const ext = dot > 0 ? proposed.slice(dot) : '';
|
|
1262
|
-
setRenaming({ destination, stem, ext });
|
|
1263
|
-
setText(stem);
|
|
1264
|
-
setStep('rename');
|
|
1265
|
-
};
|
|
1266
|
-
const cancelRename = () => {
|
|
1267
|
-
setRenaming(null);
|
|
1268
|
-
setText('');
|
|
1269
|
-
setStep('destination');
|
|
1270
|
-
};
|
|
1271
|
-
/**
|
|
1272
|
-
* A document rasterisation plans one output per page — there is no single
|
|
1273
|
-
* stem for a rename field to edit, and `resolveOutputPath`'s single-output
|
|
1274
|
-
* shape is exactly what `rasterOutputPaths` (inside `convertAction.plan()`)
|
|
1275
|
-
* exists to bypass. So this skips `startRename`/`buildPlan` entirely and
|
|
1276
|
-
* routes through the same `checkWriteSafety` + `runJobs` pipeline `/pdf`'s
|
|
1277
|
-
* five page operations already use — `handlePdfDone` is generic over any
|
|
1278
|
-
* `Job[]`, not `/pdf`-specific, and a multi-output convert job fits it
|
|
1279
|
-
* exactly (self-collision, existing-file and input-collision checks all
|
|
1280
|
-
* apply the same way here as they do to a separated extract).
|
|
1281
|
-
*/
|
|
1282
|
-
const confirmDocumentConversion = (destination) => {
|
|
1283
|
-
if (!source)
|
|
1284
|
-
return;
|
|
1285
|
-
void handlePdfDone(action.plan([source], { ...values, destination }), {
|
|
1286
|
-
cancelTo: 'destination',
|
|
1287
|
-
});
|
|
1288
|
-
};
|
|
1289
|
-
/**
|
|
1290
|
-
* Routes on how the outputs get their names, not on source kind.
|
|
1291
|
-
*
|
|
1292
|
-
* A rasterisation names one output per page (`doc-1.jpg`) — at one page as
|
|
1293
|
-
* much as at twenty — so there is no single stem for a rename field to
|
|
1294
|
-
* edit, and it takes the multi-output path. A compression keeps the
|
|
1295
|
-
* source's own format and plans one ordinarily-named output, so it takes
|
|
1296
|
-
* the ordinary path, where `finishConversion` runs the target-size search.
|
|
1297
|
-
*
|
|
1298
|
-
* Read from the engine's declared `writes` rather than a hardcoded list of
|
|
1299
|
-
* raster formats (invariant 2), the same way the CLI's `rasterises` does.
|
|
1300
|
-
*
|
|
1301
|
-
* Branching on `kind` alone sent every document down the rasterisation
|
|
1302
|
-
* route, a compression included — which is how the shell came to offer "to
|
|
1303
|
-
* a target size" for a scan, collect the number, and ignore it.
|
|
1304
|
-
*/
|
|
1305
|
-
const confirmDestination = (destination) => {
|
|
1306
|
-
if (!source)
|
|
1307
|
-
return;
|
|
1308
|
-
if (source.kind === 'document') {
|
|
1309
|
-
const [planned] = action.plan([source], { ...values, destination });
|
|
1310
|
-
if (planned?.op === 'convert' && pdfiumEngine.writes.has(planned.target)) {
|
|
1311
|
-
confirmDocumentConversion(destination);
|
|
1312
|
-
return;
|
|
1313
|
-
}
|
|
1314
|
-
}
|
|
1315
|
-
startRename(destination);
|
|
1316
|
-
};
|
|
1317
|
-
/** Back from `destination`: to whichever step actually precedes it for this source. */
|
|
1318
|
-
const destinationBack = () => {
|
|
1319
|
-
if (specFor('quality')) {
|
|
1320
|
-
setStep('quality');
|
|
1321
|
-
return;
|
|
1322
|
-
}
|
|
1323
|
-
setStep(specFor('dpi') ? 'dpi' : 'target');
|
|
1324
|
-
};
|
|
1325
|
-
const submitRename = (raw) => {
|
|
1326
|
-
if (!renaming)
|
|
1327
|
-
return;
|
|
1328
|
-
const stem = raw.trim().replace(/\//g, '-') || renaming.stem;
|
|
1329
|
-
setText('');
|
|
1330
|
-
setRenaming(null);
|
|
1331
|
-
void convert(renaming.destination, {
|
|
1332
|
-
output: `${renaming.destination}/${stem}${renaming.ext}`,
|
|
1333
|
-
});
|
|
1334
|
-
};
|
|
1335
|
-
/**
|
|
1336
|
-
* Validates in the field rather than at conversion time — the difference
|
|
1337
|
-
* between catching a typo and failing a run that already chose a folder.
|
|
1338
|
-
*/
|
|
1339
|
-
/**
|
|
1340
|
-
* What the field actually means: the typed text if it already names a unit,
|
|
1341
|
-
* otherwise that text plus whichever unit the row is on. Written as one
|
|
1342
|
-
* function because three places need the same answer — the live echo, the
|
|
1343
|
-
* submit, and the error message about what could not be read.
|
|
1344
|
-
*/
|
|
1345
|
-
const sizeWithUnit = (raw) => /[a-z]/i.test(raw) ? raw.trim() : `${raw.trim()}${sizeUnit}`;
|
|
1346
|
-
const submitSize = (typed) => {
|
|
1347
|
-
const raw = sizeWithUnit(typed);
|
|
1348
|
-
const bytes = parseSize(raw);
|
|
1349
|
-
if (bytes === undefined) {
|
|
1350
|
-
setSizeError(`${raw.trim() || 'that'} is not a size. Try 500kb or 2mb.`);
|
|
1351
|
-
return;
|
|
1352
|
-
}
|
|
1353
|
-
setSizeError(undefined);
|
|
1354
|
-
setValues((v) => ({ ...v, size: raw, targetBytes: bytes }));
|
|
1355
|
-
setText('');
|
|
1356
|
-
// Both halves of the field are left as they were found. Clearing the
|
|
1357
|
-
// amount without releasing the unit row would hand the next visit an
|
|
1358
|
-
// inert amount field — the caret would be in it, and typing would go to
|
|
1359
|
-
// the units instead.
|
|
1360
|
-
setUnitFocused(false);
|
|
1361
|
-
setStep('destination');
|
|
1362
|
-
};
|
|
1363
|
-
const chooseQuality = (quality) => {
|
|
1364
|
-
setValues((v) => ({ ...v, quality }));
|
|
1365
|
-
setStep('destination');
|
|
1366
|
-
};
|
|
1367
|
-
// The destination preview shows the resolved output path as the user
|
|
1368
|
-
// highlights each preset. Truncated with `middleEllipsis`, budgeted off the
|
|
1369
|
-
// live terminal width, so a deep preset path can't push the line past the
|
|
1370
|
-
// edge of a narrow terminal.
|
|
1371
|
-
const previewDestination = (candidate) => {
|
|
1372
|
-
const stem = source ? (source.path.split('/').pop() ?? 'file').replace(/\.[^.]+$/, '') : '';
|
|
1373
|
-
const full = source && typeof values.target === 'string'
|
|
1374
|
-
? `${candidate}/${stem}${primaryExtension(values.target)}`
|
|
1375
|
-
: candidate;
|
|
1376
|
-
return middleEllipsis(full, Math.max(12, width - 4));
|
|
1377
|
-
};
|
|
1378
|
-
/**
|
|
1379
|
-
* Two Enters delivered in the same tick — a held key repeating, or a paste
|
|
1380
|
-
* carrying two line endings — both reach `convert` from the destination
|
|
1381
|
-
* step's synchronous `useInput` handler. Moving `step` to `'converting'`
|
|
1382
|
-
* does not stop the second: React unmounts that handler on the next
|
|
1383
|
-
* render, and both calls have already run by then. Measured before this
|
|
1384
|
-
* ref existed: two `runJobs` calls, two encodes, two renames onto the same
|
|
1385
|
-
* path, two result blocks. So this is claimed synchronously, before the
|
|
1386
|
-
* first `await`, for the same reason `requestId` above is.
|
|
1387
|
-
*/
|
|
1388
|
-
const converting = useRef(false);
|
|
1389
|
-
/**
|
|
1390
|
-
* Spec §8's write-safety rules live in `core/write-safety.ts` and reach this
|
|
1391
|
-
* path through `runPlan`: never write over the input, never replace an
|
|
1392
|
-
* existing output without consent. The shell needs them for exactly the
|
|
1393
|
-
* reason the CLI does — `targetIdsFor` legitimately offers jpeg for a JPEG,
|
|
1394
|
-
* and "Same folder" is legitimately the first destination preset, so the
|
|
1395
|
-
* all-defaults keypath resolves the output straight onto the user's
|
|
1396
|
-
* original unless something refuses.
|
|
1397
|
-
*
|
|
1398
|
-
* `action.plan()` derives the job; `runPlan` decides whether it may happen,
|
|
1399
|
-
* resolves any target size, and runs it. `buildPlan` used to sit in between
|
|
1400
|
-
* re-deriving a job that already existed, which is why the output path had
|
|
1401
|
-
* two authorities and the rename field once offered a name with no
|
|
1402
|
-
* extension.
|
|
1403
|
-
*
|
|
1404
|
-
* Still one source, not `stage.sources`: `output` here is one exact
|
|
1405
|
-
* filename, since the rename step builds `${destination}/${stem}${ext}` for
|
|
1406
|
-
* a single representative source. Handing the whole stage the same output
|
|
1407
|
-
* would make every source past the first collide on that path — correctly
|
|
1408
|
-
* refused, but the branch below treats any refusal as the whole run being
|
|
1409
|
-
* refused, so a two-file stage would convert nothing instead of batching.
|
|
1410
|
-
* Making that work needs the wizard to know it is planning for a batch
|
|
1411
|
-
* (skip or reinterpret the rename step, run what did resolve, show more
|
|
1412
|
-
* than one result) — UX decisions this change does not make.
|
|
1413
|
-
*/
|
|
1414
|
-
/**
|
|
1415
|
-
* The part of a conversion that runs once quality is settled — a plan
|
|
1416
|
-
* already carrying the quality it will encode at, never one still waiting
|
|
1417
|
-
* on a target-size search. Split out of `convert()` so the "use the lowest
|
|
1418
|
-
* quality anyway" answer to `sizeUnreachable` can finish the same
|
|
1419
|
-
* conversion the search already ran most of, instead of re-planning or
|
|
1420
|
-
* re-searching from scratch.
|
|
1421
|
-
*/
|
|
1422
|
-
const finishConversion = async (planned, destination, output, opts) => {
|
|
1423
|
-
if (!source)
|
|
1424
|
-
return;
|
|
1425
|
-
// The rename step can redirect where this lands, so the job carries the
|
|
1426
|
-
// final path rather than a second module re-deriving it.
|
|
1427
|
-
planned.outputs[0] = output;
|
|
1428
|
-
/**
|
|
1429
|
-
* One call for write safety, the target-size search and the run.
|
|
1430
|
-
*
|
|
1431
|
-
* This used to be `buildPlan` (which re-planned a job `action.plan()` had
|
|
1432
|
-
* already produced) followed by `runJobs`, with the search living in
|
|
1433
|
-
* `convert()` — where a document source never reached it. Routing both
|
|
1434
|
-
* kinds through here is what makes a PDF target size take effect.
|
|
1435
|
-
*/
|
|
1436
|
-
const controller = new AbortController();
|
|
1437
|
-
searchAbort.current = controller;
|
|
1438
|
-
const outcome = await runPlan([planned], {
|
|
1439
|
-
force: opts.force ?? false,
|
|
1440
|
-
signal: controller.signal,
|
|
1441
|
-
...(opts.targetBytes === undefined ? {} : { targetBytes: opts.targetBytes }),
|
|
1442
|
-
onEvent: (event) => {
|
|
1443
|
-
if (event.type === 'search:attempt') {
|
|
1444
|
-
setAttempt({ n: event.attempt, of: event.of, dpi: event.rung.dpi });
|
|
1445
|
-
}
|
|
1446
|
-
},
|
|
1447
|
-
});
|
|
1448
|
-
setAttempt(undefined);
|
|
1449
|
-
searchAbort.current = undefined;
|
|
1450
|
-
/**
|
|
1451
|
-
* Cancelled by esc, which has already put the screen back on the size
|
|
1452
|
-
* field (see the `converting` key handler). Nothing further to do:
|
|
1453
|
-
* a cancelled run has no result, no refusal and no unreachable target to
|
|
1454
|
-
* report, and reporting one anyway would be inventing an answer the user
|
|
1455
|
-
* stopped waiting for.
|
|
1456
|
-
*/
|
|
1457
|
-
if (outcome.cancelled)
|
|
1458
|
-
return;
|
|
1459
|
-
/**
|
|
1460
|
-
* Nothing gets small enough — but the search measured the smallest it
|
|
1461
|
-
* *can* get, so this asks rather than refuses: take that size, or go pick
|
|
1462
|
-
* a format with more room to shrink.
|
|
1463
|
-
*/
|
|
1464
|
-
const missed = outcome.unreachable[0];
|
|
1465
|
-
if (missed && opts.targetBytes !== undefined) {
|
|
1466
|
-
setSizeUnreachable({
|
|
1467
|
-
planned,
|
|
1468
|
-
destination,
|
|
1469
|
-
output,
|
|
1470
|
-
opts,
|
|
1471
|
-
targetBytes: opts.targetBytes,
|
|
1472
|
-
smallest: missed.smallest,
|
|
1473
|
-
quality: missed.settings.quality,
|
|
1474
|
-
...(missed.settings.dpi === undefined ? {} : { dpi: missed.settings.dpi }),
|
|
1475
|
-
});
|
|
1476
|
-
setStep('size-unreachable');
|
|
1477
|
-
return;
|
|
1478
|
-
}
|
|
1479
|
-
const refusal = outcome.refusals[0];
|
|
1480
|
-
if (refusal) {
|
|
1481
|
-
// An output that already exists is a question, not a refusal: spec §8
|
|
1482
|
-
// says the shell asks — keep both, replace, or cancel.
|
|
1483
|
-
if (refusal.error.code === 'output-exists') {
|
|
1484
|
-
setPending({ destination, output, keepBoth: uniqueOutputPath(output) });
|
|
1485
|
-
setStep('overwrite');
|
|
1486
|
-
return;
|
|
1487
|
-
}
|
|
1488
|
-
push({ kind: 'error', id: nextId(), error: refusal.error });
|
|
1489
|
-
// Writing over the source has no "replace" worth offering — there is
|
|
1490
|
-
// no outcome there that keeps the original. Back to the destination
|
|
1491
|
-
// step, where choosing a different folder is the actual fix. Any
|
|
1492
|
-
// other refusal ends the action, and ending one clears the stage —
|
|
1493
|
-
// see `clearSource`.
|
|
1494
|
-
if (refusal.error.code === 'output-is-input')
|
|
1495
|
-
setStep('destination');
|
|
1496
|
-
else
|
|
1497
|
-
clearSource();
|
|
1498
|
-
return;
|
|
1499
|
-
}
|
|
1500
|
-
const summary = outcome;
|
|
1501
|
-
const result = summary.results[0];
|
|
1502
|
-
if (result) {
|
|
1503
|
-
setLastResult(result);
|
|
1504
|
-
push({ kind: 'result', id: nextId(), result });
|
|
1505
|
-
setStep('result');
|
|
1506
|
-
/**
|
|
1507
|
-
* Only after a compression, and only once the file is safely written:
|
|
1508
|
-
* this is an extra encode purely to find out whether a sentence is
|
|
1509
|
-
* worth saying, and it must not be able to cost the user the
|
|
1510
|
-
* conversion they actually asked for.
|
|
1511
|
-
*/
|
|
1512
|
-
if (mode === 'compress') {
|
|
1513
|
-
const found = await suggestFormat({
|
|
1514
|
-
source,
|
|
1515
|
-
resultBytes: result.outputBytes,
|
|
1516
|
-
quality: planned.options.quality ?? livePrefs.quality,
|
|
1517
|
-
encode: async (target, quality) => (await encodeToBuffer(source, target, { ...planned.options, quality })).length,
|
|
1518
|
-
});
|
|
1519
|
-
setSuggestion(found);
|
|
1520
|
-
setMergeOffer(undefined);
|
|
1521
|
-
}
|
|
1522
|
-
else {
|
|
1523
|
-
setSuggestion(undefined);
|
|
1524
|
-
// Compress never reaches here with `target === 'pdf'` — it keeps
|
|
1525
|
-
// the source's own format (see `compressAction.appliesTo`) — so
|
|
1526
|
-
// this only ever counts conversions the user actually chose 'PDF'
|
|
1527
|
-
// for.
|
|
1528
|
-
if (planned.target === 'pdf') {
|
|
1529
|
-
pdfOutputsThisSession.current += 1;
|
|
1530
|
-
setMergeOffer(pdfOutputsThisSession.current > 1 ? pdfOutputsThisSession.current : undefined);
|
|
1531
|
-
}
|
|
1532
|
-
else {
|
|
1533
|
-
setMergeOffer(undefined);
|
|
1534
|
-
}
|
|
1535
|
-
}
|
|
1536
|
-
}
|
|
1537
|
-
else {
|
|
1538
|
-
const failure = summary.failures[0];
|
|
1539
|
-
if (failure)
|
|
1540
|
-
push({ kind: 'error', id: nextId(), error: failure.error });
|
|
1541
|
-
clearSource();
|
|
1542
|
-
}
|
|
1543
|
-
};
|
|
1544
|
-
const convert = async (destination, opts = {}) => {
|
|
1545
|
-
if (!source)
|
|
1546
|
-
return;
|
|
1547
|
-
if (converting.current)
|
|
1548
|
-
return;
|
|
1549
|
-
converting.current = true;
|
|
1550
|
-
setStep('converting');
|
|
1551
|
-
try {
|
|
1552
|
-
const planned = action.plan([source], { ...values, destination })[0];
|
|
1553
|
-
// `action` here is always convertAction or compressAction — both plan
|
|
1554
|
-
// only ever produce a `convert` job — but `plan()`'s return type is now
|
|
1555
|
-
// the full `Job` union (widened for the page actions), so the `target`/
|
|
1556
|
-
// `options` reads below need this narrowed explicitly rather than
|
|
1557
|
-
// assumed.
|
|
1558
|
-
if (planned?.op !== 'convert') {
|
|
1559
|
-
setStep('idle');
|
|
1560
|
-
return;
|
|
1561
|
-
}
|
|
1562
|
-
const output = opts.output ?? planned.outputs[0];
|
|
1563
|
-
/**
|
|
1564
|
-
* A target size means the quality is the search's answer, not the
|
|
1565
|
-
* user's — but the search itself belongs to `runPlan`, which picks the
|
|
1566
|
-
* right ladder from the engine. The shell used to run a one-dimensional
|
|
1567
|
-
* image search here, which a document source never reached at all.
|
|
1568
|
-
*/
|
|
1569
|
-
await finishConversion(planned, destination, output, {
|
|
1570
|
-
...opts,
|
|
1571
|
-
...(typeof values.targetBytes === 'number' ? { targetBytes: values.targetBytes } : {}),
|
|
1572
|
-
});
|
|
1573
|
-
}
|
|
1574
|
-
catch (e) {
|
|
1575
|
-
// convertAction.plan() throws synchronously on a bad target, and
|
|
1576
|
-
// nothing guarantees runPlan() can never reject for some
|
|
1577
|
-
// cause they don't themselves catch. Either way, this runs inside an
|
|
1578
|
-
// async handler nothing awaits — PathInput fires onSubmit from a
|
|
1579
|
-
// synchronous useInput handler — so a rethrow here would become an
|
|
1580
|
-
// unhandled rejection instead of something the user ever sees. Render
|
|
1581
|
-
// it instead, exactly like submitPath does for probe().
|
|
1582
|
-
showError(e);
|
|
1583
|
-
clearSource();
|
|
1584
|
-
}
|
|
1585
|
-
finally {
|
|
1586
|
-
converting.current = false;
|
|
1587
|
-
}
|
|
1588
|
-
};
|
|
1589
|
-
/** Answers `sizeUnreachable`: take the smallest size the search found, or back off to pick a format instead. */
|
|
1590
|
-
const answerSizeUnreachable = (choice) => {
|
|
1591
|
-
if (!sizeUnreachable)
|
|
1592
|
-
return;
|
|
1593
|
-
const { planned, destination, output, opts, quality, dpi } = sizeUnreachable;
|
|
1594
|
-
setSizeUnreachable(null);
|
|
1595
|
-
if (choice === 'lowest') {
|
|
1596
|
-
if (converting.current)
|
|
1597
|
-
return;
|
|
1598
|
-
converting.current = true;
|
|
1599
|
-
planned.options.quality = quality;
|
|
1600
|
-
// A document's smallest came off a resolution rung as well as a quality,
|
|
1601
|
-
// so taking that size means taking both.
|
|
1602
|
-
if (dpi !== undefined)
|
|
1603
|
-
planned.options.dpi = dpi;
|
|
1604
|
-
setStep('converting');
|
|
1605
|
-
// Deliberately without `targetBytes`: the search already ran and this is
|
|
1606
|
-
// the answer to it. Passing it again would search a second time and miss
|
|
1607
|
-
// a second time.
|
|
1608
|
-
const { targetBytes: _alreadySearched, ...settled } = opts;
|
|
1609
|
-
void finishConversion(planned, destination, output, settled)
|
|
1610
|
-
.catch((e) => {
|
|
1611
|
-
showError(e);
|
|
1612
|
-
clearSource();
|
|
1613
|
-
})
|
|
1614
|
-
.finally(() => {
|
|
1615
|
-
converting.current = false;
|
|
1616
|
-
});
|
|
1617
|
-
return;
|
|
1618
|
-
}
|
|
1619
|
-
/**
|
|
1620
|
-
* The other three answers all reuse a step that already exists rather
|
|
1621
|
-
* than inventing a screen: the size field the number came from, the
|
|
1622
|
-
* quality slider the other compress mode uses, and `/convert`'s own
|
|
1623
|
-
* target picker. A search that missed is a fork in the road, not a
|
|
1624
|
-
* failure with one exit.
|
|
1625
|
-
*/
|
|
1626
|
-
if (choice === 'size') {
|
|
1627
|
-
// `text` still holds what was typed, so this lands on their own number.
|
|
1628
|
-
setStep('size');
|
|
1629
|
-
return;
|
|
1630
|
-
}
|
|
1631
|
-
if (choice === 'quality') {
|
|
1632
|
-
setValues((v) => ({ ...v, mode: 'quality', targetBytes: undefined }));
|
|
1633
|
-
setStep('quality');
|
|
1634
|
-
return;
|
|
1635
|
-
}
|
|
1636
|
-
setMode('convert');
|
|
1637
|
-
setValues({});
|
|
1638
|
-
setStep(source && hasConvertTarget(source) ? 'target' : 'idle');
|
|
1639
|
-
};
|
|
1640
|
-
const answerOverwrite = (choice) => {
|
|
1641
|
-
if (!pending)
|
|
1642
|
-
return;
|
|
1643
|
-
const { destination, keepBoth } = pending;
|
|
1644
|
-
setPending(null);
|
|
1645
|
-
if (choice === 'replace')
|
|
1646
|
-
void convert(destination, { force: true });
|
|
1647
|
-
else if (choice === 'keep')
|
|
1648
|
-
void convert(destination, { output: keepBoth });
|
|
1649
|
-
else if (choice === 'rename')
|
|
1650
|
-
startRename(destination);
|
|
1651
|
-
else
|
|
1652
|
-
setStep('destination');
|
|
1653
|
-
};
|
|
1654
|
-
/**
|
|
1655
|
-
* `PdfFlow` only ever decides *what* to run — `onDone` is where that
|
|
1656
|
-
* handoff happens, through the same `runJobs` the convert/compress wizard
|
|
1657
|
-
* uses. Page-op outputs are named by the action's own `plan()` (suffixed,
|
|
1658
|
-
* numbered, or merged beside the source) rather than a destination the
|
|
1659
|
-
* user picks, so there is no `buildPlan`/overwrite step here the way
|
|
1660
|
-
* `convert()` has one — see the note on `convert()` for why that function
|
|
1661
|
-
* still only ever plans for `[source]`, not `stage.sources`; `/pdf` is the
|
|
1662
|
-
* one place in this file that deliberately does act on the whole staged
|
|
1663
|
-
* list, because merge is defined by having several files staged.
|
|
1664
|
-
*/
|
|
1665
|
-
/**
|
|
1666
|
-
* Actually runs jobs already cleared by `checkWriteSafety`.
|
|
1667
|
-
*
|
|
1668
|
-
* A rasterisation job's `total` is `job.options.pages.length` — the
|
|
1669
|
-
* *selected* page count, not the document's — because that is exactly
|
|
1670
|
-
* what `engines/pdfium.ts` reports (see its own doc comment); this only
|
|
1671
|
-
* relays it, never recomputes one of its own. `detail` is the basename of
|
|
1672
|
-
* whichever output the just-finished page wrote, read back off the job's
|
|
1673
|
-
* own `outputs[done - 1]` rather than threaded through separately, so it
|
|
1674
|
-
* can never name a different file than the one `Progress` is counting.
|
|
1675
|
-
*/
|
|
1676
|
-
const runPdfJobs = async (jobs, opts = {}) => {
|
|
1677
|
-
setStep('pdf-running');
|
|
1678
|
-
setPageProgress(null);
|
|
1679
|
-
try {
|
|
1680
|
-
/**
|
|
1681
|
-
* `force` is threaded rather than defaulted because these jobs have
|
|
1682
|
-
* already cleared `handlePdfDone`'s check — including, after "Replace",
|
|
1683
|
-
* a deliberate overwrite. Running them through `runPlan` at `force:
|
|
1684
|
-
* false` would refuse exactly the outputs the user just chose to
|
|
1685
|
-
* replace.
|
|
1686
|
-
*
|
|
1687
|
-
* No `targetBytes`: a page operation has no quality dial, so there is
|
|
1688
|
-
* nothing here for a search to settle.
|
|
1689
|
-
*/
|
|
1690
|
-
const summary = await runPlan(jobs, {
|
|
1691
|
-
force: opts.force ?? false,
|
|
1692
|
-
onEvent: (event) => {
|
|
1693
|
-
if (event.type !== 'job:phase' || event.progress.phase !== 'page')
|
|
1694
|
-
return;
|
|
1695
|
-
const { done, total } = event.progress;
|
|
1696
|
-
const output = event.job.op === 'convert' ? event.job.outputs[done - 1] : undefined;
|
|
1697
|
-
setPageProgress({
|
|
1698
|
-
done,
|
|
1699
|
-
total,
|
|
1700
|
-
detail: output ? basename(output) : undefined,
|
|
1701
|
-
op: event.job.op,
|
|
1702
|
-
});
|
|
1703
|
-
},
|
|
1704
|
-
});
|
|
1705
|
-
for (const result of summary.results) {
|
|
1706
|
-
push({
|
|
1707
|
-
kind: 'note',
|
|
1708
|
-
id: nextId(),
|
|
1709
|
-
text: `${SYMBOLS.ok} ${describePdfResult(result)}`,
|
|
1710
|
-
savedTo: result.job.outputs[0],
|
|
1711
|
-
});
|
|
1712
|
-
// Warnings used to stop here: only the note was pushed, and
|
|
1713
|
-
// `result.warnings` was never read. No page operation emits one today,
|
|
1714
|
-
// so this is a guard against the next one that does rather than a live
|
|
1715
|
-
// fix — but it costs a loop and the alternative was a silent drop.
|
|
1716
|
-
for (const warning of result.warnings) {
|
|
1717
|
-
push({ kind: 'note', id: nextId(), text: `${SYMBOLS.warn} ${warning.message}` });
|
|
1718
|
-
}
|
|
1719
|
-
}
|
|
1720
|
-
for (const failure of [...summary.refusals, ...summary.failures]) {
|
|
1721
|
-
push({ kind: 'error', id: nextId(), error: failure.error });
|
|
1722
|
-
}
|
|
1723
|
-
}
|
|
1724
|
-
catch (e) {
|
|
1725
|
-
// Mirrors `convert()`'s own catch: this runs from a handler PdfFlow's
|
|
1726
|
-
// synchronous `useInput` fired, and nothing else awaits this promise.
|
|
1727
|
-
showError(e);
|
|
1728
|
-
}
|
|
1729
|
-
finally {
|
|
1730
|
-
setPageProgress(null);
|
|
1731
|
-
setStage(clearStage());
|
|
1732
|
-
setValues({});
|
|
1733
|
-
setStep('idle');
|
|
1734
|
-
}
|
|
1735
|
-
};
|
|
1736
|
-
/**
|
|
1737
|
-
* `PdfFlow`'s `plan()` output bypasses `buildPlan` (see the note above) and
|
|
1738
|
-
* so bypasses its write-safety checks too — merge, split, extract, delete
|
|
1739
|
-
* and rotate can each collide with an existing file, and merge and rotate
|
|
1740
|
-
* can even target a path that is one of their own inputs (rotate twice,
|
|
1741
|
-
* or merge a folder a second time after its own merged output already
|
|
1742
|
-
* landed there). `checkWriteSafety` is the same check the CLI's page-op
|
|
1743
|
-
* path applies before its own `runJobs` call — this is the shell applying
|
|
1744
|
-
* it too, in the one spot both paths share: right before the actual run.
|
|
1745
|
-
*
|
|
1746
|
-
* The shell has no `--force` flag, so a refusal has to be answered
|
|
1747
|
-
* in-flow rather than by re-typing the command with a flag. Only
|
|
1748
|
-
* `output-exists` gets an in-flow bypass ("Replace"): it is the ordinary,
|
|
1749
|
-
* expected case (rerunning an operation regenerates a file that is
|
|
1750
|
-
* already there) and `checkWriteSafety` supports overriding it safely.
|
|
1751
|
-
* `output-is-input` is deliberately given no bypass here even though
|
|
1752
|
-
* `checkWriteSafety` could technically allow one with `force: true` — an
|
|
1753
|
-
* operation reading and overwriting its own input in place, with no
|
|
1754
|
-
* `--output` to redirect to, is confusing enough that "go back and choose
|
|
1755
|
-
* something else" is the honest answer, not a one-keystroke override.
|
|
1756
|
-
* `output-collision` has no bypass at all, in the shell or the CLI: it is
|
|
1757
|
-
* the job's own plan asking to write two things to one path, which is not
|
|
1758
|
-
* a preference `force` can express (see `checkWriteSafety`'s doc).
|
|
1759
|
-
*/
|
|
1760
|
-
const handlePdfDone = async (jobs, opts = {}) => {
|
|
1761
|
-
const safe = checkWriteSafety(jobs, { force: false });
|
|
1762
|
-
if (safe.failures.length > 0) {
|
|
1763
|
-
setPdfBlocked({ jobs, failures: safe.failures, cancelTo: opts.cancelTo ?? 'pdf' });
|
|
1764
|
-
setStep('pdf-blocked');
|
|
1765
|
-
return;
|
|
1766
|
-
}
|
|
1767
|
-
await runPdfJobs(safe.jobs);
|
|
1768
|
-
};
|
|
1769
|
-
/** `replace` retries `pdfBlocked.jobs` with `force: true`; anything else cancels. */
|
|
1770
|
-
const answerPdfBlocked = (choice) => {
|
|
1771
|
-
if (!pdfBlocked)
|
|
1772
|
-
return;
|
|
1773
|
-
if (choice !== 'replace') {
|
|
1774
|
-
const cancelTo = pdfBlocked.cancelTo;
|
|
1775
|
-
setPdfBlocked(null);
|
|
1776
|
-
setStep(cancelTo);
|
|
1777
|
-
return;
|
|
1778
|
-
}
|
|
1779
|
-
const forced = checkWriteSafety(pdfBlocked.jobs, { force: true });
|
|
1780
|
-
setPdfBlocked(null);
|
|
1781
|
-
if (forced.failures.length > 0) {
|
|
1782
|
-
// A collision: `force` never bypasses it (see `checkWriteSafety`), so
|
|
1783
|
-
// this is the rare remainder "Replace" cannot fix.
|
|
1784
|
-
for (const failure of forced.failures) {
|
|
1785
|
-
push({ kind: 'error', id: nextId(), error: failure.error });
|
|
1786
|
-
}
|
|
1787
|
-
setStep('pdf');
|
|
1788
|
-
return;
|
|
1789
|
-
}
|
|
1790
|
-
void runPdfJobs(forced.jobs, { force: true });
|
|
1791
|
-
};
|
|
1792
|
-
// `Select` owns arrow/enter for the output-exists choice; a plain refusal
|
|
1793
|
-
// (no bypass offered) has nothing mounted to answer escape or enter, so
|
|
1794
|
-
// this step owns both directly — same reasoning as the 'rename' and
|
|
1795
|
-
// 'size' steps above, which own escape for the same reason.
|
|
1796
|
-
useKeys((_input, key) => {
|
|
1797
|
-
if (key.escape || key.return)
|
|
1798
|
-
answerPdfBlocked('cancel');
|
|
1799
|
-
}, { isActive: step === 'pdf-blocked' && pdfBlocked?.failures[0]?.error.code !== 'output-exists' });
|
|
1800
|
-
const modeSpec = specFor('mode');
|
|
1801
|
-
const sizeSpec = specFor('size');
|
|
1802
|
-
const targetSpec = specFor('target');
|
|
1803
|
-
const pagesSpec = specFor('pages');
|
|
1804
|
-
const dpiSpec = specFor('dpi');
|
|
1805
|
-
const qualitySpec = specFor('quality');
|
|
1806
|
-
const destinationSpec = specFor('destination');
|
|
1807
|
-
/**
|
|
1808
|
-
* The Box the whole frame is measured from. `useFrameOrigin` needs its
|
|
1809
|
-
* height to place the frame, and `<Static>` is excluded from this Box's
|
|
1810
|
-
* layout (measured against Ink 7.1.1) — which is what makes the height the
|
|
1811
|
-
* *live* frame's height rather than the whole session's.
|
|
1812
|
-
*/
|
|
1813
|
-
const rootRef = useRef(null);
|
|
1814
|
-
return (_jsx(ThemeProvider, { palette: paletteFor(theme), children: _jsx(ClickTargetProvider, { children: _jsxs(Box, { flexDirection: "column", ref: rootRef, children: [_jsx(MouseRouter, { rootRef: rootRef, revision: history.length }), step === 'theme' ? _jsx(ThemePicker, { onChoose: chooseTheme }) : null, step !== 'theme' && step !== 'result' ? (_jsx(Box, { width: width, marginBottom: 1, paddingX: 1, backgroundColor: colourProp(modeBg), children: modeLine(true) })) : null, stage.sources.length > 0 &&
|
|
1815
|
-
step !== 'theme' &&
|
|
1816
|
-
step !== 'result' &&
|
|
1817
|
-
(step !== 'idle' || stage.sources.length > 1) ? (_jsx(Box, { marginBottom: 1, children: _jsx(StagedFiles, { stage: stage, width: width }) })) : null, _jsx(Static, { items: history, children: (block) => _jsx(HistoryEntry, { block: block, width: width }, block.id) }, staticGeneration), step === 'mode' && source && modeSpec?.kind === 'select' ? (_jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [_jsx(Text, { color: colourProp(palette.label), children: modeSpec.label }), _jsx(Select, { width: width, items: modeSpec.choices, initialValue: modeSpec.default, onSubmit: (chosen) => {
|
|
1818
|
-
setValues((v) => ({ ...v, mode: chosen }));
|
|
1819
|
-
setStep(chosen === 'size' ? 'size' : 'quality');
|
|
1820
|
-
}, onCancel: clearSource, showHints: band !== 'compact' }), _jsx(HintBar, { width: width, pairs: [
|
|
1821
|
-
['↑↓', 'choose'],
|
|
1822
|
-
['↵', 'confirm'],
|
|
1823
|
-
['esc', 'remove file'],
|
|
1824
|
-
] })] })) : null, step === 'size' && sizeSpec?.kind === 'text' ? (_jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [_jsx(Text, { color: colourProp(palette.label), children: sizeSpec.label }), _jsx(Prompt, { value: text, onChange: setText, onSubmit: submitSize, placeholder: sizeSpec.placeholder, isActive: !unitFocused, variant: band === 'compact' ? 'plain' : 'field', width: width }), _jsx(UnitRow, { unit: sizeUnit, focused: unitFocused }), text.trim() !== '' ? (_jsx(Text, { color: colourProp(palette.dim), children: (() => {
|
|
1825
|
-
const understood = describeSize(sizeWithUnit(text));
|
|
1826
|
-
return understood === undefined
|
|
1827
|
-
? ` ${SYMBOLS.warn} not a size — try 500kb or 2mb`
|
|
1828
|
-
: ` ${SYMBOLS.arrow} ${understood}`;
|
|
1829
|
-
})() })) : null, sizeError ? (_jsx(Text, { color: colourProp(palette.warn), children: ` ${SYMBOLS.warn} ${sizeError}` })) : null, _jsx(HintBar, { width: width, pairs: [
|
|
1830
|
-
['↵', 'confirm'],
|
|
1831
|
-
['tab', unitFocused ? 'amount' : 'unit'],
|
|
1832
|
-
...(unitFocused ? [['←→', 'change unit']] : []),
|
|
1833
|
-
['esc', 'clear / back'],
|
|
1834
|
-
] })] })) : null, step === 'target' && source && targetSpec?.kind === 'select' ? (_jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [_jsx(Text, { children: targetSpec.label }), _jsx(Select, { width: width, items:
|
|
1835
|
-
// A PDF reaching this screen still has page operations on
|
|
1836
|
-
// the table too — see `backToPromptKeepingStage`. A dim
|
|
1837
|
-
// line below the list used to be the only pointer to
|
|
1838
|
-
// `/pdf`, which said where to go but not how to get there
|
|
1839
|
-
// short of escaping and typing the command from memory.
|
|
1840
|
-
// This is that same pointer, but reachable the way JPEG
|
|
1841
|
-
// or PNG are: a disabled, unlabelled row first, so it
|
|
1842
|
-
// reads as its own group rather than a sixth format
|
|
1843
|
-
// (`nextEnabledIndex` in Select already skips a disabled
|
|
1844
|
-
// row when the cursor walks past it), then the row
|
|
1845
|
-
// itself.
|
|
1846
|
-
//
|
|
1847
|
-
// `format === 'pdf'` matters as much as `kind` does: a
|
|
1848
|
-
// docx/doc source has no page operations `/pdf` could
|
|
1849
|
-
// offer it, so the row would be a dead end for it.
|
|
1850
|
-
source.kind === 'document' && source.format === 'pdf'
|
|
1851
|
-
? [
|
|
1852
|
-
...targetSpec.choices,
|
|
1853
|
-
{ value: '__gap__', label: '', hint: '', disabled: true },
|
|
1854
|
-
{ value: GOTO_PDF, label: '/pdf', hint: 'for more options' },
|
|
1855
|
-
]
|
|
1856
|
-
: targetSpec.choices, onSubmit: (target) => {
|
|
1857
|
-
if (target === GOTO_PDF) {
|
|
1858
|
-
if (pdfCommand)
|
|
1859
|
-
runCommand(pdfCommand);
|
|
1860
|
-
return;
|
|
1861
|
-
}
|
|
1862
|
-
chooseTarget(source, target);
|
|
1863
|
-
}, onCancel: source.kind === 'document' ? backToPromptKeepingStage : clearSource, showHints: band !== 'compact' }), _jsx(HintBar, { width: width, pairs: [
|
|
1864
|
-
['↑↓', 'choose'],
|
|
1865
|
-
['↵', 'confirm'],
|
|
1866
|
-
['esc', 'back'],
|
|
1867
|
-
] })] })) : null, step === 'pages' && source && pagesSpec?.kind === 'select' ? (_jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [_jsx(Text, { color: colourProp(palette.label), children: pagesSpec.label }), _jsx(Select, { width: width, items: pagesSpec.choices, initialValue: pagesSpec.default, onSubmit: choosePages, onCancel: () => setStep('target'), showHints: band !== 'compact' }), _jsx(HintBar, { width: width, pairs: [
|
|
1868
|
-
['↑↓', 'choose'],
|
|
1869
|
-
['↵', 'confirm'],
|
|
1870
|
-
['esc', 'back'],
|
|
1871
|
-
] })] })) : null, step === 'page-picker' && source && source.kind === 'document' ? (_jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [_jsx(PageGrid, { mode: "cell", pageCount: source.pages, selected: Array.isArray(values.pages) ? values.pages : [], cuts: [], onSubmit: submitPagePicker, onCancel: () => setStep('pages'), width: width, height: height }), _jsx(HintBar, { width: width, pairs: [
|
|
1872
|
-
['space', 'toggle'],
|
|
1873
|
-
['a', 'all'],
|
|
1874
|
-
['↵', 'confirm'],
|
|
1875
|
-
['esc', 'back'],
|
|
1876
|
-
] })] })) : null, step === 'dpi' && source && dpiSpec?.kind === 'select' ? (_jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [_jsx(Text, { color: colourProp(palette.label), children: dpiSpec.label }), _jsx(Select, { width: width, items: dpiSpec.choices, initialValue: dpiSpec.default, onSubmit: (dpi) => chooseDpi(source, dpi), onCancel: () => setStep(Array.isArray(values.pages) ? 'page-picker' : 'pages'), showHints: band !== 'compact' }), _jsx(HintBar, { width: width, pairs: [
|
|
1877
|
-
['↑↓', 'choose'],
|
|
1878
|
-
['↵', 'confirm'],
|
|
1879
|
-
['esc', 'back'],
|
|
1880
|
-
] })] })) : null, step === 'quality' && qualitySpec?.kind === 'slider' ? (_jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [_jsx(Slider, { label: qualitySpec.label, min: qualitySpec.min, max: qualitySpec.max, step: qualitySpec.step, value: typeof values.quality === 'number' ? values.quality : qualitySpec.default, onChange: (q) => setValues((v) => ({ ...v, quality: q })), onSubmit: chooseQuality, onCancel: () => setStep(dpiSpec ? 'dpi' : 'target') }), _jsx(HintBar, { width: width, pairs: [
|
|
1881
|
-
['←→', 'adjust'],
|
|
1882
|
-
['↵', 'confirm'],
|
|
1883
|
-
['esc', 'back'],
|
|
1884
|
-
] })] })) : null, step === 'destination' && destinationSpec?.kind === 'path' ? (_jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [_jsx(PathInput, { label: destinationSpec.label, presets: destinationSpec.presets, preview: previewDestination, onSubmit: confirmDestination, onCancel: destinationBack, width: width, showHints: band !== 'compact', defaultPath: expandTilde(livePrefs.defaultOutput), onMakeDefault: makeDefault }), _jsx(HintBar, { width: width, pairs: band === 'compact'
|
|
1885
|
-
? [['d', 'make default']]
|
|
1886
|
-
: [
|
|
1887
|
-
['↑↓', 'choose'],
|
|
1888
|
-
['↵', 'next'],
|
|
1889
|
-
['d', 'make default'],
|
|
1890
|
-
] })] })) : null, step === 'rename' && renaming ? (_jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [_jsx(Text, { color: colourProp(palette.label), children: "Name the file" }), _jsx(Prompt, { value: text, onChange: setText, onSubmit: submitRename, placeholder: "file name", isActive: true, variant: band === 'compact' ? 'plain' : 'field', width: width }), _jsx(Text, { color: colourProp(palette.dim), children: ` ${SYMBOLS.arrow} ${middleEllipsis(`${renaming.destination}/${text || renaming.stem}${renaming.ext}`, Math.max(12, width - 4))}` }), _jsx(HintBar, { width: width, pairs: [
|
|
1891
|
-
['↵', 'save'],
|
|
1892
|
-
['esc', 'clear / back'],
|
|
1893
|
-
] })] })) : null, step === 'overwrite' && pending ? (_jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [_jsx(Text, { children: `${middleEllipsis(basename(pending.output), Math.max(12, width - 16))} already exists` }), _jsx(Select, { width: width, items: [
|
|
1894
|
-
{ value: 'keep', label: 'Keep both', hint: basename(pending.keepBoth) },
|
|
1895
|
-
{ value: 'replace', label: 'Replace', hint: 'the existing file is lost' },
|
|
1896
|
-
{ value: 'cancel', label: 'Cancel', hint: 'pick a different folder' },
|
|
1897
|
-
], onSubmit: answerOverwrite, onCancel: () => {
|
|
1898
|
-
setPending(null);
|
|
1899
|
-
setStep('destination');
|
|
1900
|
-
}, showHints: band !== 'compact' }), _jsx(HintBar, { width: width, pairs: [
|
|
1901
|
-
['↑↓', 'choose'],
|
|
1902
|
-
['↵', 'confirm'],
|
|
1903
|
-
['esc', 'cancel'],
|
|
1904
|
-
] })] })) : null, step === 'size-unreachable' && sizeUnreachable ? (_jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [_jsx(Text, { children: `${source ? basename(source.path) : 'This file'} can't get below ${formatBytes(sizeUnreachable.smallest)} — you asked for ${formatBytes(sizeUnreachable.targetBytes)}.` }), _jsx(Select, { width: width, items: [
|
|
1905
|
-
{
|
|
1906
|
-
value: 'lowest',
|
|
1907
|
-
label: `Use ${formatBytes(sizeUnreachable.smallest)} anyway`,
|
|
1908
|
-
},
|
|
1909
|
-
{ value: 'size', label: 'Try a different target size' },
|
|
1910
|
-
{ value: 'quality', label: 'Compress by quality instead' },
|
|
1911
|
-
{ value: 'format', label: 'Convert to a different format' },
|
|
1912
|
-
], onSubmit: answerSizeUnreachable, onCancel: () => {
|
|
1913
|
-
setSizeUnreachable(null);
|
|
1914
|
-
clearSource();
|
|
1915
|
-
}, showHints: band !== 'compact' }), _jsx(HintBar, { width: width, pairs: [
|
|
1916
|
-
['↑↓', 'choose'],
|
|
1917
|
-
['↵', 'confirm'],
|
|
1918
|
-
['esc', 'cancel'],
|
|
1919
|
-
] })] })) : null, step === 'converting' ? (_jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [_jsx(Text, { color: colourProp(palette.dim), children: attempt ? 'Finding the right quality…' : 'Converting…' }), attempt ? (_jsxs(Text, { children: [_jsx(Text, { color: colourProp(palette.modeCompress), children: SYMBOLS.dotFilled.repeat(attempt.n) }), _jsx(Text, { color: colourProp(palette.border), children: SYMBOLS.dotEmpty.repeat(Math.max(0, attempt.of - attempt.n)) }), _jsx(Text, { color: colourProp(palette.dim), children: ` attempt ${attempt.n} of ${attempt.of}` })] })) : null, _jsx(HintBar, { width: width, pairs: [['esc', 'back — nothing is written yet']] })] })) : null, step === 'result' && lastResult ? (_jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [suggestion ? (_jsx(Box, { marginBottom: 1, children: _jsx(Text, { color: colourProp(palette.accent), children: `${SYMBOLS.tip} ${FORMATS[suggestion.target].label} would be ${formatBytes(suggestion.bytes)} — ${Math.round(suggestion.saving * 100)}% smaller again.` }) })) : null, mergeOffer ? (_jsx(Box, { marginBottom: 1, children: _jsx(Text, { color: colourProp(palette.accent), children: `${SYMBOLS.tip} ${mergeOffer} PDFs from this session could become one — /pdf, then Merge.` }) })) : null, mouseSupported() ? (_jsx(ResultLinks, { outputPath: lastResult.job.outputs[0], revealLabel: revealLabel(), onOpen: openLastResult, onReveal: revealLastResult })) : null, _jsxs(Box, { flexDirection: "column", width: width, borderStyle: "single", borderColor: colourProp(palette.border), borderBottom: false, borderLeft: false, borderRight: false, children: [_jsx(Hints, { pairs: [
|
|
1920
|
-
['↵', mode === 'compress' ? 'compress again' : 'convert another'],
|
|
1921
|
-
...(suggestion
|
|
1922
|
-
? [['c', `convert to ${FORMATS[suggestion.target].label}`]]
|
|
1923
|
-
: []),
|
|
1924
|
-
['o', 'open'],
|
|
1925
|
-
['s', revealLabel().toLowerCase()],
|
|
1926
|
-
['ctrl-c', 'close app'],
|
|
1927
|
-
] }), _jsx(Box, { width: width, paddingX: 1, marginTop: 1, backgroundColor: colourProp(modeBg), children: modeLine(false) })] })] })) : null, step === 'pdf' ? (_jsx(PdfFlow, { stage: stage, width: width, height: height, prefs: livePrefs, onDone: (jobs) => {
|
|
1928
|
-
void handlePdfDone(jobs);
|
|
1929
|
-
},
|
|
1930
|
-
// Keeps the stage rather than `clearSource`: `mode` is still
|
|
1931
|
-
// 'pdf' on the way back out (nothing here resets it), so
|
|
1932
|
-
// dropping a second PDF at idle re-enters the hub with both
|
|
1933
|
-
// staged — the escape hatch merge needs, now that a single
|
|
1934
|
-
// drop opens the hub directly instead of requiring `/pdf`
|
|
1935
|
-
// to be typed again. Abandoning the file entirely is still
|
|
1936
|
-
// one keystroke further: esc again at idle, on an empty
|
|
1937
|
-
// field, clears the stage the same way it already does
|
|
1938
|
-
// everywhere else in this file.
|
|
1939
|
-
onCancel: backToPromptKeepingStage })) : null, step === 'pdf-running' ? (_jsx(Box, { marginBottom: 1, children: pageProgress ? (_jsx(Progress, { label: pageProgressLabel(pageProgress.op), done: pageProgress.done, total: pageProgress.total, detail: pageProgress.detail, width: width })) : (_jsx(Text, { color: colourProp(palette.dim), children: "Running\u2026" })) })) : null, step === 'pdf-blocked' && pdfBlocked?.failures[0] ? (_jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [_jsxs(Text, { color: colourProp(palette.fail), children: [SYMBOLS.fail, " ", pdfBlocked.failures[0].error.title] }), _jsx(Text, { color: colourProp(palette.fg), children: ` ${pdfBlocked.failures[0].error.detail}` }), pdfBlocked.failures[0].error.code === 'output-exists' ? (_jsx(Select, { width: width, items: [
|
|
1940
|
-
{
|
|
1941
|
-
value: 'cancel',
|
|
1942
|
-
label: 'Cancel',
|
|
1943
|
-
// Says where it actually goes: a page operation run from
|
|
1944
|
-
// `/pdf` has only the hub to return to, but an ordinary
|
|
1945
|
-
// document conversion has its own destination step —
|
|
1946
|
-
// see `PendingPdfRefusal.cancelTo`'s doc comment.
|
|
1947
|
-
hint: pdfBlocked.cancelTo === 'destination'
|
|
1948
|
-
? 'pick a different folder, nothing written'
|
|
1949
|
-
: 'back to /pdf, nothing written',
|
|
1950
|
-
},
|
|
1951
|
-
{ value: 'replace', label: 'Replace', hint: 'overwrite the existing file' },
|
|
1952
|
-
], onSubmit: answerPdfBlocked, onCancel: () => answerPdfBlocked('cancel'), showHints: band !== 'compact' })) : (_jsx(Text, { color: colourProp(palette.dim), children: ' esc or enter to go back' })), _jsx(HintBar, { width: width, pairs: pdfBlocked.failures[0].error.code === 'output-exists'
|
|
1953
|
-
? [
|
|
1954
|
-
['↑↓', 'choose'],
|
|
1955
|
-
['↵', 'confirm'],
|
|
1956
|
-
['esc', 'cancel'],
|
|
1957
|
-
]
|
|
1958
|
-
: [['esc', 'back']] })] })) : null, step === 'idle' ? (_jsxs(Box, { flexDirection: "column", children: [isCommandBuffer(text) ? (_jsx(CommandPalette, { fragment: text.slice(1), width: width, onRun: runCommand, onCancel: () => setText('') })) : null, !isCommandBuffer(text) &&
|
|
1959
|
-
stage.sources.some((s) => s.kind === 'document' && s.format === 'pdf') ? (_jsx(Box, { marginBottom: 1, children: _jsx(Text, { color: colourProp(palette.dim), children: `${SYMBOLS.arrow} /pdf for page operations` }) })) : null, _jsx(Prompt, { value: text, onChange: setText, onSubmit: submitPath, placeholder: "drop a file or type a path", isActive: true, variant: band === 'compact' ? 'plain' : 'drop', width: width, rawOnSubmit: true, disableSubmit: paletteOwnsEscape }), _jsx(HintBar, { width: width, pairs: band === 'compact'
|
|
1960
|
-
? [
|
|
1961
|
-
['↵', 'send'],
|
|
1962
|
-
['/', 'commands'],
|
|
1963
|
-
]
|
|
1964
|
-
: [
|
|
1965
|
-
['↵', 'send'],
|
|
1966
|
-
['/', 'commands'],
|
|
1967
|
-
['esc', 'clear'],
|
|
1968
|
-
['ctrl-n', 'new'],
|
|
1969
|
-
['ctrl-c', 'close app'],
|
|
1970
|
-
] })] })) : null] }) }) }));
|
|
1971
|
-
}
|
|
1972
|
-
//# sourceMappingURL=App.js.map
|