pi-odd-worktree 3.11.2 → 3.12.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/lib/odd-view.js CHANGED
@@ -25,6 +25,19 @@
25
25
  // mark, no toggle, no save — and the association lives in the worktree
26
26
  // detail instead.
27
27
  //
28
+ // S10/S11 (T9): the list groups its documents by checkout, like the
29
+ // gentle-shell CHANGES panel, and `a` alternates the session's checkouts with
30
+ // every worktree. The caller owns the model — it hands over `groups`, one entry
31
+ // per checkout carrying the documents that checkout owns — and this view never
32
+ // runs git: `a` flips a local mode, reports the new value once through
33
+ // `onToggleAll`, and the caller reloads the groups — handing the new model back
34
+ // through `applyGroups`, the grouped sibling of `applyDocs`. The main group is
35
+ // always drawn; a worktree group is drawn only while it still has documents, so an
36
+ // empty worktree group is never rendered and a set where every worktree is empty
37
+ // stays the ordinary main-only flat listing with no header at all (S13). A
38
+ // header row is focusable and Enter folds it. With `groups` absent the panel is
39
+ // exactly the flat listing it was before this unit.
40
+ //
28
41
  // The TUI helpers arrive injected (visibleWidth/truncateToWidth/matchesKey/
29
42
  // isKeyRelease) because @earendil-works/pi-tui is a lazily imported peer of
30
43
  // this package: the command loads it and passes it down, and the raw-byte
@@ -99,6 +112,28 @@ const RELOAD_KEY = 'r';
99
112
  // `t search` (45) and `s sort` (50), so a live action hint is still preferred over
100
113
  // a spent reload message on a still-narrower row.
101
114
  const RELOAD_PRIORITY = 41;
115
+ // D2 (T6): the answer a reload seam resolves when its request was SUPERSEDED.
116
+ // "No stale result may land" means this view must do NOTHING at all with it: no
117
+ // listing, no re-read, no scroll reset, no footer token, no repaint — the frame on
118
+ // screen belongs to a LATER request and stays exactly as the reader left it.
119
+ // `Symbol.for` keeps one identity even when a caller reloads this module and holds
120
+ // its own require of it, so the caller can name the sentinel without a second copy
121
+ // of the key string.
122
+ const RELOAD_SUPERSEDED = Symbol.for('odd-view.reload-superseded');
123
+
124
+ // S11 (T9): the listing key that alternates this session's checkouts with every
125
+ // worktree. `a` is free — `t`, `o`, `s` and `r` are taken — and the mode it names
126
+ // belongs to this view while the GROUPS belong to the caller, which is why the
127
+ // key only reports the new value and reloads nothing itself. Its priority sits
128
+ // below the live actions it rides beside (`t search` 45, `s sort` 50) and above
129
+ // the spent reload outcome (41), so a narrow legend still names the toggle.
130
+ const ALL_KEY = 'a';
131
+ const ALL_PRIORITY = 44;
132
+
133
+ // S10 (T9): the two markers a checkout header paints — the same chevron pair the
134
+ // files picker folds its own groups with, so a fold reads the same everywhere.
135
+ const GROUP_EXPANDED_MARK = '\u25be'; // ▾
136
+ const GROUP_COLLAPSED_MARK = '\u25b8'; // ▸
102
137
 
103
138
  // While the filter box holds the keyboard the footer names THAT interaction
104
139
  // once — enter and esc each keep the filter, Delete clears the whole query and
@@ -313,6 +348,74 @@ function compareByName(left, right) {
313
348
  return a < b ? -1 : 1;
314
349
  }
315
350
 
