forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiB5fcd955Burak Boduroğlu2 months ago730 commits

infinite-list.ts170 lines, 6.1 KiBHistoryRawDownload
1import { createEffect, createSignal, on, onCleanup } from "solid-js";
2import type { Page, PageParams } from "@/api/client";
3
4/** Rows fetched per request while the reader scrolls a server-paged list. */
5export const INFINITE_PAGE_SIZE = 50;
6/** The most rows one request may ask for when refetching or restoring. */
7const MAX_BATCH = 500;
8
9export type InfiniteList<T> = {
10 /** Every row fetched so far, in server order. */
11 items: () => T[];
12 /** Row count on the server for the current query. */
13 total: () => number;
14 /** True until the first page of the current query lands. */
15 initialLoading: () => boolean;
16 /** A page request is in flight (the first or a later one). */
17 loading: () => boolean;
18 error: () => unknown;
19 hasMore: () => boolean;
20 /** Fetch the next page; a no-op while one is in flight or none is left. */
21 loadMore: () => void;
22 /** Start the current query over from its first page. */
23 reload: () => void;
24 /**
25 * Refetch every row loaded so far in one request and swap them in place,
26 * keeping the reader's place (a poll, or after an edit or delete). Skipped
27 * while a page is in flight.
28 */
29 refresh: () => Promise<void>;
30 /** Patch the loaded rows in place (an edit that needs no refetch). */
31 mutate: (update: (items: T[]) => T[]) => void;
32};
33
34/**
35 * A list that fetches page by page as the reader scrolls, instead of reading
36 * every row up front. `source` is the query: search text and server filters.
37 * A new value (compared with `equals`) drops the rows and starts from offset
38 * 0; `null`/`undefined`/`false` means "not ready" and fetches nothing.
39 *
40 * Only fit for a list whose every search and filter the backend applies —
41 * the backend takes no sort parameter, so the order is the server's, and a
42 * filter applied in the browser would only see the rows loaded so far.
43 */
44export function createInfiniteList<T, K>(
45 source: () => K | null | undefined | false,
46 fetchPage: (key: K, params: PageParams) => Promise<Page<T>>,
47 options: {
48 pageSize?: number;
49 equals?: (a: K, b: K) => boolean;
50 /**
51 * Remember how many rows were loaded (per query, for this tab) so coming
52 * back from a detail page loads them again in one request and the
53 * browser's scroll restoration has the rows to land on.
54 */
55 restoreKey?: string;
56 } = {},
57): InfiniteList<T> {
58 const pageSize = options.pageSize ?? INFINITE_PAGE_SIZE;
59 const [items, setItems] = createSignal<T[]>([]);
60 const [total, setTotal] = createSignal(0);
61 const [loading, setLoading] = createSignal(false);
62 const [loaded, setLoaded] = createSignal(false);
63 const [error, setError] = createSignal<unknown>(undefined);
64 // Bumped on every new query so a slow response for an old one is dropped.
65 let generation = 0;
66 let key: K | null = null;
67
68 const storageKey = () => (options.restoreKey && key !== null ? `infinite:${options.restoreKey}:${JSON.stringify(key)}` : null);
69 const savedCount = () => {
70 const name = storageKey();
71 if (!name) return 0;
72 try {
73 const count = Number(sessionStorage.getItem(name));
74 return Number.isFinite(count) ? Math.min(Math.max(0, Math.floor(count)), MAX_BATCH) : 0;
75 } catch {
76 return 0;
77 }
78 };
79 const saveCount = (count: number) => {
80 const name = storageKey();
81 if (!name) return;
82 try {
83 sessionStorage.setItem(name, String(count));
84 } catch {
85 // storage full or blocked: the list still works, it just starts short
86 }
87 };
88
89 const fetchNext = async () => {
90 if (key === null || loading()) return;
91 const run = generation;
92 const current = key;
93 const offset = items().length;
94 // The first page of a query restored from session storage asks for as
95 // many rows as were loaded before, in one request.
96 const limit = offset === 0 ? Math.max(pageSize, savedCount()) : pageSize;
97 setLoading(true);
98 setError(undefined);
99 try {
100 const page = await fetchPage(current, { limit, offset });
101 if (run !== generation) return;
102 const rows = Array.isArray(page.items) ? page.items : [];
103 setItems((prev) => (offset === 0 ? rows : [...prev, ...rows]));
104 const next = offset + rows.length;
105 // A short page ends the list even if `total` says otherwise, so a stale
106 // count never keeps asking for pages that are not there.
107 setTotal(rows.length < limit ? next : Math.max(typeof page.total === "number" ? page.total : next, next));
108 setLoaded(true);
109 saveCount(next);
110 } catch (err) {
111 if (run === generation) setError(err);
112 } finally {
113 if (run === generation) setLoading(false);
114 }
115 };
116
117 const start = () => {
118 generation += 1;
119 setItems([]);
120 setTotal(0);
121 setLoaded(false);
122 setLoading(false);
123 setError(undefined);
124 if (key !== null) void fetchNext();
125 };
126
127 createEffect(
128 on(source, (next) => {
129 const ready = next !== null && next !== undefined && next !== false;
130 if (ready && key !== null && (options.equals ? options.equals(key, next as K) : key === next)) return;
131 key = ready ? (next as K) : null;
132 start();
133 }),
134 );
135 onCleanup(() => {
136 generation += 1;
137 });
138
139 const hasMore = () => loaded() && error() === undefined && items().length < total();
140
141 return {
142 items,
143 total,
144 initialLoading: () => key !== null && !loaded() && error() === undefined,
145 loading,
146 error,
147 hasMore,
148 loadMore: () => {
149 if (hasMore()) void fetchNext();
150 },
151 reload: start,
152 refresh: async () => {
153 if (key === null || loading() || !loaded()) return;
154 const run = generation;
155 const current = key;
156 const limit = Math.min(Math.max(pageSize, items().length), MAX_BATCH);
157 try {
158 const page = await fetchPage(current, { limit, offset: 0 });
159 if (run !== generation) return;
160 const rows = Array.isArray(page.items) ? page.items : [];
161 setItems(rows);
162 setTotal(rows.length < limit ? rows.length : Math.max(typeof page.total === "number" ? page.total : rows.length, rows.length));
163 setError(undefined);
164 } catch (err) {
165 if (run === generation) setError(err);
166 }
167 },
168 mutate: (update) => setItems((prev) => update(prev)),
169 };
170}