tsdf 16.0.3 → 17.0.0-alpha.10
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/LICENSE +140 -0
- package/README.md +5 -0
- package/dist/async-storage.d.ts +2 -0
- package/dist/async-storage.js +2 -0
- package/dist/asyncStorageAdapter-BMYAF6rt.d.ts +6 -0
- package/dist/asyncStorageAdapter-BZSj1ZO5.js +1868 -0
- package/dist/asyncStorageAdapters-DbyKyARM.js +3 -0
- package/dist/indexed-db-storage.d.ts +14 -0
- package/dist/indexed-db-storage.js +2 -0
- package/dist/indexedDbPersistentStorage-DlUjN1qY.js +902 -0
- package/dist/main.d.ts +1487 -373
- package/dist/main.js +16146 -2475
- package/dist/opfs-storage.d.ts +2 -0
- package/dist/opfs-storage.js +2 -0
- package/dist/opfsPersistentStorage-BO_uDxe4.js +838 -0
- package/dist/opfsPersistentStorage-CBnUebnf.d.ts +6 -0
- package/dist/types-2zQlbxtw.d.ts +1475 -0
- package/docs/README.md +98 -0
- package/docs/batch-fetching.md +125 -0
- package/docs/browser-tabs-sync.md +61 -0
- package/docs/cache-limits.md +105 -0
- package/docs/collection-store.md +173 -0
- package/docs/document-store.md +149 -0
- package/docs/fetch-scheduling.md +93 -0
- package/docs/hooks.md +416 -0
- package/docs/invalidation.md +135 -0
- package/docs/list-query-store.md +352 -0
- package/docs/mutations.md +266 -0
- package/docs/offline.md +207 -0
- package/docs/offset-pagination.md +111 -0
- package/docs/optimistic-list-updates.md +180 -0
- package/docs/partial-resources.md +168 -0
- package/docs/persistent-storage.md +290 -0
- package/docs/real-time-updates.md +158 -0
- package/docs/shared-types.md +181 -0
- package/docs/store-manager.md +147 -0
- package/package.json +81 -47
- package/dist/main.cjs +0 -2511
- package/dist/main.d.cts +0 -400
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
# Mutations
|
|
2
|
+
|
|
3
|
+
TSDF provides a structured mutation lifecycle that coordinates with the fetch scheduler to prevent conflicts, supports optimistic updates, and handles error recovery with automatic revalidation.
|
|
4
|
+
|
|
5
|
+
See also: [Offline](./offline.md) for durable offline queueing and replay.
|
|
6
|
+
|
|
7
|
+
## performMutation
|
|
8
|
+
|
|
9
|
+
The primary way to perform mutations. Available on all store types.
|
|
10
|
+
|
|
11
|
+
### Document Store
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
const result = await store.performMutation({
|
|
15
|
+
// Optional: update state optimistically before the mutation executes
|
|
16
|
+
optimisticUpdate: (currentState) => {
|
|
17
|
+
if (!currentState) return;
|
|
18
|
+
currentState.name = 'New Name'; // immer-style draft mutation
|
|
19
|
+
},
|
|
20
|
+
|
|
21
|
+
// The actual mutation
|
|
22
|
+
mutation: ({ updateState, currentState }) => {
|
|
23
|
+
return api.updateUser({ name: 'New Name' });
|
|
24
|
+
},
|
|
25
|
+
|
|
26
|
+
// After success, invalidate data to refetch from the server
|
|
27
|
+
revalidateOnSuccess: true,
|
|
28
|
+
|
|
29
|
+
// Ask the global/store onMutationError handler to stay quiet
|
|
30
|
+
silentErrors: true,
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
if (result.ok) {
|
|
34
|
+
console.log('Success:', result.value);
|
|
35
|
+
} else {
|
|
36
|
+
console.log('Error:', result.error);
|
|
37
|
+
}
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
The `mutation` callback receives:
|
|
41
|
+
|
|
42
|
+
- `updateState` - An immer-based function to update state during the mutation
|
|
43
|
+
- `currentState` - The current data at the time the mutation executes
|
|
44
|
+
|
|
45
|
+
Mutation callbacks return promises. The resolved value may be either a plain value or a `Result`. `Result.ok(value)` is treated like resolving to `value`; `Result.err(error)` is handled like rejecting with `error`, including optimistic rollback, error normalization, and offline fallback classification.
|
|
46
|
+
|
|
47
|
+
### Collection Store
|
|
48
|
+
|
|
49
|
+
```ts
|
|
50
|
+
const result = await store.performMutation('item-id', {
|
|
51
|
+
optimisticUpdate: (payload) => {
|
|
52
|
+
store.updateItemState(payload, (draft) => {
|
|
53
|
+
draft.name = 'Updated';
|
|
54
|
+
});
|
|
55
|
+
},
|
|
56
|
+
mutation: (payload) => api.updateItem(payload, { name: 'Updated' }),
|
|
57
|
+
revalidateOnSuccess: true,
|
|
58
|
+
});
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
### List Query Store
|
|
62
|
+
|
|
63
|
+
```ts
|
|
64
|
+
const result = await store.performMutation('item-id', {
|
|
65
|
+
optimisticUpdate: (payload) => {
|
|
66
|
+
store.updateItemState(payload, (draft) => {
|
|
67
|
+
draft.status = 'done';
|
|
68
|
+
});
|
|
69
|
+
},
|
|
70
|
+
mutation: (payload) => api.updateTask(payload, { status: 'done' }),
|
|
71
|
+
revalidateOnSuccess: true,
|
|
72
|
+
});
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
The payload can be:
|
|
76
|
+
|
|
77
|
+
- A single item payload
|
|
78
|
+
- An array of item payloads
|
|
79
|
+
- A filter function `(payload, data) => boolean`
|
|
80
|
+
- `null` or `undefined` (matches all items)
|
|
81
|
+
|
|
82
|
+
## Mutation Lifecycle
|
|
83
|
+
|
|
84
|
+
1. **Lock**: The scheduler is locked for the affected items/queries, preventing concurrent fetches
|
|
85
|
+
2. **Optimistic update**: If provided, runs immediately. If it returns `false`, the mutation is cancelled
|
|
86
|
+
3. **Debounce** (optional): Waits for `ms` milliseconds. During debounce, the window close is blocked
|
|
87
|
+
4. **Execute mutation**: The async mutation function runs
|
|
88
|
+
5. **On success**: Calls `onSuccess`, optionally invalidates data
|
|
89
|
+
6. **On error**: Rolls back optimistic state, normalizes the error, and calls `onMutationError` with the `silentErrors` flag
|
|
90
|
+
7. **Unlock**: The scheduler is unlocked, pending fetches resume
|
|
91
|
+
|
|
92
|
+
## Return Value
|
|
93
|
+
|
|
94
|
+
`performMutation` returns a `Result<T, StoreMutationError | MutationSkipped>`:
|
|
95
|
+
|
|
96
|
+
```ts
|
|
97
|
+
const result = await store.performMutation(/* ... */);
|
|
98
|
+
|
|
99
|
+
if (result.ok) {
|
|
100
|
+
// result.value is the mutation return value
|
|
101
|
+
} else {
|
|
102
|
+
if (result.error.kind === 'skipped') {
|
|
103
|
+
// optimisticUpdate returned false, or this call was skipped by debounce
|
|
104
|
+
} else {
|
|
105
|
+
// result.error is a StoreMutationError with code/id/message and cause
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
When a mutation uses the `offline` option, the success value is `OfflineMutationResult<T>`:
|
|
111
|
+
|
|
112
|
+
- `{ kind: 'online', data }` when the direct mutation completed.
|
|
113
|
+
- `{ kind: 'queued' }` when TSDF persisted the mutation for offline replay.
|
|
114
|
+
|
|
115
|
+
## Optimistic Updates
|
|
116
|
+
|
|
117
|
+
Optimistic updates let you update the UI immediately before the server responds.
|
|
118
|
+
|
|
119
|
+
```ts
|
|
120
|
+
await store.performMutation('item-id', {
|
|
121
|
+
optimisticUpdate: () => {
|
|
122
|
+
// Update the store directly — the UI updates immediately
|
|
123
|
+
store.updateItemState('item-id', (draft) => {
|
|
124
|
+
draft.completed = true;
|
|
125
|
+
});
|
|
126
|
+
},
|
|
127
|
+
mutation: () => api.completeItem('item-id'),
|
|
128
|
+
});
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
If the mutation **fails**, TSDF automatically invalidates the data, causing a refetch that reverts the optimistic update to the server's actual state.
|
|
132
|
+
|
|
133
|
+
### Cancelling a Mutation
|
|
134
|
+
|
|
135
|
+
Return `false` from `optimisticUpdate` to cancel the mutation entirely.
|
|
136
|
+
The returned `Result` will be `Err({ kind: 'skipped' })` rather than a thrown or normalized error:
|
|
137
|
+
|
|
138
|
+
```ts
|
|
139
|
+
optimisticUpdate: (currentState) => {
|
|
140
|
+
if (currentState?.locked) return false; // cancel mutation
|
|
141
|
+
currentState.name = 'Updated';
|
|
142
|
+
};
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
## Debouncing
|
|
146
|
+
|
|
147
|
+
For frequent mutations (e.g., typing), use debounce to batch them:
|
|
148
|
+
|
|
149
|
+
```ts
|
|
150
|
+
await store.performMutation({
|
|
151
|
+
debounce: {
|
|
152
|
+
context: 'update-name', // debounce key
|
|
153
|
+
payload: newName, // only the latest payload is used
|
|
154
|
+
ms: 500, // wait 500ms of inactivity
|
|
155
|
+
},
|
|
156
|
+
mutation: () => api.updateName(newName),
|
|
157
|
+
});
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
During the debounce period, the window close is blocked to prevent data loss.
|
|
161
|
+
|
|
162
|
+
## Revalidation on Success
|
|
163
|
+
|
|
164
|
+
| Option | Behavior |
|
|
165
|
+
| ------------------------------------------------ | ----------------------------------------------------------------- |
|
|
166
|
+
| `revalidateOnSuccess: true` | Invalidates all affected items and queries |
|
|
167
|
+
| `revalidateOnSuccess: 'queries'` | (List Query only) Invalidates only queries, not individual items |
|
|
168
|
+
| `revalidateOnSuccess: (query) => ...` | (List Query only) Invalidates affected items and matching queries |
|
|
169
|
+
| `revalidateOnSuccess: { queries, items: false }` | (List Query only) Invalidates matching queries only |
|
|
170
|
+
| `revalidateOnSuccess: false` (default) | No automatic revalidation |
|
|
171
|
+
|
|
172
|
+
### Error Handling
|
|
173
|
+
|
|
174
|
+
On error, TSDF **rolls back** optimistic updates to their pre-mutation state. Non-optimistic mutations leave state untouched on error.
|
|
175
|
+
|
|
176
|
+
## List Query Store Specific Options
|
|
177
|
+
|
|
178
|
+
```ts
|
|
179
|
+
await store.performMutation(payload, {
|
|
180
|
+
// Revalidate only active queries, without invalidating individual items
|
|
181
|
+
revalidateOnSuccess: {
|
|
182
|
+
queries: (queryPayload) => queryPayload.status === 'active',
|
|
183
|
+
items: false,
|
|
184
|
+
},
|
|
185
|
+
|
|
186
|
+
// Ask the global/store onMutationError handler to stay quiet
|
|
187
|
+
silentErrors: true,
|
|
188
|
+
|
|
189
|
+
// Callbacks
|
|
190
|
+
onSuccess: (response, payload) => {
|
|
191
|
+
/* ... */
|
|
192
|
+
},
|
|
193
|
+
onError: (error) => {
|
|
194
|
+
/* ... */
|
|
195
|
+
},
|
|
196
|
+
});
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
## Manual Mutation Control
|
|
200
|
+
|
|
201
|
+
For cases where `performMutation` doesn't fit, you can manually control the mutation lock:
|
|
202
|
+
|
|
203
|
+
```ts
|
|
204
|
+
// Document Store
|
|
205
|
+
const endMutation = store.startMutation();
|
|
206
|
+
try {
|
|
207
|
+
await doSomething();
|
|
208
|
+
} finally {
|
|
209
|
+
endMutation();
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// Collection Store — locks a specific item
|
|
213
|
+
const endMutation = store.startMutation('item-id');
|
|
214
|
+
|
|
215
|
+
// List Query Store — locks an item and all queries containing it
|
|
216
|
+
const endMutation = store.startItemMutation('item-id');
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
While a mutation lock is held, the scheduler defers any fetch requests for the locked items/queries.
|
|
220
|
+
|
|
221
|
+
## Window Close Blocking
|
|
222
|
+
|
|
223
|
+
The manager-level `blockWindowClose` option prevents the user from accidentally closing the browser during a mutation:
|
|
224
|
+
|
|
225
|
+
```ts
|
|
226
|
+
const storeManager = createStoreManager({
|
|
227
|
+
getSessionKey: () => currentTenantId ?? false,
|
|
228
|
+
errorNormalizer: normalizeError,
|
|
229
|
+
blockWindowClose: () => {
|
|
230
|
+
const handler = (e: BeforeUnloadEvent) => {
|
|
231
|
+
e.preventDefault();
|
|
232
|
+
e.returnValue = '';
|
|
233
|
+
};
|
|
234
|
+
window.addEventListener('beforeunload', handler);
|
|
235
|
+
return {
|
|
236
|
+
unblock: () => window.removeEventListener('beforeunload', handler),
|
|
237
|
+
};
|
|
238
|
+
},
|
|
239
|
+
});
|
|
240
|
+
|
|
241
|
+
const store = createDocumentStore({
|
|
242
|
+
id: 'document-store',
|
|
243
|
+
storeManager,
|
|
244
|
+
// ...
|
|
245
|
+
});
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
Pass `null` to disable this behavior.
|
|
249
|
+
|
|
250
|
+
## Mutation Events
|
|
251
|
+
|
|
252
|
+
All stores emit events for mutation lifecycle tracking:
|
|
253
|
+
|
|
254
|
+
```ts
|
|
255
|
+
store.storeEvents.on('mutationStart', ({ mutationId }) => {
|
|
256
|
+
console.log('Mutation started:', mutationId);
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
store.storeEvents.on('mutationEnd', ({ mutationId, status }) => {
|
|
260
|
+
console.log('Mutation ended:', mutationId, status);
|
|
261
|
+
});
|
|
262
|
+
```
|
|
263
|
+
|
|
264
|
+
`status` is `'success' | 'error' | 'skipped'`. A mutation is `'skipped'` when its `optimisticUpdate` callback returns `false` or when a debounced mutation is superseded by a newer one with the same debounce key — these are not failures and should usually not trigger error handling.
|
|
265
|
+
|
|
266
|
+
Collection and List Query stores also include the affected `payload`/`items` in the event.
|
package/docs/offline.md
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
# Offline
|
|
2
|
+
|
|
3
|
+
TSDF's offline support is built on top of [Persistent Storage](./persistent-storage.md). It lets offline-enabled mutations fall back to a durable queue, keeps optimistic local state visible, replays queued work when the session recovers, and exposes queue/status data for UI.
|
|
4
|
+
|
|
5
|
+
See also: [Store Manager](./store-manager.md) | [Persistent Storage](./persistent-storage.md) | [Mutations](./mutations.md) | [Hooks](./hooks.md#usependingofflineitems)
|
|
6
|
+
|
|
7
|
+
## Enabling Offline
|
|
8
|
+
|
|
9
|
+
Offline has two pieces:
|
|
10
|
+
|
|
11
|
+
1. A shared `offlineSession` on `createStoreManager(...)`.
|
|
12
|
+
2. Store-local `persistentStorage.offline` config, optionally with operation definitions.
|
|
13
|
+
|
|
14
|
+
```ts
|
|
15
|
+
import {
|
|
16
|
+
createListQueryStore,
|
|
17
|
+
createStoreManager,
|
|
18
|
+
type DefineListQueryOfflineOperations,
|
|
19
|
+
type DefineOfflineOperation,
|
|
20
|
+
} from 'tsdf';
|
|
21
|
+
|
|
22
|
+
type User = { id: number; name: string };
|
|
23
|
+
type UserPayload = { id: number };
|
|
24
|
+
type RenameInput = { id: number; name: string };
|
|
25
|
+
type UsersQuery = { teamId: string };
|
|
26
|
+
|
|
27
|
+
type UserOfflineOperations = DefineListQueryOfflineOperations<
|
|
28
|
+
User,
|
|
29
|
+
UsersQuery,
|
|
30
|
+
UserPayload,
|
|
31
|
+
{ renameUser: DefineOfflineOperation<RenameInput> }
|
|
32
|
+
>;
|
|
33
|
+
|
|
34
|
+
const storeManager = createStoreManager({
|
|
35
|
+
getSessionKey: () => currentTenantId ?? false,
|
|
36
|
+
errorNormalizer: normalizeError,
|
|
37
|
+
lowPriorityThrottleMs: 5,
|
|
38
|
+
baseCoalescingWindowMs: 10,
|
|
39
|
+
blockWindowClose: null,
|
|
40
|
+
offlineSession: {
|
|
41
|
+
network: { enabled: true },
|
|
42
|
+
mutationQueueing: { network: 'allow', outage: 'allow' },
|
|
43
|
+
},
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
const userStore = createListQueryStore<
|
|
47
|
+
User,
|
|
48
|
+
UsersQuery,
|
|
49
|
+
UserPayload,
|
|
50
|
+
false,
|
|
51
|
+
false,
|
|
52
|
+
UserOfflineOperations
|
|
53
|
+
>({
|
|
54
|
+
id: 'users',
|
|
55
|
+
storeManager,
|
|
56
|
+
fetchListFn: (query, size, { signal }) => api.listUsers(query, size, signal),
|
|
57
|
+
fetchItemFn: (payload, { signal }) => api.getUser(payload, signal),
|
|
58
|
+
getItemKey: (payload) => payload.id,
|
|
59
|
+
persistentStorage: {
|
|
60
|
+
adapter: 'local-sync',
|
|
61
|
+
schema: userSchema,
|
|
62
|
+
itemPayloadSchema: userPayloadSchema,
|
|
63
|
+
queryPayloadSchema: usersQuerySchema,
|
|
64
|
+
offline: {
|
|
65
|
+
operations: {
|
|
66
|
+
renameUser: {
|
|
67
|
+
inputSchema: renameUserSchema,
|
|
68
|
+
kind: 'update',
|
|
69
|
+
getEntityRefs: ({ input }) => [{ id: input.id }],
|
|
70
|
+
execute: ({ input }) => api.renameUser(input),
|
|
71
|
+
onSuccessExecute: ({ input }) => {
|
|
72
|
+
userStore.updateItemState({ id: input.id }, (user) => ({
|
|
73
|
+
...user,
|
|
74
|
+
name: input.name,
|
|
75
|
+
}));
|
|
76
|
+
},
|
|
77
|
+
},
|
|
78
|
+
},
|
|
79
|
+
},
|
|
80
|
+
},
|
|
81
|
+
});
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
`persistentStorage.offline: {}` is valid when a store only needs session-level offline read/status behavior and has no store-local queued mutation operations.
|
|
85
|
+
|
|
86
|
+
## Queuing Mutations
|
|
87
|
+
|
|
88
|
+
Use the normal `performMutation(...)` API and add an `offline` descriptor:
|
|
89
|
+
|
|
90
|
+
```ts
|
|
91
|
+
await userStore.performMutation(
|
|
92
|
+
{ id: 1 },
|
|
93
|
+
{
|
|
94
|
+
optimisticUpdate: () => {
|
|
95
|
+
userStore.updateItemState({ id: 1 }, (user) => ({
|
|
96
|
+
...user,
|
|
97
|
+
name: 'Ada',
|
|
98
|
+
}));
|
|
99
|
+
},
|
|
100
|
+
mutation: () => api.renameUser({ id: 1, name: 'Ada' }),
|
|
101
|
+
offline: { operation: 'renameUser', input: { id: 1, name: 'Ada' } },
|
|
102
|
+
},
|
|
103
|
+
);
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
When the online mutation succeeds, the result value is `{ kind: 'online', data }`. When TSDF queues the mutation for offline replay, the result value is `{ kind: 'queued' }`.
|
|
107
|
+
|
|
108
|
+
## Operation Definitions
|
|
109
|
+
|
|
110
|
+
All offline operations define:
|
|
111
|
+
|
|
112
|
+
- `inputSchema` - Validates mutation input before it enters the queue and again when restored.
|
|
113
|
+
- `kind` - `create`, `update`, or `delete`; TSDF derives each affected entity's lifecycle from this.
|
|
114
|
+
- `execute(ctx)` - Sends queued work to the server during replay.
|
|
115
|
+
|
|
116
|
+
Collection and list-query operations also define:
|
|
117
|
+
|
|
118
|
+
- `getEntityRefs({ input })` - Returns affected item/entity refs.
|
|
119
|
+
- `dependsOn({ input })` - Optional dependencies on other offline entities.
|
|
120
|
+
|
|
121
|
+
Optional replay behavior:
|
|
122
|
+
|
|
123
|
+
- `onSuccessExecute(ctx)` - Updates live store state after replay succeeds.
|
|
124
|
+
- `getServerSnapshot(ctx)` - Loads fresh server state before replay checks.
|
|
125
|
+
- `shouldSkipSync(ctx)` - Drops queued work when the server already reflects it.
|
|
126
|
+
- `conflictHandling` - Detects conflicts and creates manual resolution records.
|
|
127
|
+
- `accumulation` - Merges newer queued inputs into an existing queued mutation.
|
|
128
|
+
- `supersedes` - Prunes older queued work for the same entity.
|
|
129
|
+
|
|
130
|
+
Create flows for collection and list-query stores can use `tempEntity` or `tempEntities` to insert optimistic entities with temporary payloads and reconcile them to final server payloads after replay. Document stores do not support temp entities.
|
|
131
|
+
|
|
132
|
+
## Conflict Resolution
|
|
133
|
+
|
|
134
|
+
Stores expose resolution APIs:
|
|
135
|
+
|
|
136
|
+
```ts
|
|
137
|
+
const resolutions = userStore.getOfflineResolutions();
|
|
138
|
+
|
|
139
|
+
await userStore.resolveOfflineResolution(resolutions[0].id, 'renameUser', {
|
|
140
|
+
action: 'requeue',
|
|
141
|
+
input: { id: 1, name: 'Ada resolved' },
|
|
142
|
+
});
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
Supported resolution actions include:
|
|
146
|
+
|
|
147
|
+
- `discard` - Drop the resolution record.
|
|
148
|
+
- `requeue` - Queue replacement input for an operation conflict.
|
|
149
|
+
- `commit` - Accept an externally completed resolution result.
|
|
150
|
+
- `retry` - Retry a retry-exhausted record.
|
|
151
|
+
|
|
152
|
+
Use `parseOfflineResolutionConflict(resolution)` to narrow a persisted resolution back to the operation-specific conflict/input type before rendering a manual resolution UI.
|
|
153
|
+
|
|
154
|
+
## Reading Offline State
|
|
155
|
+
|
|
156
|
+
Use manager-level APIs for session-wide UI:
|
|
157
|
+
|
|
158
|
+
```tsx
|
|
159
|
+
const status = storeManager.useOfflineStatus();
|
|
160
|
+
const entities = storeManager.useOfflineEntities();
|
|
161
|
+
const resolutions = storeManager.useOfflineResolutions();
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
Equivalent global helpers are exported for code that only has a session key:
|
|
165
|
+
|
|
166
|
+
```ts
|
|
167
|
+
import {
|
|
168
|
+
getGlobalOfflineStatus,
|
|
169
|
+
useGlobalOfflineEntities,
|
|
170
|
+
useGlobalOfflineResolutions,
|
|
171
|
+
} from 'tsdf';
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
Each store also exposes scoped APIs:
|
|
175
|
+
|
|
176
|
+
- `getOfflineEntities()` / `useOfflineEntities()`
|
|
177
|
+
- `getOfflineResolutions()` / `useOfflineResolutions()`
|
|
178
|
+
- `resolveOfflineResolution(...)`
|
|
179
|
+
- `parseOfflineResolutionConflict(...)`
|
|
180
|
+
|
|
181
|
+
List-query stores additionally expose `usePendingOfflineItems(...)`, which returns pending creates/updates and pending deletes without mounting or fetching a query.
|
|
182
|
+
|
|
183
|
+
## Runtime Controls
|
|
184
|
+
|
|
185
|
+
The store manager owns runtime controls for the shared session:
|
|
186
|
+
|
|
187
|
+
```ts
|
|
188
|
+
storeManager.setOfflineRuntimeConfig({ network: { enabled: false } });
|
|
189
|
+
|
|
190
|
+
storeManager.resetOfflineRuntimeConfig();
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
`getOfflineRuntimeConfig()` returns the current effective controls. Runtime updates are useful for explicit "work offline" toggles, diagnostics, or temporarily disabling queueing modes.
|
|
194
|
+
|
|
195
|
+
## Uploads
|
|
196
|
+
|
|
197
|
+
Configure uploads on `offlineSession.uploads` when queued mutations depend on local files. The manager exposes upload helpers:
|
|
198
|
+
|
|
199
|
+
- `saveOfflineUpload({ id, file })`
|
|
200
|
+
- `replaceOfflineUpload({ id, file })`
|
|
201
|
+
- `loadOfflineUpload(id)`
|
|
202
|
+
- `deleteOfflineUpload(id)`
|
|
203
|
+
- `resolveOfflineUpload(id)`
|
|
204
|
+
- `resolveOfflineUploads(ids)`
|
|
205
|
+
- `useOfflineUploads()`
|
|
206
|
+
|
|
207
|
+
Operations can declare `dependsOnUploads({ input })` and then read resolved upload refs from `execute({ uploads })`. `opfsOfflineUploadAdapter` is exported as a built-in OPFS-backed upload adapter.
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
# Offset Pagination
|
|
2
|
+
|
|
3
|
+
By default, List Query Store uses "size mode" pagination where the entire result set is re-fetched when loading more items. Offset pagination mode uses actual offset/limit-based pagination, which is more efficient for large datasets.
|
|
4
|
+
|
|
5
|
+
**Store**: [List Query Store](./list-query-store.md) only.
|
|
6
|
+
|
|
7
|
+
## Enabling Offset Pagination
|
|
8
|
+
|
|
9
|
+
Enable by setting the `TOffsetPagination` type parameter to `true` and providing an `offsetPagination` config:
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
const store = createListQueryStore<Task, TaskFilter, string, false, true>({
|
|
13
|
+
// ^^^^ enables offset pagination
|
|
14
|
+
|
|
15
|
+
// In offset mode, fetchListFn receives { offset, limit } instead of size
|
|
16
|
+
fetchListFn: (filter, { offset, limit }, { signal }) => {
|
|
17
|
+
return api.getTasks(filter, { offset, limit, signal });
|
|
18
|
+
},
|
|
19
|
+
|
|
20
|
+
offsetPagination: {
|
|
21
|
+
maxInvalidationLimit: 200,
|
|
22
|
+
maxParallel: 3,
|
|
23
|
+
},
|
|
24
|
+
|
|
25
|
+
// ...other options
|
|
26
|
+
});
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## How It Works
|
|
30
|
+
|
|
31
|
+
### Size Mode (Default)
|
|
32
|
+
|
|
33
|
+
In size mode, `loadMore` re-fetches the entire range from 0 to the new total size:
|
|
34
|
+
|
|
35
|
+
```
|
|
36
|
+
Initial load: fetchListFn(filter, 50) → items 0-49
|
|
37
|
+
Load more: fetchListFn(filter, 100) → items 0-99 (re-fetches everything)
|
|
38
|
+
Load more: fetchListFn(filter, 150) → items 0-149 (re-fetches everything)
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
### Offset Mode
|
|
42
|
+
|
|
43
|
+
In offset mode, `loadMore` fetches only the new items:
|
|
44
|
+
|
|
45
|
+
```
|
|
46
|
+
Initial load: fetchListFn(filter, { offset: 0, limit: 50 }) → items 0-49
|
|
47
|
+
Load more: fetchListFn(filter, { offset: 50, limit: 50 }) → items 50-99 (new items only)
|
|
48
|
+
Load more: fetchListFn(filter, { offset: 100, limit: 50 }) → items 100-149 (new items only)
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
New items are appended to the existing list.
|
|
52
|
+
|
|
53
|
+
## Chunked Invalidation
|
|
54
|
+
|
|
55
|
+
When a query with many loaded items is invalidated, fetching all items in a single request could be slow or hit API limits. Offset pagination handles this by splitting the invalidation into parallel chunks:
|
|
56
|
+
|
|
57
|
+
```
|
|
58
|
+
Query has 500 items loaded, maxInvalidationLimit = 200, maxParallel = 3
|
|
59
|
+
|
|
60
|
+
Chunk 1: fetchListFn(filter, { offset: 0, limit: 200 })
|
|
61
|
+
Chunk 2: fetchListFn(filter, { offset: 200, limit: 200 })
|
|
62
|
+
Chunk 3: fetchListFn(filter, { offset: 400, limit: 100 })
|
|
63
|
+
|
|
64
|
+
Chunks 1-3 run in parallel (up to maxParallel concurrent)
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Results are deduplicated (in case of overlapping items) and combined into the final query state.
|
|
68
|
+
|
|
69
|
+
## Configuration
|
|
70
|
+
|
|
71
|
+
### maxInvalidationLimit
|
|
72
|
+
|
|
73
|
+
The maximum number of items to fetch in a single request during invalidation. When the loaded size exceeds this, the fetch is split into chunks.
|
|
74
|
+
|
|
75
|
+
### maxParallel
|
|
76
|
+
|
|
77
|
+
Maximum number of parallel chunk requests during chunked invalidation. Defaults to `3`.
|
|
78
|
+
|
|
79
|
+
## Loading More
|
|
80
|
+
|
|
81
|
+
```tsx
|
|
82
|
+
function TaskList() {
|
|
83
|
+
const { items, hasMore, isLoadingMore } = store.useListQuery(filter);
|
|
84
|
+
|
|
85
|
+
return (
|
|
86
|
+
<div>
|
|
87
|
+
{items.map((task) => (
|
|
88
|
+
<TaskRow
|
|
89
|
+
key={task.id}
|
|
90
|
+
task={task}
|
|
91
|
+
/>
|
|
92
|
+
))}
|
|
93
|
+
|
|
94
|
+
{hasMore && (
|
|
95
|
+
<button
|
|
96
|
+
onClick={() => store.loadMore(filter)}
|
|
97
|
+
disabled={isLoadingMore}
|
|
98
|
+
>
|
|
99
|
+
{isLoadingMore ? 'Loading...' : 'Load More'}
|
|
100
|
+
</button>
|
|
101
|
+
)}
|
|
102
|
+
</div>
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
You can specify a custom size for `loadMore`:
|
|
108
|
+
|
|
109
|
+
```ts
|
|
110
|
+
store.loadMore(filter, 25); // load 25 more items (instead of defaultQuerySize)
|
|
111
|
+
```
|