@confect/react 10.0.0-next.9 → 10.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.
@@ -0,0 +1,403 @@
1
+ /**
2
+ * EXPERIMENTAL—the pure state machine behind {@link useStreamPaginatedQuery}
3
+ * (see `notes/stream-based-querying.md` in the repo root).
4
+ *
5
+ * Reactive pagination without the query journal: every loaded page—including
6
+ * the first—is pinned to a fixed index range by echoing its `continueCursor`
7
+ * back as the next subscription's `endCursor` (the last page pins to the
8
+ * end-of-stream sentinel once exhausted), so adjacent pages stay exactly
9
+ * contiguous and pages never shed items as data changes—the "range-defined
10
+ * pages" the Fully Reactive Pagination article calls for, and the mechanism of
11
+ * `convex-helpers/react`'s `usePaginatedQuery`.
12
+ *
13
+ * Pinning a freshly loaded page, loading more, and splitting an overgrown page
14
+ * are the same transition shape: the affected page keeps rendering while its
15
+ * replacement subscriptions ("ongoing split") load, and is swapped out once all
16
+ * of them have results.
17
+ *
18
+ * This module is framework-free (it imports only `effect/*` and a type from
19
+ * `convex/server`); it lives here for now because the React hook is its only
20
+ * consumer—a second client (e.g. `@confect/foldkit`) should prompt a move down
21
+ * to `@confect/js`.
22
+ */
23
+ import type { PaginationResult } from "convex/server";
24
+ import * as Array from "effect/Array";
25
+ import * as Option from "effect/Option";
26
+ import { pipe } from "effect/Function";
27
+ import * as Record from "effect/Record";
28
+
29
+ /**
30
+ * The `paginationOpts` one subscribed page queries with.
31
+ */
32
+ export interface PageRequest {
33
+ readonly numItems: number;
34
+ readonly cursor: string | null;
35
+ /**
36
+ * Present once the page is pinned to a fixed range.
37
+ */
38
+ readonly endCursor?: string;
39
+ /**
40
+ * Per-page read budgets, forwarded to the server so a scan-heavy page fails
41
+ * over to `SplitRequired` instead of exceeding query limits.
42
+ */
43
+ readonly maximumRowsRead?: number;
44
+ readonly maximumBytesRead?: number;
45
+ }
46
+
47
+ /**
48
+ * The per-page read budgets every growing page is requested with.
49
+ */
50
+ export interface ReadBudget {
51
+ readonly maximumRowsRead?: number | undefined;
52
+ readonly maximumBytesRead?: number | undefined;
53
+ }
54
+
55
+ /**
56
+ * A fresh growing-page request (no `endCursor`).
57
+ */
58
+ const growingRequest = (
59
+ numItems: number,
60
+ cursor: string | null,
61
+ budget: ReadBudget,
62
+ ): PageRequest => ({
63
+ numItems,
64
+ cursor,
65
+ ...(budget.maximumRowsRead === undefined
66
+ ? {}
67
+ : { maximumRowsRead: budget.maximumRowsRead }),
68
+ ...(budget.maximumBytesRead === undefined
69
+ ? {}
70
+ : { maximumBytesRead: budget.maximumBytesRead }),
71
+ });
72
+
73
+ export interface State {
74
+ readonly nextPageKey: number;
75
+ /**
76
+ * Page keys in display order.
77
+ */
78
+ readonly pageKeys: ReadonlyArray<string>;
79
+ /**
80
+ * The request each subscribed page queries with, by page key.
81
+ */
82
+ readonly pages: Record.ReadonlyRecord<string, PageRequest>;
83
+ /**
84
+ * Pages being replaced by one (a pin) or two (a split) narrower
85
+ * subscriptions: the original stays subscribed (and rendered) until every
86
+ * replacement has a result.
87
+ */
88
+ readonly ongoingSplits: Record.ReadonlyRecord<string, ReadonlyArray<string>>;
89
+ }
90
+
91
+ /**
92
+ * The skipped state: nothing subscribed.
93
+ */
94
+ export const empty: State = {
95
+ nextPageKey: 0,
96
+ pageKeys: [],
97
+ pages: Record.empty(),
98
+ ongoingSplits: Record.empty(),
99
+ };
100
+
101
+ /**
102
+ * One growing (unpinned) page from the start of the stream.
103
+ */
104
+ export const initial = (
105
+ initialNumItems: number,
106
+ budget: ReadBudget = {},
107
+ ): State => ({
108
+ nextPageKey: 1,
109
+ pageKeys: ["0"],
110
+ pages: Record.singleton("0", growingRequest(initialNumItems, null, budget)),
111
+ ongoingSplits: Record.empty(),
112
+ });
113
+
114
+ /**
115
+ * Pin a freshly loaded growing page at its `continueCursor` (or, once
116
+ * exhausted, at the end-of-stream sentinel), so it stops being a sliding
117
+ * window: a pinned page grows and shrinks with the data in its range but never
118
+ * sheds items past its edges. Modeled as a one-replacement split so the
119
+ * original keeps rendering until the pinned twin has a result.
120
+ */
121
+ export const pin =
122
+ (key: string, endCursor: string): ((state: State) => State) =>
123
+ (state) =>
124
+ Option.match(Record.get(state.pages, key), {
125
+ onNone: () => state,
126
+ onSome: (page) => {
127
+ if (
128
+ page.endCursor !== undefined ||
129
+ Record.has(state.ongoingSplits, key)
130
+ ) {
131
+ return state;
132
+ }
133
+ const pinnedKey = String(state.nextPageKey);
134
+ return {
135
+ nextPageKey: state.nextPageKey + 1,
136
+ pageKeys: state.pageKeys,
137
+ pages: Record.set(state.pages, pinnedKey, { ...page, endCursor }),
138
+ ongoingSplits: Record.set(state.ongoingSplits, key, [pinnedKey]),
139
+ };
140
+ },
141
+ });
142
+
143
+ /**
144
+ * Pin the growing last page at `continueCursor` and start a new growing page
145
+ * from there. Modeled as a split of the last page into its pinned replacement
146
+ * and the new page, so the swap waits for both.
147
+ */
148
+ export const loadMore =
149
+ (
150
+ continueCursor: string,
151
+ numItems: number,
152
+ budget: ReadBudget = {},
153
+ ): ((state: State) => State) =>
154
+ (state) =>
155
+ pipe(
156
+ Option.Do,
157
+ Option.bind("lastKey", () => Array.last(state.pageKeys)),
158
+ Option.bind("lastPage", ({ lastKey }) =>
159
+ Record.get(state.pages, lastKey),
160
+ ),
161
+ Option.match({
162
+ onNone: () => state,
163
+ onSome: ({ lastKey, lastPage }) => {
164
+ if (lastPage.endCursor !== undefined) {
165
+ // The last page is already pinned (the usual case, since pages
166
+ // pin themselves on first load): just append a new growing page.
167
+ const nextKey = String(state.nextPageKey);
168
+ return {
169
+ nextPageKey: state.nextPageKey + 1,
170
+ pageKeys: Array.append(state.pageKeys, nextKey),
171
+ pages: Record.set(
172
+ state.pages,
173
+ nextKey,
174
+ growingRequest(numItems, continueCursor, budget),
175
+ ),
176
+ ongoingSplits: state.ongoingSplits,
177
+ };
178
+ }
179
+ const pinnedKey = String(state.nextPageKey);
180
+ const nextKey = String(state.nextPageKey + 1);
181
+ return {
182
+ nextPageKey: state.nextPageKey + 2,
183
+ pageKeys: state.pageKeys,
184
+ pages: pipe(
185
+ state.pages,
186
+ Record.set(pinnedKey, { ...lastPage, endCursor: continueCursor }),
187
+ Record.set(
188
+ nextKey,
189
+ growingRequest(numItems, continueCursor, budget),
190
+ ),
191
+ ),
192
+ ongoingSplits: Record.set(state.ongoingSplits, lastKey, [
193
+ pinnedKey,
194
+ nextKey,
195
+ ]),
196
+ };
197
+ },
198
+ }),
199
+ );
200
+
201
+ /**
202
+ * Split the page at `key` in two at `splitCursor`. The first replacement pins
203
+ * at the split point; the second keeps the page's own `endCursor`—for a pinned
204
+ * page its original end (so a truncated `SplitRequired` page loses none of its
205
+ * range), and for a growing page no end at all (it keeps growing).
206
+ */
207
+ export const split =
208
+ (key: string, splitCursor: string): ((state: State) => State) =>
209
+ (state) =>
210
+ Option.match(Record.get(state.pages, key), {
211
+ onNone: () => state,
212
+ onSome: (page) => {
213
+ const firstKey = String(state.nextPageKey);
214
+ const secondKey = String(state.nextPageKey + 1);
215
+ return {
216
+ nextPageKey: state.nextPageKey + 2,
217
+ pageKeys: state.pageKeys,
218
+ pages: pipe(
219
+ state.pages,
220
+ Record.set(firstKey, { ...page, endCursor: splitCursor }),
221
+ Record.set(secondKey, { ...page, cursor: splitCursor }),
222
+ ),
223
+ ongoingSplits: Record.set(state.ongoingSplits, key, [
224
+ firstKey,
225
+ secondKey,
226
+ ]),
227
+ };
228
+ },
229
+ });
230
+
231
+ /**
232
+ * Swap a completed split's replacements in for the original page.
233
+ */
234
+ export const completeSplit =
235
+ (key: string): ((state: State) => State) =>
236
+ (state) =>
237
+ Option.match(Record.get(state.ongoingSplits, key), {
238
+ onNone: () => state,
239
+ onSome: (replacements) => ({
240
+ nextPageKey: state.nextPageKey,
241
+ pageKeys: Array.flatMap(state.pageKeys, (pageKey) =>
242
+ pageKey === key ? replacements : [pageKey],
243
+ ),
244
+ pages: Record.remove(state.pages, key),
245
+ ongoingSplits: Record.remove(state.ongoingSplits, key),
246
+ }),
247
+ });
248
+
249
+ /**
250
+ * Whether the last (rendered) page is currently being split or pinned.
251
+ */
252
+ export const isLastPageSplitting = (state: State): boolean =>
253
+ Option.exists(Array.last(state.pageKeys), (lastKey) =>
254
+ Record.has(state.ongoingSplits, lastKey),
255
+ );
256
+
257
+ /**
258
+ * Build one subscription request per subscribed page.
259
+ */
260
+ export const pageRequests = <A>(
261
+ state: State,
262
+ f: (page: PageRequest) => A,
263
+ ): Record.ReadonlyRecord<string, A> => Record.map(state.pages, f);
264
+
265
+ /**
266
+ * The per-page results a render observes, keyed like {@link pageRequests}.
267
+ */
268
+ export type Results = Record.ReadonlyRecord<
269
+ string,
270
+ PageResult | Error | undefined
271
+ >;
272
+
273
+ // -----------------------------------------------------------------------------
274
+ // Interpretation
275
+ // -----------------------------------------------------------------------------
276
+
277
+ /**
278
+ * The wire shape of one loaded page—`PaginationResult` from `convex/server`, so
279
+ * the protocol has a single source of truth.
280
+ */
281
+ export type PageResult = PaginationResult<unknown>;
282
+
283
+ /**
284
+ * What one render pass derives from the subscribed pages' results: the items to
285
+ * show, the trailing complete result (absent while the tail is loading or
286
+ * force-splitting), state transitions to apply, and whether a failure or an
287
+ * invalid cursor was hit.
288
+ */
289
+ export type Interpretation =
290
+ | { readonly _tag: "ResetRequired" }
291
+ | {
292
+ readonly _tag: "Failed";
293
+ readonly error: unknown;
294
+ /**
295
+ * Encoded items loaded before the failing page.
296
+ */
297
+ readonly items: ReadonlyArray<unknown>;
298
+ }
299
+ | {
300
+ readonly _tag: "Interpreted";
301
+ /**
302
+ * Encoded items across the loaded pages, in order.
303
+ */
304
+ readonly items: ReadonlyArray<unknown>;
305
+ /**
306
+ * The last page's result, when every page has loaded completely.
307
+ */
308
+ readonly lastResult: Option.Option<PageResult>;
309
+ /**
310
+ * Split/swap transitions this render discovered.
311
+ */
312
+ readonly transitions: ReadonlyArray<(state: State) => State>;
313
+ };
314
+
315
+ const interpreted = (
316
+ items: ReadonlyArray<unknown>,
317
+ lastResult: Option.Option<PageResult>,
318
+ transitions: ReadonlyArray<(state: State) => State>,
319
+ ): Interpretation => ({ _tag: "Interpreted", items, lastResult, transitions });
320
+
321
+ /**
322
+ * Walk the pages in display order, concatenating their items and collecting the
323
+ * transitions to apply (completed split swaps, recommended splits, eager splits
324
+ * of pages that outgrew `initialNumItems`).
325
+ *
326
+ * `isInvalidCursorError` marks errors that call for a full pagination reset
327
+ * rather than a failure (the cursor no longer matches the query).
328
+ */
329
+ export const interpret = (
330
+ state: State,
331
+ results: Record.ReadonlyRecord<string, PageResult | Error | undefined>,
332
+ options: {
333
+ readonly initialNumItems: number;
334
+ readonly isInvalidCursorError: (error: Error) => boolean;
335
+ },
336
+ ): Interpretation => {
337
+ const go = (
338
+ remaining: ReadonlyArray<string>,
339
+ items: ReadonlyArray<unknown>,
340
+ transitions: ReadonlyArray<(s: State) => State>,
341
+ lastResult: Option.Option<PageResult>,
342
+ ): Interpretation =>
343
+ Option.match(Array.head(remaining), {
344
+ onNone: () => interpreted(items, lastResult, transitions),
345
+ onSome: (pageKey) => {
346
+ const result = Record.get(results, pageKey).pipe(
347
+ Option.flatMap(Option.fromNullishOr),
348
+ Option.getOrUndefined,
349
+ );
350
+ if (result === undefined) {
351
+ // The trailing pages are still loading.
352
+ return interpreted(items, Option.none(), transitions);
353
+ }
354
+ if (result instanceof Error) {
355
+ return options.isInvalidCursorError(result)
356
+ ? { _tag: "ResetRequired" }
357
+ : { _tag: "Failed", error: result, items };
358
+ }
359
+
360
+ const hasResult = (key: string) =>
361
+ Record.get(results, key).pipe(
362
+ Option.flatMap(Option.fromNullishOr),
363
+ Option.isSome,
364
+ );
365
+ const ongoingSplit = Record.get(state.ongoingSplits, pageKey);
366
+ const nextTransitions = Option.match(ongoingSplit, {
367
+ onSome: (replacements) =>
368
+ // Swap the replacements in once all of them have results.
369
+ Array.every(replacements, hasResult)
370
+ ? Array.append(transitions, completeSplit(pageKey))
371
+ : transitions,
372
+ onNone: () =>
373
+ typeof result.splitCursor === "string" &&
374
+ (result.pageStatus === "SplitRecommended" ||
375
+ result.pageStatus === "SplitRequired" ||
376
+ result.page.length > options.initialNumItems)
377
+ ? Array.append(transitions, split(pageKey, result.splitCursor))
378
+ : // A loaded growing page pins itself to the range it just
379
+ // served (`END_CURSOR` once exhausted), so it stops being a
380
+ // sliding window that sheds items as new documents arrive.
381
+ Option.exists(
382
+ Record.get(state.pages, pageKey),
383
+ (request) => request.endCursor === undefined,
384
+ ) && result.pageStatus !== "SplitRequired"
385
+ ? Array.append(transitions, pin(pageKey, result.continueCursor))
386
+ : transitions,
387
+ });
388
+
389
+ // A force-split page couldn't be fetched in full: show the items
390
+ // before it and report the tail as still loading.
391
+ return result.pageStatus === "SplitRequired"
392
+ ? interpreted(items, Option.none(), nextTransitions)
393
+ : go(
394
+ Array.drop(remaining, 1),
395
+ Array.appendAll(items, result.page),
396
+ nextTransitions,
397
+ Option.some(result),
398
+ );
399
+ },
400
+ });
401
+
402
+ return go(state.pageKeys, [], [], Option.none());
403
+ };