351
+ // S10 (T9): the grouped model's own vocabulary. A document names its absolute
352
+ // location `docPath` (the shape lib/odd-group.js returns) or `path` (the shape
353
+ // every existing caller and this view already used), so ONE accessor reads
354
+ // either and identity is always that location — only two same-named documents
355
+ // from different checkouts are told apart by it.
356
+ function documentLocation(docEntry) {
357
+ if (!docEntry || typeof docEntry !== 'object') return undefined;
358
+ if (typeof docEntry.path === 'string' && docEntry.path.length > 0) return docEntry.path;
359
+ if (typeof docEntry.docPath === 'string' && docEntry.docPath.length > 0) return docEntry.docPath;
360
+ return undefined;
361
+ }
362
+
363
+ function documentKey(docEntry) {
364
+ if (!docEntry) return null;
365
+ const location = documentLocation(docEntry);
366
+ if (location !== undefined) return location;
367
+ return typeof docEntry.name === 'string' ? docEntry.name : null;
368
+ }
369
+
370
+ function documentName(docEntry) {
371
+ if (!docEntry || typeof docEntry !== 'object') return '';
372
+ if (typeof docEntry.name === 'string' && docEntry.name.length > 0) return docEntry.name;
373
+ const location = documentLocation(docEntry);
374
+ if (location === undefined) return '';
375
+ const base = location.slice(location.lastIndexOf('/') + 1);
376
+ return base.endsWith('.md') ? base.slice(0, -3) : base;
377
+ }
378
+
379
+ // A grouped document keeps every field the model carries (status, mtimeMs) and
380
+ // gains the `path` this view's list, opener and reader already agree on, so the
381
+ // newer `docPath` spelling never needs a second code path here.
382
+ function normalizeGroupDoc(raw) {
383
+ if (!raw || typeof raw !== 'object') return null;
384
+ const location = documentLocation(raw);
385
+ const name = documentName(raw);
386
+ if (location === undefined && name === '') return null;
387
+ return location === undefined ? { ...raw, name } : { ...raw, name, path: location };
388
+ }
389
+
390
+ function checkoutGroupKey(group) {
391
+ if (typeof group.checkoutRoot === 'string' && group.checkoutRoot.length > 0) return group.checkoutRoot;
392
+ if (typeof group.checkoutName === 'string' && group.checkoutName.length > 0) return group.checkoutName;
393
+ return group.isMain === true ? 'main' : '';
394
+ }
395
+
396
+ function checkoutGroupName(group) {
397
+ if (typeof group.checkoutName === 'string' && group.checkoutName.length > 0) return group.checkoutName;
398
+ const root = typeof group.checkoutRoot === 'string' ? group.checkoutRoot.replace(/\/+$/, '') : '';
399
+ if (root !== '') return root.slice(root.lastIndexOf('/') + 1);
400
+ return group.isMain === true ? 'main' : '';
401
+ }
402
+
403
+ function normalizeGroups(raw) {
404
+ if (!Array.isArray(raw)) return null;
405
+ const out = [];
406
+ for (const entry of raw) {
407
+ if (!entry || typeof entry !== 'object') continue;
408
+ const list = Array.isArray(entry.docs) ? entry.docs.map(normalizeGroupDoc).filter(Boolean) : [];
409
+ out.push({
410
+ checkoutName: checkoutGroupName(entry),
411
+ checkoutRoot: typeof entry.checkoutRoot === 'string' ? entry.checkoutRoot : '',
412
+ isMain: entry.isMain === true,
413
+ docs: list,
414
+ });
415
+ }
416
+ return out;
417
+ }
418
+
316
419
  function normalizeLoad(result) {
317
420
  if (!result || typeof result !== 'object') return { ok: false, error: 'document unreadable' };
318
421
  if (result.ok === true && typeof result.text === 'string') return { ok: true, text: result.text };
@@ -334,9 +437,39 @@ function createOddView(options = {}) {
334
437
  // S10b: `options.assigned`, `options.saveAssignment` and
335
438
  // `options.assignmentEnabled` are deliberately not read: the association
336
439
  // belongs to the worktree detail, and this view stays read-only.
440
+ // S10/S11 (T9): the grouped model belongs to the caller, the mode belongs to
441
+ // this view, and the two meet ONE way — `onToggleAll` reports a mode change so
442
+ // the caller can reload the groups (this view never runs git).
443
+ let groups = normalizeGroups(options.groups);
444
+ // S11 (T12): TWO modes, and they are not the same value while a reload is in
445
+ // flight. `requestedAll` is the mode the reader asked for — every `a` press
446
+ // flips it, so the second press returns to where the first started, and a press
447
+ // whose load FAILS returns it to the value it held before that press — while
448
+ // `allMode` is the mode of the data last APPLIED, which is the only thing the
449
+ // footer may name: while a git read is pending the frame still draws the older
450
+ // listing, so a hint describing the request would describe the wrong rows.
451
+ // S11 (T15): the request is also readable (`requestedAll()` on the returned
452
+ // surface) so the caller reloads `r` in the scope the reader is really in — one
453
+ // owner for the request, one for the applied mode, no third copy to drift.
454
+ let allMode = false;
455
+ let requestedAll = false;
456
+ const notifyToggleAll = typeof options.onToggleAll === 'function' ? options.onToggleAll : null;
457
+ // The groups the reader folded away, keyed by checkout, so a fold survives a
458
+ // reload of the same listing and a checkout that leaves drops its own key.
459
+ const foldedCheckouts = new Set();
337
460
  let docs = Array.isArray(options.docs) ? options.docs.slice() : [];
338
461
  const entries = new Map();
339
- const state = { index: 0, scroll: 0, query: '', searching: false, listStart: 0, order: ORDER.RECENT };
462
+ const state = {
463
+ index: 0,
464
+ scroll: 0,
465
+ query: '',
466
+ searching: false,
467
+ listStart: 0,
468
+ order: ORDER.RECENT,
469
+ // S10 (T9): the document being READ, which is not the focused row while a
470
+ // group header holds the focus.
471
+ activeKey: null,
472
+ };
340
473
  let openError = null;
341
474
  // S9: 'idle' | 'reloaded' | 'failed' — the outcome of the last `r` press.
342
475
  let reloadState = 'idle';
@@ -358,7 +491,7 @@ function createOddView(options = {}) {
358
491
  const TITLE_NAME = '✎ Odd';
359
492
 
360
493
  function titleParts() {
361
- return { name: TITLE_NAME, count: `${docs.length} documents` };
494
+ return { name: TITLE_NAME, count: `${documentCount()} documents` };
362
495
  }
363
496
 
364
497
  function titleText() {
@@ -366,20 +499,171 @@ function createOddView(options = {}) {
366
499
  return `${parts.name} · ${parts.count}`;
367
500
  }
368
501
 
502
+ // S10 (T9): the number the frame reports. Without `groups` it is the flat
503
+ // list's own length — the panel of before this unit. With them it is every
504
+ // document the listing is made of, so folding a group never changes the count
505
+ // and an empty worktree never inflates it.
506
+ function documentCount() {
507
+ const drawn = drawnGroups();
508
+ if (!drawn) return flatDocs().length;
509
+ let total = 0;
510
+ for (const group of drawn) total += group.total;
511
+ return total;
512
+ }
513
+
514
+ // S10/S13 (T9): the documents a FLAT listing is made of. With groups that is
515
+ // the main checkout's own documents — main always carries every ODD of main —
516
+ // and without them it is the `docs` array the existing callers hand over. A
517
+ // group set with no main entry keeps answering from `docs`, so a caller that
518
+ // has not started grouping is never left with an empty panel.
519
+ function flatDocs() {
520
+ if (!groups) return docs;
521
+ const main = groups.find((group) => group.isMain === true);
522
+ return main ? main.docs : docs;
523
+ }
524
+
369
525
  // The visible list: the filter narrows by document name
370
526
  // (case-insensitive substring), exactly like the issues viewer keeps its
371
527
  // query after leaving the box — selection indexes into this list. S12: the
372
528
  // ACTIVE order decides the sequence of the filtered rows; the recency order
373
529
  // is whatever the loader returned, so this view only ever sorts a copy.
374
- function shown() {
530
+ function filterAndOrder(list) {
375
531
  const q = state.query.trim().toLowerCase();
376
532
  const matched = q === ''
377
- ? docs
378
- : docs.filter((docEntry) => String((docEntry && docEntry.name) || '').toLowerCase().includes(q));
533
+ ? list
534
+ : list.filter((docEntry) => String((docEntry && docEntry.name) || '').toLowerCase().includes(q));
379
535
  if (state.order !== ORDER.NAME) return matched;
380
536
  return matched.slice().sort(compareByName);
381
537
  }
382
538
 
539
+ function shown() {
540
+ return filterAndOrder(flatDocs());
541
+ }
542
+
543
+ function groupView(group, list) {
544
+ const key = checkoutGroupKey(group);
545
+ return {
546
+ key,
547
+ name: checkoutGroupName(group),
548
+ isMain: group.isMain === true,
549
+ folded: foldedCheckouts.has(key),
550
+ // `list` is what the filter leaves to paint; `total` is what the checkout
551
+ // owns, so the frame's count never moves with the query.
552
+ total: group.docs.length,
553
+ docs: list,
554
+ };
555
+ }
556
+
557
+ // S10/S13 (T9): the groups a frame actually draws, or null for the ordinary
558
+ // flat listing. The main group is ALWAYS drawn so every ODD of main stays
559
+ // reachable; a worktree group is drawn only while it still has documents after
560
+ // the filter, and when no worktree group has one the whole set falls back to
561
+ // the flat main-only listing — never an empty worktree group and never group
562
+ // chrome that says nothing.
563
+ function drawnGroups() {
564
+ if (!groups) return null;
565
+ const main = groups.find((group) => group.isMain === true) || null;
566
+ if (!main) return null;
567
+ const worktrees = groups
568
+ .filter((group) => group !== main)
569
+ .map((group) => ({ group, list: filterAndOrder(group.docs) }))
570
+ .filter((entry) => entry.list.length > 0);
571
+ if (worktrees.length === 0) return null;
572
+ return [
573
+ groupView(main, filterAndOrder(main.docs)),
574
+ ...worktrees.map((entry) => groupView(entry.group, entry.list)),
575
+ ];
576
+ }
577
+
578
+ // S10 (T9): the rows a frame paints. Without groups every row is a document,
579
+ // which is exactly the flat list of before this unit; with them a header opens
580
+ // each drawn group and a folded group paints its header alone. Selection
581
+ // indexes into THIS list, so a header is focusable and a fold changes the rows
582
+ // that follow it without moving the header.
583
+ function visibleRows() {
584
+ const drawn = drawnGroups();
585
+ if (!drawn) return shown().map((docEntry) => ({ kind: 'doc', doc: docEntry }));
586
+ const out = [];
587
+ for (const group of drawn) {
588
+ out.push({ kind: 'header', group });
589
+ if (group.folded) continue;
590
+ for (const docEntry of group.docs) out.push({ kind: 'doc', doc: docEntry, group });
591
+ }
592
+ return out;
593
+ }
594
+
595
+ // S10 (T9): what a row paints. A group header names its checkout behind the
596
+ // fold chevron; a document paints the name without extension or path, exactly
597
+ // as the flat list always has — unless the caller handed a LABEL over with it
598
+ // (T17/F3), in which case that label is what the row reads. `lib/odd-listing.js`
599
+ // derives those labels once, for the panel and the menu alike, so two checkouts
600
+ // that share a name can never paint the same row; a document that carries none
601
+ // keeps the plain reader it always had.
602
+ function rowLabel(row) {
603
+ if (row.kind === 'header') {
604
+ return `${row.group.folded ? GROUP_COLLAPSED_MARK : GROUP_EXPANDED_MARK} ${row.group.name}`;
605
+ }
606
+ const label = row.doc && row.doc.label;
607
+ if (typeof label === 'string' && label.length > 0) return label;
608
+ return String((row.doc && row.doc.name) || '');
609
+ }
610
+
611
+ // S6/S10 (T9): find a document ANYWHERE in the model — across every group, not
612
+ // just the rows a frame happens to draw — by its absolute location first and by
613
+ // the name the list paints second.
614
+ function locateDocument(request) {
615
+ if (typeof request !== 'string' || request.length === 0) return null;
616
+ const sources = groups
617
+ ? groups.map((group) => ({ group, list: group.docs }))
618
+ : [{ group: null, list: docs }];
619
+ for (const source of sources) {
620
+ const hit = source.list.find((docEntry) => docEntry && documentLocation(docEntry) === request);
621
+ if (hit) return { group: source.group, doc: hit };
622
+ }
623
+ for (const source of sources) {
624
+ const hit = source.list.find((docEntry) => docEntry && String(docEntry.name || '') === request);
625
+ if (hit) return { group: source.group, doc: hit };
626
+ }
627
+ return null;
628
+ }
629
+
630
+ function rowOfDoc(key) {
631
+ if (key === null) return -1;
632
+ return visibleRows().findIndex((row) => row.kind === 'doc' && documentKey(row.doc) === key);
633
+ }
634
+
635
+ // S10 (T9): the document being READ. A group header carries no document — it
636
+ // folds a group — so focusing one keeps the pane on the document the reader was
637
+ // already in instead of blanking it or jumping into a hidden group.
638
+ function activeDocument() {
639
+ if (state.activeKey === null) return null;
640
+ const located = locateDocument(state.activeKey);
641
+ return located ? located.doc : null;
642
+ }
643
+
644
+ function activateRow(row) {
645
+ if (row && row.kind === 'doc') state.activeKey = documentKey(row.doc);
646
+ }
647
+
648
+ // S6/S10 (T9): the requested document becomes the selection inside whatever
649
+ // group holds it — its group is unfolded first, so the row exists to select.
650
+ // With no request (or an unknown one) the first DOCUMENT row opens, which is
651
+ // the flat list's first row and, in a grouped listing, main's newest ODD
652
+ // rather than a header.
653
+ function mountIndex(request) {
654
+ const located = locateDocument(request);
655
+ if (located) {
656
+ if (located.group) foldedCheckouts.delete(checkoutGroupKey(located.group));
657
+ const at = rowOfDoc(documentKey(located.doc));
658
+ if (at >= 0) return at;
659
+ }
660
+ const first = visibleRows().findIndex((row) => row.kind === 'doc');
661
+ return first >= 0 ? first : 0;
662
+ }
663
+
664
+ // The host's row budget. `render` is the ONLY caller: one sample per frame, so
665
+ // the body it paints and the scroll it clamps both measure the same viewport
666
+ // even when the source answers differently twice in a row (D2).
383
667
  function availableRows() {
384
668
  try {
385
669
  if (typeof rowsAvailable === 'function') {
@@ -401,8 +685,10 @@ function createOddView(options = {}) {
401
685
  }
402
686
 
403
687
  function current() {
404
- const list = shown();
405
- return list[state.index] || null;
688
+ const row = visibleRows()[state.index] || null;
689
+ if (row === null) return null;
690
+ if (row.kind === 'doc') return row.doc;
691
+ return activeDocument();
406
692
  }
407
693
 
408
694
  function renderLines(entry, text, width) {
@@ -464,6 +750,12 @@ function createOddView(options = {}) {
464
750
  return entry;
465
751
  }
466
752
 
753
+ // The budget is the body this view PAINTED (`bodyRows`), never a second live
754
+ // read of the host's row source: that source can answer differently twice inside
755
+ // one frame, so a second sample would clamp the reader against a viewport no
756
+ // frame ever drew and hide the end of the document (D2). `render` sets bodyRows
757
+ // from its own single sample before clamping, so a key press that lands before
758
+ // the first frame or after a resize still clamps against the viewport on screen.
467
759
  function clampScroll() {
468
760
  const entry = current() ? ensureEntry(current()) : null;
469
761
  const total = entry && entry.status === 'ready' ? entry.lines.length : 0;
@@ -499,7 +791,7 @@ function createOddView(options = {}) {
499
791
  // wrapped name actually needs, never a fixed document count. (The older "para
500
792
  // odd igual, si son muchas igual se pagina" page marker went with the pager.)
501
793
  function listCosts() {
502
- return shown().map((docEntry) => labelRows(String((docEntry && docEntry.name) || ''), listWidthCache, '▸ ', ' ').length);
794
+ return visibleRows().map((row) => labelRows(rowLabel(row), listWidthCache, '▸ ', ' ').length);
503
795
  }
504
796
 
505
797
  // The window the list paints: bounded by the body budget and always holding
@@ -525,6 +817,22 @@ function createOddView(options = {}) {
525
817
  };
526
818
  }
527
819
 
820
+ // S11: the mode token names the ACTION the key would perform — the listing it
821
+ // would show next — so `a all worktrees` and `a session only` can never be read
822
+ // as the same binding. `allMode` is the APPLIED mode (see above), so the token
823
+ // always describes the rows on screen and never a load still in flight.
824
+ // Without the caller's reload seam the key cannot do anything, so its hint is
825
+ // not listed at all.
826
+ function allKey() {
827
+ if (notifyToggleAll === null) return null;
828
+ return {
829
+ key: ALL_KEY,
830
+ text: allMode ? `${ALL_KEY} session only` : `${ALL_KEY} all worktrees`,
831
+ short: allMode ? `${ALL_KEY} session` : `${ALL_KEY} all`,
832
+ priority: ALL_PRIORITY,
833
+ };
834
+ }
835
+
528
836
  // S1: the reader legend is the static keys plus the scroll hints the shared
529
837
  // binding helper says this terminal can actually deliver.
530
838
  //
@@ -542,6 +850,7 @@ function createOddView(options = {}) {
542
850
  selectKey,
543
851
  documentScroll,
544
852
  orderKey(),
853
+ allKey(),
545
854
  searchKey,
546
855
  reloadKey(),
547
856
  ...actionKeys,
@@ -590,6 +899,30 @@ function createOddView(options = {}) {
590
899
  repaint();
591
900
  }
592
901
 
902
+ // S10/S12 (T9): the focused document is remembered by IDENTITY and re-found in
903
+ // the listing that replaced the old one, and a group that folded it away is
904
+ // unfolded first, so a re-grouping can never silently drop the document being
905
+ // read. The window re-anchors on its new position.
906
+ function reanchor(focusedKey) {
907
+ if (focusedKey !== null) {
908
+ let at = rowOfDoc(focusedKey);
909
+ if (at < 0) {
910
+ const located = locateDocument(focusedKey);
911
+ if (located && located.group) {
912
+ foldedCheckouts.delete(checkoutGroupKey(located.group));
913
+ at = rowOfDoc(focusedKey);
914
+ }
915
+ }
916
+ if (at >= 0) state.index = at;
917
+ }
918
+ const rows = visibleRows();
919
+ state.index = Math.max(0, Math.min(state.index, Math.max(0, rows.length - 1)));
920
+ activateRow(rows[state.index] || null);
921
+ const win = layout.scrollWindow(listCosts(), { budget: Math.max(1, bodyRows), index: state.index, start: 0 });
922
+ state.listStart = win.start;
923
+ ensureEntry(current());
924
+ }
925
+
593
926
  // S12: `s` alternates the loader's recency order with a case-insensitive
594
927
  // alphabetical one. The focused document is remembered by identity and
595
928
  // re-found in the new sequence, so the reader keeps reading the SAME document
@@ -599,18 +932,25 @@ function createOddView(options = {}) {
599
932
  // its alphabetical place is far from the old one.
600
933
  function toggleOrder() {
601
934
  const focused = current();
602
- const focusedKey = focused ? (focused.path || focused.name) : null;
935
+ const focusedKey = focused ? documentKey(focused) : null;
603
936
  state.order = state.order === ORDER.NAME ? ORDER.RECENT : ORDER.NAME;
604
- const list = shown();
605
- let next = Math.min(state.index, Math.max(0, list.length - 1));
606
- if (focusedKey !== null) {
607
- const at = list.findIndex((docEntry) => docEntry && (docEntry.path || docEntry.name) === focusedKey);
608
- if (at >= 0) next = at;
609
- }
610
- state.index = Math.max(0, next);
611
- const win = layout.scrollWindow(listCosts(), { budget: Math.max(1, bodyRows), index: state.index, start: 0 });
937
+ reanchor(focusedKey);
938
+ repaint();
939
+ }
940
+
941
+ // S10 (T9): Enter folds the focused checkout's group — the header stays, the
942
+ // documents under it go, and so the focus stays where it was.
943
+ function toggleFold(group) {
944
+ if (foldedCheckouts.has(group.key)) foldedCheckouts.delete(group.key);
945
+ else foldedCheckouts.add(group.key);
946
+ const at = visibleRows().findIndex((row) => row.kind === 'header' && row.group.key === group.key);
947
+ if (at >= 0) state.index = at;
948
+ const win = layout.scrollWindow(listCosts(), {
949
+ budget: Math.max(1, bodyRows),
950
+ index: state.index,
951
+ start: state.listStart,
952
+ });
612
953
  state.listStart = win.start;
613
- ensureEntry(current());
614
954
  repaint();
615
955
  }
616
956
 
@@ -622,8 +962,8 @@ function createOddView(options = {}) {
622
962
  if (w < MIN_WIDTH || height < 4) {
623
963
  return [pad(helpers, fit(helpers, `${title} — enlarge the terminal`, w), w)].slice(0, Math.max(1, Math.min(height, 1)));
624
964
  }
625
- const list = shown();
626
- if (state.index >= list.length) state.index = Math.max(0, list.length - 1);
965
+ const rows = visibleRows();
966
+ if (state.index >= rows.length) state.index = Math.max(0, rows.length - 1);
627
967
  // S3: the shared 30/70 reader rule owns this geometry, so ODD matches the
628
968
  // issues reader with the smaller list index and the larger reading pane.
629
969
  // CARD_PADDING covers the frame's own `│ ` and ` │` cells, so this inner
@@ -684,28 +1024,40 @@ function createOddView(options = {}) {
684
1024
  lines.push(`${border('│')} ${pad(helpers, searchCell, inner)} ${border('│')}`);
685
1025
 
686
1026
  const listLines = [];
687
- if (docs.length === 0) {
1027
+ if (documentCount() === 0) {
688
1028
  listLines.push(paint(theme, 'muted', EMPTY_LIST));
689
1029
  listLines.push(paint(theme, 'dim', EMPTY_HINT));
690
- } else if (list.length === 0) {
1030
+ } else if (rows.length === 0) {
691
1031
  listLines.push(paint(theme, 'muted', '(no matches)'));
692
1032
  } else {
693
- // S3/S5/S17: each name wraps over the rows it needs — at spaces and at
694
- // its own hyphens — and the ONE window paints the documents whose wrapped
695
- // rows fit the body budget, keeping the focused document inside it.
1033
+ // S3/S5/S17: each row wraps over the rows it needs — at spaces and at its
1034
+ // own hyphens — and the ONE window paints the rows whose wrapped lines fit
1035
+ // the body budget, keeping the focused row inside it.
696
1036
  const win = listWindow();
697
1037
  state.listStart = win.start;
698
1038
  for (let at = win.start; at < win.end; at += 1) {
1039
+ const row = rows[at];
1040
+ if (!row) continue;
699
1041
  const focused = at === state.index;
700
- const rows = labelRows(String((list[at] && list[at].name) || ''), listWidth, focused ? '▸ ' : ' ', ' ');
701
- for (const row of rows) {
702
- listLines.push(highlight(theme, pad(helpers, row, listWidth), focused));
1042
+ // S10 (T9): a checkout header takes the neutral grey role (the files
1043
+ // picker's own group rows do), so it reads as chrome beside the documents
1044
+ // while the focus band and the `▸` mark still tell where the cursor is.
1045
+ if (row.kind === 'header') {
1046
+ const wrapped = labelRows(rowLabel(row), listWidth, focused ? '▸ ' : ' ', ' ');
1047
+ for (const line of wrapped) {
1048
+ listLines.push(highlight(theme, palette.label(theme, pad(helpers, line, listWidth)), focused));
1049
+ }
1050
+ continue;
1051
+ }
1052
+ const wrapped = labelRows(rowLabel(row), listWidth, focused ? '▸ ' : ' ', ' ');
1053
+ for (const line of wrapped) {
1054
+ listLines.push(highlight(theme, pad(helpers, line, listWidth), focused));
703
1055
  }
704
1056
  }
705
1057
  }
706
1058
  const contentLines = [];
707
1059
  if (!docEntry) {
708
- if (docs.length === 0) {
1060
+ if (documentCount() === 0) {
709
1061
  contentLines.push(paint(theme, 'muted', EMPTY_LIST));
710
1062
  contentLines.push(paint(theme, 'dim', EMPTY_HINT));
711
1063
  } else {
@@ -736,10 +1088,18 @@ function createOddView(options = {}) {
736
1088
  }
737
1089
 
738
1090
  function selectNext(step) {
739
- const list = shown();
740
- if (list.length === 0) return;
741
- state.index = (state.index + step + list.length) % list.length;
1091
+ const rows = visibleRows();
1092
+ if (rows.length === 0) return;
1093
+ state.index = (state.index + step + rows.length) % rows.length;
1094
+ const row = rows[state.index] || null;
1095
+ // S10 (T9): a header folds a group, it opens nothing, so the pane keeps the
1096
+ // document the reader was already in and its reading position.
1097
+ if (row && row.kind === 'header') {
1098
+ repaint();
1099
+ return;
1100
+ }
742
1101
  state.scroll = 0;
1102
+ activateRow(row);
743
1103
  ensureEntry(current());
744
1104
  repaint();
745
1105
  }
@@ -826,6 +1186,14 @@ function createOddView(options = {}) {
826
1186
  scrollBy(down ? step : -step);
827
1187
  return;
828
1188
  }
1189
+ // S10 (T9): Enter on a checkout header folds it — documents hidden, header
1190
+ // kept, focus kept on the header. On a document it is today's no-op: a
1191
+ // document opens by being selected.
1192
+ if (keyMatches(helpers, data, ['enter', 'return'])) {
1193
+ const row = visibleRows()[state.index] || null;
1194
+ if (row && row.kind === 'header') toggleFold(row.group);
1195
+ return;
1196
+ }
829
1197
  if (keyMatches(helpers, data, ['escape', 'ctrl+c', 'q'])) {
830
1198
  if (typeof done === 'function') done(null);
831
1199
  return;
@@ -843,6 +1211,54 @@ function createOddView(options = {}) {
843
1211
  toggleOrder();
844
1212
  return;
845
1213
  }
1214
+ // S11 (T9): `a` alternates this session's checkouts with every worktree. The
1215
+ // MODE lives here; the groups belong to the caller, which is told once with
1216
+ // the new value and reloads them (this view never runs git). The document
1217
+ // being read is re-applied when the reloaded listing still carries it.
1218
+ //
1219
+ // T12: the hint follows the data, so the ANSWER decides when it may flip. A
1220
+ // caller that reloads asynchronously (a real git read) hands back a promise
1221
+ // and the new mode is recorded when that load is APPLIED through
1222
+ // `applyGroups(list, { all })` — or never, if it is dropped as stale. A
1223
+ // caller with the listing already in hand answers synchronously and the hint
1224
+ // flips at once, exactly as it always has. Either way `a` makes ONE call.
1225
+ //
1226
+ // T13/S11: a promise that resolves `false`, or rejects, is a FAILED load. The
1227
+ // rows and the applied mode stay and the toggle is rolled back to the value it
1228
+ // held BEFORE this press, so the next press asks again for the scope this one
1229
+ // asked for instead of flipping to the opposite one — in every order, even
1230
+ // when a second press (or a reload that landed) moved the mode meanwhile.
1231
+ if (keyMatches(helpers, data, [ALL_KEY])) {
1232
+ if (notifyToggleAll === null) return;
1233
+ const focused = current();
1234
+ const focusedKey = focused ? documentKey(focused) : null;
1235
+ // The request this press starts from: what a failed load returns to.
1236
+ const before = requestedAll;
1237
+ requestedAll = !requestedAll;
1238
+ const mode = requestedAll;
1239
+ let answer = null;
1240
+ try {
1241
+ answer = notifyToggleAll(mode);
1242
+ } catch {
1243
+ // A throwing loader never breaks the view; the next listing answers.
1244
+ }
1245
+ if (!answer || typeof answer.then !== 'function') {
1246
+ allMode = mode;
1247
+ } else {
1248
+ const revert = () => {
1249
+ // Only roll back while this press is still the LATEST one: a newer press
1250
+ // owns the request now, and its own failure (or apply) decides.
1251
+ if (requestedAll === mode) requestedAll = before;
1252
+ repaint();
1253
+ };
1254
+ Promise.resolve(answer).then((applied) => {
1255
+ if (applied === false) revert();
1256
+ }, revert);
1257
+ }
1258
+ if (focusedKey !== null) reanchor(focusedKey);
1259
+ repaint();
1260
+ return;
1261
+ }
846
1262
  // `o` opens the focused document outside Pi through $VISUAL/$EDITOR:
847
1263
  // the injected opener reports honestly, so a missing editor or a
848
1264
  // failed spawn shows its error instead of failing silently.
@@ -911,6 +1327,9 @@ function createOddView(options = {}) {
911
1327
  // PROMISE — the interactive caller re-lists through the awaited Git reader,
912
1328
  // so a slow history walk is never a blocking read inside this key handler
913
1329
  // (the view keeps painting and the outcome lands when the listing does).
1330
+ // D2 (T6): the seam may instead resolve RELOAD_SUPERSEDED, which means its
1331
+ // answer lost the race and the view does nothing with it — no row, no scroll,
1332
+ // no footer token (see `settle` below).
914
1333
  if (keyMatches(helpers, data, [RELOAD_KEY])) {
915
1334
  if (typeof reloadDocs !== 'function') return;
916
1335
  let result = null;
@@ -922,6 +1341,9 @@ function createOddView(options = {}) {
922
1341
  return;
923
1342
  }
924
1343
  const settle = (next) => {
1344
+ // D2: a superseded answer is inert — not even a footer token moves,
1345
+ // because what is painted belongs to a later reload than this one.
1346
+ if (next === RELOAD_SUPERSEDED) return;
925
1347
  if (!next || next.ok !== true || !Array.isArray(next.docs)) {
926
1348
  reloadState = 'failed';
927
1349
  repaint();
@@ -932,7 +1354,8 @@ function createOddView(options = {}) {
932
1354
  reloadState = 'reloaded';
933
1355
  // The filter survives a reload: clamp the selection into the
934
1356
  // still-visible list, exactly like the issues viewer keeps its query.
935
- if (state.index >= shown().length) state.index = Math.max(0, shown().length - 1);
1357
+ const rows = visibleRows();
1358
+ if (state.index >= rows.length) state.index = Math.max(0, rows.length - 1);
936
1359
  state.scroll = 0;
937
1360
  ensureEntry(current());
938
1361
  repaint();
@@ -961,30 +1384,61 @@ function createOddView(options = {}) {
961
1384
  // reader the pane they are already reading (and could only surface a
962
1385
  // difference the settled order never claimed). An answer that is not a list
963
1386
  // leaves the open view exactly as it is.
1387
+ //
1388
+ // S10 (T9): this seam carries the FLAT listing. A grouped panel is reloaded
1389
+ // through `applyGroups` below, which is the same discipline over the model that
1390
+ // replaced it.
964
1391
  function applyDocs(next) {
965
1392
  if (!Array.isArray(next)) return;
966
1393
  const focused = current();
967
- const focusedKey = focused ? (focused.path || focused.name) : null;
1394
+ const focusedKey = focused ? documentKey(focused) : null;
968
1395
  docs = next.slice();
969
- const list = shown();
970
- let target = Math.min(state.index, Math.max(0, list.length - 1));
971
- if (focusedKey !== null) {
972
- const at = list.findIndex((docEntry) => docEntry && (docEntry.path || docEntry.name) === focusedKey);
973
- if (at >= 0) target = at;
974
- }
975
- state.index = Math.max(0, target);
976
- const win = layout.scrollWindow(listCosts(), { budget: Math.max(1, bodyRows), index: state.index, start: 0 });
977
- state.listStart = win.start;
978
- ensureEntry(current());
1396
+ reanchor(focusedKey);
1397
+ repaint();
1398
+ }
1399
+
1400
+ // S11/S13 (T9): the caller owns the grouped model — git is never run here — so
1401
+ // an `a` toggle is answered by handing the NEW grouping back. The reader's
1402
+ // document is re-applied when the reloaded listing still has it (S11), the fold
1403
+ // state is kept per checkout for the groups that survive, and an answer that is
1404
+ // not a list leaves the open panel exactly as it is — the same discipline
1405
+ // `applyDocs` keeps for the flat listing.
1406
+ //
1407
+ // T12: `applied.all` names the scope this listing was read in, so the footer's
1408
+ // hint moves WITH the data it describes. A reload that keeps the mode (the `r`
1409
+ // key, the startup ranking) omits it and the applied mode stands.
1410
+ function applyGroups(next, applied = {}) {
1411
+ if (!Array.isArray(next)) return;
1412
+ if (applied.all === true) allMode = true;
1413
+ else if (applied.all === false) allMode = false;
1414
+ const focused = current();
1415
+ const focusedKey = focused ? documentKey(focused) : null;
1416
+ groups = normalizeGroups(next);
1417
+ reanchor(focusedKey);
979
1418
  repaint();
980
1419
  }
981
1420
 
1421
+ // S6/S10: the requested document becomes the selection BEFORE the mount load,
1422
+ // so the very first frame carries its body and its highlighted row — no key press
1423
+ // is needed to see the ODD the caller opened.
1424
+ state.index = mountIndex(options.initialDoc);
1425
+ activateRow(visibleRows()[state.index] || null);
1426
+
982
1427
  // The selected document starts loading as soon as the view exists, so the
983
1428
  // first frame the host paints already carries content instead of a
984
1429
  // placeholder.
985
1430
  ensureEntry(current());
986
1431
 
987
- return { render, handleInput, invalidate, handleMouse, applyDocs, state };
1432
+ // S11 (T15): the scope the READER is asking for — the mode every `a` press asks
1433
+ // the caller to load, returned to the value it held before a press whose load
1434
+ // failed. The caller reloads `r` in it, so a pending request and a failed one
1435
+ // both land on the scope the reader is really in, and the view stays the only
1436
+ // owner of that request.
1437
+ function requestedScope() {
1438
+ return requestedAll;
1439
+ }
1440
+
1441
+ return { render, handleInput, invalidate, handleMouse, applyDocs, applyGroups, requestedAll: requestedScope, state };
988
1442
  }
989
1443
 
990
- module.exports = { createOddView, CONTENT_KEYS, SEARCH_KEYS, EMPTY_LIST, EMPTY_HINT };
1444
+ module.exports = { createOddView, CONTENT_KEYS, SEARCH_KEYS, EMPTY_LIST, EMPTY_HINT, RELOAD_SUPERSEDED };