pi-odd-worktree 2.0.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/README.md +54 -311
  2. package/extensions/odd-worktree-tools.ts +4149 -2447
  3. package/lib/bash-activity.js +1164 -0
  4. package/lib/bash-design.js +684 -0
  5. package/lib/bash-destructive.js +559 -0
  6. package/lib/bash-frame.js +205 -0
  7. package/lib/card-content.js +23 -0
  8. package/lib/card-style.js +175 -0
  9. package/lib/checkout-facts.js +30 -70
  10. package/lib/codegraph-card-preview.js +628 -0
  11. package/lib/codegraph-card.js +515 -0
  12. package/lib/codegraph-compaction.js +76 -0
  13. package/lib/codegraph-daemon.js +246 -0
  14. package/lib/codegraph-edit-sync.js +182 -0
  15. package/lib/codegraph-guard-target.js +337 -0
  16. package/lib/codegraph-guard.js +211 -0
  17. package/lib/codegraph-index.js +1020 -0
  18. package/lib/codegraph-lock.js +607 -0
  19. package/lib/codegraph-mcp-config.js +134 -0
  20. package/lib/codegraph-mcp.js +123 -0
  21. package/lib/codegraph-paths.js +69 -0
  22. package/lib/codegraph-prompt/explore.md +11 -0
  23. package/lib/codegraph-prompt/fix.md +6 -0
  24. package/lib/codegraph-prompt/generic.md +8 -0
  25. package/lib/codegraph-prompt/judge.md +9 -0
  26. package/lib/codegraph-prompt/orchestrator.md +17 -0
  27. package/lib/codegraph-prompt/verify.md +10 -0
  28. package/lib/codegraph-prompt/worker.md +7 -0
  29. package/lib/codegraph-role.js +55 -0
  30. package/lib/codegraph-rules.js +146 -0
  31. package/lib/codegraph-session.js +303 -383
  32. package/lib/codegraph-warmup.js +139 -0
  33. package/lib/file-card-markdown.js +141 -0
  34. package/lib/file-card-resolver.js +245 -0
  35. package/lib/file-card.js +659 -0
  36. package/lib/files-index.js +387 -0
  37. package/lib/files-insert.js +81 -0
  38. package/lib/files-orders.js +326 -0
  39. package/lib/files-picker-view.js +1416 -0
  40. package/lib/files-preview.js +338 -0
  41. package/lib/files-scope-detail.js +171 -0
  42. package/lib/files-scope-view.js +507 -0
  43. package/lib/gh-issues.js +308 -14
  44. package/lib/issue-preview.js +26 -7
  45. package/lib/issues-bash-mutation.js +206 -0
  46. package/lib/issues-cache-store.js +261 -0
  47. package/lib/issues-section.js +710 -0
  48. package/lib/issues-view.js +649 -52
  49. package/lib/odd-prompt/odd-worktrees.md +21 -0
  50. package/lib/odd-worktrees-prompt.js +10 -28
  51. package/lib/related-issues-cache.js +210 -0
  52. package/lib/shell-card.js +825 -0
  53. package/lib/skill-odd-card.js +183 -0
  54. package/lib/tui-paint.js +4 -5
  55. package/lib/warp-create-panel.js +538 -250
  56. package/lib/warp-create-picker.js +56 -9
  57. package/lib/warp-delete-confirm.js +19 -28
  58. package/lib/warp-selector-view.js +160 -82
  59. package/lib/which-command.js +90 -0
  60. package/lib/worktree-card.js +267 -897
  61. package/lib/worktree-cards.js +383 -0
  62. package/lib/worktree-create.js +287 -0
  63. package/lib/worktree-git.js +3 -3
  64. package/lib/worktree-guard.js +548 -0
  65. package/lib/worktree-hooks.js +421 -711
  66. package/lib/worktree-list.js +120 -0
  67. package/lib/worktree-registry.js +162 -879
  68. package/lib/{worktree-close-herdr.js → worktree-remove.js} +9 -11
  69. package/lib/worktree-setup-runner.js +376 -0
  70. package/lib/worktree-setup.js +140 -0
  71. package/lib/worktree-warp-busy.js +462 -85
  72. package/lib/worktree-warp-sessions.js +1 -2
  73. package/package.json +2 -2
  74. package/tools/bash-activity.test.js +1419 -0
  75. package/tools/bash-design.test.js +1091 -0
  76. package/tools/bash-destructive.test.js +139 -0
  77. package/tools/card-content.test.js +44 -0
  78. package/tools/card-style.test.js +298 -0
  79. package/tools/codegraph-card-preview.test.js +254 -0
  80. package/tools/codegraph-card.test.js +1080 -0
  81. package/tools/codegraph-compaction.test.js +378 -0
  82. package/tools/codegraph-daemon.test.js +248 -0
  83. package/tools/codegraph-edit-sync.test.js +295 -0
  84. package/tools/codegraph-guard-target.test.js +174 -0
  85. package/tools/codegraph-guard.test.js +238 -0
  86. package/tools/codegraph-index.test.js +1948 -0
  87. package/tools/codegraph-lock.test.js +932 -0
  88. package/tools/codegraph-mcp-config.test.js +181 -0
  89. package/tools/codegraph-mcp.test.js +194 -0
  90. package/tools/codegraph-paths.test.js +44 -0
  91. package/tools/codegraph-role.test.js +30 -0
  92. package/tools/codegraph-rules.test.js +250 -0
  93. package/tools/codegraph-session.test.js +660 -391
  94. package/tools/codegraph-warmup.test.js +316 -0
  95. package/tools/commands.test.js +510 -31
  96. package/tools/file-card-markdown.test.js +188 -0
  97. package/tools/file-card.test.js +1289 -0
  98. package/tools/files-bridge.test.js +575 -0
  99. package/tools/files-command.test.js +610 -0
  100. package/tools/files-index.test.js +473 -0
  101. package/tools/files-insert.test.js +139 -0
  102. package/tools/files-orders.test.js +597 -0
  103. package/tools/files-picker-view.test.js +1871 -0
  104. package/tools/files-preview.test.js +452 -0
  105. package/tools/files-scope-detail.test.js +264 -0
  106. package/tools/files-scope-view.test.js +614 -0
  107. package/tools/fixtures/card-codegraph-outputs.js +110 -0
  108. package/tools/fixtures/codegraph-cli-stub.js +16 -0
  109. package/tools/fixtures/codegraph-init-process.js +28 -0
  110. package/tools/fixtures/codegraph-lock-worker.js +117 -0
  111. package/tools/fixtures/daemon-fake.js +98 -0
  112. package/tools/fixtures/daemon-mcp-server.js +39 -0
  113. package/tools/fixtures/daemon-warmup-worker.js +12 -0
  114. package/tools/fixtures/load-extension.js +136 -3
  115. package/tools/gh-issues-feedback.test.js +31 -7
  116. package/tools/gh-issues.test.js +391 -1
  117. package/tools/issue-preview.test.js +44 -7
  118. package/tools/issues-bash-mutation.test.js +101 -0
  119. package/tools/issues-cache-store.test.js +222 -0
  120. package/tools/issues-command.test.js +1512 -66
  121. package/tools/issues-open-guard.test.js +1096 -0
  122. package/tools/issues-section.test.js +4195 -0
  123. package/tools/issues-seed-query-regression.test.js +67 -0
  124. package/tools/issues-view.test.js +1489 -60
  125. package/tools/odd-worktrees-prompt.test.js +98 -65
  126. package/tools/package-surface.test.js +431 -36
  127. package/tools/related-issues-cache.test.js +324 -0
  128. package/tools/shell-card.test.js +834 -0
  129. package/tools/skill-odd-card.test.js +200 -0
  130. package/tools/t5-session-identity.test.js +44 -22
  131. package/tools/warp-busy-guard.test.js +2569 -308
  132. package/tools/warp-create-panel.test.js +499 -74
  133. package/tools/warp-create-picker.test.js +101 -5
  134. package/tools/warp-delete-confirm.test.js +49 -15
  135. package/tools/warp-empty-session.test.js +0 -1
  136. package/tools/warp-fallback-regression.test.js +533 -0
  137. package/tools/warp-selector-view.test.js +460 -196
  138. package/tools/which-command.test.js +126 -0
  139. package/tools/worktree-card.test.js +551 -0
  140. package/tools/worktree-cards.test.js +845 -0
  141. package/tools/worktree-changes.test.js +4 -5
  142. package/tools/worktree-create.test.js +489 -0
  143. package/tools/worktree-guard.test.js +823 -0
  144. package/tools/worktree-hooks.test.js +905 -0
  145. package/tools/worktree-list.test.js +170 -0
  146. package/tools/worktree-registry.test.js +89 -230
  147. package/tools/worktree-remove-async.test.js +318 -0
  148. package/tools/worktree-setup-runner.test.js +276 -0
  149. package/tools/worktree-setup.test.js +140 -0
  150. package/tools/worktree-tools.test.js +477 -93
  151. package/lib/codegraph-commands.js +0 -165
  152. package/lib/odd-prompt/odd-worktrees.with-codegraph.md +0 -19
  153. package/lib/odd-prompt/odd-worktrees.without-codegraph.md +0 -15
  154. package/lib/worktree-model-result.js +0 -291
  155. package/tools/codegraph-commands.test.js +0 -371
  156. package/tools/herdr-free-create.test.js +0 -161
  157. package/tools/worktree-close-herdr-async.test.js +0 -204
  158. package/tools/worktree-odd-migration.test.js +0 -224
  159. package/tools/worktree-registry-cache.test.js +0 -163
  160. package/tools/worktree-registry-odd.test.js +0 -231
