cursedbelt 5.22.1 → 5.23.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.
@@ -0,0 +1,248 @@
1
+ /**
2
+ * Closing a file puts the grid back where you were — task 2255.
3
+ *
4
+ * Owner, 2026-09-28, after flix's "Back keeps your place": *"is a common enough need … I want it
5
+ * to be in cb … find other apps we have that have scrolling and similar issues where we can't
6
+ * go back to the right place like flix had"*.
7
+ *
8
+ * `MediaGallery` draws `DenseGalleryDetail` while a file is open and `DenseGalleryShell`
9
+ * otherwise. They are different trees, so closing a file — by ✕, by a deep link's Back
10
+ * (`useGalleryDeepLink`'s `?i=`), by deleting it — MOUNTS A NEW GRID, and its scroller starts
11
+ * at zero. Measured in Chromium before this (`e2e/gallery-return.spec.ts`, 240 tiles, scrolled
12
+ * to 3,000px): every close landed at scrollTop 0, at phone and desktop size, two hundred tiles
13
+ * from where you had been.
14
+ *
15
+ * 🔴 Why not `useScrollMemory`. That hook is per HISTORY ENTRY, and a gallery's open/close is
16
+ * a history entry only when its consumer deep-links it. An uncontrolled gallery closes with no
17
+ * navigation at all, so the memory has to live with the gallery — which is also what keeps
18
+ * every consumer from having to wire anything.
19
+ *
20
+ * Two rules, in order:
21
+ * 1. **The offset comes back** — the browse scroller's own `scrollTop` (the tile grid's
22
+ * `.cbgd-grid`, or the table's `.cbgt-root`), recorded while you browse and put back when
23
+ * the view returns, if it returns in the same grid/table mode. It retries each frame while
24
+ * the virtualized track is still growing into the offset, and a touch, wheel, key or
25
+ * pointer press cancels it — the viewer always wins.
26
+ * 2. **…then the last file SHOWN is on screen.** Stepping through twenty files moves you: the
27
+ * place you are now is the last file the stage showed, not the one you opened. When that
28
+ * file's tile is not visible after rule 1 it is brought to the middle of the scroller. A
29
+ * tile that is already even partly visible is left alone — a grid that jumps a few pixels
30
+ * under a tile you can see reads as a bug (the same limit the strip's reveal keeps).
31
+ * A virtualized tile that is not mounted is found by arithmetic on the tiles that are:
32
+ * their row pitch and column count place it, and the next frame centres it exactly.
33
+ */
34
+ import { type RefObject, useEffect, useLayoutEffect, useRef } from 'react';
35
+
36
+ /** The browse view's scroller in either view: the tile grid, or the table's frame. */
37
+ const SCROLLER = '.cbgd-grid, .cbgt-root';
38
+ /** Every tile and every table row carries its item's id under this attribute. */
39
+ export const ITEM_ID_ATTR = 'data-item-id';
40
+ /** How long a return may keep trying before it settles for what the scroller can hold. */
41
+ const DEADLINE_MS = 1500;
42
+ const CANCEL_EVENTS = ['wheel', 'touchstart', 'pointerdown', 'keydown'] as const;
43
+
44
+ export interface GalleryReturnOptions {
45
+ /** `.cbgd-root` of the browse view — `DenseGalleryShell`'s `rootRef`. */
46
+ rootRef: RefObject<HTMLDivElement | null>;
47
+ /** True while the browse view (no file open) is the one on screen. */
48
+ browsing: boolean;
49
+ /** Grid or table: an offset recorded in one means nothing in the other. */
50
+ viewMode: string;
51
+ /** The file on the stage right now, or null. */
52
+ shownId: string | null;
53
+ /** The displayed order, which is what places a tile that is not mounted. */
54
+ displayIds: readonly string[];
55
+ }
56
+
57
+ export function useGalleryReturn({
58
+ rootRef,
59
+ browsing,
60
+ viewMode,
61
+ shownId,
62
+ displayIds,
63
+ }: GalleryReturnOptions): void {
64
+ const saved = useRef<{ mode: string; top: number } | null>(null);
65
+ const lastShown = useRef<string | null>(null);
66
+ const restoring = useRef(false);
67
+ const wasBrowsing = useRef(browsing);
68
+ // Read through refs at fire time: they are inputs the return needs CURRENT, not triggers.
69
+ const modeRef = useRef(viewMode);
70
+ const idsRef = useRef(displayIds);
71
+ modeRef.current = viewMode;
72
+ idsRef.current = displayIds;
73
+ if (shownId) lastShown.current = shownId;
74
+
75
+ // Record the browse scroller's offset while browsing. Capture phase, because `scroll` does
76
+ // not bubble and the scroller is whichever of the two views is mounted.
77
+ useEffect(() => {
78
+ const root = rootRef.current;
79
+ if (!browsing || !root) return;
80
+ const onScroll = (event: Event): void => {
81
+ const target = event.target;
82
+ if (restoring.current || !(target instanceof HTMLElement) || !target.matches(SCROLLER)) return;
83
+ saved.current = { mode: modeRef.current, top: target.scrollTop };
84
+ };
85
+ root.addEventListener('scroll', onScroll, { capture: true, passive: true });
86
+ return () => root.removeEventListener('scroll', onScroll, { capture: true });
87
+ }, [browsing, rootRef]);
88
+
89
+ // A layout effect, so the offset is back before the returning grid is ever painted at zero.
90
+ // biome-ignore lint/correctness/useExhaustiveDependencies: `browsing` is the one trigger — a return is the moment it turns true. Everything else is read through refs above, on purpose: a re-sort or a new page of items must not replay a return.
91
+ useLayoutEffect(() => {
92
+ const returning = browsing && !wasBrowsing.current;
93
+ wasBrowsing.current = browsing;
94
+ if (!returning) return;
95
+ const scroller = rootRef.current?.querySelector<HTMLElement>(SCROLLER);
96
+ if (!scroller) return;
97
+ const target = saved.current?.mode === modeRef.current ? saved.current.top : null;
98
+ const revealId = lastShown.current;
99
+ if (target === null && !revealId) return;
100
+ return returnTo(scroller, target, revealId, idsRef, () => {
101
+ restoring.current = false;
102
+ saved.current = { mode: modeRef.current, top: scroller.scrollTop };
103
+ }, restoring);
104
+ }, [browsing]);
105
+ }
106
+
107
+ /**
108
+ * Put `scroller` back at `target`, then bring `revealId`'s tile into view. Returns the cancel.
109
+ */
110
+ function returnTo(
111
+ scroller: HTMLElement,
112
+ target: number | null,
113
+ revealId: string | null,
114
+ idsRef: RefObject<readonly string[]>,
115
+ done: () => void,
116
+ restoring: { current: boolean },
117
+ ): () => void {
118
+ // Each phase gets its own deadline, so a list that never grows back into the offset still
119
+ // leaves the reveal its full budget.
120
+ let started = performance.now();
121
+ let frame = 0;
122
+ let phase: 'offset' | 'reveal' | 'centre' = target === null ? 'reveal' : 'offset';
123
+ let finished = false;
124
+ restoring.current = true;
125
+
126
+ const finish = (): void => {
127
+ if (finished) return;
128
+ finished = true;
129
+ cancelAnimationFrame(frame);
130
+ for (const type of CANCEL_EVENTS) scroller.removeEventListener(type, finish);
131
+ done();
132
+ };
133
+ for (const type of CANCEL_EVENTS) scroller.addEventListener(type, finish, { passive: true });
134
+
135
+ const tick = (): void => {
136
+ if (finished) return;
137
+ const late = performance.now() - started > DEADLINE_MS;
138
+ if (phase === 'offset' && target !== null) {
139
+ scroller.scrollTop = target;
140
+ // Reached, or the list is simply shorter now (a filter, a delete): settle for its end.
141
+ if (Math.abs(scroller.scrollTop - target) < 1 || late) {
142
+ phase = 'reveal';
143
+ started = performance.now();
144
+ }
145
+ frame = requestAnimationFrame(tick);
146
+ return;
147
+ }
148
+ const ids = idsRef.current ?? [];
149
+ const index = revealId ? ids.indexOf(revealId) : -1;
150
+ if (index < 0 || late) {
151
+ finish();
152
+ return;
153
+ }
154
+ const tile = scroller.querySelector<HTMLElement>(`[${ITEM_ID_ATTR}="${cssEscape(revealId ?? '')}"]`);
155
+ const band = visibleBand(scroller);
156
+ if (tile) {
157
+ const box = tile.getBoundingClientRect();
158
+ const visible = box.bottom > band.top && box.top < band.bottom;
159
+ // Rule 2's limit: a tile you can already see is not moved — unless WE just jumped to an
160
+ // estimate of it, which is only ever close.
161
+ if (!visible || phase === 'centre') scroller.scrollTop += centreDelta(box, band);
162
+ finish();
163
+ return;
164
+ }
165
+ // 🔴 Not mounted — but first make sure the VIRTUALIZER has caught up with the offset just
166
+ // set. The table re-windows on its own scroll state a render later, so for a frame or two
167
+ // after a jump it still holds the rows from the top; estimating off those would place a
168
+ // tile that is about to appear right where you are. Nothing mounted in the band = wait.
169
+ if (!mountedInBand(scroller, band)) {
170
+ frame = requestAnimationFrame(tick);
171
+ return;
172
+ }
173
+ // Truly windowed out. Place it by the tiles that ARE mounted.
174
+ const estimate = estimateTop(scroller, band, ids, index);
175
+ if (estimate === null) {
176
+ finish();
177
+ return;
178
+ }
179
+ scroller.scrollTop = estimate;
180
+ phase = 'centre';
181
+ frame = requestAnimationFrame(tick);
182
+ };
183
+
184
+ tick();
185
+ return () => {
186
+ if (finished) return;
187
+ finished = true;
188
+ cancelAnimationFrame(frame);
189
+ for (const type of CANCEL_EVENTS) scroller.removeEventListener(type, finish);
190
+ restoring.current = false;
191
+ };
192
+ }
193
+
194
+ interface Band {
195
+ top: number;
196
+ bottom: number;
197
+ }
198
+
199
+ /** The part of the scroller a person can see — below the table's sticky header, if any. */
200
+ function visibleBand(scroller: HTMLElement): Band {
201
+ const view = scroller.getBoundingClientRect();
202
+ const head = scroller.querySelector('thead');
203
+ const top = head ? Math.max(view.top, head.getBoundingClientRect().bottom) : view.top;
204
+ return { top, bottom: view.bottom };
205
+ }
206
+
207
+ /** Does any tile or row sit in the visible band — i.e. has the window caught up? */
208
+ function mountedInBand(scroller: HTMLElement, band: Band): boolean {
209
+ for (const el of scroller.querySelectorAll<HTMLElement>(`[${ITEM_ID_ATTR}]`)) {
210
+ const box = el.getBoundingClientRect();
211
+ if (box.bottom > band.top && box.top < band.bottom) return true;
212
+ }
213
+ return false;
214
+ }
215
+
216
+ function centreDelta(box: DOMRect, band: Band): number {
217
+ return box.top + box.height / 2 - (band.top + band.bottom) / 2;
218
+ }
219
+
220
+ /**
221
+ * A `scrollTop` that centres the tile at `index`, derived from the mounted ones: the first
222
+ * mounted row gives the column count (only the LAST row of a grid can be short), and the next
223
+ * row down gives the pitch. A table is the same arithmetic with one column.
224
+ */
225
+ function estimateTop(scroller: HTMLElement, band: Band, ids: readonly string[], index: number): number | null {
226
+ const placed: { index: number; top: number; height: number }[] = [];
227
+ for (const el of scroller.querySelectorAll<HTMLElement>(`[${ITEM_ID_ATTR}]`)) {
228
+ const at = ids.indexOf(el.getAttribute(ITEM_ID_ATTR) ?? '');
229
+ if (at < 0) continue;
230
+ const box = el.getBoundingClientRect();
231
+ placed.push({ index: at, top: box.top - band.top + scroller.scrollTop, height: box.height });
232
+ }
233
+ if (placed.length === 0) return null;
234
+ placed.sort((a, b) => a.index - b.index);
235
+ const anchor = placed[0] as (typeof placed)[number];
236
+ const cols = Math.max(1, placed.filter((p) => Math.abs(p.top - anchor.top) < 1).length);
237
+ const below = placed.find((p) => p.top - anchor.top >= 1);
238
+ const rowOf = (at: number): number => Math.floor(at / cols);
239
+ const pitch = below ? (below.top - anchor.top) / (rowOf(below.index) - rowOf(anchor.index) || 1) : anchor.height;
240
+ const rows = rowOf(index) - rowOf(anchor.index);
241
+ const top = anchor.top + rows * pitch;
242
+ return Math.max(0, top + anchor.height / 2 - (band.bottom - band.top) / 2);
243
+ }
244
+
245
+ /** `CSS.escape` where it exists (every browser); ids are app-chosen strings. */
246
+ function cssEscape(value: string): string {
247
+ return typeof CSS !== 'undefined' && CSS.escape ? CSS.escape(value) : value.replace(/["\\]/g, '\\$&');
248
+ }