cursedbelt 6.26.0 → 6.29.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.
- package/dist/react/components/DataTable/DataTable.d.ts.map +1 -1
- package/dist/react/components/DataTable/DataTable.js +28 -9
- package/dist/react/components/DataTable/DataTable.js.map +1 -1
- package/dist/react/index.d.ts +1 -0
- package/dist/react/index.d.ts.map +1 -1
- package/dist/react/index.js +1 -0
- package/dist/react/index.js.map +1 -1
- package/dist/react/media/DenseGalleryShell.d.ts +7 -1
- package/dist/react/media/DenseGalleryShell.d.ts.map +1 -1
- package/dist/react/media/DenseGalleryShell.js +2 -2
- package/dist/react/media/DenseGalleryShell.js.map +1 -1
- package/dist/react/media-gallery/GalleryTable.d.ts +12 -1
- package/dist/react/media-gallery/GalleryTable.d.ts.map +1 -1
- package/dist/react/media-gallery/GalleryTable.js +37 -6
- package/dist/react/media-gallery/GalleryTable.js.map +1 -1
- package/dist/react/media-gallery/MediaGallery.d.ts +39 -3
- package/dist/react/media-gallery/MediaGallery.d.ts.map +1 -1
- package/dist/react/media-gallery/MediaGallery.js +122 -12
- package/dist/react/media-gallery/MediaGallery.js.map +1 -1
- package/dist/react/media-gallery/index.d.ts +1 -1
- package/dist/react/media-gallery/index.d.ts.map +1 -1
- package/dist/react/media-gallery/index.js.map +1 -1
- package/dist/react/media-gallery/mediaGallery.css +16 -0
- package/dist/react/notifications/issueCapture.d.ts +9 -0
- package/dist/react/notifications/issueCapture.d.ts.map +1 -1
- package/dist/react/notifications/issueCapture.js +25 -3
- package/dist/react/notifications/issueCapture.js.map +1 -1
- package/dist/react/usePrefixList.d.ts +82 -0
- package/dist/react/usePrefixList.d.ts.map +1 -0
- package/dist/react/usePrefixList.js +139 -0
- package/dist/react/usePrefixList.js.map +1 -0
- package/dist/scripts/guardrailsEnforce.d.ts.map +1 -1
- package/dist/testing/shell.d.ts +1 -0
- package/dist/testing/shell.d.ts.map +1 -1
- package/dist/testing/shell.js +2 -0
- package/dist/testing/shell.js.map +1 -1
- package/package.json +2 -2
- package/scripts/guardrails-baseline.json +1 -0
- package/scripts/guardrailsEnforce.spec.ts +31 -0
- package/scripts/guardrailsEnforce.ts +49 -0
- package/scripts/styleAreas.ts +2 -0
- package/src/react/components/DataTable/DataTable.tsx +26 -7
- package/src/react/components/DataTable/selection.spec.tsx +36 -0
- package/src/react/index.ts +6 -0
- package/src/react/media/DenseGalleryShell.tsx +8 -0
- package/src/react/media-gallery/GalleryTable.tsx +54 -6
- package/src/react/media-gallery/MediaGallery.spec.tsx +61 -0
- package/src/react/media-gallery/MediaGallery.tsx +170 -12
- package/src/react/media-gallery/index.ts +1 -0
- package/src/react/media-gallery/mediaGallery.css +16 -0
- package/src/react/notifications/issueCapture.spec.ts +21 -0
- package/src/react/notifications/issueCapture.ts +29 -3
- package/src/react/usePrefixList.spec.tsx +156 -0
- package/src/react/usePrefixList.ts +229 -0
- package/src/testing/shell.ts +2 -0
|
@@ -101,6 +101,28 @@ function keyOf(text: string): string {
|
|
|
101
101
|
/** Noise every browser emits that is not a bug in the app. */
|
|
102
102
|
const BENIGN = [/ResizeObserver loop/i, /^Script error\.?$/i, /AbortError/i, /The user aborted a request/i];
|
|
103
103
|
|
|
104
|
+
/** A file the page loads as code — the bundle, or a module the dev server serves. */
|
|
105
|
+
const SCRIPT_FILE = /\.(?:[mc]?[jt]sx?)$/i;
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* 🔴 An error thrown by a script the BROWSER put in the page, not one the app shipped (forge tasks
|
|
109
|
+
* 5719-5728). iOS browsers inject their own user scripts — Brave and Firefox's `__firefox__.reader`,
|
|
110
|
+
* a wallet's `window.ethereum`, Dark Reader — and when one throws, WebKit names the DOCUMENT as its
|
|
111
|
+
* file at line 1. The app's code never does: the bundle reports its `/assets/*.js`, and an inline
|
|
112
|
+
* script in `index.html` sits below the doctype. So "the page itself, line 1" is somebody else's
|
|
113
|
+
* code, and calling it "a bug in the code" filed ten health tasks off one visitor's Brave on iPhone.
|
|
114
|
+
*/
|
|
115
|
+
export function isInjectedByBrowser(filename: string | undefined, lineno: number | undefined): boolean {
|
|
116
|
+
if (!filename || (lineno ?? 0) > 1) return false;
|
|
117
|
+
let url: URL;
|
|
118
|
+
try {
|
|
119
|
+
url = new URL(filename);
|
|
120
|
+
} catch {
|
|
121
|
+
return false;
|
|
122
|
+
}
|
|
123
|
+
return /^https?:$/.test(url.protocol) && !SCRIPT_FILE.test(url.pathname);
|
|
124
|
+
}
|
|
125
|
+
|
|
104
126
|
/**
|
|
105
127
|
* Start watching. Returns the uninstall. Installing twice replaces the first, so a hot reload
|
|
106
128
|
* does not wrap `fetch` in itself.
|
|
@@ -272,11 +294,11 @@ export function installIssueCapture(options: IssueCaptureOptions = {}): () => vo
|
|
|
272
294
|
|
|
273
295
|
// ── code ────────────────────────────────────────────────────────────────────────────────────
|
|
274
296
|
const moments = new Map<string, ReturnType<typeof setTimeout>>();
|
|
275
|
-
const broke = (raw: string, where?: string): void => {
|
|
297
|
+
const broke = (raw: string, where?: string, foreign = false): void => {
|
|
276
298
|
// The raw message only CLASSIFIES (benign, stale deploy); what is kept is the scrubbed one.
|
|
277
299
|
const text = keep(raw, 'error');
|
|
278
300
|
recordDiagnostic({ kind: 'error', text: where ? `${text} (${where})` : text, bad: true });
|
|
279
|
-
if (BENIGN.some((pattern) => pattern.test(raw))) return;
|
|
301
|
+
if (foreign || BENIGN.some((pattern) => pattern.test(raw))) return;
|
|
280
302
|
// 🔴 A file this page asked for is gone: the tab is one deploy behind, which is not a bug in the
|
|
281
303
|
// code and is fixed by loading the current page (forge task 4622 — photos called it a bug).
|
|
282
304
|
// `lazyWithReload` reloads on its own for a view; this is the same failure arriving from a
|
|
@@ -314,7 +336,11 @@ export function installIssueCapture(options: IssueCaptureOptions = {}): () => vo
|
|
|
314
336
|
);
|
|
315
337
|
};
|
|
316
338
|
const onError = (event: ErrorEvent): void => {
|
|
317
|
-
broke(
|
|
339
|
+
broke(
|
|
340
|
+
event.message || messageOf(event.error),
|
|
341
|
+
event.filename ? `${event.filename}:${event.lineno}:${event.colno}` : undefined,
|
|
342
|
+
isInjectedByBrowser(event.filename, event.lineno),
|
|
343
|
+
);
|
|
318
344
|
};
|
|
319
345
|
const onRejection = (event: PromiseRejectionEvent): void => broke(messageOf(event.reason));
|
|
320
346
|
window.addEventListener('error', onError);
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
|
3
|
+
import { act, renderHook, waitFor } from '@testing-library/react';
|
|
4
|
+
import type { ReactNode } from 'react';
|
|
5
|
+
import { createElement } from 'react';
|
|
6
|
+
import { joinPrefix, prefixEnabledThrough, prefixPageCount, usePrefixList } from './usePrefixList.js';
|
|
7
|
+
import type { WindowPage } from './useWindowedList.js';
|
|
8
|
+
|
|
9
|
+
// The prefix behind Collections' whole-album scroller (forge task 5701). The browser half — a thumb dragged to the
|
|
10
|
+
// bottom of 4,180 files at 390×844 — is `e2e/gallery-window.spec.ts`; these pin the page math and the request shape.
|
|
11
|
+
|
|
12
|
+
const page = (from: number, n: number, total: number): WindowPage<number> => ({
|
|
13
|
+
items: Array.from({ length: n }, (_, i) => from + i),
|
|
14
|
+
total,
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
describe('prefixPageCount', () => {
|
|
18
|
+
test('holds enough pages for the reach, at least one', () => {
|
|
19
|
+
expect(prefixPageCount(0, 500, undefined)).toBe(1);
|
|
20
|
+
expect(prefixPageCount(500, 500, undefined)).toBe(1);
|
|
21
|
+
expect(prefixPageCount(501, 500, undefined)).toBe(2);
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
test('never asks past the last page once the size is known', () => {
|
|
25
|
+
expect(prefixPageCount(99_999, 500, 4180)).toBe(9);
|
|
26
|
+
expect(prefixPageCount(10, 500, 0)).toBe(1);
|
|
27
|
+
});
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
describe('prefixEnabledThrough', () => {
|
|
31
|
+
test('opens `inFlight` pages from the first one missing', () => {
|
|
32
|
+
expect(prefixEnabledThrough([true, true, false, false, false, false, false], 4)).toBe(6);
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
test('opens every page once all are in hand', () => {
|
|
36
|
+
expect(prefixEnabledThrough([true, true, true], 4)).toBe(3);
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
test('opens at least one, whatever inFlight says', () => {
|
|
40
|
+
expect(prefixEnabledThrough([false, false], 0)).toBe(1);
|
|
41
|
+
});
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
describe('joinPrefix', () => {
|
|
45
|
+
test('joins the pages from 0 and stops at the first gap', () => {
|
|
46
|
+
const joined = joinPrefix([page(0, 3, 10), undefined, page(6, 3, 10)], 3);
|
|
47
|
+
expect(joined.items).toEqual([0, 1, 2]);
|
|
48
|
+
expect(joined.total).toBe(10);
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
test('has no size before the first page', () => {
|
|
52
|
+
expect(joinPrefix([undefined, page(3, 3, 10)], 3)).toEqual({ items: [], total: undefined });
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
test('🔴 an optimistic delete in page 0 keeps the size right — what lies past the last page is the one true number', () => {
|
|
56
|
+
// Row 1 deleted: page 0 lost it and its own total dropped to 9; page 1 still says 10.
|
|
57
|
+
const edited = { items: [0, 2], total: 9 };
|
|
58
|
+
const joined = joinPrefix([edited, page(3, 3, 10)], 3);
|
|
59
|
+
expect(joined.items).toEqual([0, 2, 3, 4, 5]);
|
|
60
|
+
expect(joined.total).toBe(9);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
test('drops a row a refetched page repeats from the page after it', () => {
|
|
64
|
+
// Page 0 refetched after a delete elsewhere shifted every offset by one: its last row is page 1's first.
|
|
65
|
+
const joined = joinPrefix([{ items: [0, 1, 3], total: 9 }, { items: [3, 4, 5], total: 10 }], 3, (n) => n);
|
|
66
|
+
expect(joined.items).toEqual([0, 1, 3, 4, 5]);
|
|
67
|
+
});
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
describe('usePrefixList', () => {
|
|
71
|
+
const TOTAL = 4180;
|
|
72
|
+
const PAGE = 500;
|
|
73
|
+
const makeServer = () => {
|
|
74
|
+
const calls: number[] = [];
|
|
75
|
+
const fetchRange = (offset: number, limit: number) => {
|
|
76
|
+
calls.push(offset);
|
|
77
|
+
return Promise.resolve(page(offset, Math.max(0, Math.min(limit, TOTAL - offset)), TOTAL));
|
|
78
|
+
};
|
|
79
|
+
return { calls, fetchRange };
|
|
80
|
+
};
|
|
81
|
+
const wrapper = () => {
|
|
82
|
+
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
|
83
|
+
return ({ children }: { children: ReactNode }) => createElement(QueryClientProvider, { client }, children);
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
test('loads one page, then THROUGH a far reach — each offset once, in order, the last item last', async () => {
|
|
87
|
+
const server = makeServer();
|
|
88
|
+
const { result } = renderHook(
|
|
89
|
+
() => usePrefixList({ queryKey: ['album'], fetchRange: server.fetchRange, pageSize: PAGE }),
|
|
90
|
+
{ wrapper: wrapper() },
|
|
91
|
+
);
|
|
92
|
+
expect(result.current.isLoading).toBe(true);
|
|
93
|
+
await waitFor(() => expect(result.current.items.length).toBe(PAGE));
|
|
94
|
+
expect(result.current.total).toBe(TOTAL);
|
|
95
|
+
expect(result.current.serverWindow.total).toBe(TOTAL);
|
|
96
|
+
|
|
97
|
+
act(() => result.current.serverWindow.onNeedThrough(TOTAL));
|
|
98
|
+
await waitFor(() => expect(result.current.items.length).toBe(TOTAL));
|
|
99
|
+
expect(result.current.items.at(-1)).toBe(TOTAL - 1);
|
|
100
|
+
expect(result.current.items.every((n, i) => n === i)).toBe(true);
|
|
101
|
+
expect(server.calls).toEqual([0, 500, 1000, 1500, 2000, 2500, 3000, 3500, 4000]);
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
test('an ask the prefix already answers fetches nothing', async () => {
|
|
105
|
+
const server = makeServer();
|
|
106
|
+
const { result } = renderHook(
|
|
107
|
+
() => usePrefixList({ queryKey: ['again'], fetchRange: server.fetchRange, pageSize: PAGE }),
|
|
108
|
+
{ wrapper: wrapper() },
|
|
109
|
+
);
|
|
110
|
+
await waitFor(() => expect(result.current.items.length).toBe(PAGE));
|
|
111
|
+
act(() => result.current.needThrough(120));
|
|
112
|
+
act(() => result.current.needThrough(PAGE));
|
|
113
|
+
await new Promise((r) => setTimeout(r, 20));
|
|
114
|
+
expect(server.calls).toEqual([0]);
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
test('a new key starts again at one page', async () => {
|
|
118
|
+
const server = makeServer();
|
|
119
|
+
let key = 'a';
|
|
120
|
+
const { result, rerender } = renderHook(
|
|
121
|
+
() => usePrefixList({ queryKey: ['place', key], fetchRange: server.fetchRange, pageSize: PAGE }),
|
|
122
|
+
{ wrapper: wrapper() },
|
|
123
|
+
);
|
|
124
|
+
await waitFor(() => expect(result.current.items.length).toBe(PAGE));
|
|
125
|
+
act(() => result.current.needThrough(1200));
|
|
126
|
+
await waitFor(() => expect(result.current.items.length).toBe(1500));
|
|
127
|
+
key = 'b';
|
|
128
|
+
rerender();
|
|
129
|
+
await waitFor(() => expect(result.current.items.length).toBe(PAGE));
|
|
130
|
+
expect(server.calls.slice(3)).toEqual([0]);
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
test('🔴 a failed refresh over a held page is a refetch error, never the empty-state error (STA-11)', async () => {
|
|
134
|
+
let fail = false;
|
|
135
|
+
const fetchRange = (offset: number, limit: number) =>
|
|
136
|
+
fail ? Promise.reject(new Error('offline')) : Promise.resolve(page(offset, limit, TOTAL));
|
|
137
|
+
const { result } = renderHook(() => usePrefixList({ queryKey: ['held'], fetchRange, pageSize: PAGE }), {
|
|
138
|
+
wrapper: wrapper(),
|
|
139
|
+
});
|
|
140
|
+
await waitFor(() => expect(result.current.items.length).toBe(PAGE));
|
|
141
|
+
fail = true;
|
|
142
|
+
act(() => result.current.refetch());
|
|
143
|
+
await waitFor(() => expect(result.current.isRefetchError).toBe(true));
|
|
144
|
+
expect(result.current.isLoadingError).toBe(false);
|
|
145
|
+
expect(result.current.items.length).toBe(PAGE);
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
test('a first page that fails is a loading error', async () => {
|
|
149
|
+
const fetchRange = () => Promise.reject(new Error('offline'));
|
|
150
|
+
const { result } = renderHook(() => usePrefixList({ queryKey: ['never'], fetchRange, pageSize: PAGE }), {
|
|
151
|
+
wrapper: wrapper(),
|
|
152
|
+
});
|
|
153
|
+
await waitFor(() => expect(result.current.isLoadingError).toBe(true));
|
|
154
|
+
expect(result.current.isRefetchError).toBe(false);
|
|
155
|
+
});
|
|
156
|
+
});
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
import { type QueryKey, useQueries, useQueryClient } from '@tanstack/react-query';
|
|
2
|
+
import { useCallback, useMemo, useRef, useState } from 'react';
|
|
3
|
+
import type { WindowPage } from './useWindowedList.js';
|
|
4
|
+
|
|
5
|
+
// ── usePrefixList — the FIRST n of an offset-paged result set, grown to wherever the reader reaches ─────────────────
|
|
6
|
+
// `useWindowedList` slides a window to the reader; this holds a PREFIX instead: the items are always `[0, n)` of `total`
|
|
7
|
+
// in the server's order, so every index a consumer already keeps — a selection, a keyboard cursor, a `?i=` deep link, a
|
|
8
|
+
// stage's next and previous — is the same number however far the prefix has grown. A reach past the loaded end (a fast
|
|
9
|
+
// scroller's thumb dropped at the bottom) loads THROUGH that index: the pages fetched in parallel, a few in flight at a
|
|
10
|
+
// time, appended in order. It hands back what `MediaGallery`'s `serverWindow` takes:
|
|
11
|
+
//
|
|
12
|
+
// const list = usePrefixList({ queryKey, fetchRange: (offset, limit) => api.items({ ...query, offset, limit }) });
|
|
13
|
+
// <MediaGallery items={list.items} serverWindow={list.serverWindow} … />
|
|
14
|
+
//
|
|
15
|
+
// Why (forge task 5701): Collections grew a `limit` by 200 each time the grid neared its end, so in a 4,000-file album a
|
|
16
|
+
// thumb dragged to the bottom reached file 200, the next 200 loaded, the thumb jumped back up the track — twenty drags.
|
|
17
|
+
//
|
|
18
|
+
// Each page is its own query (`pageKey(offset, limit)`), so a page fetched once is cached across a trip away and back,
|
|
19
|
+
// and an app's optimistic edits (`setQueriesData` over its key prefix) reach every page. The public surface keeps
|
|
20
|
+
// @tanstack's types out, as `useWindowedList`'s does.
|
|
21
|
+
|
|
22
|
+
export interface UsePrefixListOptions<T> {
|
|
23
|
+
/** The listing's key; encode every filter INTO it — a change starts again at one page. */
|
|
24
|
+
queryKey: QueryKey;
|
|
25
|
+
/** One page's cache key. Default `[...queryKey, 'prefix', limit, offset]`. */
|
|
26
|
+
pageKey?: (offset: number, limit: number) => QueryKey;
|
|
27
|
+
/** Fetch `limit` items from `offset`, in the SAME order every time. */
|
|
28
|
+
fetchRange: (offset: number, limit: number) => Promise<WindowPage<T>>;
|
|
29
|
+
/** Items per request. Default 200. */
|
|
30
|
+
pageSize?: number;
|
|
31
|
+
/** The most pages fetched at once while the prefix grows toward a far reach. Default 4. */
|
|
32
|
+
inFlight?: number;
|
|
33
|
+
/**
|
|
34
|
+
* The item's identity. A page refetched alone after a change elsewhere can repeat the first row of the page after it
|
|
35
|
+
* (a delete shifted every offset by one); the repeat is dropped rather than drawn twice under one React key.
|
|
36
|
+
*/
|
|
37
|
+
idOf?: (item: T) => string | number;
|
|
38
|
+
/** Skip fetching while false. Default `true`. */
|
|
39
|
+
enabled?: boolean;
|
|
40
|
+
/** ms a page stays fresh (TanStack `staleTime`). */
|
|
41
|
+
staleTime?: number;
|
|
42
|
+
/** ms an unwatched page stays cached (TanStack `gcTime`). */
|
|
43
|
+
gcTime?: number;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** `MediaGallery`'s `serverWindow` — spread it in whole. */
|
|
47
|
+
export interface PrefixListWindow {
|
|
48
|
+
/** How many the query matches (0 before the first page). */
|
|
49
|
+
total: number;
|
|
50
|
+
/** Load at least the first `end` items. An ask the loaded or in-flight pages already answer does nothing. */
|
|
51
|
+
onNeedThrough: (end: number) => void;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface PrefixList<T> {
|
|
55
|
+
/** The loaded items, `[0, items.length)` of `total` — the same array until a page changes. */
|
|
56
|
+
items: T[];
|
|
57
|
+
/** How many the query matches, or `undefined` before the first page. */
|
|
58
|
+
total: number | undefined;
|
|
59
|
+
/** No page yet — drive the first skeleton off this. */
|
|
60
|
+
isLoading: boolean;
|
|
61
|
+
/** Any page in flight. */
|
|
62
|
+
isFetching: boolean;
|
|
63
|
+
/** A page failed with nothing loaded in its place — draw the error state off this. */
|
|
64
|
+
isLoadingError: boolean;
|
|
65
|
+
/** A refresh failed while the loaded pages are held — a `StaleNote` above them, never a blank (STA-11). */
|
|
66
|
+
isRefetchError: boolean;
|
|
67
|
+
error: unknown;
|
|
68
|
+
/** Load at least the first `end` items — see {@link PrefixListWindow.onNeedThrough}. */
|
|
69
|
+
needThrough: (end: number) => void;
|
|
70
|
+
serverWindow: PrefixListWindow;
|
|
71
|
+
/** Fetch every loaded page again. */
|
|
72
|
+
refetch: () => void;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* How many pages the prefix asks for: enough to hold `need` items, at least one, never past the set's last page once
|
|
77
|
+
* its size is known.
|
|
78
|
+
*/
|
|
79
|
+
export function prefixPageCount(need: number, pageSize: number, total: number | undefined): number {
|
|
80
|
+
const wanted = Math.max(1, Math.ceil(Math.max(0, need) / pageSize));
|
|
81
|
+
if (total === undefined) return wanted;
|
|
82
|
+
return Math.max(1, Math.min(wanted, Math.ceil(total / pageSize)));
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Which pages may fetch now: every page before the first one missing, and `inFlight` from it on — so a reach to item
|
|
87
|
+
* 4,000 fills the prefix four requests at a time rather than opening twenty at once.
|
|
88
|
+
*/
|
|
89
|
+
export function prefixEnabledThrough(loaded: readonly boolean[], inFlight: number): number {
|
|
90
|
+
const missing = loaded.indexOf(false);
|
|
91
|
+
return missing < 0 ? loaded.length : missing + Math.max(1, inFlight);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* The loaded pages from page 0, flattened, up to the first one not loaded — and the set's size.
|
|
96
|
+
*
|
|
97
|
+
* 🔴 The size is read off the LAST joined page as "how many come after it": `page.total - (offset + page.items.length)`.
|
|
98
|
+
* An optimistic delete takes a row out of one page and that page's `total` down by one, so each page's own `total`
|
|
99
|
+
* stops agreeing with the others; what lies past a page is the one number such an edit leaves alone, and the rows the
|
|
100
|
+
* edit removed are already out of `items.length`.
|
|
101
|
+
*/
|
|
102
|
+
export function joinPrefix<T>(
|
|
103
|
+
pages: readonly (WindowPage<T> | undefined)[],
|
|
104
|
+
pageSize: number,
|
|
105
|
+
idOf?: (item: T) => string | number,
|
|
106
|
+
): { items: T[]; total: number | undefined } {
|
|
107
|
+
const items: T[] = [];
|
|
108
|
+
const seen = idOf ? new Set<string | number>() : null;
|
|
109
|
+
let after: number | undefined;
|
|
110
|
+
for (let p = 0; p < pages.length; p++) {
|
|
111
|
+
const page = pages[p];
|
|
112
|
+
if (!page) break;
|
|
113
|
+
for (const item of page.items) {
|
|
114
|
+
if (seen) {
|
|
115
|
+
const id = idOf?.(item) as string | number;
|
|
116
|
+
if (seen.has(id)) continue;
|
|
117
|
+
seen.add(id);
|
|
118
|
+
}
|
|
119
|
+
items.push(item);
|
|
120
|
+
}
|
|
121
|
+
after = Math.max(0, page.total - (p * pageSize + page.items.length));
|
|
122
|
+
}
|
|
123
|
+
return { items, total: after === undefined ? undefined : items.length + after };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Where each listing's prefix reached when it was left — a return draws that much from the cache in its first frame. */
|
|
127
|
+
const remembered = new Map<string, number>();
|
|
128
|
+
const REMEMBERED_MAX = 50;
|
|
129
|
+
|
|
130
|
+
function remember(key: string, need: number): void {
|
|
131
|
+
remembered.delete(key);
|
|
132
|
+
remembered.set(key, need);
|
|
133
|
+
if (remembered.size > REMEMBERED_MAX) remembered.delete(remembered.keys().next().value as string);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* An offset-paged list as a prefix that grows to wherever the reader reaches. Point it at `fetchRange(offset, limit)`
|
|
138
|
+
* and a `queryKey` that encodes the filters; render `items`, and hand `serverWindow` to `MediaGallery`.
|
|
139
|
+
*
|
|
140
|
+
* Requires `@tanstack/react-query` wrapped in a `QueryClientProvider`.
|
|
141
|
+
*/
|
|
142
|
+
export function usePrefixList<T>({
|
|
143
|
+
queryKey,
|
|
144
|
+
pageKey,
|
|
145
|
+
fetchRange,
|
|
146
|
+
pageSize = 200,
|
|
147
|
+
inFlight = 4,
|
|
148
|
+
idOf,
|
|
149
|
+
enabled = true,
|
|
150
|
+
staleTime,
|
|
151
|
+
gcTime,
|
|
152
|
+
}: UsePrefixListOptions<T>): PrefixList<T> {
|
|
153
|
+
const keyHash = JSON.stringify(queryKey);
|
|
154
|
+
const [state, setState] = useState<{ key: string; need: number }>(() => ({ key: keyHash, need: remembered.get(keyHash) ?? pageSize }));
|
|
155
|
+
// A new listing starts where it was last left, or at one page — in THIS render, so no frame asks for the old reach.
|
|
156
|
+
const need = state.key === keyHash ? state.need : (remembered.get(keyHash) ?? pageSize);
|
|
157
|
+
if (state.key !== keyHash) setState({ key: keyHash, need });
|
|
158
|
+
|
|
159
|
+
const fetchRef = useRef(fetchRange);
|
|
160
|
+
fetchRef.current = fetchRange;
|
|
161
|
+
const keyOf = (offset: number, limit: number): QueryKey => (pageKey ? pageKey(offset, limit) : [...queryKey, 'prefix', limit, offset]);
|
|
162
|
+
|
|
163
|
+
// The set's size, as last known for THIS listing: what caps the pages asked for.
|
|
164
|
+
const knownTotal = useRef<{ key: string; total: number } | null>(null);
|
|
165
|
+
const capTotal = knownTotal.current?.key === keyHash ? knownTotal.current.total : undefined;
|
|
166
|
+
const count = prefixPageCount(need, pageSize, capTotal);
|
|
167
|
+
// Which pages are in hand, read off the cache itself — a page cached from an earlier visit counts at once, so a
|
|
168
|
+
// return to a long prefix opens the next requests in the same render instead of waiting for one to land.
|
|
169
|
+
const client = useQueryClient();
|
|
170
|
+
const through = prefixEnabledThrough(
|
|
171
|
+
Array.from({ length: count }, (_, p) => client.getQueryState(keyOf(p * pageSize, pageSize))?.data !== undefined),
|
|
172
|
+
inFlight,
|
|
173
|
+
);
|
|
174
|
+
const results = useQueries({
|
|
175
|
+
queries: Array.from({ length: count }, (_, p) => ({
|
|
176
|
+
queryKey: keyOf(p * pageSize, pageSize),
|
|
177
|
+
queryFn: () => fetchRef.current(p * pageSize, pageSize),
|
|
178
|
+
enabled: enabled && p < through,
|
|
179
|
+
staleTime,
|
|
180
|
+
gcTime,
|
|
181
|
+
})),
|
|
182
|
+
});
|
|
183
|
+
const pages = results.map((r) => r.data as WindowPage<T> | undefined);
|
|
184
|
+
|
|
185
|
+
// Kept while every page is the same object — TanStack keeps a page's data stable while it is unchanged — so `items`
|
|
186
|
+
// is the same array until a page changes, and safe as a consumer's memo dependency.
|
|
187
|
+
const joinedRef = useRef<{ pages: (WindowPage<T> | undefined)[]; joined: ReturnType<typeof joinPrefix<T>> } | null>(null);
|
|
188
|
+
const kept = joinedRef.current;
|
|
189
|
+
const same = kept !== null && kept.pages.length === pages.length && kept.pages.every((page, i) => page === pages[i]);
|
|
190
|
+
const joined = same && kept ? kept.joined : joinPrefix(pages, pageSize, idOf);
|
|
191
|
+
if (!same) joinedRef.current = { pages, joined };
|
|
192
|
+
const total = joined.total;
|
|
193
|
+
if (total !== undefined) knownTotal.current = { key: keyHash, total: Math.max(total, ...pages.map((page) => page?.total ?? 0)) };
|
|
194
|
+
|
|
195
|
+
const live = useRef({ keyHash, need, results, total, loaded: joined.items.length });
|
|
196
|
+
live.current = { keyHash, need, results, total, loaded: joined.items.length };
|
|
197
|
+
|
|
198
|
+
const needThrough = useCallback(
|
|
199
|
+
(end: number) => {
|
|
200
|
+
const now = live.current;
|
|
201
|
+
const capped = now.total === undefined ? end : Math.min(end, now.total);
|
|
202
|
+
if (capped <= now.need) {
|
|
203
|
+
// Asked again for what is already wanted: a page that failed is fetched again; one in flight answers it.
|
|
204
|
+
if (capped > now.loaded) for (const r of now.results) if (r.isError && !r.isFetching) void r.refetch();
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
remember(now.keyHash, capped);
|
|
208
|
+
setState({ key: now.keyHash, need: capped });
|
|
209
|
+
},
|
|
210
|
+
[],
|
|
211
|
+
);
|
|
212
|
+
|
|
213
|
+
const serverWindow = useMemo(() => ({ total: total ?? 0, onNeedThrough: needThrough }), [total, needThrough]);
|
|
214
|
+
const firstError = results.find((r) => r.isError);
|
|
215
|
+
return {
|
|
216
|
+
items: joined.items,
|
|
217
|
+
total,
|
|
218
|
+
isLoading: total === undefined && results.some((r) => r.isLoading),
|
|
219
|
+
isFetching: results.some((r) => r.isFetching),
|
|
220
|
+
isLoadingError: results.some((r) => r.isLoadingError),
|
|
221
|
+
isRefetchError: results.some((r) => r.isRefetchError),
|
|
222
|
+
error: firstError?.error ?? null,
|
|
223
|
+
needThrough,
|
|
224
|
+
serverWindow,
|
|
225
|
+
refetch: () => {
|
|
226
|
+
for (const r of live.current.results) if (r.data !== undefined || r.isError) void r.refetch();
|
|
227
|
+
},
|
|
228
|
+
};
|
|
229
|
+
}
|
package/src/testing/shell.ts
CHANGED
|
@@ -100,6 +100,8 @@ export const BELT = {
|
|
|
100
100
|
// The fast scroller a finger drags through a long list (`FastScroller`); `data-shown` while it is up.
|
|
101
101
|
fastScroller: '[data-cb-fast-scroller]',
|
|
102
102
|
fastScrollBubble: '[data-cb-fast-scroll-bubble]',
|
|
103
|
+
// A card a server window has not loaded yet (`VirtualCardGrid` under `serverWindow`) — none once the window reaches it.
|
|
104
|
+
gridPlaceholder: '[data-cb-grid-placeholder]',
|
|
103
105
|
tableList: '[data-cb-table-list]',
|
|
104
106
|
tableListHeader: '[data-cb-table-list-header]',
|
|
105
107
|
tableSelectAll: '[data-cb-table-select-all]',
|