@@ -0,0 +1,1416 @@
1
+ 'use strict';
2
+ // T6 (files-picker S1-S6, S14, S15): the file picker overlay `/files` opens on
3
+ // one checkout. It is a COMPOSITION, never a second copy of the rules it paints:
4
+ //
5
+ // - the listing, its change state and its ages come from `lib/files-index.js`
6
+ // through the injected `loadEntries` / `loadPreview` seams (T1);
7
+ // - the three orders, their foldable trees and the per-order fold state come
8
+ // from `lib/files-orders.js` (T4): this view only owns the fold SETS and
9
+ // hands them in;
10
+ // - the preview pane, its own box, the `line/total` position, the gutter and
11
+ // the ANSI-aware wrap come from `lib/files-preview.js` (T5): this view paints
12
+ // the cells it returns and never builds one itself;
13
+ // - the frame, the tones and the row chrome come from `lib/shell-card.js`, the
14
+ // key/label vocabulary from `lib/tui-paint.js`, and the measurement and the
15
+ // list window from `lib/view-layout.js`.
16
+ //
17
+ // PAINT LAST (AGENTS.md invariant 17): every row is composed, clipped and padded
18
+ // as PLAIN text and only then painted in its roles, so the injected helpers never
19
+ // measure an escape sequence this repo composed. The four pieces of state a key
20
+ // changes — the query, the order, the per-order folds and the Tab selection — are
21
+ // the picker's own; everything else is read from the modules above.
22
+ //
23
+ // Round L9 (S22, S24, S25, S26) reshaped the body around the same seams: an info
24
+ // row between the search row and the list, the preview box riding that row and
25
+ // closing on the list's last row, a rule under the body and a mark bar painted in a
26
+ // theme role. Its "a cursor only rests on file rows" rule is superseded by S38: the
27
+ // cursor takes every row, while S24's mark, insert and open refusals for a group row
28
+ // stand. The geometry is computed once per render and both the paint and the hit map
29
+ // read it.
30
+ //
31
+ // Round L11 (S29-S34) is the trees' round, and it owns no rule the order module
32
+ // does not already answer: both trees open folded with a `▾`/`▸` chevron in the
33
+ // marker column (S29), an order change replaces that order's fold set with `foldsFor`
34
+ // so only the highlighted file's own groups are open (S30), group rows paint in
35
+ // the grey role (S31), and the flat order is `files`, where neither fold key is
36
+ // named or has any effect (S32, S33). This view still only owns the fold SETS and
37
+ // hands them in.
38
+ //
39
+ // Round L12 (S37-S40) moves the title's two ends and the cursor: the listing path
40
+ // rides the panel's own title at the left, elided from its own left so the tail
41
+ // identifying the checkout survives (S37), `esc` keeps the far-right corner alone,
42
+ // every row of a tree order takes the cursor while `tab` stays inert there (S38),
43
+ // `shift+space` is one toggle over every group with the cursor left on the group
44
+ // that held the file (S39), and the footer legend names the action it performs
45
+ // (S40).
46
+ //
47
+ // The shapes it consumes are the module contracts in `odd/tasks/files-picker.md`:
48
+ // `loadEntries()` resolves `{ ok: true, entries } | { ok: false, message }` with
49
+ // entries already changed-first; `loadPreview(path)` resolves one
50
+ // `lib/files-index.js` preview object; `buildRows(entries, { order, folded,
51
+ // query })` answers the rows; `previewRows(preview, { width, height, scroll,
52
+ // highlight, languageForPath, path, metrics })` answers exact-width cells.
53
+ //
54
+ // Nothing here reads a file, spawns a process, paints a card into the transcript
55
+ // or decides which overlay the session is in: the wiring (T7) resolves the scope,
56
+ // reads the listing, formats the inserted references and stops the terminal for
57
+ // the editor. This module answers keys, hits and rows.
58
+
59
+ const { CARD_GLYPH, CARD_TONE, cardBottom, cardInnerWidth, cardTop } = require('./shell-card.js');
60
+ const {
61
+ highlight: paintFocused,
62
+ key: keyText,
63
+ label,
64
+ legendRow,
65
+ paint,
66
+ value,
67
+ } = require('./tui-paint.js');
68
+ const { measure, scrollWindow } = require('./view-layout.js');
69
+ const { ORDERS, buildRows, everyGroupFolded, foldsFor, holderGroup, holderKeys, nextOrder, toggleEveryFold, toggleFold } = require('./files-orders.js');
70
+ const { previewRows } = require('./files-preview.js');
71
+ const { formatAge } = require('./files-index.js');
72
+
73
+ const TITLE = 'Files';
74
+ // The tone every informational card uses; its frame role is the theme's plain
75
+ // `border` (lib/shell-card.js FRAME_ROLE), which is why the side cells and the
76
+ // pane rule below are painted with that one role.
77
+ const TONE = CARD_TONE.INFO;
78
+ const FRAME_ROLE = 'border';
79
+ const FRAME_SIDE = '\u2502'; // │
80
+ const PANE_RULE = '\u2502'; // │
81
+ // The ` │ ` between the two panes: one blank cell, the rule, one blank cell.
82
+ const PANE_RULE_COLUMNS = 3;
83
+ // The list pane's share of the card content width and its cap (S15), so longer
84
+ // names and paths fit while the preview keeps the rest.
85
+ const LIST_SHARE = 0.45;
86
+ const LIST_MAX_WIDTH = 64;
87
+ // The card takes the room the terminal offers instead of a short fixed card (S15).
88
+ const HEIGHT_RATIO = 0.85;
89
+ // The rows the card spends on chrome: the top rule, the search row, the info row
90
+ // (S22), the footer and the bottom rule. The rule that closes the body under both
91
+ // columns is counted apart, so the body keeps its own row budget (S25).
92
+ const CHROME_ROWS = 5;
93
+ // The columns `cardTop` spends around a heading: the corner, the lead, the space
94
+ // before the filling rule, the space after it and the far corner. The ` esc ` hint
95
+ // costs five more and the heading's own ` · ` separator three (S37).
96
+ const TOP_CHROME_COLUMNS = 5;
97
+ const CLOSE_HINT = 'esc';
98
+ const HINT_COLUMNS = CLOSE_HINT.length + 2;
99
+ const TITLE_SEPARATOR_COLUMNS = 3;
100
+ // The fewest columns a left-elided path is worth painting beside the title.
101
+ const MIN_DETAIL_COLUMNS = 4;
102
+ const BODY_RULE_ROWS = 1;
103
+ const MIN_CARD_HEIGHT = CHROME_ROWS + 1;
104
+ const MIN_WIDTH = 20;
105
+ // 0-based row of the first body row: the top rule, the search row and the info row.
106
+ const BODY_TOP = 3;
107
+ // The row the info row paints, which is also where the preview's box top border
108
+ // and the unboxed fallback's position row ride (S25).
109
+ const INFO_TOP = BODY_TOP - 1;
110
+ // The rule that closes the body under both columns, on its own row (S25).
111
+ const BODY_RULE = '\u2500'; // ─
112
+ // The cursor cell, the Tab selection cell and the space before the name. It is
113
+ // the same in every row state, so marking a row never moves it (S7).
114
+ const MARKER_WIDTH = 3;
115
+ const CURSOR_MARK = '\u25b8'; // ▸
116
+ const SELECTION_MARK = '\u258f'; // ▏
117
+ // S29: the fold state a group row shows, in the marker column's Tab cell — the one
118
+ // cell a group row never fills, because a group is never marked (S24). The column
119
+ // keeps its three cells, so a group name and a file name start in the same one.
120
+ const GROUP_EXPANDED_MARK = '\u25be'; // ▾
121
+ const GROUP_COLLAPSED_MARK = '\u25b8'; // ▸
122
+ // The flat order's id (S33): the listing without groups, so `space` has nothing to
123
+ // fold there and the footer never names it (S32).
124
+ const FLAT_ORDER = ORDERS[0];
125
+ // One level of the `tree` order's nesting.
126
+ const GROUP_INDENT = 2;
127
+ const SEARCH_PROMPT = '\u203a'; // ›
128
+ const SEARCH_PLACEHOLDER = 'Search';
129
+ // The row a pending or absent body paints, so the card never claims a listing it
130
+ // does not have (S13).
131
+ const LOADING_FILES = 'Loading files \u2026';
132
+ const LOADING_PREVIEW = 'Loading preview \u2026';
133
+ const NO_FILES = 'No files in this repository.';
134
+ const UNTRACKED_BADGE = 'U';
135
+ const MODIFIED_BADGE = 'M';
136
+ // S38: a group row is a row the cursor rests on and it holds no file, so the preview
137
+ // keeps its box and says so — in the one notice shape T5 gives a preview with no
138
+ // numbered lines — instead of claiming a `line/total` position or blanking the pane.
139
+ const NO_FILE_SELECTED = 'No file selected.';
140
+
141
+ // A preview that has not landed yet paints as the notice shape T5 already knows:
142
+ // one message, no line number and no `line/total` position to claim.
143
+ const PENDING_PREVIEW = Object.freeze({ kind: 'binary', message: LOADING_PREVIEW });
144
+ // S38: the same shape for a row that holds no file at all.
145
+ const NO_FILE_PREVIEW = Object.freeze({ kind: 'binary', message: NO_FILE_SELECTED });
146
+
147
+ // The footer (S4): ONE option per key even when several work. `ctrl+c` closes and
148
+ // `ctrl+shift+j`/`ctrl+shift+k` scroll, `home`/`end` jump and `ctrl+home`/
149
+ // `ctrl+end` reach the preview's edges, but no key hint names them.
150
+ const FOOTER_ENTRIES = Object.freeze([
151
+ { key: '\u2191/\u2193', text: '\u2191/\u2193 move', short: '\u2191/\u2193', priority: 90 },
152
+ { key: 'tab', text: 'tab select', short: 'tab', priority: 80 },
153
+ { key: 'ctrl+j/k', text: 'ctrl+j/k scroll', short: 'ctrl+j/k', priority: 30 },
154
+ { key: 'ctrl+o', text: 'ctrl+o order', short: 'ctrl+o', priority: 45 },
155
+ { key: 'ctrl+u', text: 'ctrl+u clear', short: 'ctrl+u', priority: 40 },
156
+ { key: 'ctrl+e', text: 'ctrl+e edit', short: 'ctrl+e', priority: 60 },
157
+ { key: 'enter', text: 'enter insert', short: 'enter', priority: 95 },
158
+ { key: 'esc', text: 'esc close', short: 'esc', priority: 100 },
159
+ ]);
160
+
161
+ // The two fold keys a TREE order adds (S32), after `ctrl+o order` where S4 placed
162
+ // `space fold`. The flat `files` order paints no group, so it names neither.
163
+ const SPACE_FOLD_ENTRY = Object.freeze({ key: 'space', text: 'space fold', short: 'space', priority: 50 });
164
+ // S40: the shift+space entry states the action the key would perform now, so the
165
+ // legend answers "what happens if I press it" instead of repeating the chord.
166
+ const SHIFT_EXPAND_ENTRY = Object.freeze({
167
+ key: 'shift+space',
168
+ text: 'shift+space expand all',
169
+ short: 'shift+space',
170
+ priority: 35,
171
+ });
172
+ const SHIFT_COLLAPSE_ENTRY = Object.freeze({
173
+ key: 'shift+space',
174
+ text: 'shift+space collapse all',
175
+ short: 'shift+space',
176
+ priority: 35,
177
+ });
178
+ // The legend position the fold keys occupy: after move, select, scroll and order.
179
+ const FOLD_FOOTER_AT = 4;
180
+ // Both tree legends, built once: the same entries with the two fold keys spliced in
181
+ // where S4 placed `space fold`, so a render never rebuilds either of them (S40).
182
+ function treeLegend(shiftEntry) {
183
+ return Object.freeze([
184
+ ...FOOTER_ENTRIES.slice(0, FOLD_FOOTER_AT),
185
+ SPACE_FOLD_ENTRY,
186
+ shiftEntry,
187
+ ...FOOTER_ENTRIES.slice(FOLD_FOOTER_AT),
188
+ ]);
189
+ }
190
+ const TREE_LEGEND_EXPAND = treeLegend(SHIFT_EXPAND_ENTRY);
191
+ const TREE_LEGEND_COLLAPSE = treeLegend(SHIFT_COLLAPSE_ENTRY);
192
+
193
+ // The key names a hostile terminal hands over as a raw sequence, spelled the way
194
+ // this view names them, so every binding works with no `matchesKey` in reach.
195
+ const KEY_SEQUENCES = Object.freeze({
196
+ '\r': 'enter',
197
+ '\n': 'ctrl+j',
198
+ '\t': 'tab',
199
+ '\x1b': 'escape',
200
+ '\x7f': 'backspace',
201
+ '\b': 'backspace',
202
+ '\x03': 'ctrl+c',
203
+ '\x05': 'ctrl+e',
204
+ '\x0f': 'ctrl+o',
205
+ '\x15': 'ctrl+u',
206
+ '\x0b': 'ctrl+k',
207
+ '\x0a': 'ctrl+j',
208
+ ' ': 'space',
209
+ '\x1b[A': 'up',
210
+ '\x1b[B': 'down',
211
+ '\x1b[H': 'home',
212
+ '\x1bOH': 'home',
213
+ '\x1b[1~': 'home',
214
+ '\x1b[7~': 'home',
215
+ '\x1b[F': 'end',
216
+ '\x1bOF': 'end',
217
+ '\x1b[4~': 'end',
218
+ '\x1b[8~': 'end',
219
+ '\x1b[1;5H': 'ctrl+home',
220
+ '\x1b[7;5~': 'ctrl+home',
221
+ '\x1b[1;5F': 'ctrl+end',
222
+ '\x1b[8;5~': 'ctrl+end',
223
+ // The page moves are compatibility bindings S4 never names, like home/end (S38).
224
+ '\x1b[5~': 'pageup',
225
+ '\x1b[6~': 'pagedown',
226
+ '\x1b[106;6u': 'ctrl+shift+j',
227
+ '\x1b[107;6u': 'ctrl+shift+k',
228
+ '\x1b[106;5u': 'ctrl+j',
229
+ '\x1b[107;5u': 'ctrl+k',
230
+ // S39's key, in the two shapes a terminal actually delivers: Kitty CSI-u
231
+ // (codepoint 32, modifier value 2 = shift) and xterm modifyOtherKeys. The host's
232
+ // own `matchesKey(data, 'shift+space')` accepts both; a legacy terminal cannot
233
+ // tell the chord from a plain space, so it stays the `space fold` key there.
234
+ '\x1b[32;2u': 'shift+space',
235
+ '\x1b[27;2;32~': 'shift+space',
236
+ });
237
+
238
+ // The card substrate and the palette both call the injected theme directly, and
239
+ // only the palette guards a throwing one. The view wraps it once here, so a
240
+ // missing, partial or hostile theme leaves the text plain instead of breaking a
241
+ // render — the same guarantee `lib/tui-paint.js` gives on its own.
242
+ function guardedTheme(theme) {
243
+ const source = theme !== null && typeof theme === 'object' ? theme : {};
244
+ const call = (name, role, text) => {
245
+ try {
246
+ if (typeof source[name] === 'function') {
247
+ const painted = name === 'bold' ? source[name](text) : source[name](role, text);
248
+ if (typeof painted === 'string') return painted;
249
+ }
250
+ } catch {
251
+ // Fall through to the plain text.
252
+ }
253
+ return String(text);
254
+ };
255
+ return {
256
+ fg: (role, text) => call('fg', role, text),
257
+ bg: (role, text) => call('bg', role, text),
258
+ bold: (text) => call('bold', undefined, text),
259
+ };
260
+ }
261
+
262
+ // The sanitizer a terminal value passes before it is measured: no escape
263
+ // sequence and no control character reaches a painted row, so a path or a query
264
+ // can never move the cursor or break the frame.
265
+ function sanitize(value) {
266
+ const text = typeof value === 'string' ? value : (value == null ? '' : String(value));
267
+ return text
268
+ .replace(/\x1b\[[0-9;]*m/g, '')
269
+ .replace(/\x1b\][^\x07]*\x07/g, '')
270
+ .replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, ' ');
271
+ }
272
+
273
+ function errorMessage(error) {
274
+ return error instanceof Error ? error.message : String(error);
275
+ }
276
+
277
+ // One sentence a panel can paint, with exactly one full stop — the same rule
278
+ // lib/files-index.js uses for the messages it hands this view.
279
+ function sentence(text) {
280
+ const trimmed = String(text === undefined || text === null ? '' : text).trim();
281
+ if (trimmed.length === 0) return '';
282
+ return /[.!?]$/.test(trimmed) ? trimmed : `${trimmed}.`;
283
+ }
284
+
285
+ // One single Basic-Multilingual-Plane printable character: a paste is never a
286
+ // keystroke, so it never lands in the query (S3).
287
+ function isSinglePrintable(data) {
288
+ if (typeof data !== 'string' || data.length !== 1) return false;
289
+ const code = data.charCodeAt(0);
290
+ return code >= 0x20 && code !== 0x7f;
291
+ }
292
+
293
+ /**
294
+ * Mount the file picker (S1-S6, S14, S15).
295
+ *
296
+ * @param {object} options
297
+ * @param {object} [options.theme] the host theme; a missing or hostile one leaves text plain.
298
+ * @param {object} [options.helpers] `visibleWidth`/`truncateToWidth`/`wrapTextWithAnsi`/`matchesKey`/`isKeyRelease`, injected.
299
+ * @param {number|Function} [options.rowsAvailable] the terminal rows the host offers, or a reader for them.
300
+ * @param {{root: string, kind: 'main'|'worktree', label: string}} [options.scope] the checkout being listed; its `root` rides the title at the left (S37).
301
+ * @param {string} [options.cwd] the session cwd; the picker emits relative paths, so it only documents the scope.
302
+ * @param {Function} options.loadEntries `() -> Promise<{ok: true, entries} | {ok: false, message}>` (lib/files-index.js).
303
+ * @param {Function} options.loadPreview `(relativePath) -> Promise<preview>` (lib/files-index.js shape).
304
+ * @param {Function} [options.highlight] `(code, language) -> string[]` (the host's `highlightCode`).
305
+ * @param {Function} [options.languageForPath] `(path) -> string|undefined` (the host's `getLanguageFromPath`).
306
+ * @param {number} [options.now] the clock a row age falls back to; defaults to `Date.now()`, read once.
307
+ * @param {Function} [options.onInsert] called with the chosen relative paths, in list order.
308
+ * @param {Function} [options.onOpen] called with the highlighted relative path for `ctrl+e`.
309
+ * @param {Function} [options.onClose] called to settle the overlay.
310
+ * @param {Function} [options.requestRender] called when a key or mouse event changed what is painted.
311
+ * @returns {{render: Function, handleInput: Function, handleMouse: Function, invalidate: Function, dispose: Function}}
312
+ */
313
+ function createFilesPickerView(options = {}) {
314
+ const opts = options !== null && typeof options === 'object' ? options : {};
315
+ const theme = guardedTheme(opts.theme);
316
+ const helpers = opts.helpers !== null && typeof opts.helpers === 'object' ? opts.helpers : {};
317
+ const rowsAvailable = opts.rowsAvailable;
318
+ const scope = opts.scope !== null && typeof opts.scope === 'object' ? opts.scope : {};
319
+ const loadEntries = typeof opts.loadEntries === 'function' ? opts.loadEntries : null;
320
+ const loadPreview = typeof opts.loadPreview === 'function' ? opts.loadPreview : null;
321
+ const highlighter = typeof opts.highlight === 'function' ? opts.highlight : undefined;
322
+ const languageForPath = typeof opts.languageForPath === 'function' ? opts.languageForPath : undefined;
323
+ const onInsert = typeof opts.onInsert === 'function' ? opts.onInsert : null;
324
+ const onOpen = typeof opts.onOpen === 'function' ? opts.onOpen : null;
325
+ const onClose = typeof opts.onClose === 'function' ? opts.onClose : null;
326
+ const requestRender = typeof opts.requestRender === 'function' ? opts.requestRender : null;
327
+ // The ages are computed once when the panel opens and never refreshed live (S6).
328
+ const now = Number.isFinite(Number(opts.now)) ? Number(opts.now) : Date.now();
329
+ const titleHeadWidth = measure(helpers, `${CARD_GLYPH} ${TITLE}`);
330
+
331
+ let query = '';
332
+ let order = ORDERS[0];
333
+ let selected = 0;
334
+ let previewScroll = 0;
335
+ let previewScrollLimit = 0;
336
+ // The rows one page move crosses: the body rows the last paint showed, so a page
337
+ // is exactly what the reader can see.
338
+ let pageRows = 1;
339
+ let hovered;
340
+ let pointerFrame;
341
+ let entries = [];
342
+ let loaded = false;
343
+ let listingError;
344
+ const foldedByOrder = new Map();
345
+ // Tab multi-select (S7): the paths, in the order the reader marked them.
346
+ const selection = new Set();
347
+ // One preview per path, read once; a failed read keeps its own sentence.
348
+ const previews = new Map();
349
+ let completed = false;
350
+ let disposed = false;
351
+
352
+ const CARD = Object.freeze({ title: TITLE, tone: TONE });
353
+ const BLANK_ITEM = Object.freeze({ painted: '', width: 0 });
354
+
355
+ function repaint() {
356
+ try {
357
+ if (requestRender !== null) requestRender();
358
+ } catch {
359
+ // A hostile host callback never breaks the panel.
360
+ }
361
+ }
362
+
363
+ function clipPlain(text, room) {
364
+ const value = sanitize(text);
365
+ if (room <= 0) return '';
366
+ if (measure(helpers, value) <= room) return value;
367
+ try {
368
+ if (typeof helpers.truncateToWidth === 'function') {
369
+ const cut = helpers.truncateToWidth(value, room, '\u2026');
370
+ if (typeof cut === 'string') return cut;
371
+ }
372
+ } catch {
373
+ // Fall through to the plain codepoint slice.
374
+ }
375
+ const chars = [...value];
376
+ return chars.length <= room ? value : `${chars.slice(0, Math.max(0, room - 1)).join('')}\u2026`;
377
+ }
378
+
379
+ // Keep the tail of a path, which is what identifies the checkout.
380
+ function elideLeft(text, room) {
381
+ const value = sanitize(text);
382
+ if (room <= 0) return '';
383
+ if (measure(helpers, value) <= room) return value;
384
+ const chars = [...value];
385
+ let tail = '';
386
+ for (let index = chars.length - 1; index >= 0; index -= 1) {
387
+ const candidate = `${chars[index]}${tail}`;
388
+ if (measure(helpers, candidate) > room - 1) break;
389
+ tail = candidate;
390
+ }
391
+ return `\u2026${tail}`;
392
+ }
393
+
394
+ // The measurement seam the substrate takes: the same injected helpers the rows
395
+ // are measured with, so a paint and a clip can never disagree.
396
+ const metrics = {
397
+ visibleWidth: (text) => measure(helpers, text),
398
+ truncateToWidth(text, width, ellipsis) {
399
+ try {
400
+ if (typeof helpers.truncateToWidth === 'function') {
401
+ const cut = helpers.truncateToWidth(text, width, ellipsis);
402
+ if (typeof cut === 'string') return cut;
403
+ }
404
+ } catch {
405
+ // Fall through to the plain codepoint slice.
406
+ }
407
+ const chars = [...String(text)];
408
+ return chars.length > width
409
+ ? `${chars.slice(0, Math.max(0, width - 1)).join('')}${ellipsis === undefined ? '' : ellipsis}`
410
+ : String(text);
411
+ },
412
+ wrapTextWithAnsi(text, width) {
413
+ try {
414
+ if (typeof helpers.wrapTextWithAnsi === 'function') {
415
+ const rows = helpers.wrapTextWithAnsi(text, width);
416
+ if (Array.isArray(rows)) return rows;
417
+ }
418
+ } catch {
419
+ // Fall through to the plain codepoint split.
420
+ }
421
+ const chars = [...String(text)];
422
+ const rows = [];
423
+ for (let at = 0; at < chars.length; at += Math.max(1, width)) {
424
+ rows.push(chars.slice(at, at + Math.max(1, width)).join(''));
425
+ }
426
+ return rows.length > 0 ? rows : [''];
427
+ },
428
+ };
429
+
430
+ function frameSide() {
431
+ return paint(theme, FRAME_ROLE, FRAME_SIDE);
432
+ }
433
+
434
+ // One row of the card's body, framed with the same chrome `cardLine` draws. The
435
+ // content is PLAIN and exactly the inner width; its roles are painted already.
436
+ function frameRow(paintedContent) {
437
+ const side = frameSide();
438
+ return `${side} ${paintedContent} ${side}`;
439
+ }
440
+
441
+ function cardHeight() {
442
+ let available = rowsAvailable;
443
+ if (typeof available === 'function') {
444
+ try {
445
+ available = available();
446
+ } catch {
447
+ return 0;
448
+ }
449
+ }
450
+ const value = Number(available);
451
+ if (!Number.isFinite(value)) return 0;
452
+ const rows = Math.max(0, Math.floor(value));
453
+ // The overlay hands the picker the whole terminal, so the card takes its
454
+ // share of it and never more than it was given (S15).
455
+ return Math.min(rows, Math.max(MIN_CARD_HEIGHT, Math.floor(rows * HEIGHT_RATIO)));
456
+ }
457
+
458
+ function paneLayout(inner) {
459
+ const listWidth = Math.max(1, Math.min(LIST_MAX_WIDTH, Math.floor(inner * LIST_SHARE)));
460
+ const previewWidth = Math.max(0, inner - listWidth - PANE_RULE_COLUMNS);
461
+ return { listWidth, previewWidth };
462
+ }
463
+
464
+ // ---- the listing, the rows and the fold state -----------------------------
465
+
466
+ function currentFolds() {
467
+ let folded = foldedByOrder.get(order);
468
+ if (!folded) {
469
+ // S29: an order that has not been chosen yet opens with every group folded.
470
+ // Choosing one runs `foldsFor` with the highlighted path instead (S30).
471
+ folded = foldsFor(entries, order, undefined);
472
+ foldedByOrder.set(order, folded);
473
+ }
474
+ return folded;
475
+ }
476
+
477
+ function rows() {
478
+ return buildRows(entries, { order, folded: currentFolds(), query });
479
+ }
480
+
481
+ function selectedRow() {
482
+ const list = rows();
483
+ if (list.length === 0) return undefined;
484
+ return list[Math.max(0, Math.min(list.length - 1, selected))];
485
+ }
486
+
487
+ function selectedPath() {
488
+ const row = selectedRow();
489
+ return row !== undefined && row.kind === 'file' ? row.entry.path : undefined;
490
+ }
491
+
492
+ // A file row is the only row that can be previewed, marked, inserted or opened —
493
+ // S24's refusals for a group row stand — while the cursor itself takes every row
494
+ // of a tree order (S38).
495
+ function isFileRow(row) {
496
+ return row !== undefined && row.kind === 'file';
497
+ }
498
+
499
+ // The last row of the list (S38): `end` stops there, group row or file row.
500
+ function lastRow() {
501
+ return Math.max(0, rows().length - 1);
502
+ }
503
+
504
+ /** An index clamped into the list: every row of a tree order takes the cursor (S38). */
505
+ function clampRow(list, index) {
506
+ if (list.length === 0) return 0;
507
+ return Math.max(0, Math.min(list.length - 1, Number.isFinite(index) ? Math.trunc(index) : 0));
508
+ }
509
+
510
+ /** Move the cursor to `index`, clamped; true when it moved. */
511
+ function selectRow(index) {
512
+ const list = rows();
513
+ if (list.length === 0) return false;
514
+ const next = clampRow(list, index);
515
+ if (next === selected) return false;
516
+ selected = next;
517
+ previewScroll = 0;
518
+ return true;
519
+ }
520
+
521
+ /**
522
+ * One arrow, wheel or page step (S5, S38). Every row is a row the cursor may rest
523
+ * on, a folder or extension group included, and a step past either end changes
524
+ * nothing.
525
+ */
526
+ function moveSelection(delta) {
527
+ const step = Number(delta);
528
+ if (!Number.isFinite(step) || step === 0) return false;
529
+ return selectRow(selected + Math.trunc(step));
530
+ }
531
+
532
+ function setQuery(next) {
533
+ query = next;
534
+ selected = 0;
535
+ previewScroll = 0;
536
+ }
537
+
538
+ function toggleSelection() {
539
+ const path = selectedPath();
540
+ if (path === undefined) return false;
541
+ if (selection.has(path)) selection.delete(path);
542
+ else selection.add(path);
543
+ return true;
544
+ }
545
+
546
+ /**
547
+ * space and Enter fold a group (S10, S32). The cursor rests on a group row — every
548
+ * row of a tree order takes it (S38) — so the row folds itself; on a file row the
549
+ * group folded is the one HOLDING that file, its folder in `tree` and its extension
550
+ * group in `ext`. The toggled group row is then the row the cursor keeps, which is
551
+ * the IDE behaviour the reader asked for and a row that always paints. A file at
552
+ * the repository root has no folder to fold, a non-empty query holds every group
553
+ * open, and the flat `files` order paints no group at all, so the key is inert in
554
+ * all three cases.
555
+ */
556
+ function toggleFocusedGroup() {
557
+ if (order === FLAT_ORDER || query.length > 0) return false;
558
+ const list = rows();
559
+ if (list.length === 0) return false;
560
+ const index = clampRow(list, selected);
561
+ const row = list[index];
562
+ const target = row.kind === 'group' ? row : holderGroup(list, index);
563
+ if (target === null || target === undefined) return false;
564
+ if (!toggleFold(target, currentFolds())) return false;
565
+ const next = rows();
566
+ const at = next.findIndex((candidate) => candidate.kind === 'group' && candidate.key === target.key);
567
+ selected = clampRow(next, at < 0 ? index : at);
568
+ previewScroll = 0;
569
+ return true;
570
+ }
571
+
572
+ /**
573
+ * shift+space (S39): ONE toggle over every group of the active order, through the
574
+ * order module's own rule. A tree with any group still expanded collapses them all
575
+ * — the ones holding the highlighted file included, so no group is held open — and
576
+ * a tree whose groups are all collapsed expands them all instead.
577
+ *
578
+ * The cursor then parks on the group row the reader came from: the focused group
579
+ * row itself, or the group that HELD the focused file. A nested folder hidden by
580
+ * its own collapse cannot hold the cursor, so the nearest ancestor still painting
581
+ * takes it (`src/web/test.ts` parks on `src`); a repository-root file in `tree` has
582
+ * no group at all and simply keeps its row. The flat `files` order has nothing to
583
+ * toggle and a query holds every group open, so the key is inert in both.
584
+ */
585
+ function toggleEveryGroup() {
586
+ if (order === FLAT_ORDER || query.length > 0) return false;
587
+ const list = rows();
588
+ if (list.length === 0) return false;
589
+ const index = clampRow(list, selected);
590
+ const row = list[index];
591
+ const path = row !== undefined && row.kind === 'file' ? row.entry.path : undefined;
592
+ // Deepest holder first, so the closest group row that still paints wins; a
593
+ // focused group row is its own answer.
594
+ let keys = holderKeys(path, order).slice().reverse();
595
+ if (row !== undefined && row.kind === 'group') keys = [row.key];
596
+ if (!toggleEveryFold(entries, order, currentFolds())) return false;
597
+ const next = rows();
598
+ let at = -1;
599
+ for (const key of keys) {
600
+ at = next.findIndex((candidate) => candidate.kind === 'group' && candidate.key === key);
601
+ if (at >= 0) break;
602
+ }
603
+ if (at < 0 && path !== undefined) {
604
+ at = next.findIndex((candidate) => candidate.kind === 'file' && candidate.entry.path === path);
605
+ }
606
+ selected = clampRow(next, at < 0 ? index : at);
607
+ previewScroll = 0;
608
+ return true;
609
+ }
610
+
611
+ /** ctrl+o: the next order, with the highlight following the same FILE (S10). */
612
+ function cycleOrder() {
613
+ const previous = selectedPath();
614
+ order = nextOrder(order);
615
+ // S30: the order is chosen, not remembered — it opens with exactly the groups
616
+ // holding the highlighted file and every other group collapsed (S29, S30).
617
+ foldedByOrder.set(order, foldsFor(entries, order, previous));
618
+ const list = rows();
619
+ const moved = previous === undefined
620
+ ? -1
621
+ : list.findIndex((row) => row.kind === 'file' && row.entry.path === previous);
622
+ selected = clampRow(list, moved >= 0 ? moved : selected);
623
+ if (selectedPath() !== previous) previewScroll = 0;
624
+ return true;
625
+ }
626
+
627
+ /**
628
+ * Enter's payload (S7): the selected files in LIST order, then any selection a
629
+ * query hides in its marking order, then the highlighted file when Tab never
630
+ * marked it. No file is emitted twice.
631
+ */
632
+ function insertionPaths() {
633
+ const paths = [];
634
+ const seen = new Set();
635
+ const push = (path) => {
636
+ if (seen.has(path)) return;
637
+ seen.add(path);
638
+ paths.push(path);
639
+ };
640
+ for (const row of rows()) {
641
+ if (row.kind === 'file' && selection.has(row.entry.path)) push(row.entry.path);
642
+ }
643
+ for (const path of selection) push(path);
644
+ const highlighted = selectedPath();
645
+ if (highlighted !== undefined) push(highlighted);
646
+ return paths;
647
+ }
648
+
649
+ // ---- the preview ----------------------------------------------------------
650
+
651
+ /**
652
+ * One highlighter call per preview, kept for that path: T5 decides WHEN to
653
+ * highlight, this seam makes sure a repaint cannot pay for it twice (S12 — the
654
+ * highlight runs once per preview load, never per repaint).
655
+ */
656
+ function highlightOnce() {
657
+ if (highlighter === undefined) return undefined;
658
+ let cached;
659
+ return (code, language) => {
660
+ if (cached !== undefined && cached.code === code && cached.language === language) return cached.painted;
661
+ const painted = highlighter(code, language);
662
+ cached = { code, language, painted };
663
+ return painted;
664
+ };
665
+ }
666
+
667
+ function landedPreview(path) {
668
+ const entry = previews.get(path);
669
+ return entry !== undefined && entry.status === 'ready' ? entry.preview : PENDING_PREVIEW;
670
+ }
671
+
672
+ function failPreview(path, error) {
673
+ previews.set(path, {
674
+ status: 'ready',
675
+ preview: { kind: 'error', message: sentence(`Cannot read ${path}: ${errorMessage(error)}`) },
676
+ highlight: undefined,
677
+ });
678
+ }
679
+
680
+ /** Read the highlighted file's preview once; a pending read paints its own notice. */
681
+ function ensurePreview() {
682
+ const path = selectedPath();
683
+ if (path === undefined || previews.has(path)) return;
684
+ const entry = { status: 'loading', highlight: highlightOnce() };
685
+ previews.set(path, entry);
686
+ if (loadPreview === null) {
687
+ failPreview(path, new Error('no preview reader was supplied'));
688
+ return;
689
+ }
690
+ let pending;
691
+ try {
692
+ pending = loadPreview(path);
693
+ } catch (error) {
694
+ failPreview(path, error);
695
+ return;
696
+ }
697
+ Promise.resolve(pending).then(
698
+ (preview) => {
699
+ if (disposed || completed) return;
700
+ previews.set(path, { status: 'ready', preview, highlight: entry.highlight });
701
+ repaint();
702
+ },
703
+ (error) => {
704
+ if (disposed || completed) return;
705
+ failPreview(path, error);
706
+ repaint();
707
+ },
708
+ );
709
+ }
710
+
711
+ function setPreviewScroll(next) {
712
+ const wanted = Math.max(0, Math.min(previewScrollLimit, Math.trunc(next)));
713
+ if (wanted === previewScroll) return false;
714
+ previewScroll = wanted;
715
+ return true;
716
+ }
717
+
718
+ function scrollPreview(delta) {
719
+ if (delta === 0) return false;
720
+ return setPreviewScroll(previewScroll + delta);
721
+ }
722
+
723
+ // ---- the listing load -----------------------------------------------------
724
+
725
+ function settleListing(result) {
726
+ if (disposed || completed) return;
727
+ loaded = true;
728
+ if (result === null || typeof result !== 'object' || result.ok !== true) {
729
+ entries = [];
730
+ listingError = result !== null && typeof result === 'object' && typeof result.message === 'string'
731
+ ? result.message
732
+ : sentence('Cannot list repository files');
733
+ } else {
734
+ entries = Array.isArray(result.entries) ? result.entries : [];
735
+ listingError = undefined;
736
+ }
737
+ // S29: the listing is what the group keys are made of, so the trees' fold sets
738
+ // are seeded from it — every group folded — the moment it lands.
739
+ foldedByOrder.clear();
740
+ for (const target of ORDERS) {
741
+ if (target === FLAT_ORDER) continue;
742
+ foldedByOrder.set(target, foldsFor(entries, target, undefined));
743
+ }
744
+ selected = clampRow(rows(), selected);
745
+ repaint();
746
+ }
747
+
748
+ function loadListing() {
749
+ if (loaded) return;
750
+ if (loadEntries === null) {
751
+ settleListing({ ok: false, message: sentence('Cannot list repository files: no listing reader was supplied') });
752
+ return;
753
+ }
754
+ let pending;
755
+ try {
756
+ pending = loadEntries();
757
+ } catch (error) {
758
+ settleListing({ ok: false, message: sentence(`Cannot list repository files: ${errorMessage(error)}`) });
759
+ return;
760
+ }
761
+ Promise.resolve(pending).then(settleListing, (error) => {
762
+ settleListing({ ok: false, message: sentence(`Cannot list repository files: ${errorMessage(error)}`) });
763
+ });
764
+ }
765
+
766
+ // ---- painting -------------------------------------------------------------
767
+
768
+ /**
769
+ * S37: the checkout's path rides the panel's OWN title — `Files · <path>` — so it
770
+ * reads beside the panel's name and elides from its own left, which is what keeps
771
+ * the tail that identifies the checkout. `cardTop` clips a heading's detail from
772
+ * its RIGHT, so the path is elided here first, at exactly the columns the heading
773
+ * leaves it, and the substrate is handed one that already fits.
774
+ */
775
+ function titleDetail(width) {
776
+ const room = width - TOP_CHROME_COLUMNS - HINT_COLUMNS - titleHeadWidth - TITLE_SEPARATOR_COLUMNS;
777
+ if (room < MIN_DETAIL_COLUMNS) return undefined;
778
+ const root = sanitize(scope.root === undefined ? '' : scope.root);
779
+ if (root === '') return undefined;
780
+ return elideLeft(root, room);
781
+ }
782
+
783
+ // The card the top rule draws: the panel's name, and the path as its detail when
784
+ // the card has the room for one (S37).
785
+ function cardFor(width) {
786
+ const detail = titleDetail(width);
787
+ return detail === undefined ? CARD : { title: TITLE, tone: TONE, subtitle: detail };
788
+ }
789
+
790
+ // The right corner holds `esc` and nothing else (S37). A card too narrow for the
791
+ // hint paints no hint at all, exactly as before.
792
+ function titleHint(width) {
793
+ // cardTop spends five cells on the chrome and two around the hint it shows.
794
+ const room = width - TOP_CHROME_COLUMNS - titleHeadWidth - 2;
795
+ return room >= CLOSE_HINT.length ? CLOSE_HINT : undefined;
796
+ }
797
+
798
+ // S25: the search row is the LIST pane's width, its right column left blank, so
799
+ // the query reads as the list's own field and the preview owns the body beside
800
+ // it.
801
+ function searchRow(pane, inner) {
802
+ const room = Math.max(0, Math.min(inner, pane.listWidth));
803
+ let plain;
804
+ let painted;
805
+ if (query.length === 0) {
806
+ plain = clipPlain(`${SEARCH_PROMPT} ${SEARCH_PLACEHOLDER}`, room);
807
+ painted = paint(theme, 'dim', plain);
808
+ } else {
809
+ const prompt = `${SEARCH_PROMPT} `;
810
+ const shown = clipPlain(query, Math.max(0, room - measure(helpers, prompt)));
811
+ plain = `${prompt}${shown}`;
812
+ painted = `${paint(theme, 'dim', SEARCH_PROMPT)} ${value(theme, shown)}`;
813
+ }
814
+ const padding = ' '.repeat(Math.max(0, inner - measure(helpers, plain)));
815
+ return frameRow(`${painted}${padding}`);
816
+ }
817
+
818
+ /**
819
+ * S22: the files the active query lists, counted through the row builder so the
820
+ * number and the list can never disagree about what a query matches. Folding is
821
+ * not a filter, so the flat `files` rows answer it.
822
+ */
823
+ function listedCount() {
824
+ return buildRows(entries, { order: ORDERS[0], query }).filter(isFileRow).length;
825
+ }
826
+
827
+ /**
828
+ * The info row's list cell (S22): `listed/total (selected)`, then a `─` fill and
829
+ * the active order right-aligned at the list pane's edge. It is the one place the
830
+ * order is named: too narrow for it, the counts keep the column and the order gives
831
+ * way, which only happens in a list pane under about 17 columns.
832
+ */
833
+ function infoItem(listWidth) {
834
+ const counts = `${listedCount()}/${entries.length} (${selection.size})`;
835
+ const countsWidth = measure(helpers, counts);
836
+ const orderText = order;
837
+ const orderWidth = measure(helpers, orderText);
838
+ let plain;
839
+ let painted;
840
+ if (listWidth >= countsWidth + orderWidth + 3) {
841
+ const fill = BODY_RULE.repeat(listWidth - countsWidth - orderWidth - 2);
842
+ plain = `${counts} ${fill} ${orderText}`;
843
+ painted = `${value(theme, counts)} ${paint(theme, 'dim', fill)} ${value(theme, orderText)}`;
844
+ } else if (listWidth >= countsWidth + orderWidth + 1) {
845
+ plain = `${counts} ${orderText}`;
846
+ painted = `${value(theme, counts)} ${value(theme, orderText)}`;
847
+ } else {
848
+ plain = clipPlain(counts, listWidth);
849
+ painted = value(theme, plain);
850
+ }
851
+ const padding = ' '.repeat(Math.max(0, listWidth - measure(helpers, plain)));
852
+ return { painted: `${painted}${padding}`, width: listWidth };
853
+ }
854
+
855
+ // The info row: the counts inside the list column, the pane rule, and the
856
+ // preview's first row — its box top — riding the same row (S22, S25).
857
+ function infoRow(pane, previewTopItem) {
858
+ const side = frameSide();
859
+ const rule = paint(theme, FRAME_ROLE, PANE_RULE);
860
+ return `${side} ${padItem(infoItem(pane.listWidth), pane.listWidth)} ${rule} ${padItem(previewTopItem, pane.previewWidth)} ${side}`;
861
+ }
862
+
863
+ // S25: the rule that closes the body under both columns, on its own row.
864
+ function bodyRuleRow(inner) {
865
+ return frameRow(paint(theme, FRAME_ROLE, BODY_RULE.repeat(Math.max(0, inner))));
866
+ }
867
+
868
+ /** What the panes paint instead of a list, or `undefined` when the list is real. */
869
+ function stateLine() {
870
+ if (listingError !== undefined) return { text: listingError, role: 'error' };
871
+ if (!loaded) return { text: LOADING_FILES, role: 'dim' };
872
+ if (entries.length === 0) return { text: NO_FILES, role: 'dim' };
873
+ if (rows().length === 0) return { text: `No files match "${sanitize(query)}"`, role: 'dim' };
874
+ return undefined;
875
+ }
876
+
877
+ function ageOf(entry) {
878
+ if (typeof entry.age === 'string' && entry.age.length > 0) return entry.age;
879
+ if (Number.isFinite(entry.mtimeMs)) return formatAge(entry.mtimeMs, now);
880
+ return '';
881
+ }
882
+
883
+ // The trailing badge and age, plain: `/changes` own letters, `U` for a file Git
884
+ // does not track yet and `M` for a tracked one with an uncommitted change (S6).
885
+ function suffixOf(entry) {
886
+ if (entry.state === 'clean') return '';
887
+ const badge = entry.state === 'new' ? UNTRACKED_BADGE : MODIFIED_BADGE;
888
+ const age = ageOf(entry);
889
+ return age === '' ? badge : `${badge} ${age}`;
890
+ }
891
+
892
+ function paintSuffix(suffix) {
893
+ const [badge, ...rest] = suffix.split(' ');
894
+ const paintedBadge = paint(theme, 'accent', badge);
895
+ return rest.length === 0 ? paintedBadge : `${paintedBadge} ${paint(theme, 'muted', rest.join(' '))}`;
896
+ }
897
+
898
+ // The label a file row paints: its name, then — only where the order asks for
899
+ // it — the parent directory, which the `tree` order already expresses (S15).
900
+ function labelOf(entry, showDirectory) {
901
+ const name = sanitize(entry.path.slice(entry.path.lastIndexOf('/') + 1));
902
+ if (!showDirectory) return { text: name, nameLength: name.length };
903
+ const slash = entry.path.lastIndexOf('/');
904
+ const directory = slash < 0 ? '' : sanitize(entry.path.slice(0, slash));
905
+ if (directory === '') return { text: name, nameLength: name.length };
906
+ return { text: `${name} ${directory}`, nameLength: name.length };
907
+ }
908
+
909
+ function markerPlain(cursor, marked) {
910
+ return `${cursor ? CURSOR_MARK : ' '}${marked ? SELECTION_MARK : ' '} `;
911
+ }
912
+
913
+ // A group row's marker column (S29): the cursor mark stays in the cell it always
914
+ // occupies, and the chevron takes the Tab cell — which a group row never fills,
915
+ // because a group is never marked (S24), even though the row itself is focusable
916
+ // (S38). The column keeps its three cells, so a group name and a file name still
917
+ // start in the same one.
918
+ function groupMarkerPlain(cursor, folded) {
919
+ return `${cursor ? CURSOR_MARK : ' '}${folded ? GROUP_COLLAPSED_MARK : GROUP_EXPANDED_MARK} `;
920
+ }
921
+
922
+ // The idle marker (S26): a Tab-marked row's bar carries a theme role in EVERY
923
+ // state, focused or not, so the mark reads in the theme's colour instead of as an
924
+ // unstyled cell. It keeps the marker column's three cells and the same glyph, so
925
+ // marking a row still never moves it (S7). A group row is never marked (S24), so
926
+ // it never reaches this cell.
927
+ function markerIdle(marked) {
928
+ return marked ? ` ${keyText(theme, SELECTION_MARK)} ` : ' ';
929
+ }
930
+
931
+ // One list row as `{ painted, width }`: `width` is its PLAIN width, so the
932
+ // caller pads it without ever measuring a painted string.
933
+ function listRowItem(row, index, focusedIndex, listWidth) {
934
+ const cursor = index === focusedIndex;
935
+ const mark = row.kind === 'file' && selection.has(row.entry.path);
936
+ const indent = ' '.repeat(Math.max(0, row.depth) * GROUP_INDENT);
937
+ const indentWidth = Math.max(0, row.depth) * GROUP_INDENT;
938
+
939
+ if (row.kind === 'group') {
940
+ const room = Math.max(0, listWidth - MARKER_WIDTH - indentWidth);
941
+ const shown = clipPlain(row.label, room);
942
+ const padding = ' '.repeat(Math.max(0, listWidth - MARKER_WIDTH - indentWidth - measure(helpers, shown)));
943
+ // S31: a group row reads in the neutral grey role, never the file row's text
944
+ // tone, focused row included — the focus band stays the focus cue, and the
945
+ // theme's `bg`/`fg` resets do not cancel each other, so the grey survives it.
946
+ const hoveredRow = !cursor && index === hovered;
947
+ const paintedLabel = hoveredRow ? keyText(theme, shown) : label(theme, shown);
948
+ const content = `${groupMarkerPlain(cursor, row.folded)}${indent}${paintedLabel}${padding}`;
949
+ if (cursor) return { painted: paintFocused(theme, content, true), width: listWidth };
950
+ return { painted: content, width: listWidth };
951
+ }
952
+
953
+ const entry = row.entry;
954
+ const suffix = suffixOf(entry);
955
+ const suffixWidth = measure(helpers, suffix);
956
+ // The name leads and the state trails: a narrow pane costs the name first.
957
+ const showsSuffix = suffixWidth > 0 && suffixWidth + MARKER_WIDTH + indentWidth + 1 <= listWidth;
958
+ const labelRoom = Math.max(0, listWidth - MARKER_WIDTH - indentWidth - (showsSuffix ? suffixWidth + 1 : 0));
959
+ const nameLabel = labelOf(entry, row.showDirectory !== false);
960
+ const shown = clipPlain(nameLabel.text, labelRoom);
961
+ const split = Math.min(shown.length, nameLabel.nameLength);
962
+ const name = shown.slice(0, split);
963
+ const tail = shown.slice(split);
964
+ const gapEnd = tail.startsWith(' ') ? 2 : tail.search(/[^ ]/);
965
+ const nameGap = gapEnd === -1 ? tail : tail.slice(0, gapEnd);
966
+ const directory = tail.slice(nameGap.length);
967
+ const gap = ' '.repeat(Math.max(
968
+ 0,
969
+ listWidth - MARKER_WIDTH - indentWidth - measure(helpers, shown) - (showsSuffix ? suffixWidth : 0),
970
+ ));
971
+ const plain = `${markerPlain(cursor, mark)}${indent}${shown}${gap}${showsSuffix ? suffix : ''}`;
972
+ if (cursor) return { painted: paintFocused(theme, plain, true), width: listWidth };
973
+ const hoveredRow = !cursor && index === hovered;
974
+ const paintedName = mark || hoveredRow ? keyText(theme, name) : value(theme, name);
975
+ const paintedLabel = directory === ''
976
+ ? paintedName
977
+ : `${paintedName}${nameGap}${paint(theme, 'dim', directory)}`;
978
+ const paintedSuffix = showsSuffix ? paintSuffix(suffix) : '';
979
+ return { painted: `${markerIdle(mark)}${indent}${paintedLabel}${gap}${paintedSuffix}`, width: listWidth };
980
+ }
981
+
982
+ function indicatorItem(text, width) {
983
+ const shown = clipPlain(text, width);
984
+ return { painted: label(theme, shown), width: Math.max(0, Math.min(width, measure(helpers, shown))) };
985
+ }
986
+
987
+ function listColumn(pane, bodyRows, hits) {
988
+ const list = rows();
989
+ const items = [];
990
+ if (bodyRows <= 0 || list.length === 0) {
991
+ for (let row = 0; row < bodyRows; row += 1) items.push(BLANK_ITEM);
992
+ return items;
993
+ }
994
+ const focused = Math.max(0, Math.min(list.length - 1, selected));
995
+ const costs = list.map(() => 1);
996
+ let window = scrollWindow(costs, { budget: bodyRows, index: focused });
997
+ // Indicators cost two rows; reserve them only when something remains on
998
+ // either side AND the body can still show a row between them.
999
+ if ((window.above || window.below) && bodyRows >= 4) {
1000
+ window = scrollWindow(costs, { budget: bodyRows - 2, index: focused });
1001
+ }
1002
+ if (window.above && items.length < bodyRows) {
1003
+ items.push(indicatorItem(` \u2191 ${window.start} more`, pane.listWidth));
1004
+ }
1005
+ for (let index = window.start; index < window.end; index += 1) {
1006
+ hits.push({ y: BODY_TOP + items.length, index });
1007
+ items.push(listRowItem(list[index], index, focused, pane.listWidth));
1008
+ }
1009
+ if (window.below && items.length < bodyRows) {
1010
+ items.push(indicatorItem(` \u2193 ${list.length - window.end} more`, pane.listWidth));
1011
+ }
1012
+ while (items.length < bodyRows) items.push(BLANK_ITEM);
1013
+ return items.slice(0, bodyRows);
1014
+ }
1015
+
1016
+ /**
1017
+ * The preview column, one row taller than the body: its FIRST row is what rides
1018
+ * the info row — the box's top border with the `line/total` position, or the
1019
+ * unboxed fallback's own position row — and the body rows follow it, so the box
1020
+ * closes on the list's last body row (S25).
1021
+ */
1022
+ function previewColumn(pane, bodyRows) {
1023
+ const blank = { top: BLANK_ITEM, rows: new Array(Math.max(0, bodyRows)).fill(BLANK_ITEM) };
1024
+ if (pane.previewWidth <= 0) return blank;
1025
+ // S38: the cursor can rest on a group row, which holds no file to read — the pane
1026
+ // then keeps its box and paints its own notice, so the column never collapses and
1027
+ // no position is claimed for a file that is not there.
1028
+ const path = selectedPath();
1029
+ const entry = path === undefined ? undefined : previews.get(path);
1030
+ const painted = previewRows(path === undefined ? NO_FILE_PREVIEW : landedPreview(path), {
1031
+ width: pane.previewWidth,
1032
+ height: bodyRows + 1,
1033
+ scroll: previewScroll,
1034
+ highlight: entry !== undefined ? entry.highlight : undefined,
1035
+ languageForPath,
1036
+ path,
1037
+ metrics,
1038
+ });
1039
+ // The painted window is what a scroll is clamped against, so the last page is
1040
+ // always full and the position indicator never lies.
1041
+ previewScrollLimit = painted.maxScroll;
1042
+ previewScroll = Math.max(0, Math.min(previewScrollLimit, previewScroll));
1043
+ const items = painted.rows.map((row) => ({
1044
+ painted: row.cells.map((cell) => paint(theme, cell.role, cell.text)).join(''),
1045
+ width: pane.previewWidth,
1046
+ }));
1047
+ while (items.length < bodyRows + 1) items.push(BLANK_ITEM);
1048
+ return { top: items[0] === undefined ? BLANK_ITEM : items[0], rows: items.slice(1, bodyRows + 1) };
1049
+ }
1050
+
1051
+ function padItem(item, width) {
1052
+ const source = item === undefined ? BLANK_ITEM : item;
1053
+ return source.painted + ' '.repeat(Math.max(0, width - source.width));
1054
+ }
1055
+
1056
+ // The legend entries the active order earns (S32, S40): the fold keys only while
1057
+ // the order paints groups, and the shift+space one names the action it would
1058
+ // perform — expanding while every group is collapsed, collapsing otherwise.
1059
+ function footerEntries() {
1060
+ if (order === FLAT_ORDER) return FOOTER_ENTRIES;
1061
+ // A non-empty query holds every group open (S10), so the legend can never claim it
1062
+ // would expand them then.
1063
+ const collapsed = query.length === 0 && everyGroupFolded(entries, order, currentFolds());
1064
+ return collapsed ? TREE_LEGEND_EXPAND : TREE_LEGEND_COLLAPSE;
1065
+ }
1066
+
1067
+ // The footer (S4, S10): the legend names ONE option per key and nothing else. The
1068
+ // active order is named once, on the info row under the search row, so the footer
1069
+ // never repeats it and the legend keeps the whole row.
1070
+ function footerRow(inner) {
1071
+ const legend = legendRow(theme, footerEntries(), inner, (text) => measure(helpers, text));
1072
+ // The row is exactly the frame's width, so the legend is padded to the edge.
1073
+ const pad = ' '.repeat(Math.max(0, inner - measure(helpers, legend)));
1074
+ return frameRow(`${legend}${pad}`);
1075
+ }
1076
+
1077
+ function render(width) {
1078
+ const requested = Number(width);
1079
+ const w = Number.isFinite(requested) ? Math.floor(requested) : 0;
1080
+ if (w <= 0) {
1081
+ pointerFrame = undefined;
1082
+ return [];
1083
+ }
1084
+ const height = cardHeight();
1085
+ if (height <= 0) {
1086
+ pointerFrame = undefined;
1087
+ return [];
1088
+ }
1089
+ if (w < MIN_WIDTH || height < MIN_CARD_HEIGHT) {
1090
+ pointerFrame = undefined;
1091
+ return [clipPlain(`${TITLE} \u2014 enlarge the terminal`, w)];
1092
+ }
1093
+ const inner = cardInnerWidth(w);
1094
+ const bodyRows = Math.max(0, height - CHROME_ROWS - BODY_RULE_ROWS);
1095
+ // A page move crosses what the reader can see (S38).
1096
+ pageRows = Math.max(1, bodyRows);
1097
+ const pane = paneLayout(inner);
1098
+ ensurePreview();
1099
+
1100
+ const hits = [];
1101
+ const state = stateLine();
1102
+ // The preview is asked for the body plus the row it rides, so the box's top
1103
+ // border lands on the info row and its bottom border on the last body row
1104
+ // (S25). A state line has no file to preview, so its right column stays blank.
1105
+ const preview = state === undefined ? previewColumn(pane, bodyRows) : undefined;
1106
+ const lines = [
1107
+ cardTop(cardFor(w), theme, w, titleHint(w), metrics),
1108
+ searchRow(pane, inner),
1109
+ infoRow(pane, preview === undefined ? BLANK_ITEM : preview.top),
1110
+ ];
1111
+ if (state !== undefined) {
1112
+ // The empty, pending and failed lines are unchanged: one full-width row, the
1113
+ // rest of the body blank (S13).
1114
+ if (bodyRows > 0) {
1115
+ const shown = clipPlain(state.text, inner);
1116
+ const padding = ' '.repeat(Math.max(0, inner - measure(helpers, shown)));
1117
+ lines.push(frameRow(`${paint(theme, state.role, shown)}${padding}`));
1118
+ for (let row = 1; row < bodyRows; row += 1) lines.push(frameRow(' '.repeat(inner)));
1119
+ }
1120
+ } else {
1121
+ const left = listColumn(pane, bodyRows, hits);
1122
+ const rule = paint(theme, FRAME_ROLE, PANE_RULE);
1123
+ for (let row = 0; row < bodyRows; row += 1) {
1124
+ const side = frameSide();
1125
+ lines.push(
1126
+ `${side} ${padItem(left[row], pane.listWidth)} ${rule} ${padItem(preview.rows[row], pane.previewWidth)} ${side}`,
1127
+ );
1128
+ }
1129
+ }
1130
+ lines.push(bodyRuleRow(inner));
1131
+ lines.push(footerRow(inner));
1132
+ lines.push(cardBottom(TONE, theme, w, undefined, metrics));
1133
+
1134
+ pointerFrame = completed || disposed ? undefined : {
1135
+ width: w,
1136
+ height: lines.length,
1137
+ bodyTop: BODY_TOP,
1138
+ bodyRows,
1139
+ // The box's top border rides the info row, so that row is part of the
1140
+ // preview for the pointer (S25).
1141
+ previewTop: INFO_TOP,
1142
+ listStart: 2,
1143
+ listEnd: 2 + pane.listWidth,
1144
+ previewStart: 2 + pane.listWidth + PANE_RULE_COLUMNS,
1145
+ previewEnd: 2 + inner,
1146
+ hits,
1147
+ };
1148
+ return lines;
1149
+ }
1150
+
1151
+ // ---- input ----------------------------------------------------------------
1152
+
1153
+ function keyMatches(data, names) {
1154
+ for (const name of names) {
1155
+ try {
1156
+ if (typeof helpers.matchesKey === 'function' && helpers.matchesKey(data, name)) return true;
1157
+ } catch {
1158
+ // A throwing matcher never matches; the spelled fallback decides below.
1159
+ }
1160
+ }
1161
+ let text = typeof data === 'string' ? data : (data && (data.name || data.key)) || '';
1162
+ if (typeof text === 'string' && Object.prototype.hasOwnProperty.call(KEY_SEQUENCES, text)) {
1163
+ text = KEY_SEQUENCES[text];
1164
+ }
1165
+ return names.some((name) => text === name);
1166
+ }
1167
+
1168
+ function isRelease(data) {
1169
+ try {
1170
+ return typeof helpers.isKeyRelease === 'function' && helpers.isKeyRelease(data) === true;
1171
+ } catch {
1172
+ return false;
1173
+ }
1174
+ }
1175
+
1176
+ function complete() {
1177
+ completed = true;
1178
+ pointerFrame = undefined;
1179
+ hovered = undefined;
1180
+ }
1181
+
1182
+ /**
1183
+ * Settle the panel (S14). Nothing repaints here: the host owns the frame the
1184
+ * panel leaves behind. `onClose` is the extension's single close path, and it
1185
+ * settles the overlay and then forces one full repaint while the terminal is
1186
+ * still the session's (S27) — the editor handoff only starts after that, from
1187
+ * the resolved overlay, so nothing here has to choose between the two.
1188
+ */
1189
+ function finish(action) {
1190
+ if (completed || disposed) return;
1191
+ if (action === 'insert') {
1192
+ const paths = insertionPaths();
1193
+ if (paths.length === 0) return;
1194
+ complete();
1195
+ // The overlay closes even when the paste throws: a completed panel with
1196
+ // dead input would strand the session in the picker.
1197
+ try {
1198
+ if (onInsert !== null) onInsert(paths);
1199
+ } finally {
1200
+ if (onClose !== null) onClose();
1201
+ }
1202
+ return;
1203
+ }
1204
+ const path = action === 'open' ? selectedPath() : undefined;
1205
+ if (action === 'open' && path === undefined) return;
1206
+ complete();
1207
+ try {
1208
+ if (path !== undefined && onOpen !== null) onOpen(path);
1209
+ } finally {
1210
+ if (onClose !== null) onClose();
1211
+ }
1212
+ }
1213
+
1214
+ function touch() {
1215
+ pointerFrame = undefined;
1216
+ hovered = undefined;
1217
+ }
1218
+
1219
+ function handleInput(data) {
1220
+ if (completed || disposed || isRelease(data)) return;
1221
+ touch();
1222
+ // ctrl+j/k scroll the preview and the ctrl+shift forms are the same action
1223
+ // for terminals where they are the deliverable shape (S4). A bare line feed
1224
+ // is ctrl+j here, so it scrolls instead of inserting.
1225
+ if (keyMatches(data, ['ctrl+shift+j', 'ctrl+j'])) {
1226
+ if (scrollPreview(1)) repaint();
1227
+ return;
1228
+ }
1229
+ if (keyMatches(data, ['ctrl+shift+k', 'ctrl+k'])) {
1230
+ if (scrollPreview(-1)) repaint();
1231
+ return;
1232
+ }
1233
+ // ctrl+home/ctrl+end and home/end are compatibility bindings: they work and
1234
+ // the footer never names them (S4).
1235
+ if (keyMatches(data, ['ctrl+home'])) {
1236
+ if (setPreviewScroll(0)) repaint();
1237
+ return;
1238
+ }
1239
+ if (keyMatches(data, ['ctrl+end'])) {
1240
+ if (setPreviewScroll(previewScrollLimit)) repaint();
1241
+ return;
1242
+ }
1243
+ if (keyMatches(data, ['up'])) {
1244
+ if (moveSelection(-1)) repaint();
1245
+ return;
1246
+ }
1247
+ if (keyMatches(data, ['down'])) {
1248
+ if (moveSelection(1)) repaint();
1249
+ return;
1250
+ }
1251
+ // The page moves cross the rows the last paint showed. They are compatibility
1252
+ // bindings S4 never names, exactly as home/end are (S38).
1253
+ if (keyMatches(data, ['pageup', 'pageUp'])) {
1254
+ if (moveSelection(-Math.max(1, pageRows))) repaint();
1255
+ return;
1256
+ }
1257
+ if (keyMatches(data, ['pagedown', 'pageDown'])) {
1258
+ if (moveSelection(Math.max(1, pageRows))) repaint();
1259
+ return;
1260
+ }
1261
+ if (keyMatches(data, ['home'])) {
1262
+ if (selectRow(0)) repaint();
1263
+ return;
1264
+ }
1265
+ if (keyMatches(data, ['end'])) {
1266
+ if (selectRow(lastRow())) repaint();
1267
+ return;
1268
+ }
1269
+ if (keyMatches(data, ['tab'])) {
1270
+ if (toggleSelection()) repaint();
1271
+ return;
1272
+ }
1273
+ // shift+space toggles every group of the active order in one press (S39), and
1274
+ // only where the order paints groups.
1275
+ if (keyMatches(data, ['shift+space'])) {
1276
+ if (toggleEveryGroup()) repaint();
1277
+ return;
1278
+ }
1279
+ // space folds the focused group row and never reaches the query (S3, S10); in
1280
+ // the flat `files` order it does nothing at all (S32).
1281
+ if (keyMatches(data, ['space'])) {
1282
+ if (toggleFocusedGroup()) repaint();
1283
+ return;
1284
+ }
1285
+ if (keyMatches(data, ['ctrl+o'])) {
1286
+ if (cycleOrder()) repaint();
1287
+ return;
1288
+ }
1289
+ if (keyMatches(data, ['escape', 'ctrl+c'])) {
1290
+ finish('close');
1291
+ return;
1292
+ }
1293
+ if (keyMatches(data, ['enter'])) {
1294
+ // Enter on a group row folds it; on a file row it inserts and closes (S7).
1295
+ const focused = selectedRow();
1296
+ if (focused !== undefined && focused.kind === 'group') {
1297
+ if (toggleFocusedGroup()) repaint();
1298
+ } else {
1299
+ finish('insert');
1300
+ }
1301
+ return;
1302
+ }
1303
+ if (keyMatches(data, ['ctrl+e'])) {
1304
+ finish('open');
1305
+ return;
1306
+ }
1307
+ if (keyMatches(data, ['backspace'])) {
1308
+ if (query.length > 0) {
1309
+ setQuery(query.slice(0, -1));
1310
+ repaint();
1311
+ }
1312
+ return;
1313
+ }
1314
+ if (keyMatches(data, ['ctrl+u'])) {
1315
+ if (query.length > 0) {
1316
+ setQuery('');
1317
+ repaint();
1318
+ }
1319
+ return;
1320
+ }
1321
+ if (isSinglePrintable(data)) {
1322
+ setQuery(query + data);
1323
+ repaint();
1324
+ }
1325
+ }
1326
+
1327
+ /** Mouse events are local to the last painted card, including its borders (S5). */
1328
+ function handleMouse(event) {
1329
+ if (completed || disposed || event === null || typeof event !== 'object') return undefined;
1330
+ const moving = event.type === 'move' && event.button === 'none';
1331
+ const frame = pointerFrame;
1332
+ if (!frame || event.width !== frame.width || event.height !== frame.height) {
1333
+ pointerFrame = undefined;
1334
+ const changed = hovered !== undefined;
1335
+ hovered = undefined;
1336
+ return changed && moving ? { handled: true, render: true } : undefined;
1337
+ }
1338
+ const inBody = event.y >= frame.bodyTop && event.y < frame.bodyTop + frame.bodyRows;
1339
+ const inList = inBody && event.x >= frame.listStart && event.x < frame.listEnd;
1340
+ const inPreview = event.y >= frame.previewTop && event.y < frame.bodyTop + frame.bodyRows
1341
+ && event.x >= frame.previewStart && event.x < frame.previewEnd;
1342
+ const hit = inList ? frame.hits.find((candidate) => candidate.y === event.y) : undefined;
1343
+ if (moving) {
1344
+ const changed = hovered !== (hit === undefined ? undefined : hit.index);
1345
+ hovered = hit === undefined ? undefined : hit.index;
1346
+ if (changed) repaint();
1347
+ return { handled: true, render: changed };
1348
+ }
1349
+ if (event.type === 'wheel' && event.wheelDelta) {
1350
+ const delta = Math.sign(Number(event.wheelDelta));
1351
+ if (inList) {
1352
+ const changed = moveSelection(delta);
1353
+ if (changed) repaint();
1354
+ return { handled: true, render: changed };
1355
+ }
1356
+ if (inPreview) {
1357
+ const changed = scrollPreview(delta);
1358
+ if (changed) repaint();
1359
+ return { handled: true, render: changed };
1360
+ }
1361
+ return undefined;
1362
+ }
1363
+ if (event.button !== 'left') return undefined;
1364
+ // A preview click never breaks the panel and never changes the selection.
1365
+ if (inPreview) return { handled: true, render: false };
1366
+ if (!inList) return undefined;
1367
+ if (event.type === 'press') return { handled: true, render: false };
1368
+ if (event.type !== 'click' || hit === undefined) return undefined;
1369
+ const list = rows();
1370
+ const row = list[hit.index];
1371
+ if (row !== undefined && row.kind === 'group') {
1372
+ // S38: a click parks the cursor on the group row exactly as on a file row, and
1373
+ // S10's fold still happens with it, so the reader lands on the row it clicked
1374
+ // and `space`/`enter` then have that row. A query holds every group open, so
1375
+ // only the focus moves then.
1376
+ const focused = selectRow(hit.index);
1377
+ if (query.length > 0) {
1378
+ if (focused) repaint();
1379
+ return { handled: true, render: focused };
1380
+ }
1381
+ if (!toggleFold(row, currentFolds())) {
1382
+ if (focused) repaint();
1383
+ return { handled: true, render: focused };
1384
+ }
1385
+ // The toggled group row keeps the cursor: it always paints, so the click never
1386
+ // leaves the reader on a row that just disappeared. The fold itself is what the
1387
+ // panel repaints for.
1388
+ const next = rows();
1389
+ const at = next.findIndex((candidate) => candidate.kind === 'group' && candidate.key === row.key);
1390
+ selectRow(at < 0 ? hit.index : at);
1391
+ repaint();
1392
+ return { handled: true, render: true };
1393
+ }
1394
+ const changed = selectRow(hit.index);
1395
+ if (changed) repaint();
1396
+ return { handled: true, render: changed };
1397
+ }
1398
+
1399
+ function invalidate() {
1400
+ pointerFrame = undefined;
1401
+ hovered = undefined;
1402
+ }
1403
+
1404
+ function dispose() {
1405
+ disposed = true;
1406
+ pointerFrame = undefined;
1407
+ hovered = undefined;
1408
+ previews.clear();
1409
+ }
1410
+
1411
+ loadListing();
1412
+
1413
+ return { render, handleInput, handleMouse, invalidate, dispose };
1414
+ }
1415
+
1416
+ module.exports = { createFilesPickerView, FOOTER_ENTRIES };