stream-chat 10.0.0-rc.21 → 10.0.0-rc.23
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/cjs/index.browser.js +2196 -3902
- package/dist/cjs/index.browser.js.map +3 -3
- package/dist/cjs/index.node.js +2197 -3902
- package/dist/cjs/index.node.js.map +3 -3
- package/dist/esm/index.mjs +2199 -3905
- package/dist/esm/index.mjs.map +4 -4
- package/dist/types/ChannelManager.d.ts +120 -233
- package/dist/types/CooldownTimer.d.ts +8 -23
- package/dist/types/EventHandlerPipeline.d.ts +17 -37
- package/dist/types/LiveLocationManager.d.ts +22 -50
- package/dist/types/api-client.d.ts +9 -14
- package/dist/types/channel.d.ts +253 -448
- package/dist/types/channel_state.d.ts +48 -95
- package/dist/types/client.d.ts +245 -370
- package/dist/types/client_state.d.ts +1 -3
- package/dist/types/configuration/ConfigController.d.ts +30 -124
- package/dist/types/configuration/InstanceConfigurationRegistry.d.ts +31 -123
- package/dist/types/configuration/keys.d.ts +5 -19
- package/dist/types/configuration/shape.d.ts +12 -29
- package/dist/types/configuration/types.d.ts +59 -87
- package/dist/types/configuration/utils/applyInstanceConfiguration.d.ts +13 -35
- package/dist/types/configuration/utils/copyConfigPatch.d.ts +8 -0
- package/dist/types/configuration/utils/declarativeSlices.d.ts +5 -16
- package/dist/types/configuration/utils/deepFreezeConfig.d.ts +3 -17
- package/dist/types/configuration/utils/serverAuthority.d.ts +9 -29
- package/dist/types/connection/ConnectionIdManager.d.ts +18 -40
- package/dist/types/connection/ConnectionRecoveryManager.d.ts +29 -120
- package/dist/types/connection/networkConnection/NetworkConnectionObserver.d.ts +32 -103
- package/dist/types/connection/networkConnection/reporters.d.ts +9 -32
- package/dist/types/connection/networkConnection/types.d.ts +12 -27
- package/dist/types/connection/wsConnection/StableWSConnection.d.ts +37 -116
- package/dist/types/connection/wsConnection/WSConnection.d.ts +41 -104
- package/dist/types/connection/wsConnection/WSConnectionFallback.d.ts +8 -16
- package/dist/types/connection/wsConnection/config.d.ts +8 -28
- package/dist/types/connection/wsConnection/types.d.ts +17 -70
- package/dist/types/entityStore/EntityStore.d.ts +153 -113
- package/dist/types/entityStore/StoreBackedItemIndex.d.ts +13 -46
- package/dist/types/errors.d.ts +7 -19
- package/dist/types/gen/chat/ChannelApi.d.ts +2 -1
- package/dist/types/gen/chat/ChatApi.d.ts +28 -14
- package/dist/types/gen/models/index.d.ts +769 -86
- package/dist/types/gen/moderation/ModerationApi.d.ts +4 -4
- package/dist/types/index.d.ts +2 -4
- package/dist/types/languageNames.d.ts +9 -24
- package/dist/types/logger.d.ts +1 -3
- package/dist/types/messageComposer/LocationComposer.d.ts +1 -1
- package/dist/types/messageComposer/attachmentIdentity.d.ts +1 -6
- package/dist/types/messageComposer/attachmentManager.d.ts +10 -32
- package/dist/types/messageComposer/attachmentUtils.d.ts +3 -14
- package/dist/types/messageComposer/configuration/configuration.d.ts +2 -5
- package/dist/types/messageComposer/configuration/types.d.ts +29 -56
- package/dist/types/messageComposer/linkPreviewsManager.d.ts +6 -9
- package/dist/types/messageComposer/messageComposer.d.ts +30 -164
- package/dist/types/messageComposer/middleware/attachmentManager/postUpload/attachmentEnrichment.d.ts +4 -14
- package/dist/types/messageComposer/middleware/messageComposer/attachments.d.ts +2 -9
- package/dist/types/messageComposer/middleware/pollComposer/types.d.ts +2 -4
- package/dist/types/messageComposer/middleware/pollComposer/validation.d.ts +7 -19
- package/dist/types/messageComposer/middleware/textComposer/commands.d.ts +9 -0
- package/dist/types/messageComposer/middleware/textComposer/mentions.d.ts +11 -18
- package/dist/types/messageComposer/middleware/textComposer/textMiddlewareUtils.d.ts +9 -3
- package/dist/types/messageComposer/middleware/textComposer/types.d.ts +1 -6
- package/dist/types/messageComposer/pollComposer.d.ts +8 -4
- package/dist/types/messageComposer/textComposer.d.ts +3 -9
- package/dist/types/messageComposer/types.d.ts +5 -8
- package/dist/types/messageDelivery/MessageDeliveryReporter.d.ts +25 -79
- package/dist/types/messageDelivery/MessageReceiptsTracker.d.ts +15 -82
- package/dist/types/messageOperations/FailedSendCache.d.ts +4 -9
- package/dist/types/messageOperations/MessageOperationStatePolicy.d.ts +10 -20
- package/dist/types/messageOperations/MessageOperations.d.ts +20 -40
- package/dist/types/messageOperations/applyReactionLocally.d.ts +5 -22
- package/dist/types/messageOperations/createMessageOperations.d.ts +3 -5
- package/dist/types/messageOperations/reflectReactionEvent.d.ts +5 -13
- package/dist/types/messageOperations/sendOrdering.d.ts +4 -7
- package/dist/types/messageOperations/settlePendingAttachmentUploads.d.ts +7 -15
- package/dist/types/messageOperations/types.d.ts +15 -30
- package/dist/types/middleware.d.ts +7 -5
- package/dist/types/moderation.d.ts +21 -14
- package/dist/types/notifications/NotificationManager.d.ts +8 -31
- package/dist/types/notifications/types.d.ts +19 -59
- package/dist/types/offline-support/offline_support_api.d.ts +145 -539
- package/dist/types/offline-support/offline_sync_manager.d.ts +18 -42
- package/dist/types/offline-support/queueableOperations.d.ts +24 -52
- package/dist/types/offline-support/types.d.ts +24 -187
- package/dist/types/pagination/ItemIndex.d.ts +4 -12
- package/dist/types/pagination/cursorDerivation/aroundPaginationFlags.d.ts +13 -0
- package/dist/types/pagination/cursorDerivation/createdAtAroundPaginationFlags.d.ts +2 -4
- package/dist/types/pagination/cursorDerivation/linearPaginationFlags.d.ts +2 -3
- package/dist/types/pagination/paginators/BasePaginator.d.ts +235 -622
- package/dist/types/pagination/paginators/ChannelPaginator.d.ts +67 -125
- package/dist/types/pagination/paginators/MessageIntervalPaginator.d.ts +133 -292
- package/dist/types/pagination/paginators/MessagePaginator.d.ts +69 -118
- package/dist/types/pagination/paginators/PinnedMessagePaginator.d.ts +7 -26
- package/dist/types/pagination/paginators/ReminderPaginator.d.ts +2 -2
- package/dist/types/pagination/paginators/ThreadPaginator.d.ts +15 -23
- package/dist/types/pagination/paginators/UserGroupPaginator.d.ts +2 -6
- package/dist/types/pagination/sortCompiler.d.ts +11 -22
- package/dist/types/pagination/utility.normalization.d.ts +5 -23
- package/dist/types/pagination/utility.search.d.ts +3 -8
- package/dist/types/poll.d.ts +14 -14
- package/dist/types/poll_manager.d.ts +11 -2
- package/dist/types/poll_optimistic_votes.d.ts +10 -14
- package/dist/types/reminders/Reminder.d.ts +4 -4
- package/dist/types/reminders/ReminderManager.d.ts +7 -20
- package/dist/types/search/BaseSearchSource.d.ts +7 -12
- package/dist/types/search/ChannelSearchSource.d.ts +7 -7
- package/dist/types/search/MessageSearchSource.d.ts +7 -9
- package/dist/types/search/SearchController.d.ts +17 -22
- package/dist/types/search/types.d.ts +6 -10
- package/dist/types/signing.d.ts +12 -3
- package/dist/types/thread.d.ts +23 -71
- package/dist/types/thread_manager.d.ts +45 -70
- package/dist/types/token_manager.d.ts +8 -13
- package/dist/types/types.d.ts +64 -125
- package/dist/types/types.utility.d.ts +3 -3
- package/dist/types/upload-utils.d.ts +5 -10
- package/dist/types/uploadManager.d.ts +17 -45
- package/dist/types/utils/FixedSizeQueueCache.d.ts +6 -11
- package/dist/types/utils/WithSubscriptions.d.ts +5 -15
- package/dist/types/utils/concurrency.d.ts +11 -19
- package/dist/types/utils/mergeWith/mergeWith.d.ts +8 -11
- package/dist/types/utils/mergeWith/mergeWithCore.d.ts +5 -13
- package/dist/types/utils/mergeWith/mergeWithDiff.d.ts +22 -0
- package/dist/types/utils/objectPath.d.ts +6 -41
- package/dist/types/utils/retryable.d.ts +8 -12
- package/dist/types/utils/throttling/throttle.d.ts +8 -23
- package/dist/types/utils/time.d.ts +24 -64
- package/dist/types/utils.d.ts +40 -86
- package/package.json +7 -2
- package/src/ChannelManager.ts +159 -300
- package/src/CooldownTimer.ts +11 -29
- package/src/EventHandlerPipeline.ts +21 -44
- package/src/LiveLocationManager.ts +35 -74
- package/src/api-client.ts +43 -61
- package/src/campaign.ts +1 -1
- package/src/channel.ts +396 -749
- package/src/channel_batch_updater.ts +1 -1
- package/src/channel_state.ts +50 -105
- package/src/client.ts +360 -588
- package/src/client_state.ts +1 -6
- package/src/configuration/ConfigController.ts +41 -157
- package/src/configuration/InstanceConfigurationRegistry.ts +42 -171
- package/src/configuration/index.ts +1 -1
- package/src/configuration/keys.ts +13 -32
- package/src/configuration/shape.ts +67 -70
- package/src/configuration/types.ts +60 -100
- package/src/configuration/utils/applyInstanceConfiguration.ts +21 -53
- package/src/configuration/utils/copyConfigPatch.ts +11 -32
- package/src/configuration/utils/declarativeSlices.ts +9 -39
- package/src/configuration/utils/deepFreezeConfig.ts +3 -17
- package/src/configuration/utils/index.ts +2 -4
- package/src/configuration/utils/serverAuthority.ts +20 -68
- package/src/connection/ConnectionIdManager.ts +20 -49
- package/src/connection/ConnectionRecoveryManager.ts +51 -178
- package/src/connection/networkConnection/NetworkConnectionObserver.ts +37 -114
- package/src/connection/networkConnection/reporters.ts +9 -36
- package/src/connection/networkConnection/types.ts +12 -27
- package/src/connection/wsConnection/StableWSConnection.ts +73 -193
- package/src/connection/wsConnection/WSConnection.ts +56 -131
- package/src/connection/wsConnection/WSConnectionFallback.ts +22 -31
- package/src/connection/wsConnection/config.ts +13 -48
- package/src/connection/wsConnection/types.ts +17 -70
- package/src/constants.ts +4 -4
- package/src/entityStore/EntityStore.ts +162 -167
- package/src/entityStore/StoreBackedItemIndex.ts +14 -47
- package/src/errors.ts +7 -19
- package/src/formatMessageMemo.ts +3 -9
- package/src/gen/chat/ChannelApi.ts +19 -0
- package/src/gen/chat/ChatApi.ts +87 -13
- package/src/gen/models/index.ts +793 -71
- package/src/gen/moderation/ModerationApi.ts +0 -4
- package/src/index.ts +10 -14
- package/src/languageNames.ts +9 -24
- package/src/logger.ts +1 -3
- package/src/messageComposer/LocationComposer.ts +7 -23
- package/src/messageComposer/MessageComposerEffectHandlers.ts +1 -2
- package/src/messageComposer/attachmentIdentity.ts +2 -13
- package/src/messageComposer/attachmentManager.ts +17 -63
- package/src/messageComposer/attachmentUtils.ts +3 -17
- package/src/messageComposer/configuration/configuration.ts +5 -8
- package/src/messageComposer/configuration/types.ts +29 -56
- package/src/messageComposer/fileUtils.ts +1 -1
- package/src/messageComposer/linkPreviewsManager.ts +8 -20
- package/src/messageComposer/messageComposer.ts +54 -222
- package/src/messageComposer/middleware/attachmentManager/postUpload/attachmentEnrichment.ts +4 -16
- package/src/messageComposer/middleware/attachmentManager/postUpload/uploadErrorHandler.ts +1 -2
- package/src/messageComposer/middleware/messageComposer/attachments.ts +14 -40
- package/src/messageComposer/middleware/messageComposer/linkPreviews.ts +3 -4
- package/src/messageComposer/middleware/messageComposer/textComposer.ts +1 -1
- package/src/messageComposer/middleware/messageComposer/userDataInjection.ts +4 -11
- package/src/messageComposer/middleware/pollComposer/state.ts +2 -2
- package/src/messageComposer/middleware/pollComposer/types.ts +2 -4
- package/src/messageComposer/middleware/pollComposer/validation.ts +8 -26
- package/src/messageComposer/middleware/textComposer/TextComposerMiddlewareExecutor.ts +1 -6
- package/src/messageComposer/middleware/textComposer/commandUtils.ts +1 -2
- package/src/messageComposer/middleware/textComposer/commands.ts +11 -16
- package/src/messageComposer/middleware/textComposer/mentions.ts +32 -70
- package/src/messageComposer/middleware/textComposer/textMiddlewareUtils.ts +10 -4
- package/src/messageComposer/middleware/textComposer/types.ts +1 -6
- package/src/messageComposer/pollComposer.ts +11 -8
- package/src/messageComposer/textComposer.ts +9 -59
- package/src/messageComposer/types.ts +9 -12
- package/src/messageDelivery/MessageDeliveryReporter.ts +60 -113
- package/src/messageDelivery/MessageReceiptsTracker.ts +21 -105
- package/src/messageOperations/FailedSendCache.ts +4 -9
- package/src/messageOperations/MessageOperationStatePolicy.ts +40 -67
- package/src/messageOperations/MessageOperations.ts +33 -62
- package/src/messageOperations/applyReactionLocally.ts +9 -28
- package/src/messageOperations/createMessageOperations.ts +17 -33
- package/src/messageOperations/reflectReactionEvent.ts +5 -13
- package/src/messageOperations/sendOrdering.ts +4 -7
- package/src/messageOperations/settlePendingAttachmentUploads.ts +10 -21
- package/src/messageOperations/types.ts +15 -30
- package/src/middleware.ts +7 -10
- package/src/moderation.ts +25 -21
- package/src/notifications/NotificationManager.ts +11 -35
- package/src/notifications/types.ts +19 -59
- package/src/offline-support/offline_support_api.ts +178 -608
- package/src/offline-support/offline_sync_manager.ts +25 -69
- package/src/offline-support/queueableOperations.ts +31 -84
- package/src/offline-support/types.ts +25 -188
- package/src/pagination/ItemIndex.ts +4 -12
- package/src/pagination/cursorDerivation/aroundPaginationFlags.ts +29 -0
- package/src/pagination/cursorDerivation/createdAtAroundPaginationFlags.ts +13 -62
- package/src/pagination/cursorDerivation/idAroundPaginationFlags.ts +11 -39
- package/src/pagination/cursorDerivation/linearPaginationFlags.ts +4 -6
- package/src/pagination/filterCompiler.ts +11 -25
- package/src/pagination/paginators/BasePaginator.ts +422 -976
- package/src/pagination/paginators/ChannelPaginator.ts +130 -190
- package/src/pagination/paginators/MessageIntervalPaginator.ts +226 -457
- package/src/pagination/paginators/MessagePaginator.ts +135 -175
- package/src/pagination/paginators/PinnedMessagePaginator.ts +13 -38
- package/src/pagination/paginators/ReminderPaginator.ts +12 -15
- package/src/pagination/paginators/ThreadPaginator.ts +16 -26
- package/src/pagination/paginators/UserGroupPaginator.ts +6 -17
- package/src/pagination/paginators/stateThrottling.ts +5 -10
- package/src/pagination/sortCompiler.ts +23 -50
- package/src/pagination/utility.normalization.ts +8 -30
- package/src/pagination/utility.search.ts +4 -11
- package/src/poll.ts +19 -19
- package/src/poll_manager.ts +16 -20
- package/src/poll_optimistic_votes.ts +17 -22
- package/src/reminders/Reminder.ts +5 -6
- package/src/reminders/ReminderManager.ts +9 -34
- package/src/reminders/ReminderTimer.ts +1 -2
- package/src/search/BaseSearchSource.ts +14 -29
- package/src/search/ChannelSearchSource.ts +8 -8
- package/src/search/MessageSearchSource.ts +19 -25
- package/src/search/SearchController.ts +18 -24
- package/src/search/types.ts +6 -10
- package/src/segment.ts +1 -1
- package/src/signing.ts +23 -3
- package/src/thread.ts +72 -173
- package/src/thread_manager.ts +59 -76
- package/src/token_manager.ts +11 -21
- package/src/types.ts +78 -126
- package/src/types.utility.ts +3 -3
- package/src/upload-utils.ts +5 -10
- package/src/uploadManager.ts +22 -54
- package/src/utils/FixedSizeQueueCache.ts +13 -21
- package/src/utils/WithSubscriptions.ts +5 -15
- package/src/utils/concurrency.ts +16 -55
- package/src/utils/mergeWith/mergeWith.ts +10 -13
- package/src/utils/mergeWith/mergeWithCore.ts +24 -81
- package/src/utils/mergeWith/mergeWithDiff.ts +15 -33
- package/src/utils/objectPath.ts +6 -41
- package/src/utils/retryable.ts +10 -14
- package/src/utils/throttling/throttle.ts +9 -25
- package/src/utils/time.ts +26 -66
- package/src/utils.ts +72 -128
|
@@ -32,27 +32,9 @@ export type Interval = {
|
|
|
32
32
|
hasMoreTail: boolean;
|
|
33
33
|
itemIds: string[];
|
|
34
34
|
id: string;
|
|
35
|
-
/**
|
|
36
|
-
* True if this interval represents the global head of the dataset
|
|
37
|
-
* under the current sortComparator.
|
|
38
|
-
*
|
|
39
|
-
* Cursor pagination:
|
|
40
|
-
* headward === null
|
|
41
|
-
*
|
|
42
|
-
* Offset pagination:
|
|
43
|
-
* offset === 0
|
|
44
|
-
*/
|
|
35
|
+
/** Reaches the dataset head (cursor: `headward === null`, offset: `offset === 0`). */
|
|
45
36
|
isHead: boolean;
|
|
46
|
-
/**
|
|
47
|
-
* True if this interval represents the global tail of the dataset
|
|
48
|
-
* under the current sortComparator.
|
|
49
|
-
*
|
|
50
|
-
* Cursor pagination:
|
|
51
|
-
* tailward === null
|
|
52
|
-
*
|
|
53
|
-
* Offset pagination:
|
|
54
|
-
* returnedItems.length < pageSize
|
|
55
|
-
*/
|
|
37
|
+
/** Reaches the dataset tail (cursor: `tailward === null`, offset: a short page). */
|
|
56
38
|
isTail: boolean;
|
|
57
39
|
};
|
|
58
40
|
|
|
@@ -96,17 +78,9 @@ export type MakeIntervalParams<T> = {
|
|
|
96
78
|
export type SetPaginatorItemsParams<T> = {
|
|
97
79
|
valueOrFactory: ValueOrPatch<T[]>;
|
|
98
80
|
cursor?: PaginatorCursor;
|
|
99
|
-
/**
|
|
100
|
-
* Relevant only is using item interval storage in the paginator.
|
|
101
|
-
* Indicates that the page would be the head of pagination intervals array.
|
|
102
|
-
* Items falling outside this intervals head bound will be merged into this interval.
|
|
103
|
-
*/
|
|
81
|
+
/** The page is the head interval: items beyond its head bound merge into it. */
|
|
104
82
|
isFirstPage?: boolean;
|
|
105
|
-
/**
|
|
106
|
-
* Relevant only is using item interval storage in the paginator.
|
|
107
|
-
* Indicates that the page would be the tail of pagination intervals array
|
|
108
|
-
* Items falling outside this intervals tail bound will be merged into this interval.
|
|
109
|
-
*/
|
|
83
|
+
/** The page is the tail interval: items beyond its tail bound merge into it. */
|
|
110
84
|
isLastPage?: boolean;
|
|
111
85
|
};
|
|
112
86
|
|
|
@@ -117,35 +91,22 @@ type MergeIntervalsResult = {
|
|
|
117
91
|
};
|
|
118
92
|
|
|
119
93
|
/**
|
|
120
|
-
* headward
|
|
121
|
-
*
|
|
122
|
-
*
|
|
123
|
-
* Head is the place where new items are added - same as git.
|
|
124
|
-
* Tail is the place where retrieved pages are appended.
|
|
94
|
+
* `headward` moves toward page 0, `tailward` away from it. New items are added at the head,
|
|
95
|
+
* retrieved pages are appended at the tail.
|
|
125
96
|
*/
|
|
126
97
|
export type PaginationDirection = 'headward' | 'tailward';
|
|
127
98
|
|
|
128
99
|
export type CursorDeriveContext<T, Q> = {
|
|
129
|
-
/**
|
|
130
|
-
* Current cursor to be merged with the newly derived cursor.
|
|
131
|
-
* Allows to preserve the direction we have not paginated with the given request.
|
|
132
|
-
*/
|
|
100
|
+
/** Current cursor, merged with the derived one to keep the direction not paginated. */
|
|
133
101
|
cursor: PaginatorCursor | undefined;
|
|
134
|
-
/**
|
|
135
|
-
* Direction we just paginated in.
|
|
136
|
-
*
|
|
137
|
-
* May be undefined for non-directional queries (e.g. jump-to / *_around).
|
|
138
|
-
*/
|
|
102
|
+
/** Direction just paginated in. Undefined for non-directional queries (jump-to, `*_around`). */
|
|
139
103
|
direction: PaginationDirection | undefined;
|
|
140
104
|
hasMoreTail: boolean;
|
|
141
105
|
hasMoreHead: boolean;
|
|
142
|
-
/** The parent interval the page was ingested into (if any) */
|
|
143
106
|
interval: Interval;
|
|
144
|
-
/** The page
|
|
107
|
+
/** The page received, after filtering. */
|
|
145
108
|
page: T[];
|
|
146
|
-
/** Last query shape (sometimes useful for bespoke logic) */
|
|
147
109
|
queryShape: Q | undefined;
|
|
148
|
-
/** Number we asked for */
|
|
149
110
|
requestedPageSize: number;
|
|
150
111
|
};
|
|
151
112
|
|
|
@@ -185,33 +146,27 @@ export type PaginationQueryShapeChangeIdentifier<S> = (
|
|
|
185
146
|
export type PaginationQueryParams<Q> = {
|
|
186
147
|
direction?: PaginationDirection;
|
|
187
148
|
/**
|
|
188
|
-
*
|
|
189
|
-
*
|
|
190
|
-
* active interval by `postQueryReconcile` (upserting changed items, appending new ones), so the
|
|
191
|
-
* list is refreshed in place with no loading-screen flash. Used by the non-destructive refresh.
|
|
149
|
+
* Keeps loaded items (and cursor/flags) visible during a first-page query instead of resetting;
|
|
150
|
+
* `postQueryReconcile` merges the fetched page into the active interval.
|
|
192
151
|
*/
|
|
193
152
|
keepPreviousItems?: boolean;
|
|
194
153
|
/** Data that define the query (filters, sort, ...) */
|
|
195
154
|
queryShape?: Q;
|
|
196
|
-
/** Per-call override
|
|
155
|
+
/** Per-call override: 'yes' forces a first page, 'no' continues, else the query shape decides. */
|
|
197
156
|
reset?: StateResetPolicy;
|
|
198
157
|
/**
|
|
199
|
-
*
|
|
200
|
-
*
|
|
201
|
-
* others are ignored. Retries send them again.
|
|
158
|
+
* Request options outside the query shape, so they never make the query a new first page. Each
|
|
159
|
+
* paginator reads the ones it documents. Resent on retries.
|
|
202
160
|
*/
|
|
203
161
|
requestOptions?: Record<string, unknown>;
|
|
204
|
-
/**
|
|
205
|
-
* How many times to **retry** a failed request, i.e. `retryCount + 1` attempts in total. Per-call
|
|
206
|
-
* override of `PaginatorOptions.retryCount`, which defaults to 0 (no retry).
|
|
207
|
-
*/
|
|
162
|
+
/** Number of retries after a failure. Overrides `PaginatorOptions.retryCount`. */
|
|
208
163
|
retryCount?: number;
|
|
209
164
|
/**
|
|
210
|
-
*
|
|
211
|
-
* (
|
|
165
|
+
* Skips the `isLoading: true` publish for a non-first-page or `keepPreviousItems` query
|
|
166
|
+
* (background refresh). A first page without `keepPreviousItems` still surfaces loading.
|
|
212
167
|
*/
|
|
213
168
|
silent?: boolean;
|
|
214
|
-
/**
|
|
169
|
+
/** Whether the loaded page is committed to the paginator state. Defaults to true. */
|
|
215
170
|
updateState?: boolean;
|
|
216
171
|
};
|
|
217
172
|
|
|
@@ -225,12 +180,9 @@ export type PostQueryReconcileParams<T, Q> = Pick<
|
|
|
225
180
|
};
|
|
226
181
|
|
|
227
182
|
export type ExecuteQueryReturnValue<T> = {
|
|
228
|
-
/**
|
|
229
|
-
* State object resulting from the post query processing.
|
|
230
|
-
* The object is committed to the state if PaginationQueryParams<Q>['updateState'] === true.
|
|
231
|
-
*/
|
|
183
|
+
/** State from post-query processing, committed when `updateState` is true. */
|
|
232
184
|
stateCandidate: Partial<PaginatorState<T>>;
|
|
233
|
-
/**
|
|
185
|
+
/** The interval the page was merged into, when items are kept in intervals. */
|
|
234
186
|
targetInterval: AnyInterval | null;
|
|
235
187
|
};
|
|
236
188
|
|
|
@@ -264,23 +216,17 @@ export type PaginatorState<T> = {
|
|
|
264
216
|
};
|
|
265
217
|
|
|
266
218
|
/**
|
|
267
|
-
*
|
|
268
|
-
*
|
|
269
|
-
*
|
|
270
|
-
*
|
|
271
|
-
* be either a logical or an anchored interval is a derived *role*, not a fixed interval, so it is not
|
|
272
|
-
* published here — read it one-shot via {@link BasePaginator.headItems} / {@link BasePaginator.headmostItem}.)
|
|
219
|
+
* Projections of fixed-identity intervals, published independently of `state` (which tracks only
|
|
220
|
+
* the active interval; see {@link BasePaginator.intervalViews}). A field is rewritten only when its
|
|
221
|
+
* own interval changes. The head-most window (logical or anchored) is a role, not a fixed interval,
|
|
222
|
+
* so read it via {@link BasePaginator.headItems} / {@link BasePaginator.headmostItem}.
|
|
273
223
|
*/
|
|
274
224
|
export type PaginatorIntervalViews<T> = {
|
|
275
|
-
/**
|
|
225
|
+
/** Out-of-order items above the loaded window. */
|
|
276
226
|
logicalHead: T[];
|
|
277
|
-
/**
|
|
227
|
+
/** Out-of-order items below the loaded window. */
|
|
278
228
|
logicalTail: T[];
|
|
279
|
-
/**
|
|
280
|
-
* Anchored head interval — the loaded page bounded at the dataset head (`isHead`), i.e. the newest
|
|
281
|
-
* loaded page; empty when the head is not loaded. Its content updates when that page ingests/removes
|
|
282
|
-
* an item, and its identity updates when a page's `isHead` flag flips during query reconciliation.
|
|
283
|
-
*/
|
|
229
|
+
/** The loaded page bounded at the dataset head (`isHead`); empty when the head is not loaded. */
|
|
284
230
|
anchoredHead: T[];
|
|
285
231
|
};
|
|
286
232
|
|
|
@@ -293,19 +239,8 @@ export type PaginatorItemsChangeProcessor<T> = (params: {
|
|
|
293
239
|
|
|
294
240
|
export interface PaginatorPlugin<T> {
|
|
295
241
|
/**
|
|
296
|
-
*
|
|
297
|
-
* `items`
|
|
298
|
-
* changed by reference.
|
|
299
|
-
*
|
|
300
|
-
* This hook allows plugins to post-process the visible items—such as
|
|
301
|
-
* deduplicating, normalizing, sorting, enriching, or otherwise transforming
|
|
302
|
-
* the array—at the final stage of state emission. The processed value becomes
|
|
303
|
-
* the `items` value delivered to subscribers.
|
|
304
|
-
*
|
|
305
|
-
* Return a new array to replace `nextState.items`, or return `undefined`
|
|
306
|
-
* to leave the items unchanged.
|
|
307
|
-
*
|
|
308
|
-
* Executed in the order plugins are registered.
|
|
242
|
+
* Runs before `items` are emitted, only when the array changed by reference. Return a new array
|
|
243
|
+
* to replace `nextState.items`, or `undefined` to keep it. Runs in registration order.
|
|
309
244
|
*/
|
|
310
245
|
onBeforeItemsEmitted?: PaginatorItemsChangeProcessor<T>;
|
|
311
246
|
|
|
@@ -315,25 +250,14 @@ export interface PaginatorPlugin<T> {
|
|
|
315
250
|
// onQueryError?(ctx: { error: unknown; paginator: BasePaginator<T, Q> }): void | Promise<void>;
|
|
316
251
|
}
|
|
317
252
|
|
|
318
|
-
|
|
319
|
-
* Optional list of plugins that can hook into paginator lifecycle events.
|
|
320
|
-
*
|
|
321
|
-
* Plugins allow you to encapsulate cross-cutting behavior (such as items
|
|
322
|
-
* post-processing, analytics, offline caching, etc.) without modifying
|
|
323
|
-
* the core paginator logic. Each plugin can register handlers like
|
|
324
|
-
* `onItemsChange` that are invoked when relevant events occur.
|
|
325
|
-
*
|
|
326
|
-
* All registered plugins are executed in the order they appear in this array.
|
|
327
|
-
*/
|
|
253
|
+
// Plugins hook into the paginator lifecycle and run in array order.
|
|
328
254
|
// plugins?: PaginatorPlugin<T, Q>[];
|
|
329
255
|
|
|
330
256
|
/**
|
|
331
|
-
* The value-level subset of paginator
|
|
332
|
-
*
|
|
333
|
-
*
|
|
334
|
-
*
|
|
335
|
-
*
|
|
336
|
-
* Declared standalone rather than derived from {@link PaginatorOptions} to avoid a circular type.
|
|
257
|
+
* The value-level subset of paginator options that `client.config` can supply declaratively.
|
|
258
|
+
* Structural inputs (`itemIndex`, `createItemIndex`) and subclass overrides (`doRequest`,
|
|
259
|
+
* `itemOrderComparator`, `deriveCursor`) are excluded. Declared standalone to avoid a circular type
|
|
260
|
+
* with `PaginatorOptions`.
|
|
337
261
|
*/
|
|
338
262
|
export type DeclarativePaginatorConfig = {
|
|
339
263
|
debounceMs?: number;
|
|
@@ -350,83 +274,64 @@ export type DeclarativePaginatorConfig = {
|
|
|
350
274
|
|
|
351
275
|
export type PaginatorOptions<T, Q> = {
|
|
352
276
|
/**
|
|
353
|
-
* Declarative
|
|
354
|
-
*
|
|
355
|
-
* can re-derive with a *fresh* slice — a reset then drops declarative values while preserving
|
|
356
|
-
* constructor-injected ones. Excluded from {@link BasePaginatorConfig}: it is an input, not part of
|
|
357
|
-
* the resolved configuration.
|
|
277
|
+
* Declarative values from `client.config`, kept apart so a reset (`initializeConfig` with a fresh
|
|
278
|
+
* slice) drops them but keeps injected options. Not part of {@link BasePaginatorConfig}.
|
|
358
279
|
*/
|
|
359
280
|
declarativeConfig?: DeclarativePaginatorConfig;
|
|
360
|
-
/**
|
|
281
|
+
/** Debounce of the search query in milliseconds. Defaults to 300. */
|
|
361
282
|
debounceMs?: number;
|
|
362
283
|
/**
|
|
363
|
-
*
|
|
364
|
-
*
|
|
365
|
-
*
|
|
366
|
-
* publishes it ~2×/sec instead of once per event. Only the paginator's OWN writes to `state.items`
|
|
367
|
-
* are batched — `state.getLatestValue()` is untouched (no `StateStore` change), pagination / jump /
|
|
368
|
-
* query publishes stay immediate, and an immediate flush past it is available via
|
|
369
|
-
* {@link flushPendingPublishes}. Unset ⇒ no throttle (default). Enabled at
|
|
370
|
-
* 500ms for the message list — see {@link MessagePaginator}.
|
|
284
|
+
* Coalesces the paginator's own live `state.items` publishes to one per `stateThrottleMs`
|
|
285
|
+
* (leading and trailing edge). Pagination, jump and query publishes stay immediate. Disabled
|
|
286
|
+
* under test runners. Unset: no throttle.
|
|
371
287
|
*/
|
|
372
288
|
stateThrottleMs?: number;
|
|
373
289
|
/**
|
|
374
|
-
*
|
|
375
|
-
*
|
|
290
|
+
* Decides whether the next query is a first-page query. It should be when filters, sort or
|
|
291
|
+
* options (the query params except page size) changed.
|
|
376
292
|
*/
|
|
377
|
-
|
|
378
293
|
hasPaginationQueryShapeChanged?: PaginationQueryShapeChangeIdentifier<any>;
|
|
379
294
|
/**
|
|
380
|
-
*
|
|
381
|
-
*
|
|
295
|
+
* Derives the cursor and `hasMore` flags from the ingested interval. Without it, the cursor comes
|
|
296
|
+
* from the query response (`headward`/`tailward`, falsy meaning exhausted).
|
|
382
297
|
*/
|
|
383
298
|
deriveCursor?: CursorDerivator<T, Q>;
|
|
384
|
-
/**
|
|
299
|
+
/** Fetches a page of items; returns a cursor when paginating by cursor. */
|
|
385
300
|
doRequest?: (queryParams: Q) => Promise<{ items: T[]; cursor?: PaginatorCursor }>;
|
|
386
|
-
/** In case of cursor pagination, specify the initial cursor value. */
|
|
387
301
|
initialCursor?: PaginatorCursor;
|
|
388
|
-
/** In case of offset pagination, specify the initial offset value. */
|
|
389
302
|
initialOffset?: number;
|
|
390
|
-
/**
|
|
303
|
+
/** Shared item index: a single source of data for all consumers. */
|
|
391
304
|
itemIndex?: ItemIndexApi<T>;
|
|
392
305
|
/**
|
|
393
|
-
*
|
|
394
|
-
*
|
|
395
|
-
*
|
|
396
|
-
* Ignored when an explicit `itemIndex` is supplied.
|
|
306
|
+
* Builds the item index from the paginator (`owner`), for adapters that need it (e.g. a
|
|
307
|
+
* client-global store). Runs in the base constructor, before subclass fields are initialized.
|
|
308
|
+
* Ignored when `itemIndex` is supplied.
|
|
397
309
|
*/
|
|
398
310
|
createItemIndex?: (owner: BasePaginator<T, Q>) => ItemIndexApi<T>;
|
|
399
311
|
/**
|
|
400
|
-
*
|
|
401
|
-
* Defaults to `sortComparator` to preserve existing paginator behavior.
|
|
312
|
+
* Orders items in memory for interval math and the visible list. Defaults to `sortComparator`.
|
|
402
313
|
*/
|
|
403
314
|
itemOrderComparator?: (a: T, b: T) => number;
|
|
404
315
|
/**
|
|
405
|
-
*
|
|
406
|
-
*
|
|
407
|
-
* It does not guarantee global stability across interval changes or page jumps.
|
|
316
|
+
* An already visible item keeps its relative position in the current items array when updated.
|
|
317
|
+
* Does not hold across interval changes or page jumps.
|
|
408
318
|
*/
|
|
409
319
|
lockItemOrder?: boolean;
|
|
410
320
|
/**
|
|
411
|
-
* Caps
|
|
412
|
-
*
|
|
413
|
-
*
|
|
414
|
-
* the window re-opens its tailward edge, so scrolling back simply re-fetches.
|
|
415
|
-
*
|
|
416
|
-
* Unset (the default) means unbounded — see {@link BasePaginator.pruneTailToLimit} for the
|
|
417
|
-
* preconditions a prune must meet. Values below `pageSize` are clamped up to it: a cap smaller than
|
|
418
|
-
* a page would have the next page pruned away the moment it lands.
|
|
321
|
+
* Caps the loaded items: when the head window exceeds it, the oldest are released as new ones
|
|
322
|
+
* arrive and the tailward edge re-opens, so scrolling back re-fetches. Unset: unbounded. Values
|
|
323
|
+
* below `pageSize` are clamped up to it. See {@link BasePaginator.pruneTailToLimit}.
|
|
419
324
|
*/
|
|
420
325
|
maxLoadedItems?: number;
|
|
421
|
-
/**
|
|
326
|
+
/** Items requested per page. Defaults to 10. */
|
|
422
327
|
pageSize?: number;
|
|
423
328
|
/**
|
|
424
|
-
*
|
|
425
|
-
*
|
|
329
|
+
* Retries after a failed request (`retryCount + 1` attempts),
|
|
330
|
+
* `DEFAULT_QUERY_CHANNELS_MS_BETWEEN_RETRIES` apart. Defaults to 0.
|
|
426
331
|
* `PaginationQueryParams.retryCount` overrides it per call.
|
|
427
332
|
*/
|
|
428
333
|
retryCount?: number;
|
|
429
|
-
/**
|
|
334
|
+
/** Rethrows errors from pagination execution instead of swallowing them. Defaults to false. */
|
|
430
335
|
throwErrors?: boolean;
|
|
431
336
|
};
|
|
432
337
|
|
|
@@ -441,12 +346,8 @@ type OptionalPaginatorConfigFields =
|
|
|
441
346
|
| 'throwErrors';
|
|
442
347
|
|
|
443
348
|
/**
|
|
444
|
-
*
|
|
445
|
-
*
|
|
446
|
-
* `itemIndex` and `createItemIndex` are here rather than in {@link BasePaginatorConfig} because the
|
|
447
|
-
* constructor destructures them out before building the config and resolves them once into
|
|
448
|
-
* {@link BasePaginator._itemIndex}. They were typed as config members and never written, so
|
|
449
|
-
* `paginator.config.itemIndex` compiled and returned `undefined` for every paginator ever built.
|
|
349
|
+
* Options minus the construction-only inputs: the constructor resolves `itemIndex` and
|
|
350
|
+
* `createItemIndex` once into {@link BasePaginator._itemIndex}, so they are not config.
|
|
450
351
|
*/
|
|
451
352
|
type ResolvedPaginatorOptions<T, Q> = Omit<
|
|
452
353
|
PaginatorOptions<T, Q>,
|
|
@@ -477,107 +378,64 @@ export const DEFAULT_PAGINATION_OPTIONS: BasePaginatorConfig<any, any> = deepFre
|
|
|
477
378
|
export abstract class BasePaginator<T, Q> {
|
|
478
379
|
state: StateStore<PaginatorState<T>>;
|
|
479
380
|
/**
|
|
480
|
-
*
|
|
481
|
-
*
|
|
482
|
-
* its own interval changes, regardless of which interval is active — so consumers can reactively
|
|
483
|
-
* render off-window "sideloaded" content (`logicalHead`/`logicalTail`) and the newest loaded page
|
|
484
|
-
* (`anchoredHead`). Kept separate from `state` so the paginated-list contract stays focused on the
|
|
485
|
-
* active window + pagination status.
|
|
381
|
+
* Projections of specific intervals ({@link PaginatorIntervalViews}). Unlike `state`, a field is
|
|
382
|
+
* rewritten whenever its own interval changes, active or not.
|
|
486
383
|
*/
|
|
487
384
|
intervalViews: StateStore<PaginatorIntervalViews<T>>;
|
|
488
385
|
|
|
489
|
-
/** The shared configuration machinery — see {@link ConfigController}. */
|
|
490
386
|
private readonly configController: ConfigController<BasePaginatorConfig<T, Q>>;
|
|
491
|
-
/**
|
|
492
|
-
* The paginator's resolved configuration, as a store so consumers can react to it.
|
|
493
|
-
*
|
|
494
|
-
* Every configurable class exposes its resolved configuration this way — `configState` for the store,
|
|
495
|
-
* {@link config} for the current value. Before this, paginators held a plain object that changed
|
|
496
|
-
* silently, so anything displaying a paginator's settings had to poll to notice a
|
|
497
|
-
* `client.config.set()` or `reset()`.
|
|
498
|
-
*
|
|
499
|
-
* This is *resolved* configuration, distinct from `client.config`, which holds the configuration you
|
|
500
|
-
* registered. The registered tree is an input to {@link initializeConfig}; this is its output.
|
|
501
|
-
*/
|
|
502
387
|
get configState(): StateStore<BasePaginatorConfig<T, Q>> {
|
|
503
388
|
return this.configController.state;
|
|
504
389
|
}
|
|
505
390
|
|
|
506
|
-
/**
|
|
507
|
-
* Options this paginator was constructed with, kept so {@link initializeConfig} can rebuild the
|
|
508
|
-
* config from its real inputs instead of restoring a snapshot of the result. Excludes the
|
|
509
|
-
* declarative slice, which is supplied fresh on every call — that is what lets a reset drop
|
|
510
|
-
* declarative configuration while keeping constructor-injected options.
|
|
511
|
-
*/
|
|
391
|
+
/** Constructor options minus the declarative slice, for `initializeConfig` to rebuild from. */
|
|
512
392
|
private readonly explicitOptions: Omit<
|
|
513
393
|
PaginatorOptions<T, Q>,
|
|
514
394
|
'createItemIndex' | 'declarativeConfig' | 'itemIndex'
|
|
515
395
|
>;
|
|
516
396
|
|
|
517
|
-
/**
|
|
518
|
-
* Throttle for the active-window `state.items` publish (message list). Created only when
|
|
519
|
-
* `config.stateThrottleMs` is set; drives {@link scheduleWindowPublish} / {@link flushPendingPublishes}. See
|
|
520
|
-
* `stateThrottleMs` in {@link PaginatorOptions}.
|
|
521
|
-
*/
|
|
397
|
+
/** Throttle for the active-window `state.items` publish. Set only with `stateThrottleMs`. */
|
|
522
398
|
private _windowPublishThrottle?: Throttled<[]>;
|
|
523
399
|
|
|
524
400
|
/**
|
|
525
|
-
* Throttle for
|
|
526
|
-
*
|
|
527
|
-
* its own trailing edge even when `state.items` stays quiet. Created alongside it (only when
|
|
528
|
-
* `config.stateThrottleMs` is set); buffers changed ids in {@link _pendingViewChangedIds}.
|
|
401
|
+
* Throttle for interval-view publishes. Independent of {@link _windowPublishThrottle} so a view
|
|
402
|
+
* refresh lands on its own trailing edge even when `state.items` is quiet. Created with it.
|
|
529
403
|
*/
|
|
530
404
|
private _viewPublishThrottle?: Throttled<[]>;
|
|
531
405
|
|
|
532
|
-
/** Changed
|
|
406
|
+
/** Changed IDs buffered since the last {@link flushIntervalViewPublish} (throttled only). */
|
|
533
407
|
private _pendingViewChangedIds = new Set<string>();
|
|
534
408
|
|
|
535
409
|
/**
|
|
536
|
-
* Depth of active {@link batch} `coalesce` scopes. While > 0, `ingestItem`
|
|
537
|
-
*
|
|
538
|
-
* the whole batch produces a single `state.items` emit — independent of state throttling.
|
|
410
|
+
* Depth of active {@link batch} `coalesce` scopes. While > 0, `ingestItem`/`removeItem` mark the
|
|
411
|
+
* window dirty ({@link _suspendedWindowDirty}) instead of publishing.
|
|
539
412
|
*/
|
|
540
413
|
private _windowPublishSuspendDepth = 0;
|
|
541
414
|
/**
|
|
542
|
-
* The interval a prune just shortened.
|
|
543
|
-
*
|
|
544
|
-
*
|
|
545
|
-
* when it fires.
|
|
415
|
+
* The interval a prune just shortened. Its `hasMoreTail` and `cursor` ride on the next
|
|
416
|
+
* `state.items` publish, which can be a throttle interval late, so
|
|
417
|
+
* {@link consumePendingPrunePaginationState} rereads them from the interval by ID when it fires.
|
|
546
418
|
*/
|
|
547
419
|
private _prunedIntervalId?: string;
|
|
548
|
-
/** Set
|
|
420
|
+
/** Set when a suspended op changed the active window, so {@link batch} publishes on exit. */
|
|
549
421
|
private _suspendedWindowDirty = false;
|
|
550
422
|
|
|
551
|
-
/**
|
|
552
|
-
* Intervals keep items in disconnected ranges.
|
|
553
|
-
* That is a scenario of jumping to non-sequential pages.
|
|
554
|
-
* Intervals are populated only if itemIndex is provided.
|
|
555
|
-
*/
|
|
423
|
+
/** Disconnected ranges of items, e.g. after jumping to non-sequential pages. */
|
|
556
424
|
protected _itemIntervals: Map<string, AnyInterval> = new Map();
|
|
557
425
|
protected _activeIntervalId: string | undefined;
|
|
558
426
|
|
|
559
|
-
/**
|
|
560
|
-
* ItemIndex is a canonical, ID-addressable storage layer for domain items.
|
|
561
|
-
* It serves as a single source of truth for all those that need to access the items
|
|
562
|
-
* outside the paginator.
|
|
563
|
-
*/
|
|
427
|
+
/** Canonical, ID-addressable item storage: the single source of truth outside the paginator. */
|
|
564
428
|
protected _itemIndex: ItemIndexApi<T>;
|
|
565
429
|
|
|
566
430
|
protected _executeQueryDebounced!: DebouncedExecQueryFunction<Q>;
|
|
567
|
-
/** Last effective query shape produced by subclass for the most recent request. */
|
|
431
|
+
/** Last effective query shape produced by the subclass for the most recent request. */
|
|
568
432
|
protected _lastQueryShape?: Q;
|
|
569
433
|
protected _nextQueryShape?: Q;
|
|
570
434
|
|
|
571
435
|
/**
|
|
572
|
-
* Stable,
|
|
573
|
-
*
|
|
574
|
-
*
|
|
575
|
-
* 2. interval comparator
|
|
576
|
-
*
|
|
577
|
-
* Intervals cannot be sorted using boostComparator, because boosting the interval boundary (top item)
|
|
578
|
-
* would lead to the boosting of the entire interval when sorting the intervals.
|
|
579
|
-
*
|
|
580
|
-
* Sorting within a single interval should be done using effectiveComparator, which by default uses boostComparator.
|
|
436
|
+
* Stable, purely data-driven comparison (age, timestamps, ...). Default for
|
|
437
|
+
* `itemOrderComparator`, which orders items and intervals and breaks `boostComparator` ties.
|
|
438
|
+
* Intervals never use the boost order: boosting a boundary item would boost its whole interval.
|
|
581
439
|
*/
|
|
582
440
|
sortComparator: (a: T, b: T) => number;
|
|
583
441
|
protected _filterFieldToDataResolvers: FieldToDataResolver<T>[];
|
|
@@ -586,37 +444,25 @@ export abstract class BasePaginator<T, Q> {
|
|
|
586
444
|
protected _maxBoostSeq = 0;
|
|
587
445
|
|
|
588
446
|
/**
|
|
589
|
-
*
|
|
590
|
-
*
|
|
591
|
-
* - `true` => `itemIds[0]` is the pagination head edge (default)
|
|
592
|
-
* - `false` => `itemIds[itemIds.length - 1]` is the pagination head edge
|
|
593
|
-
*
|
|
594
|
-
* NOTE: This does not affect the *sorting* of `itemIds` (they are always kept
|
|
595
|
-
* in `sortComparator` order). It only affects which side is considered
|
|
596
|
-
* "head" for interval ordering and live ingestion decisions.
|
|
447
|
+
* Whether `itemIds[0]` (true) or the last ID (false) is the pagination head edge. Defaults to
|
|
448
|
+
* true. `itemIds` stay in `itemOrderComparator` order either way.
|
|
597
449
|
*/
|
|
598
450
|
protected get intervalItemIdsAreHeadFirst(): boolean {
|
|
599
451
|
return true;
|
|
600
452
|
}
|
|
601
453
|
|
|
602
454
|
/**
|
|
603
|
-
*
|
|
604
|
-
*
|
|
605
|
-
* This controls only the ordering of intervals relative to each other (by comparing
|
|
606
|
-
* their head edges using `sortComparator`). It is intentionally decoupled from:
|
|
607
|
-
* - the ordering of itemIds inside an interval
|
|
608
|
-
* - the meaning of the head edge (controlled by `intervalItemIdsAreHeadFirst`)
|
|
455
|
+
* Order of intervals relative to each other, comparing head edges under `itemOrderComparator`.
|
|
456
|
+
* Independent of the `itemIds` order and of `intervalItemIdsAreHeadFirst`.
|
|
609
457
|
*/
|
|
610
458
|
protected get intervalSortDirection(): 'asc' | 'desc' {
|
|
611
459
|
return 'asc';
|
|
612
460
|
}
|
|
613
461
|
|
|
614
462
|
/**
|
|
615
|
-
* @param options -
|
|
616
|
-
* @param builtInDefaults -
|
|
617
|
-
*
|
|
618
|
-
* two apart is what lets the documented layer order apply here at all: they arrive through the same
|
|
619
|
-
* object otherwise, and a paginator built with no configuration already carries four of them.
|
|
463
|
+
* @param options - What the integrator passed. Outranks the declarative `client.config` tree.
|
|
464
|
+
* @param builtInDefaults - What the SDK supplies on the instance's behalf (a subclass's or an
|
|
465
|
+
* owner's defaults). A `client.config.set()` overrides these.
|
|
620
466
|
*/
|
|
621
467
|
protected constructor(
|
|
622
468
|
{
|
|
@@ -636,10 +482,7 @@ export abstract class BasePaginator<T, Q> {
|
|
|
636
482
|
constructorOptions: this.explicitOptions as Partial<BasePaginatorConfig<T, Q>>,
|
|
637
483
|
initialSlice: declarativeConfig as Partial<BasePaginatorConfig<T, Q>> | undefined,
|
|
638
484
|
getBehaviourOverrides: () => this.getBehaviourOverrides(),
|
|
639
|
-
// Both
|
|
640
|
-
// Pairing the write with the rebuild here rather than in `initializeConfig` is what finally makes
|
|
641
|
-
// `updateConfig({ debounceMs })` work: it used to store 900 and leave the debounce running at 300,
|
|
642
|
-
// so `config.debounceMs` reported a value the paginator was not using.
|
|
485
|
+
// Both values are captured in closures, so a change must rebuild them.
|
|
643
486
|
onChanged: (next, previous) => {
|
|
644
487
|
if (next.debounceMs !== previous.debounceMs) {
|
|
645
488
|
this.setDebounceOptions({ debounceMs: next.debounceMs });
|
|
@@ -652,14 +495,12 @@ export abstract class BasePaginator<T, Q> {
|
|
|
652
495
|
const { debounceMs } = this.config;
|
|
653
496
|
this.state = new StateStore<PaginatorState<T>>({
|
|
654
497
|
...this.initialState,
|
|
655
|
-
// Seeded from the
|
|
656
|
-
//
|
|
657
|
-
// Reading the argument directly missed a subclass's own default once those moved to stage 1 — and
|
|
658
|
-
// it also meant a declaratively registered cursor configured the paginator without seeding it.
|
|
498
|
+
// Seeded from the resolved config (subclass defaults, declarative values), not the raw
|
|
499
|
+
// argument.
|
|
659
500
|
cursor: this.config.initialCursor,
|
|
660
501
|
offset: this.config.initialOffset ?? 0,
|
|
661
502
|
});
|
|
662
|
-
//
|
|
503
|
+
// Called directly: `onChanged` fires on changes, not on the initial build.
|
|
663
504
|
this.rebuildStatePublishThrottles(this.config.stateThrottleMs);
|
|
664
505
|
this.intervalViews = new StateStore<PaginatorIntervalViews<T>>({
|
|
665
506
|
logicalHead: [],
|
|
@@ -678,10 +519,6 @@ export abstract class BasePaginator<T, Q> {
|
|
|
678
519
|
});
|
|
679
520
|
}
|
|
680
521
|
|
|
681
|
-
// ---------------------------------------------------------------------------
|
|
682
|
-
// Basic getters
|
|
683
|
-
// ---------------------------------------------------------------------------
|
|
684
|
-
|
|
685
522
|
get lastQueryError() {
|
|
686
523
|
return this.state.getLatestValue().lastQueryError;
|
|
687
524
|
}
|
|
@@ -716,7 +553,10 @@ export abstract class BasePaginator<T, Q> {
|
|
|
716
553
|
return this.state.getLatestValue().isLoading;
|
|
717
554
|
}
|
|
718
555
|
|
|
719
|
-
/**
|
|
556
|
+
/**
|
|
557
|
+
* True once a query has run or a non-empty window was loaded without one (`setItems`, or a
|
|
558
|
+
* subclass calling `recordLoadedWindowQueryShape`). Cleared by `resetState`.
|
|
559
|
+
*/
|
|
720
560
|
get isInitialized() {
|
|
721
561
|
return typeof this._lastQueryShape !== 'undefined';
|
|
722
562
|
}
|
|
@@ -746,27 +586,16 @@ export abstract class BasePaginator<T, Q> {
|
|
|
746
586
|
}
|
|
747
587
|
|
|
748
588
|
/**
|
|
749
|
-
* The newest loaded window
|
|
750
|
-
*
|
|
751
|
-
*
|
|
752
|
-
* interval).
|
|
753
|
-
*
|
|
754
|
-
* NOTE: this deliberately uses the head-*most loaded* interval rather than requiring the
|
|
755
|
-
* `isHead` flag — the query/hydration seed does not reliably mark a freshly loaded latest page
|
|
756
|
-
* as `isHead`, so an isHead-only check would miss channel-list channels entirely. The trade-off
|
|
757
|
-
* is that after jumping to an older window with the latest window not loaded, this reports that
|
|
758
|
-
* older window as "latest" (best effort). Use for "latest"-derived reads: last message, unread
|
|
759
|
-
* counting, delivery candidates, channel-list previews.
|
|
589
|
+
* The newest loaded window, independent of the active interval: the head-most loaded interval
|
|
590
|
+
* under the paginator's ordering. It does not require `isHead` (seeds do not reliably set it), so
|
|
591
|
+
* after a jump to an older window with the latest not loaded, that older window is returned.
|
|
760
592
|
*/
|
|
761
593
|
get headItems(): T[] {
|
|
762
594
|
const head = this.getHeadIntervalFromSortedIntervals(this.itemIntervals);
|
|
763
595
|
return head ? this.intervalToItems(head) : [];
|
|
764
596
|
}
|
|
765
597
|
|
|
766
|
-
/**
|
|
767
|
-
* The item on the head edge of the head pagination interval (of {@link BasePaginator.headItems}).
|
|
768
|
-
* `undefined` when nothing is loaded.
|
|
769
|
-
*/
|
|
598
|
+
/** The item on the head edge of the `headItems` interval; `undefined` when nothing is loaded. */
|
|
770
599
|
get headmostItem(): T | undefined {
|
|
771
600
|
const head = this.getHeadIntervalFromSortedIntervals(this.itemIntervals);
|
|
772
601
|
return head ? (this.getIntervalPaginationEdges(head)?.head ?? undefined) : undefined;
|
|
@@ -780,21 +609,15 @@ export abstract class BasePaginator<T, Q> {
|
|
|
780
609
|
return this.state.getLatestValue().offset;
|
|
781
610
|
}
|
|
782
611
|
|
|
783
|
-
/**
|
|
784
|
-
* The current resolved configuration.
|
|
785
|
-
*
|
|
786
|
-
* `Readonly` on purpose: the value is the store's live object, so assigning to a field of it would
|
|
787
|
-
* mutate state without notifying anyone. That used to be the only way to change these values, so the
|
|
788
|
-
* type is what turns those call sites into compile errors rather than silent non-reactive writes —
|
|
789
|
-
* use {@link updateConfig}.
|
|
790
|
-
*/
|
|
791
612
|
get config(): Readonly<BasePaginatorConfig<T, Q>> {
|
|
792
613
|
return this.configState.getLatestValue();
|
|
793
614
|
}
|
|
794
615
|
|
|
795
616
|
/**
|
|
796
|
-
* Merges a partial configuration into the resolved config
|
|
797
|
-
*
|
|
617
|
+
* Merges a partial configuration into the resolved config. The next `initializeConfig` discards
|
|
618
|
+
* it.
|
|
619
|
+
*
|
|
620
|
+
* @param config - The fields to merge.
|
|
798
621
|
*/
|
|
799
622
|
updateConfig(config: Partial<BasePaginatorConfig<T, Q>>) {
|
|
800
623
|
this.configController.patch(config);
|
|
@@ -816,7 +639,7 @@ export abstract class BasePaginator<T, Q> {
|
|
|
816
639
|
this.updateConfig({ initialOffset: offset });
|
|
817
640
|
}
|
|
818
641
|
|
|
819
|
-
/**
|
|
642
|
+
/** The boost-aware comparator to use for ordering items. */
|
|
820
643
|
get effectiveComparator() {
|
|
821
644
|
return this.boostComparator;
|
|
822
645
|
}
|
|
@@ -829,9 +652,9 @@ export abstract class BasePaginator<T, Q> {
|
|
|
829
652
|
return (a: AnyInterval, b: AnyInterval) => {
|
|
830
653
|
const aEdges = this.getIntervalPaginationEdges(a);
|
|
831
654
|
const bEdges = this.getIntervalPaginationEdges(b);
|
|
832
|
-
if (!aEdges
|
|
833
|
-
if (!aEdges) return 1;
|
|
834
|
-
if (!bEdges) return -1;
|
|
655
|
+
if (!aEdges && !bEdges) return 0;
|
|
656
|
+
if (!aEdges) return 1;
|
|
657
|
+
if (!bEdges) return -1;
|
|
835
658
|
return this.compareIntervalHeadEdges(aEdges.head, bEdges.head);
|
|
836
659
|
};
|
|
837
660
|
}
|
|
@@ -854,43 +677,31 @@ export abstract class BasePaginator<T, Q> {
|
|
|
854
677
|
return itv && isLiveTailInterval(itv) ? itv : undefined;
|
|
855
678
|
}
|
|
856
679
|
|
|
857
|
-
/**
|
|
858
|
-
* The current contents of the live logical-head interval (items ingested out of pagination order).
|
|
859
|
-
* Reads the same value published to {@link BasePaginator.intervalViews}.`logicalHead`.
|
|
860
|
-
*/
|
|
680
|
+
/** `intervalViews.logicalHead`: out-of-order items above the loaded window. */
|
|
861
681
|
get logicalHeadItems(): T[] {
|
|
862
682
|
return this.intervalViews.getLatestValue().logicalHead;
|
|
863
683
|
}
|
|
864
684
|
|
|
865
|
-
/**
|
|
866
|
-
* The current contents of the live logical-tail interval (out-of-order items below the loaded
|
|
867
|
-
* window). Reads the same value published to {@link BasePaginator.intervalViews}.`logicalTail`.
|
|
868
|
-
*/
|
|
685
|
+
/** `intervalViews.logicalTail`: out-of-order items below the loaded window. */
|
|
869
686
|
get logicalTailItems(): T[] {
|
|
870
687
|
return this.intervalViews.getLatestValue().logicalTail;
|
|
871
688
|
}
|
|
872
689
|
|
|
873
|
-
/**
|
|
874
|
-
* The current contents of the anchored head interval (the loaded page bounded at the dataset head,
|
|
875
|
-
* `isHead`). Reads the same value published to {@link BasePaginator.intervalViews}.`anchoredHead`.
|
|
876
|
-
*/
|
|
690
|
+
/** `intervalViews.anchoredHead`: the page bounded at the dataset head. */
|
|
877
691
|
get anchoredHeadItems(): T[] {
|
|
878
692
|
return this.intervalViews.getLatestValue().anchoredHead;
|
|
879
693
|
}
|
|
880
694
|
|
|
881
695
|
/**
|
|
882
|
-
*
|
|
883
|
-
*
|
|
884
|
-
* (logical head / logical tail / anchored head). Use this instead of writing `_itemIntervals`
|
|
885
|
-
* directly — bulk re-sorting (which does not change any interval's membership) goes through
|
|
886
|
-
* {@link setIntervals}.
|
|
696
|
+
* Commits an interval to storage and republishes its {@link intervalViews} field when tracked.
|
|
697
|
+
* Use it instead of writing `_itemIntervals` (bulk re-sorting goes through {@link setIntervals}).
|
|
887
698
|
*/
|
|
888
699
|
protected commitInterval(interval: AnyInterval) {
|
|
889
700
|
this._itemIntervals.set(interval.id, interval);
|
|
890
701
|
this.publishIntervalViewFor(interval);
|
|
891
702
|
}
|
|
892
703
|
|
|
893
|
-
/**
|
|
704
|
+
/** Drops an interval from storage, republishing its {@link intervalViews} field if tracked. */
|
|
894
705
|
protected dropInterval(id: string) {
|
|
895
706
|
const removed = this._itemIntervals.get(id);
|
|
896
707
|
this._itemIntervals.delete(id);
|
|
@@ -898,11 +709,8 @@ export abstract class BasePaginator<T, Q> {
|
|
|
898
709
|
}
|
|
899
710
|
|
|
900
711
|
/**
|
|
901
|
-
*
|
|
902
|
-
*
|
|
903
|
-
* A write to an untracked interval touches nothing here. (The anchored head is also published
|
|
904
|
-
* directly via {@link publishAsAnchoredHead} from the reconciliation points that flip `isHead` —
|
|
905
|
-
* see {@link postQueryReconcile}.)
|
|
712
|
+
* Republishes the {@link intervalViews} field backed by the interval (untracked ones change
|
|
713
|
+
* nothing). {@link postQueryReconcile} also publishes the anchored head when `isHead` flips.
|
|
906
714
|
*/
|
|
907
715
|
private publishIntervalViewFor(interval: AnyInterval, { removed = false } = {}) {
|
|
908
716
|
if (interval.id === LOGICAL_HEAD_INTERVAL_ID) {
|
|
@@ -914,30 +722,19 @@ export abstract class BasePaginator<T, Q> {
|
|
|
914
722
|
logicalTail: this.intervalItemsOrEmpty(this.liveTailLogical),
|
|
915
723
|
});
|
|
916
724
|
} else if ((interval as Interval).isHead) {
|
|
917
|
-
// On removal the head page is gone (no other interval is `isHead`)
|
|
918
|
-
// committed page IS the head.
|
|
725
|
+
// On removal the head page is gone (no other interval is `isHead`): clear it.
|
|
919
726
|
this.publishAsAnchoredHead(removed ? undefined : interval);
|
|
920
727
|
}
|
|
921
728
|
}
|
|
922
729
|
|
|
923
|
-
/**
|
|
924
|
-
* Publish `interval` as the anchored head — the loaded page bounded at the dataset head (`isHead`),
|
|
925
|
-
* or `undefined` to clear it (the head page was removed or a page stopped being the head). Callers
|
|
926
|
-
* pass the interval they already have, so this does not re-scan storage for the head. Its content
|
|
927
|
-
* changes via ingest/remove (routed through {@link commitInterval}/{@link dropInterval}) and its
|
|
928
|
-
* identity changes when a page's `isHead` flag flips during query reconciliation — both call here.
|
|
929
|
-
*/
|
|
730
|
+
/** Publishes `interval` as the anchored head, or `undefined` to clear it. */
|
|
930
731
|
protected publishAsAnchoredHead(interval: AnyInterval | undefined) {
|
|
931
732
|
this.intervalViews.partialNext({ anchoredHead: this.intervalItemsOrEmpty(interval) });
|
|
932
733
|
}
|
|
933
734
|
|
|
934
735
|
/**
|
|
935
|
-
*
|
|
936
|
-
*
|
|
937
|
-
* - became the head page → publish it as the anchored head;
|
|
938
|
-
* - stopped being the head page → clear the anchored head;
|
|
939
|
-
* - unchanged → nothing (a content change, if any, was already published when the interval was
|
|
940
|
-
* committed — see {@link commitInterval}).
|
|
736
|
+
* Keeps `anchoredHead` in sync after `isHead` was recomputed in query reconciliation (`wasHead`
|
|
737
|
+
* is the previous value): publishes the page on becoming the head, clears it on losing that.
|
|
941
738
|
*/
|
|
942
739
|
protected syncAnchoredHeadAfterHeadFlip(interval: Interval, wasHead: boolean) {
|
|
943
740
|
if (interval.isHead === wasHead) return;
|
|
@@ -949,12 +746,7 @@ export abstract class BasePaginator<T, Q> {
|
|
|
949
746
|
}
|
|
950
747
|
|
|
951
748
|
/**
|
|
952
|
-
*
|
|
953
|
-
* {@link setIntervals}), which bypasses the per-interval {@link commitInterval}/{@link dropInterval}
|
|
954
|
-
* publishing. No-ops when the views are already empty so a reset does not emit needlessly.
|
|
955
|
-
*/
|
|
956
|
-
/**
|
|
957
|
-
* Drops every loaded interval and item without publishing anything, so the next ingest starts from
|
|
749
|
+
* Drops every loaded interval and item without publishing `state`, so the next ingest starts from
|
|
958
750
|
* empty storage while `state.items` keeps showing the previous window until the caller publishes.
|
|
959
751
|
*/
|
|
960
752
|
protected clearItemStorage() {
|
|
@@ -964,12 +756,12 @@ export abstract class BasePaginator<T, Q> {
|
|
|
964
756
|
this.clearIntervalViews();
|
|
965
757
|
}
|
|
966
758
|
|
|
759
|
+
/** Empties every {@link intervalViews} field, bypassing `commitInterval`/`dropInterval`. */
|
|
967
760
|
protected clearIntervalViews() {
|
|
968
761
|
this._pendingViewChangedIds.clear();
|
|
969
762
|
const { logicalHead, logicalTail, anchoredHead } =
|
|
970
763
|
this.intervalViews.getLatestValue();
|
|
971
|
-
//
|
|
972
|
-
// empty paginator does not emit a redundant empty→empty change (new `[]` refs would wake selectors).
|
|
764
|
+
// Skip when all views are already empty: fresh `[]` refs would wake selectors for nothing.
|
|
973
765
|
const alreadyEmpty =
|
|
974
766
|
logicalHead.length === 0 && logicalTail.length === 0 && anchoredHead.length === 0;
|
|
975
767
|
if (alreadyEmpty) return;
|
|
@@ -980,19 +772,13 @@ export abstract class BasePaginator<T, Q> {
|
|
|
980
772
|
});
|
|
981
773
|
}
|
|
982
774
|
|
|
983
|
-
// ---------------------------------------------------------------------------
|
|
984
|
-
// Abstracts
|
|
985
|
-
// ---------------------------------------------------------------------------
|
|
986
|
-
|
|
987
775
|
abstract query(
|
|
988
776
|
params: PaginationQueryParams<Q>,
|
|
989
777
|
): Promise<PaginationQueryReturnValue<T>>;
|
|
990
778
|
|
|
991
779
|
abstract filterQueryResults(items: T[]): T[];
|
|
992
780
|
|
|
993
|
-
/**
|
|
994
|
-
* Subclasses must return the query shape.
|
|
995
|
-
*/
|
|
781
|
+
/** Subclasses must override it and return the query shape. */
|
|
996
782
|
protected getNextQueryShape(
|
|
997
783
|
_params: Pick<PaginationQueryParams<Q>, 'direction'> & { pageSize?: number } = {},
|
|
998
784
|
): Q {
|
|
@@ -1000,13 +786,11 @@ export abstract class BasePaginator<T, Q> {
|
|
|
1000
786
|
}
|
|
1001
787
|
|
|
1002
788
|
/**
|
|
1003
|
-
* Filters
|
|
1004
|
-
*
|
|
1005
|
-
* `ChannelPaginator.buildQueryFilters`), because the two can differ: the backend may resolve a
|
|
1006
|
-
* server-side stored filter of its own, and some paginators filter locally without sending anything.
|
|
789
|
+
* Filters that `matchesFilter` applies locally, not the ones sent to the server; a subclass whose
|
|
790
|
+
* backend query is filtered builds those separately. `null`: no filters.
|
|
1007
791
|
*/
|
|
1008
792
|
protected buildMatchFilters(): object | null {
|
|
1009
|
-
return null;
|
|
793
|
+
return null;
|
|
1010
794
|
}
|
|
1011
795
|
|
|
1012
796
|
matchesFilter(item: T): boolean {
|
|
@@ -1025,9 +809,6 @@ export abstract class BasePaginator<T, Q> {
|
|
|
1025
809
|
this._filterFieldToDataResolvers.push(...resolvers);
|
|
1026
810
|
}
|
|
1027
811
|
|
|
1028
|
-
// ---------------------------------------------------------------------------
|
|
1029
|
-
// Item accessors
|
|
1030
|
-
// ---------------------------------------------------------------------------
|
|
1031
812
|
getItemId(item: T): string {
|
|
1032
813
|
return (item as { id: string }).id;
|
|
1033
814
|
}
|
|
@@ -1037,10 +818,8 @@ export abstract class BasePaginator<T, Q> {
|
|
|
1037
818
|
}
|
|
1038
819
|
|
|
1039
820
|
/**
|
|
1040
|
-
* Whether
|
|
1041
|
-
*
|
|
1042
|
-
* list must emit the caller-computed, order-preserved array, not a re-projection). When false, every
|
|
1043
|
-
* live mutation publishes immediately, exactly as before this feature.
|
|
821
|
+
* Whether live `state.items` publishes are throttled: `stateThrottleMs` is set, throttling is not
|
|
822
|
+
* disabled (tests) and item order is not locked (its emit is not a re-projection).
|
|
1044
823
|
*/
|
|
1045
824
|
protected get isStateThrottled(): boolean {
|
|
1046
825
|
return (
|
|
@@ -1050,12 +829,11 @@ export abstract class BasePaginator<T, Q> {
|
|
|
1050
829
|
);
|
|
1051
830
|
}
|
|
1052
831
|
|
|
1053
|
-
/** True while a coalescing {@link batch} scope is suspending this paginator's own window publishes. */
|
|
1054
832
|
protected get isWindowPublishSuspended(): boolean {
|
|
1055
833
|
return this._windowPublishSuspendDepth > 0;
|
|
1056
834
|
}
|
|
1057
835
|
|
|
1058
|
-
/** Re-
|
|
836
|
+
/** Re-projects the active window from its live interval; `undefined` when none is active. */
|
|
1059
837
|
private projectActiveWindow(): T[] | undefined {
|
|
1060
838
|
if (!this._activeIntervalId) return undefined;
|
|
1061
839
|
const active = this._itemIntervals.get(this._activeIntervalId);
|
|
@@ -1063,10 +841,8 @@ export abstract class BasePaginator<T, Q> {
|
|
|
1063
841
|
}
|
|
1064
842
|
|
|
1065
843
|
/**
|
|
1066
|
-
*
|
|
1067
|
-
*
|
|
1068
|
-
* this always reflects the latest settled state, so intermediate values within a window coalesce
|
|
1069
|
-
* away. Clears the visible window when the active interval is gone (e.g. the last item was removed).
|
|
844
|
+
* Publishes the active window to `state`, re-projected from the active interval at call time.
|
|
845
|
+
* Clears the visible window when the active interval is gone.
|
|
1070
846
|
*/
|
|
1071
847
|
private flushWindowPublish(): void {
|
|
1072
848
|
const items = this.projectActiveWindow();
|
|
@@ -1080,31 +856,19 @@ export abstract class BasePaginator<T, Q> {
|
|
|
1080
856
|
}
|
|
1081
857
|
|
|
1082
858
|
/**
|
|
1083
|
-
*
|
|
1084
|
-
*
|
|
1085
|
-
* {@link isStateThrottled}. Safe to call many times within one op — they coalesce to a single emit.
|
|
859
|
+
* Schedules a throttled (leading and trailing) active-window publish. Live mutations call it
|
|
860
|
+
* instead of publishing inline when {@link isStateThrottled}. Repeated calls coalesce.
|
|
1086
861
|
*/
|
|
1087
862
|
protected scheduleWindowPublish(): void {
|
|
1088
863
|
this._windowPublishThrottle?.throttledFn();
|
|
1089
864
|
}
|
|
1090
865
|
|
|
1091
866
|
/**
|
|
1092
|
-
*
|
|
1093
|
-
*
|
|
1094
|
-
*
|
|
1095
|
-
*
|
|
1096
|
-
*
|
|
1097
|
-
* `exit` decides how the single emit leaves the scope: `auto` rides the throttle when there is one
|
|
1098
|
-
* (live ops, where successive events should coalesce across the trailing edge), `sync` always
|
|
1099
|
-
* flushes ({@link batch}, whose contract is that a one-shot operation settles in a single update).
|
|
1100
|
-
*
|
|
1101
|
-
* **`lockItemOrder` lists are excluded.** Their emit is not a re-projection but a republish of the
|
|
1102
|
-
* last-published array with the item spliced back at its original index, and exiting through
|
|
1103
|
-
* {@link flushWindowPublish} re-derives from the active interval — reordering the list and dropping
|
|
1104
|
-
* whatever the interval no longer holds, which is the whole point of locking the order.
|
|
1105
|
-
*
|
|
1106
|
-
* Re-entrant: only the outermost scope emits, so an `ingestItem` inside a coalescing `batch`
|
|
1107
|
-
* defers to the batch.
|
|
867
|
+
* Runs `fn` with window publishes suspended and emits once on exit (a replace is
|
|
868
|
+
* remove-then-insert, which would emit twice). Only the outermost scope emits. `exit: 'auto'`
|
|
869
|
+
* rides the throttle when there is one, `'sync'` always flushes ({@link batch}). Skipped for
|
|
870
|
+
* `lockItemOrder` lists, whose emit republishes the last array and must not be re-derived from
|
|
871
|
+
* the interval.
|
|
1108
872
|
*/
|
|
1109
873
|
protected withSingleWindowPublish(
|
|
1110
874
|
fn: () => void,
|
|
@@ -1127,43 +891,31 @@ export abstract class BasePaginator<T, Q> {
|
|
|
1127
891
|
else this.flushWindowPublish();
|
|
1128
892
|
}
|
|
1129
893
|
|
|
1130
|
-
/**
|
|
1131
|
-
* Flush any pending throttled window + interval-view publishes immediately. No-op when nothing
|
|
1132
|
-
* is pending or throttling is off.
|
|
1133
|
-
*/
|
|
894
|
+
/** Immediately flushes the pending throttled window and interval-view publishes. */
|
|
1134
895
|
protected flushPendingPublishes(): void {
|
|
1135
896
|
this._windowPublishThrottle?.flush();
|
|
1136
897
|
this._viewPublishThrottle?.flush();
|
|
1137
898
|
}
|
|
1138
899
|
|
|
1139
|
-
// ---------------------------------------------------------------------------
|
|
1140
|
-
// Window cap (pruning)
|
|
1141
|
-
// ---------------------------------------------------------------------------
|
|
1142
|
-
|
|
1143
900
|
/**
|
|
1144
|
-
* Whether pruning is on hold.
|
|
1145
|
-
*
|
|
1146
|
-
* to not happen unless we are near to the tailing edge.
|
|
901
|
+
* Whether pruning is on hold, e.g. while the user reads near the tail edge, where a prune drops
|
|
902
|
+
* items. False: the configured cap always applies.
|
|
1147
903
|
*/
|
|
1148
904
|
protected get isPruningSuspended(): boolean {
|
|
1149
905
|
return false;
|
|
1150
906
|
}
|
|
1151
907
|
|
|
1152
908
|
/**
|
|
1153
|
-
* Whether the server knows
|
|
1154
|
-
*
|
|
1155
|
-
* subclasses holding locally-created items (an unsent message) narrow it. Both halves of a prune
|
|
1156
|
-
* ask: an item the server knows may be dropped, and only such an item may become the window's new
|
|
1157
|
-
* tailward cursor.
|
|
909
|
+
* Whether the server knows `item`, so its ID is safe as a cursor. Prunes drop and anchor on such
|
|
910
|
+
* items only. Subclasses holding locally-created items narrow it.
|
|
1158
911
|
*/
|
|
1159
912
|
protected isPaginationAnchorable(item: T | undefined): boolean {
|
|
1160
913
|
return !!item;
|
|
1161
914
|
}
|
|
1162
915
|
|
|
1163
916
|
/**
|
|
1164
|
-
* The
|
|
1165
|
-
*
|
|
1166
|
-
* it again — a loop. Read fresh (both inputs are runtime-configurable), never cached.
|
|
917
|
+
* The window cap, or `undefined` when unbounded. Clamped up to `pageSize`: a smaller cap would
|
|
918
|
+
* prune each tailward page as it lands and `onEndReached` would refetch it in a loop.
|
|
1167
919
|
*/
|
|
1168
920
|
protected get effectiveMaxLoadedItems(): number | undefined {
|
|
1169
921
|
const { maxLoadedItems, pageSize } = this.config;
|
|
@@ -1172,48 +924,22 @@ export abstract class BasePaginator<T, Q> {
|
|
|
1172
924
|
}
|
|
1173
925
|
|
|
1174
926
|
/**
|
|
1175
|
-
* Drops the oldest items from `interval` until at most `maxLoadedItems` remain, releasing
|
|
1176
|
-
* the item index
|
|
1177
|
-
*
|
|
1178
|
-
* ## Where this is called from, and why that matters
|
|
1179
|
-
*
|
|
1180
|
-
* From `ingestItem`, on the interval `insertItemIdIntoInterval` just returned — a **copy that has
|
|
1181
|
-
* not been committed yet**. So this mutates an object nothing can observe, the single
|
|
1182
|
-
* `commitInterval` that follows stores and republishes the already-pruned interval, and the window
|
|
1183
|
-
* emit after it projects from the same interval. A prune therefore costs **no publish of its own**:
|
|
1184
|
-
* it rides the ones the ingest was going to make anyway. That is the whole design — see
|
|
1185
|
-
* {@link _prunedIntervalId} for the pagination half.
|
|
1186
|
-
*
|
|
1187
|
-
* ## Preconditions
|
|
1188
|
-
*
|
|
1189
|
-
* All must hold, or this is a no-op:
|
|
1190
|
-
* - a cap is configured
|
|
1191
|
-
* - the consumer has not suspended pruning ({@link isPruningSuspended})
|
|
1192
|
-
* - the interval is anchored, is the dataset head, and is the active one. A jumped-away window is
|
|
1193
|
-
* what the user is reading, and a logical interval has no pagination provenance — nothing dropped
|
|
1194
|
-
* from it could ever be fetched back
|
|
1195
|
-
* - it actually holds more than the cap
|
|
927
|
+
* Drops the oldest items from `interval` until at most `maxLoadedItems` remain, releasing them
|
|
928
|
+
* from the item index. Returns whether anything was pruned.
|
|
1196
929
|
*
|
|
1197
|
-
*
|
|
1198
|
-
* {@link
|
|
1199
|
-
*
|
|
1200
|
-
*
|
|
1201
|
-
*
|
|
1202
|
-
*
|
|
1203
|
-
* at**: an unsent message sorts by the time it was composed, so a cap would otherwise destroy it.
|
|
1204
|
-
* Skipping leaves the window a few items above the cap at worst, and the next arrival trims it again.
|
|
1205
|
-
*
|
|
1206
|
-
* @returns whether anything was pruned.
|
|
930
|
+
* Runs from `ingestItem` on the uncommitted interval copy, so the following `commitInterval` and
|
|
931
|
+
* publish carry it (see {@link _prunedIntervalId}). No-op unless a cap is set, pruning is not
|
|
932
|
+
* suspended ({@link isPruningSuspended}) and the interval is the anchored, active head interval
|
|
933
|
+
* and over the cap. Assumes cursor pagination (`removeItem` is bypassed, so
|
|
934
|
+
* {@link shrinkOffsetAfterRemoval} never runs). Items the server does not know
|
|
935
|
+
* ({@link isPaginationAnchorable}) are skipped, so the window may sit a few items above the cap.
|
|
1207
936
|
*/
|
|
1208
937
|
protected pruneTailToLimit(interval: AnyInterval): boolean {
|
|
1209
938
|
const limit = this.effectiveMaxLoadedItems;
|
|
1210
939
|
if (typeof limit === 'undefined' || this.isPruningSuspended) return false;
|
|
1211
940
|
|
|
1212
|
-
// Anchored intervals only
|
|
1213
|
-
//
|
|
1214
|
-
// reads below depend on — `LogicalInterval` declares no `isHead`/`isTail`/`hasMore*`, so folding
|
|
1215
|
-
// it into the condition below would merely be redundant at runtime while still being required to
|
|
1216
|
-
// compile.
|
|
941
|
+
// Anchored intervals only: a logical interval has no pagination provenance, so pruned items
|
|
942
|
+
// could not be refetched. Also narrows the type for the field reads below.
|
|
1217
943
|
if (isLogicalInterval(interval)) return false;
|
|
1218
944
|
|
|
1219
945
|
if (
|
|
@@ -1224,7 +950,7 @@ export abstract class BasePaginator<T, Q> {
|
|
|
1224
950
|
return false;
|
|
1225
951
|
|
|
1226
952
|
const ids = interval.itemIds;
|
|
1227
|
-
// The tail (oldest) edge is index 0 unless the interval stores
|
|
953
|
+
// The tail (oldest) edge is index 0 unless the interval stores IDs head-first.
|
|
1228
954
|
const tailEdgeIsFirst = !this.intervalItemIdsAreHeadFirst;
|
|
1229
955
|
const step = tailEdgeIsFirst ? 1 : -1;
|
|
1230
956
|
const dropped = new Set<string>();
|
|
@@ -1244,33 +970,29 @@ export abstract class BasePaginator<T, Q> {
|
|
|
1244
970
|
|
|
1245
971
|
if (!dropped.size) return false;
|
|
1246
972
|
|
|
1247
|
-
// Rebuild rather than splice: skipped local items leave the dropped
|
|
973
|
+
// Rebuild rather than splice: skipped local items leave the dropped IDs non-contiguous.
|
|
1248
974
|
interval.itemIds = ids.filter((id) => !dropped.has(id));
|
|
1249
975
|
|
|
1250
|
-
// One
|
|
1251
|
-
//
|
|
1252
|
-
// holder lets go, so a pruned message still pinned or held by an open thread survives intact.
|
|
976
|
+
// One transaction so sibling holders re-project once. `remove` releases only this paginator's
|
|
977
|
+
// reference: content still held elsewhere survives.
|
|
1253
978
|
this._itemIndex.batch(() => {
|
|
1254
979
|
for (const id of dropped) this._itemIndex.remove(id);
|
|
1255
980
|
});
|
|
1256
981
|
|
|
1257
|
-
// Older
|
|
1258
|
-
//
|
|
982
|
+
// Older items exist on the server again: re-open the tail edge, even if the window had reached
|
|
983
|
+
// it (a stale `isTail` would also mislead interval merging).
|
|
1259
984
|
interval.isTail = false;
|
|
1260
985
|
interval.hasMoreTail = true;
|
|
1261
986
|
|
|
1262
|
-
// Only
|
|
1263
|
-
// from this interval as committed then — see {@link _prunedIntervalId}.
|
|
987
|
+
// Only the ID is recorded: the `state` fields are derived at publish time.
|
|
1264
988
|
this._prunedIntervalId = interval.id;
|
|
1265
989
|
|
|
1266
990
|
return true;
|
|
1267
991
|
}
|
|
1268
992
|
|
|
1269
993
|
/**
|
|
1270
|
-
* The
|
|
1271
|
-
*
|
|
1272
|
-
* id can be one the server has never seen, and paginating from it would send a client-generated id
|
|
1273
|
-
* as `id_lt`.
|
|
994
|
+
* The edge-most ID at `edge` that the server knows, so it is usable as a cursor. Not simply
|
|
995
|
+
* `itemIds[0]`: a prune skips locally-created items, so the outermost ID may be client-generated.
|
|
1274
996
|
*/
|
|
1275
997
|
private getPaginationEdgeId(interval: Interval, edge: 'head' | 'tail'): string | null {
|
|
1276
998
|
const ids = interval.itemIds;
|
|
@@ -1286,52 +1008,34 @@ export abstract class BasePaginator<T, Q> {
|
|
|
1286
1008
|
return null;
|
|
1287
1009
|
}
|
|
1288
1010
|
|
|
1289
|
-
/**
|
|
1290
|
-
* Filters `items` down to the members of `interval`, preserving their given order. Used by the
|
|
1291
|
-
* order-locked emit path, which composes its array from the previously published one instead of
|
|
1292
|
-
* re-projecting, and so needs pruned ids taken out explicitly.
|
|
1293
|
-
*/
|
|
1011
|
+
/** Keeps the `items` that are members of `interval`, in order. */
|
|
1294
1012
|
private retainIntervalMembers(items: T[], interval: AnyInterval): T[] {
|
|
1295
1013
|
const members = new Set(interval.itemIds);
|
|
1296
1014
|
return items.filter((item) => members.has(this.getItemId(item)));
|
|
1297
1015
|
}
|
|
1298
1016
|
|
|
1299
1017
|
/**
|
|
1300
|
-
*
|
|
1301
|
-
* at call time and
|
|
1302
|
-
*
|
|
1303
|
-
* than
|
|
1304
|
-
*
|
|
1305
|
-
* Returns only fields that actually changed, so an unchanged `cursor` keeps its object identity and
|
|
1306
|
-
* consumers selecting it are not woken.
|
|
1307
|
-
*
|
|
1308
|
-
* Three things it deliberately leaves alone:
|
|
1309
|
-
* - a window that is no longer the pruned one. `state` tracks the active interval, so once the
|
|
1310
|
-
* consumer has jumped elsewhere the prune says nothing about what is being published.
|
|
1311
|
-
* - `cursor.headward`, which the prune never touched — carried over verbatim rather than re-derived,
|
|
1312
|
-
* so a `config.deriveCursor` hook's verdict on the head edge survives.
|
|
1313
|
-
* - a null tail edge (a window whose every remaining item is locally-created). Publishing `null`
|
|
1314
|
-
* would read as "tailward exhausted"; the existing cursor still names a message the *server* has,
|
|
1315
|
-
* so leaving it in place keeps back-pagination working.
|
|
1018
|
+
* Returns the `state` pagination fields a prune moved, derived from the committed active interval
|
|
1019
|
+
* at call time, and clears the pending prune. Publishes of the active window spread it in. Only
|
|
1020
|
+
* changed fields are returned, so an unchanged `cursor` keeps its identity. Left alone: another
|
|
1021
|
+
* window than the pruned one, `cursor.headward` (a `deriveCursor` verdict survives), and a null
|
|
1022
|
+
* tail edge (every item is locally created: `null` would read as exhausted, so the cursor stays).
|
|
1316
1023
|
*/
|
|
1317
1024
|
private consumePendingPrunePaginationState(): Partial<PaginatorState<T>> {
|
|
1318
1025
|
const prunedIntervalId = this._prunedIntervalId;
|
|
1319
1026
|
if (!prunedIntervalId) return {};
|
|
1320
1027
|
this._prunedIntervalId = undefined;
|
|
1321
1028
|
|
|
1322
|
-
// Whatever is being published now is a window the prune never touched.
|
|
1323
1029
|
if (this._activeIntervalId !== prunedIntervalId) return {};
|
|
1324
1030
|
|
|
1325
1031
|
const active = this._itemIntervals.get(prunedIntervalId);
|
|
1326
|
-
// A logical interval is never pruned, and an absent one has no window left to paginate.
|
|
1327
1032
|
if (!active || isLogicalInterval(active)) return {};
|
|
1328
1033
|
|
|
1329
1034
|
const current = this.state.getLatestValue();
|
|
1330
1035
|
const next: Partial<PaginatorState<T>> = {};
|
|
1331
1036
|
|
|
1332
|
-
// Read
|
|
1333
|
-
//
|
|
1334
|
-
// between may have loaded the rest of the history - so there may be nothing older left after all.
|
|
1037
|
+
// Read from the interval, not the prune's `true`: this publish can be a throttle interval late
|
|
1038
|
+
// and a `toTail()` in between may have loaded the rest of the history.
|
|
1335
1039
|
if (current.hasMoreTail !== active.hasMoreTail) next.hasMoreTail = active.hasMoreTail;
|
|
1336
1040
|
|
|
1337
1041
|
if (this.isCursorPagination) {
|
|
@@ -1344,12 +1048,7 @@ export abstract class BasePaginator<T, Q> {
|
|
|
1344
1048
|
return next;
|
|
1345
1049
|
}
|
|
1346
1050
|
|
|
1347
|
-
/**
|
|
1348
|
-
* {@link _viewPublishThrottle} boundary: apply every interval-view change buffered since the last
|
|
1349
|
-
* flush, then clear the buffer. Independent of the `state.items` window publish, so a view update
|
|
1350
|
-
* lands within one throttle interval even when the active window stays quiet (e.g. a reaction on a
|
|
1351
|
-
* head message while a non-head window is active). No-op when nothing was buffered.
|
|
1352
|
-
*/
|
|
1051
|
+
/** {@link _viewPublishThrottle} boundary: applies the buffered interval-view changes. */
|
|
1353
1052
|
private flushIntervalViewPublish(): void {
|
|
1354
1053
|
if (!this._pendingViewChangedIds.size) return;
|
|
1355
1054
|
this.refreshIntervalViewsForChangedIds(this._pendingViewChangedIds);
|
|
@@ -1357,18 +1056,10 @@ export abstract class BasePaginator<T, Q> {
|
|
|
1357
1056
|
}
|
|
1358
1057
|
|
|
1359
1058
|
/**
|
|
1360
|
-
*
|
|
1361
|
-
*
|
|
1362
|
-
*
|
|
1363
|
-
*
|
|
1364
|
-
* would otherwise leave stale references in `anchoredHead`/`logicalHead`/`logicalTail` even though
|
|
1365
|
-
* the active window (`state.items`, see {@link reconcileChangedIds}) was refreshed.
|
|
1366
|
-
*
|
|
1367
|
-
* Called immediately for un-throttled paginators, or from {@link flushIntervalViewPublish} at the
|
|
1368
|
-
* view-publish throttle boundary when throttled — see {@link reconcileChangedIds}. Handled
|
|
1369
|
-
* independently of `state.items`. When the anchored head is also the active interval its content is
|
|
1370
|
-
* projected here as well as into `state.items`; deduping that double projection is a separate,
|
|
1371
|
-
* deferred perf follow-up.
|
|
1059
|
+
* Refreshes the tracked {@link intervalViews} fields holding one of `changedIds`. A sibling
|
|
1060
|
+
* holder writing through the shared item store swaps the item objects the views reference, and
|
|
1061
|
+
* only this paginator's own ingest/remove republishes them. Immediate unless throttled, then from
|
|
1062
|
+
* {@link flushIntervalViewPublish}.
|
|
1372
1063
|
*/
|
|
1373
1064
|
private refreshIntervalViewsForChangedIds(changedIds: ReadonlySet<string>): void {
|
|
1374
1065
|
const head = this.liveHeadLogical;
|
|
@@ -1400,17 +1091,13 @@ export abstract class BasePaginator<T, Q> {
|
|
|
1400
1091
|
}
|
|
1401
1092
|
|
|
1402
1093
|
/**
|
|
1403
|
-
*
|
|
1404
|
-
*
|
|
1405
|
-
*
|
|
1406
|
-
* publish throttles when throttling is on.
|
|
1094
|
+
* Reconciles the window and interval views after another holder swapped the shared item objects
|
|
1095
|
+
* they reference: refreshes views holding a changed ID and re-projects (or slot-swaps) the active
|
|
1096
|
+
* window, coalesced through the publish throttles when throttling is on.
|
|
1407
1097
|
*/
|
|
1408
1098
|
protected reconcileChangedIds(changedIds: ReadonlySet<string>): void {
|
|
1409
|
-
//
|
|
1410
|
-
//
|
|
1411
|
-
// hold a changed id the active window does not. When throttled, buffer the ids and tick the
|
|
1412
|
-
// view-publish throttle so refreshes coalesce (once per interval) yet still land on their own
|
|
1413
|
-
// trailing edge even if `state.items` never publishes again; otherwise publish immediately.
|
|
1099
|
+
// Views refresh independently of the active window (they can hold IDs it does not). Throttled:
|
|
1100
|
+
// buffer the IDs so refreshes coalesce.
|
|
1414
1101
|
if (this.isStateThrottled) {
|
|
1415
1102
|
for (const id of changedIds) this._pendingViewChangedIds.add(id);
|
|
1416
1103
|
this._viewPublishThrottle?.throttledFn();
|
|
@@ -1422,14 +1109,12 @@ export abstract class BasePaginator<T, Q> {
|
|
|
1422
1109
|
const activeInterval = this._itemIntervals.get(this._activeIntervalId);
|
|
1423
1110
|
if (!activeInterval) return;
|
|
1424
1111
|
|
|
1425
|
-
//
|
|
1426
|
-
//
|
|
1427
|
-
// same object this window is already showing.
|
|
1112
|
+
// Throttled: `this.items` lags the intervals, so no slot swap. Schedule a re-projection, but
|
|
1113
|
+
// only if something changed (a sibling may have written the object the window already shows).
|
|
1428
1114
|
if (this.isStateThrottled) {
|
|
1429
1115
|
const currentItems = this.items;
|
|
1430
1116
|
if (!currentItems || currentItems.length !== activeInterval.itemIds.length) {
|
|
1431
|
-
//
|
|
1432
|
-
// positions when the two have the same length and gate on membership alone.
|
|
1117
|
+
// Positions only line up when the lengths match: gate on membership alone.
|
|
1433
1118
|
if (this.intervalHoldsAnyChangedId(activeInterval, changedIds)) {
|
|
1434
1119
|
this.scheduleWindowPublish();
|
|
1435
1120
|
}
|
|
@@ -1447,13 +1132,9 @@ export abstract class BasePaginator<T, Q> {
|
|
|
1447
1132
|
return;
|
|
1448
1133
|
}
|
|
1449
1134
|
|
|
1450
|
-
// Fast path:
|
|
1451
|
-
//
|
|
1452
|
-
//
|
|
1453
|
-
// preserves every unchanged item reference (so memoized rows bail) and avoids re-mapping and
|
|
1454
|
-
// re-sorting the whole active window on every event. Skipped when a boost is active (a boost
|
|
1455
|
-
// can reorder the visible window, which a slot-swap would not reflect) — then we fall through
|
|
1456
|
-
// to the full projection below, which applies the boost order.
|
|
1135
|
+
// Fast path: an in-place update keeps membership and order, so when the window lines up with
|
|
1136
|
+
// the interval, swap only the changed slots (unchanged item references survive). Skipped when a
|
|
1137
|
+
// boost is active: it can reorder the window, which the full projection below applies.
|
|
1457
1138
|
const currentItems = this.items;
|
|
1458
1139
|
this.clearExpiredBoosts();
|
|
1459
1140
|
if (
|
|
@@ -1468,7 +1149,7 @@ export abstract class BasePaginator<T, Q> {
|
|
|
1468
1149
|
if (!changedIds.has(id)) continue;
|
|
1469
1150
|
const updated = this._itemIndex.get(id);
|
|
1470
1151
|
if (!updated) {
|
|
1471
|
-
// The
|
|
1152
|
+
// The ID left the store (a removal): resync via a full projection.
|
|
1472
1153
|
needsFullProjection = true;
|
|
1473
1154
|
break;
|
|
1474
1155
|
}
|
|
@@ -1482,17 +1163,13 @@ export abstract class BasePaginator<T, Q> {
|
|
|
1482
1163
|
}
|
|
1483
1164
|
}
|
|
1484
1165
|
|
|
1485
|
-
// Fallback
|
|
1486
|
-
//
|
|
1166
|
+
// Fallback (membership or order drifted, no window to patch, or a boost is active): re-project
|
|
1167
|
+
// only if a changed ID is in the active interval.
|
|
1487
1168
|
if (this.intervalHoldsAnyChangedId(activeInterval, changedIds)) {
|
|
1488
1169
|
this.state.partialNext({ items: this.intervalToItems(activeInterval) });
|
|
1489
1170
|
}
|
|
1490
1171
|
}
|
|
1491
1172
|
|
|
1492
|
-
// ---------------------------------------------------------------------------
|
|
1493
|
-
// Boosts
|
|
1494
|
-
// ---------------------------------------------------------------------------
|
|
1495
|
-
|
|
1496
1173
|
protected clearExpiredBoosts(now = Date.now()) {
|
|
1497
1174
|
for (const [id, b] of this.boosts) if (now > b.until) this.boosts.delete(id);
|
|
1498
1175
|
this._maxBoostSeq = Math.max(
|
|
@@ -1501,12 +1178,7 @@ export abstract class BasePaginator<T, Q> {
|
|
|
1501
1178
|
);
|
|
1502
1179
|
}
|
|
1503
1180
|
|
|
1504
|
-
/**
|
|
1505
|
-
* Applied by the effectiveComparator to take into consideration item boosts when sorting items.
|
|
1506
|
-
*
|
|
1507
|
-
* @param a - The first item to compare.
|
|
1508
|
-
* @param b - The second item to compare.
|
|
1509
|
-
*/
|
|
1181
|
+
/** Boosted items first (higher `seq` first), then `itemOrderComparator`. */
|
|
1510
1182
|
protected boostComparator = (a: T, b: T): number => {
|
|
1511
1183
|
const now = Date.now();
|
|
1512
1184
|
this.clearExpiredBoosts(now);
|
|
@@ -1530,11 +1202,12 @@ export abstract class BasePaginator<T, Q> {
|
|
|
1530
1202
|
};
|
|
1531
1203
|
|
|
1532
1204
|
/**
|
|
1533
|
-
*
|
|
1534
|
-
*
|
|
1205
|
+
* Raises the item's priority in `effectiveComparator`. Affects position inside an interval, not
|
|
1206
|
+
* interval boundaries.
|
|
1535
1207
|
*
|
|
1536
|
-
* @param itemId -
|
|
1537
|
-
* @param opts - Boost options: `
|
|
1208
|
+
* @param itemId - ID of the item to boost.
|
|
1209
|
+
* @param opts - Boost options: `until` (or `ttlMs` from now) sets the expiry and `seq` orders
|
|
1210
|
+
* concurrent boosts. Expiry defaults to 15s from now; `seq` defaults to 0.
|
|
1538
1211
|
*/
|
|
1539
1212
|
boost(itemId: string, opts?: { ttlMs?: number; until?: number; seq?: number }) {
|
|
1540
1213
|
const now = Date.now();
|
|
@@ -1565,10 +1238,6 @@ export abstract class BasePaginator<T, Q> {
|
|
|
1565
1238
|
return !!(boost && Date.now() <= boost.until);
|
|
1566
1239
|
}
|
|
1567
1240
|
|
|
1568
|
-
// ---------------------------------------------------------------------------
|
|
1569
|
-
// Interval manipulation
|
|
1570
|
-
// ---------------------------------------------------------------------------
|
|
1571
|
-
|
|
1572
1241
|
generateIntervalId(_page: (T | string)[]): string {
|
|
1573
1242
|
return `interval-${generateUUIDv4()}`;
|
|
1574
1243
|
}
|
|
@@ -1578,20 +1247,18 @@ export abstract class BasePaginator<T, Q> {
|
|
|
1578
1247
|
.map((id) => this._itemIndex?.get(id))
|
|
1579
1248
|
.filter((item): item is T => !!item);
|
|
1580
1249
|
|
|
1581
|
-
//
|
|
1250
|
+
// A locked order ignores boosts.
|
|
1582
1251
|
if (this.config.lockItemOrder) {
|
|
1583
1252
|
return items;
|
|
1584
1253
|
}
|
|
1585
1254
|
|
|
1586
|
-
// itemIds are
|
|
1587
|
-
//
|
|
1588
|
-
// active (the common case), so a page ingest / full projection is a map, not a map + sort.
|
|
1255
|
+
// `itemIds` are already in item order: only an active boost can reorder, so skip the re-sort
|
|
1256
|
+
// otherwise.
|
|
1589
1257
|
this.clearExpiredBoosts();
|
|
1590
1258
|
if (this.boosts.size === 0) {
|
|
1591
1259
|
return items;
|
|
1592
1260
|
}
|
|
1593
1261
|
|
|
1594
|
-
// Visible ordering uses boost-aware comparator
|
|
1595
1262
|
return items.sort(this.effectiveComparator.bind(this));
|
|
1596
1263
|
}
|
|
1597
1264
|
|
|
@@ -1599,9 +1266,8 @@ export abstract class BasePaginator<T, Q> {
|
|
|
1599
1266
|
const sorted = [...page].sort((a, b) => this.itemOrderComparator(a, b));
|
|
1600
1267
|
return {
|
|
1601
1268
|
id: this.generateIntervalId(page),
|
|
1602
|
-
//
|
|
1603
|
-
//
|
|
1604
|
-
// - otherwise treat it as unknown => "has more" (until proven otherwise by a query)
|
|
1269
|
+
// A known global head/tail has no more data that way, otherwise assume more until a query
|
|
1270
|
+
// proves not.
|
|
1605
1271
|
hasMoreHead: isHead ? false : true,
|
|
1606
1272
|
hasMoreTail: isTail ? false : true,
|
|
1607
1273
|
itemIds: sorted.map(this.getItemId.bind(this)),
|
|
@@ -1611,10 +1277,8 @@ export abstract class BasePaginator<T, Q> {
|
|
|
1611
1277
|
}
|
|
1612
1278
|
|
|
1613
1279
|
protected getCursorFromInterval(interval: Interval): PaginatorCursor {
|
|
1614
|
-
//
|
|
1615
|
-
//
|
|
1616
|
-
// - "head" is a semantic concept (where new items appear), not necessarily `itemIds[0]`
|
|
1617
|
-
// - itemIds are stored in sortComparator order, but we want the *pagination* edges
|
|
1280
|
+
// Resolve edges via sort bounds: "head" is where new items appear, not necessarily
|
|
1281
|
+
// `itemIds[0]`.
|
|
1618
1282
|
const edges = this.getIntervalPaginationEdges(interval);
|
|
1619
1283
|
|
|
1620
1284
|
const fallbackFirstId = interval.itemIds[0] ?? null;
|
|
@@ -1641,11 +1305,9 @@ export abstract class BasePaginator<T, Q> {
|
|
|
1641
1305
|
}
|
|
1642
1306
|
|
|
1643
1307
|
/**
|
|
1644
|
-
* Whether the
|
|
1645
|
-
* safe
|
|
1646
|
-
*
|
|
1647
|
-
* caller has jumped to an older window (active interval is NOT the head), a first-page re-seed
|
|
1648
|
-
* would force-merge the newest page into that window across the gap - so the re-seed is skipped.
|
|
1308
|
+
* Whether the active interval is the anchored head. Re-seeding a loaded paginator with a fresh
|
|
1309
|
+
* newest page is only safe then (the page overlaps it). After a jump to an older window it would
|
|
1310
|
+
* force-merge the newest page across the gap, so the re-seed is skipped.
|
|
1649
1311
|
*/
|
|
1650
1312
|
get isActiveIntervalAtHead(): boolean {
|
|
1651
1313
|
const head = this.getHeadIntervalFromSortedIntervals(this.itemIntervals);
|
|
@@ -1660,12 +1322,9 @@ export abstract class BasePaginator<T, Q> {
|
|
|
1660
1322
|
setActiveInterval(interval: AnyInterval | undefined, opts?: { updateState?: boolean }) {
|
|
1661
1323
|
this._activeIntervalId = interval?.id;
|
|
1662
1324
|
|
|
1663
|
-
//
|
|
1664
|
-
//
|
|
1665
|
-
//
|
|
1666
|
-
// Internal callers that are in the middle of a transactional `state.next()`
|
|
1667
|
-
// update must pass `{ updateState: false }` and project these flags into the
|
|
1668
|
-
// state object directly.
|
|
1325
|
+
// Activating an anchored interval immediately reflects its pagination flags in `state`. Callers
|
|
1326
|
+
// inside a transactional `state.next()` pass `{ updateState: false }` and project the flags
|
|
1327
|
+
// themselves.
|
|
1669
1328
|
if (opts?.updateState === false) return;
|
|
1670
1329
|
if (!interval || isLogicalInterval(interval)) return;
|
|
1671
1330
|
|
|
@@ -1687,14 +1346,9 @@ export abstract class BasePaginator<T, Q> {
|
|
|
1687
1346
|
}
|
|
1688
1347
|
|
|
1689
1348
|
/**
|
|
1690
|
-
*
|
|
1691
|
-
*
|
|
1692
|
-
*
|
|
1693
|
-
* - Edges are derived from the *sort bounds* of the interval (min/max under `sortComparator`).
|
|
1694
|
-
* - Which bound is treated as the pagination "head" is controlled by `intervalItemIdsAreHeadFirst`.
|
|
1695
|
-
* - This is a semantic notion of head/tail (where new items are expected to appear),
|
|
1696
|
-
* not necessarily "min/max under sortComparator".
|
|
1697
|
-
* New items are always expected to appear at the head of the interval.
|
|
1349
|
+
* Pagination head/tail edges of an interval, taken from its sort bounds.
|
|
1350
|
+
* `intervalItemIdsAreHeadFirst` decides which bound is the head: where new items appear, not
|
|
1351
|
+
* necessarily the min under `itemOrderComparator`.
|
|
1698
1352
|
*/
|
|
1699
1353
|
protected getIntervalPaginationEdges(
|
|
1700
1354
|
interval: Interval | LogicalInterval,
|
|
@@ -1772,17 +1426,9 @@ export abstract class BasePaginator<T, Q> {
|
|
|
1772
1426
|
}
|
|
1773
1427
|
|
|
1774
1428
|
/**
|
|
1775
|
-
*
|
|
1776
|
-
*
|
|
1777
|
-
*
|
|
1778
|
-
* A.min ≤ B.max AND B.min ≤ A.max
|
|
1779
|
-
*
|
|
1780
|
-
* 2) Forced merge (policy: 'auto' only):
|
|
1781
|
-
* If one interval is marked as `isHead`/`isTail`, treat the other as mergeable
|
|
1782
|
-
* when it extends beyond that interval's pagination head/tail edge
|
|
1783
|
-
* (computed via `getIntervalPaginationEdges` + headward/tailward helpers).
|
|
1784
|
-
*
|
|
1785
|
-
* In 'strict-overlap-only' policy, only (1) applies.
|
|
1429
|
+
* Whether intervals A and B should be merged: they strictly overlap in `itemOrderComparator` order
|
|
1430
|
+
* (`A.min <= B.max && B.min <= A.max`) or, under policy 'auto' only, one is marked
|
|
1431
|
+
* `isHead`/`isTail` and the other extends beyond its pagination head/tail edge.
|
|
1786
1432
|
*/
|
|
1787
1433
|
protected intervalsOverlap(
|
|
1788
1434
|
a: AnyInterval,
|
|
@@ -1793,15 +1439,12 @@ export abstract class BasePaginator<T, Q> {
|
|
|
1793
1439
|
const bBounds = this.getIntervalSortBounds(b);
|
|
1794
1440
|
if (!aBounds || !bBounds) return false;
|
|
1795
1441
|
|
|
1796
|
-
// Strict overlap if:
|
|
1797
|
-
// a.first <= b.last && b.first <= a.last
|
|
1798
1442
|
if (
|
|
1799
1443
|
this.itemOrderComparator(aBounds.start, bBounds.end) <= 0 &&
|
|
1800
1444
|
this.itemOrderComparator(bBounds.start, aBounds.end) <= 0
|
|
1801
1445
|
)
|
|
1802
1446
|
return true;
|
|
1803
1447
|
|
|
1804
|
-
// If policy is strict-overlap-only, return false if the intervals do not strictly overlap.
|
|
1805
1448
|
if (policy === 'strict-overlap-only') return false;
|
|
1806
1449
|
|
|
1807
1450
|
const aIsHead = (a as Interval).isHead;
|
|
@@ -1821,9 +1464,6 @@ export abstract class BasePaginator<T, Q> {
|
|
|
1821
1464
|
return false;
|
|
1822
1465
|
}
|
|
1823
1466
|
|
|
1824
|
-
/**
|
|
1825
|
-
* Whether an item belongs to an anchored interval.
|
|
1826
|
-
*/
|
|
1827
1467
|
protected belongsToInterval(item: T, interval: AnyInterval): boolean {
|
|
1828
1468
|
const sortBounds = this.getIntervalSortBounds(interval);
|
|
1829
1469
|
if (!sortBounds) return false;
|
|
@@ -1837,7 +1477,7 @@ export abstract class BasePaginator<T, Q> {
|
|
|
1837
1477
|
const edges = this.getIntervalPaginationEdges(interval);
|
|
1838
1478
|
if (!edges) return false;
|
|
1839
1479
|
|
|
1840
|
-
// Items beyond head/tail
|
|
1480
|
+
// Items beyond the edge of a head/tail page belong to it.
|
|
1841
1481
|
if ((interval as Interval).isHead && this.aIsMoreHeadwardThanB(item, edges.head))
|
|
1842
1482
|
return true;
|
|
1843
1483
|
|
|
@@ -1867,7 +1507,7 @@ export abstract class BasePaginator<T, Q> {
|
|
|
1867
1507
|
getItemAt: (index: number) => merged[index],
|
|
1868
1508
|
itemIdentityEquals: (item1, item2) =>
|
|
1869
1509
|
this.getItemId(item1) === this.getItemId(item2),
|
|
1870
|
-
//
|
|
1510
|
+
// Inter-interval operations use the base comparator.
|
|
1871
1511
|
compare: this.itemOrderComparator.bind(this),
|
|
1872
1512
|
});
|
|
1873
1513
|
if (insertionIndex > -1) {
|
|
@@ -1890,8 +1530,7 @@ export abstract class BasePaginator<T, Q> {
|
|
|
1890
1530
|
const isHead = preceding.isHead || following.isHead;
|
|
1891
1531
|
const isTail = preceding.isTail || following.isTail;
|
|
1892
1532
|
|
|
1893
|
-
//
|
|
1894
|
-
// - if any contributor already concluded "no more" in a direction, keep that
|
|
1533
|
+
// Conservative default: "no more" in either interval stays "no more".
|
|
1895
1534
|
let hasMoreHead = preceding.hasMoreHead && following.hasMoreHead;
|
|
1896
1535
|
let hasMoreTail = preceding.hasMoreTail && following.hasMoreTail;
|
|
1897
1536
|
|
|
@@ -1910,7 +1549,7 @@ export abstract class BasePaginator<T, Q> {
|
|
|
1910
1549
|
return {
|
|
1911
1550
|
...preceding,
|
|
1912
1551
|
itemIds: mergedItemIds,
|
|
1913
|
-
// Boundary intervals stay boundaries even
|
|
1552
|
+
// Boundary intervals stay boundaries even when forced merges shift their edge.
|
|
1914
1553
|
hasMoreHead: isHead ? false : hasMoreHead,
|
|
1915
1554
|
hasMoreTail: isTail ? false : hasMoreTail,
|
|
1916
1555
|
isHead,
|
|
@@ -1918,9 +1557,7 @@ export abstract class BasePaginator<T, Q> {
|
|
|
1918
1557
|
};
|
|
1919
1558
|
}
|
|
1920
1559
|
|
|
1921
|
-
/**
|
|
1922
|
-
* Merges anchored intervals. Returns null if there are no intervals to merge.
|
|
1923
|
-
*/
|
|
1560
|
+
/** Merges anchored intervals; `null` when there are none. */
|
|
1924
1561
|
protected mergeAnchoredIntervals(
|
|
1925
1562
|
intervals: Interval[],
|
|
1926
1563
|
baseInterval?: Interval,
|
|
@@ -1938,10 +1575,6 @@ export abstract class BasePaginator<T, Q> {
|
|
|
1938
1575
|
return acc;
|
|
1939
1576
|
}
|
|
1940
1577
|
|
|
1941
|
-
// ---------------------------------------------------------------------------
|
|
1942
|
-
// Locate items and intervals
|
|
1943
|
-
// ---------------------------------------------------------------------------
|
|
1944
|
-
|
|
1945
1578
|
protected locateIntervalIndex(interval: Interval): number {
|
|
1946
1579
|
const intervals = this.itemIntervals.filter(
|
|
1947
1580
|
(i) => !isLogicalInterval(i),
|
|
@@ -1961,16 +1594,15 @@ export abstract class BasePaginator<T, Q> {
|
|
|
1961
1594
|
plateauScan: true,
|
|
1962
1595
|
}).currentIndex;
|
|
1963
1596
|
}
|
|
1964
|
-
/**
|
|
1965
|
-
* Locate item inside a specific interval using the same logic as locateByItem,
|
|
1966
|
-
* but scoped to interval items.
|
|
1967
|
-
*/
|
|
1968
1597
|
protected locateByItemInInterval({
|
|
1969
1598
|
item,
|
|
1970
1599
|
interval,
|
|
1600
|
+
plateauScan = true,
|
|
1971
1601
|
}: {
|
|
1972
1602
|
item: T;
|
|
1973
1603
|
interval: Interval | LogicalInterval;
|
|
1604
|
+
/** Walk the interval for an item the binary search missed. Off when it cannot be there. */
|
|
1605
|
+
plateauScan?: boolean;
|
|
1974
1606
|
}): ItemLocation | null {
|
|
1975
1607
|
const ids = interval.itemIds;
|
|
1976
1608
|
|
|
@@ -1980,9 +1612,9 @@ export abstract class BasePaginator<T, Q> {
|
|
|
1980
1612
|
getItemAt: (index: number) => this.getItem(ids[index]),
|
|
1981
1613
|
itemIdentityEquals: (item1, item2) =>
|
|
1982
1614
|
this.getItemId(item1) === this.getItemId(item2),
|
|
1983
|
-
// items
|
|
1615
|
+
// Interval items are not sorted by `effectiveComparator`.
|
|
1984
1616
|
compare: this.itemOrderComparator.bind(this),
|
|
1985
|
-
plateauScan
|
|
1617
|
+
plateauScan,
|
|
1986
1618
|
});
|
|
1987
1619
|
}
|
|
1988
1620
|
|
|
@@ -1996,9 +1628,7 @@ export abstract class BasePaginator<T, Q> {
|
|
|
1996
1628
|
}
|
|
1997
1629
|
}
|
|
1998
1630
|
|
|
1999
|
-
/**
|
|
2000
|
-
* The interval whose `itemIds` lists this id, regardless of where the item now sorts.
|
|
2001
|
-
*/
|
|
1631
|
+
/** The interval whose `itemIds` lists this ID, regardless of where the item sorts. */
|
|
2002
1632
|
protected findIntervalHoldingItem(item: T): AnyInterval | undefined {
|
|
2003
1633
|
const id = this.getItemId(item);
|
|
2004
1634
|
for (const interval of this.itemIntervals) {
|
|
@@ -2008,30 +1638,24 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2008
1638
|
}
|
|
2009
1639
|
|
|
2010
1640
|
protected locateByItemInIntervals(item: T): ItemCoordinates['interval'] | undefined {
|
|
2011
|
-
|
|
2012
|
-
|
|
2013
|
-
|
|
2014
|
-
|
|
2015
|
-
|
|
2016
|
-
|
|
2017
|
-
//
|
|
2018
|
-
|
|
2019
|
-
|
|
2020
|
-
//
|
|
2021
|
-
const
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
const
|
|
2025
|
-
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
/**
|
|
2030
|
-
* Locates the current position of the item and the index at which the item should be inserted
|
|
2031
|
-
* according to effectiveComparator.
|
|
2032
|
-
*
|
|
2033
|
-
* @param item - The item to locate within the current state.
|
|
2034
|
-
*/
|
|
1641
|
+
const locateIn = (interval: AnyInterval | undefined, plateauScan?: boolean) => {
|
|
1642
|
+
const location =
|
|
1643
|
+
interval && this.locateByItemInInterval({ item, interval, plateauScan });
|
|
1644
|
+
return interval && location ? { interval, ...location } : undefined;
|
|
1645
|
+
};
|
|
1646
|
+
const boundsInterval = this.locateIntervalForItem(item);
|
|
1647
|
+
// Not held by this list, so in no interval: locate where it would go.
|
|
1648
|
+
if (!this._itemIndex.has(this.getItemId(item)))
|
|
1649
|
+
return locateIn(boundsInterval, false);
|
|
1650
|
+
// Held and unmoved: its sort value points at the interval, no scan needed.
|
|
1651
|
+
const inBounds = locateIn(boundsInterval);
|
|
1652
|
+
if (inBounds && inBounds.currentIndex > -1) return inBounds;
|
|
1653
|
+
// Held but moved: scan all intervals for it.
|
|
1654
|
+
const holdingInterval = this.findIntervalHoldingItem(item);
|
|
1655
|
+
return holdingInterval ? locateIn(holdingInterval) : inBounds;
|
|
1656
|
+
}
|
|
1657
|
+
|
|
1658
|
+
/** Position of the item in `state.items` and its insertion index under `effectiveComparator`. */
|
|
2035
1659
|
protected locateItemInState(item: T): ItemLocation | null {
|
|
2036
1660
|
const items = [...(this.items ?? [])];
|
|
2037
1661
|
|
|
@@ -2049,13 +1673,11 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2049
1673
|
locateByItem = (item: T): ItemCoordinates => {
|
|
2050
1674
|
const result: ItemCoordinates = {};
|
|
2051
1675
|
|
|
2052
|
-
// 1. Search in visible state.items
|
|
2053
1676
|
const stateLoc = this.locateItemInState(item);
|
|
2054
1677
|
if (stateLoc) {
|
|
2055
1678
|
result.state = stateLoc;
|
|
2056
1679
|
}
|
|
2057
1680
|
|
|
2058
|
-
// 2. Search in intervals if interval-mode is active
|
|
2059
1681
|
const intervalLoc = this.locateByItemInIntervals(item);
|
|
2060
1682
|
if (intervalLoc) {
|
|
2061
1683
|
result.interval = intervalLoc;
|
|
@@ -2064,16 +1686,11 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2064
1686
|
return result;
|
|
2065
1687
|
};
|
|
2066
1688
|
|
|
2067
|
-
// ---------------------------------------------------------------------------
|
|
2068
|
-
// Item ingestion
|
|
2069
|
-
// ---------------------------------------------------------------------------
|
|
2070
|
-
|
|
2071
1689
|
protected removeItemIdFromInterval({
|
|
2072
1690
|
interval,
|
|
2073
1691
|
...itemLocation
|
|
2074
1692
|
}: ItemIntervalCoordinates): ItemIntervalCoordinates {
|
|
2075
1693
|
if (
|
|
2076
|
-
// If already at the correct position, nothing to change
|
|
2077
1694
|
itemLocation.currentIndex >= 0 &&
|
|
2078
1695
|
itemLocation.currentIndex === itemLocation.insertionIndex
|
|
2079
1696
|
)
|
|
@@ -2081,8 +1698,8 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2081
1698
|
|
|
2082
1699
|
const itemIds = [...interval.itemIds];
|
|
2083
1700
|
|
|
2084
|
-
//
|
|
2085
|
-
//
|
|
1701
|
+
// `insertionIndex` was computed with the item still in the array: shift it when removing before
|
|
1702
|
+
// it.
|
|
2086
1703
|
let insertionIndex = itemLocation.insertionIndex;
|
|
2087
1704
|
if (
|
|
2088
1705
|
itemLocation.currentIndex >= 0 &&
|
|
@@ -2091,7 +1708,6 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2091
1708
|
insertionIndex--;
|
|
2092
1709
|
}
|
|
2093
1710
|
|
|
2094
|
-
// Remove existing occurrence if present
|
|
2095
1711
|
if (itemLocation.currentIndex >= 0) {
|
|
2096
1712
|
itemIds.splice(itemLocation.currentIndex, 1);
|
|
2097
1713
|
}
|
|
@@ -2102,10 +1718,7 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2102
1718
|
};
|
|
2103
1719
|
}
|
|
2104
1720
|
|
|
2105
|
-
/**
|
|
2106
|
-
* Inserts an item ID into the interval in the correct sorted position.
|
|
2107
|
-
* Returns unchanged interval if the correct insertion position could not be determined.
|
|
2108
|
-
*/
|
|
1721
|
+
/** Inserts the item ID at its sorted position; no-op when none can be determined. */
|
|
2109
1722
|
protected insertItemIdIntoInterval<I extends Interval | LogicalInterval>(
|
|
2110
1723
|
interval: I,
|
|
2111
1724
|
item: T,
|
|
@@ -2122,7 +1735,6 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2122
1735
|
|
|
2123
1736
|
const id = this.getItemId(item);
|
|
2124
1737
|
|
|
2125
|
-
// Insert at the new position
|
|
2126
1738
|
if (typeof insertionIndex !== 'undefined' && insertionIndex > -1) {
|
|
2127
1739
|
itemIds.splice(insertionIndex, 0, id);
|
|
2128
1740
|
}
|
|
@@ -2134,12 +1746,11 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2134
1746
|
}
|
|
2135
1747
|
|
|
2136
1748
|
/**
|
|
2137
|
-
* Re-evaluates what the logical (live head
|
|
2138
|
-
*
|
|
2139
|
-
* exists
|
|
2140
|
-
*
|
|
2141
|
-
*
|
|
2142
|
-
* `isHead`/overlap heuristics fire; this pass is unconditional and idempotent.
|
|
1749
|
+
* Re-evaluates what the logical (live head/tail) intervals hold against a freshly ingested page
|
|
1750
|
+
* and returns the resulting anchored interval. Live updates park items there before any page
|
|
1751
|
+
* exists; once a page covers one, leaving it gives the same ID two homes (a duplicated row).
|
|
1752
|
+
* Unlike the `ingestPage` merge, whose heuristics fire only sometimes, this pass is unconditional
|
|
1753
|
+
* and idempotent.
|
|
2143
1754
|
*/
|
|
2144
1755
|
protected reconcileLogicalIntervalsAgainst(anchored: Interval): Interval {
|
|
2145
1756
|
let merged = anchored;
|
|
@@ -2167,14 +1778,10 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2167
1778
|
}
|
|
2168
1779
|
|
|
2169
1780
|
/**
|
|
2170
|
-
* Moves items the loaded window proves are parked on the wrong side: an item
|
|
2171
|
-
*
|
|
2172
|
-
*
|
|
2173
|
-
*
|
|
2174
|
-
*
|
|
2175
|
-
* Compared against the outermost anchored interval, not the page just ingested: an item that
|
|
2176
|
-
* lands between two loaded pages is not "beyond" either side, it is a gap item, and those stay
|
|
2177
|
-
* where they are (`ingestPage` turns them into their own island once the merge reaches the edge).
|
|
1781
|
+
* Moves items the loaded window proves are parked on the wrong side: an item in the live head
|
|
1782
|
+
* that sorts past the tail edge of everything loaded belongs to the live tail, and vice versa.
|
|
1783
|
+
* Compared against the outermost anchored interval, not the page just ingested: an item between
|
|
1784
|
+
* two loaded pages is a gap item and stays.
|
|
2178
1785
|
*/
|
|
2179
1786
|
protected moveMisfiledItemsToOppositeSide(
|
|
2180
1787
|
logical: LogicalInterval,
|
|
@@ -2222,11 +1829,7 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2222
1829
|
else this.dropInterval(logical.id);
|
|
2223
1830
|
}
|
|
2224
1831
|
|
|
2225
|
-
/**
|
|
2226
|
-
* Splits a logical interval by checking each item individually.
|
|
2227
|
-
* Items overlapping anchoredInterval are merged into it.
|
|
2228
|
-
* Others stay in a retained logical interval.
|
|
2229
|
-
*/
|
|
1832
|
+
/** Merges the logical interval's items that belong to `anchored` into it; the rest stay. */
|
|
2230
1833
|
protected mergeItemsFromLogicalInterval(
|
|
2231
1834
|
logical: LogicalInterval,
|
|
2232
1835
|
anchored: Interval,
|
|
@@ -2259,10 +1862,9 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2259
1862
|
}
|
|
2260
1863
|
|
|
2261
1864
|
/**
|
|
2262
|
-
* Merges
|
|
2263
|
-
* Returns
|
|
2264
|
-
*
|
|
2265
|
-
* - possibly reduced logical head / tail intervals
|
|
1865
|
+
* Merges the anchored intervals and folds in the logical head/tail items that belong to the
|
|
1866
|
+
* result. Returns the merged interval (`null` if none) and the possibly reduced logical
|
|
1867
|
+
* intervals.
|
|
2266
1868
|
*/
|
|
2267
1869
|
protected mergeIntervals(
|
|
2268
1870
|
intervals: AnyInterval[],
|
|
@@ -2276,29 +1878,24 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2276
1878
|
|
|
2277
1879
|
const anchored: Interval[] = [];
|
|
2278
1880
|
|
|
2279
|
-
// Separate logical vs anchored
|
|
2280
1881
|
for (const itv of intervals) {
|
|
2281
1882
|
if (isLiveHeadInterval(itv)) logicalHead = itv;
|
|
2282
1883
|
else if (isLiveTailInterval(itv)) logicalTail = itv;
|
|
2283
1884
|
else anchored.push(itv);
|
|
2284
1885
|
}
|
|
2285
1886
|
|
|
2286
|
-
// nothing to merge
|
|
2287
1887
|
if (anchored.length === 0 && logicalHead && logicalTail) {
|
|
2288
1888
|
return { logicalHead, merged: null, logicalTail };
|
|
2289
1889
|
}
|
|
2290
1890
|
|
|
2291
|
-
// Merge anchored intervals into one interval (if possible)
|
|
2292
1891
|
const mergedAnchored = this.mergeAnchoredIntervals(anchored, baseInterval);
|
|
2293
1892
|
|
|
2294
|
-
// No anchored intervals → just return logical ones
|
|
2295
1893
|
if (!mergedAnchored) {
|
|
2296
1894
|
return { logicalHead, merged: null, logicalTail };
|
|
2297
1895
|
}
|
|
2298
1896
|
|
|
2299
1897
|
let merged = mergedAnchored;
|
|
2300
1898
|
|
|
2301
|
-
// Merge items from logical HEAD interval
|
|
2302
1899
|
if (logicalHead) {
|
|
2303
1900
|
const { mergedAnchored, remainingLogical } = this.mergeItemsFromLogicalInterval(
|
|
2304
1901
|
logicalHead,
|
|
@@ -2308,7 +1905,6 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2308
1905
|
logicalHead = remainingLogical;
|
|
2309
1906
|
}
|
|
2310
1907
|
|
|
2311
|
-
// Merge items from logical TAIL interval
|
|
2312
1908
|
if (logicalTail) {
|
|
2313
1909
|
const { mergedAnchored, remainingLogical } = this.mergeItemsFromLogicalInterval(
|
|
2314
1910
|
logicalTail,
|
|
@@ -2321,13 +1917,7 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2321
1917
|
return { logicalHead, merged, logicalTail };
|
|
2322
1918
|
}
|
|
2323
1919
|
|
|
2324
|
-
|
|
2325
|
-
// Consume and manage items
|
|
2326
|
-
// ---------------------------------------------------------------------------
|
|
2327
|
-
|
|
2328
|
-
/**
|
|
2329
|
-
* Ingests the whole page into intervals and returns the resulting anchored interval.
|
|
2330
|
-
*/
|
|
1920
|
+
/** Ingests the page into intervals; returns the resulting anchored interval (`null` if empty). */
|
|
2331
1921
|
ingestPage({
|
|
2332
1922
|
page,
|
|
2333
1923
|
policy = 'auto',
|
|
@@ -2338,10 +1928,8 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2338
1928
|
}: {
|
|
2339
1929
|
page: T[];
|
|
2340
1930
|
/**
|
|
2341
|
-
*
|
|
2342
|
-
*
|
|
2343
|
-
* - 'strict-overlap-only': Merge intervals only if they strictly overlap. Useful for jumping to a specific message.
|
|
2344
|
-
* - This is useful for jumping to a specific message.
|
|
1931
|
+
* 'auto' merges overlapping intervals. 'strict-overlap-only' merges only strictly overlapping
|
|
1932
|
+
* ones, e.g. when jumping to a specific item. Defaults to 'auto'.
|
|
2345
1933
|
*/
|
|
2346
1934
|
policy?: IntervalMergePolicy;
|
|
2347
1935
|
isHead?: boolean;
|
|
@@ -2357,8 +1945,7 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2357
1945
|
isTail,
|
|
2358
1946
|
});
|
|
2359
1947
|
|
|
2360
|
-
//
|
|
2361
|
-
// items wakes each subscribing paginator once rather than N times.
|
|
1948
|
+
// One flush for the whole page: subscribing paginators wake once, not per item.
|
|
2362
1949
|
this._itemIndex.batch(() => {
|
|
2363
1950
|
for (const item of page) {
|
|
2364
1951
|
this._itemIndex.setOne(item);
|
|
@@ -2369,20 +1956,14 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2369
1956
|
? this._itemIntervals.get(targetIntervalId)
|
|
2370
1957
|
: undefined;
|
|
2371
1958
|
|
|
2372
|
-
//
|
|
2373
|
-
//
|
|
2374
|
-
// a) is not logical interval and
|
|
2375
|
-
// b) merge would not lead to corrupted interval sorting
|
|
2376
|
-
// (pages: [a], [b,c], merging page [x] to [a] -> [a,x], [b,c] or pages: [b,c], [x] and merging [a] to [x] => [b,c], [a,x] )
|
|
2377
|
-
// 2. if one of the overlappingLogical is an active interval, use it as a base
|
|
2378
|
-
// 3. if existing single anchored interval use it as a base
|
|
1959
|
+
// Base interval, in order of preference: an anchored target interval, an overlapping active
|
|
1960
|
+
// anchored interval, the single overlapping anchored interval.
|
|
2379
1961
|
let baseInterval: Interval | undefined;
|
|
2380
1962
|
|
|
2381
|
-
// Find intervals that overlap with this page
|
|
2382
1963
|
const overlappingAnchored: Interval[] = [];
|
|
2383
1964
|
const overlappingLogical: LogicalInterval[] = [];
|
|
2384
1965
|
for (const itv of this.itemIntervals) {
|
|
2385
|
-
// target interval
|
|
1966
|
+
// The target interval is the base.
|
|
2386
1967
|
if (targetInterval?.id === itv.id) continue;
|
|
2387
1968
|
if (this.intervalsOverlap(pageInterval, itv, policy)) {
|
|
2388
1969
|
if (this.isActiveInterval(itv) && !isLogicalInterval(itv)) {
|
|
@@ -2399,13 +1980,8 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2399
1980
|
}
|
|
2400
1981
|
}
|
|
2401
1982
|
|
|
2402
|
-
//
|
|
2403
|
-
//
|
|
2404
|
-
// interval. Decision, whether target interval is a correct base interval is
|
|
2405
|
-
// upon the ingestPage method caller, not ingestPage method, because the method
|
|
2406
|
-
// does not know, in which context it has been invoked and cannot reliably tell,
|
|
2407
|
-
// whether it is a valid move to merge into the target interval as when
|
|
2408
|
-
// paginating linearly, the ingested page will never overlap with the previous page.
|
|
1983
|
+
// An anchored target interval is always the merge base: whether that is valid is the caller's
|
|
1984
|
+
// call (linear pagination never overlaps the previous page).
|
|
2409
1985
|
if (targetInterval && !isLogicalInterval(targetInterval)) {
|
|
2410
1986
|
baseInterval = targetInterval;
|
|
2411
1987
|
} else if (!baseInterval && overlappingAnchored.length === 1) {
|
|
@@ -2425,7 +2001,6 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2425
2001
|
);
|
|
2426
2002
|
|
|
2427
2003
|
let resultingInterval = pageInterval;
|
|
2428
|
-
// Remove all intervals that participated
|
|
2429
2004
|
if (merged) {
|
|
2430
2005
|
resultingInterval = merged;
|
|
2431
2006
|
for (const itv of toMerge) {
|
|
@@ -2434,9 +2009,8 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2434
2009
|
}
|
|
2435
2010
|
}
|
|
2436
2011
|
|
|
2437
|
-
// Store logical head/tail (if any)
|
|
2438
2012
|
if (logicalHead) {
|
|
2439
|
-
//
|
|
2013
|
+
// Leftovers that do not belong to the first page become a separate anchored interval.
|
|
2440
2014
|
if (merged?.isHead) {
|
|
2441
2015
|
const convertedInterval = {
|
|
2442
2016
|
id: this.generateIntervalId(logicalHead.itemIds),
|
|
@@ -2453,7 +2027,7 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2453
2027
|
}
|
|
2454
2028
|
|
|
2455
2029
|
if (logicalTail) {
|
|
2456
|
-
//
|
|
2030
|
+
// Leftovers that do not belong to the last page become a separate anchored interval.
|
|
2457
2031
|
if (merged?.isTail) {
|
|
2458
2032
|
const convertedInterval = {
|
|
2459
2033
|
id: this.generateIntervalId(logicalTail.itemIds),
|
|
@@ -2472,7 +2046,6 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2472
2046
|
resultingInterval = this.reconcileLogicalIntervalsAgainst(resultingInterval);
|
|
2473
2047
|
|
|
2474
2048
|
this.commitInterval(resultingInterval);
|
|
2475
|
-
// keep the intervals sorted
|
|
2476
2049
|
this.setIntervals(this.sortIntervals(this.itemIntervals));
|
|
2477
2050
|
|
|
2478
2051
|
if (
|
|
@@ -2491,11 +2064,8 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2491
2064
|
}
|
|
2492
2065
|
|
|
2493
2066
|
/**
|
|
2494
|
-
* Ingests a single item
|
|
2495
|
-
*
|
|
2496
|
-
* - find an anchored interval whose sort bounds contain the item
|
|
2497
|
-
* - insert the item into that interval using locate+plateau logic
|
|
2498
|
-
* - if this is the active interval, re-emit state.items from interval
|
|
2067
|
+
* Ingests a single live-updated item: updates the item index, inserts the item into the anchored
|
|
2068
|
+
* interval whose sort bounds contain it, and re-emits `state.items` when that interval is active.
|
|
2499
2069
|
*/
|
|
2500
2070
|
ingestItem(ingestedItem: T): boolean {
|
|
2501
2071
|
let ingested = false;
|
|
@@ -2509,13 +2079,12 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2509
2079
|
const id = this.getItemId(ingestedItem);
|
|
2510
2080
|
const previousItem = this._itemIndex.get(id);
|
|
2511
2081
|
|
|
2512
|
-
//
|
|
2082
|
+
// Capture the previous coordinates before any mutation.
|
|
2513
2083
|
const previousCoords = this.locateByItem(previousItem || ingestedItem);
|
|
2514
2084
|
|
|
2515
2085
|
const originalIndexInState = previousCoords?.state?.currentIndex ?? -1;
|
|
2516
2086
|
const keepOrderInState = this.config.lockItemOrder && originalIndexInState >= 0;
|
|
2517
2087
|
|
|
2518
|
-
// 1. Remove the old snapshot from state & intervals.
|
|
2519
2088
|
const activeIntervalIdBeforeRemoval = this._activeIntervalId;
|
|
2520
2089
|
let removedItemCoordinates: ItemCoordinates | undefined;
|
|
2521
2090
|
if (previousCoords) {
|
|
@@ -2524,19 +2093,17 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2524
2093
|
const itemHasBeenRemoved =
|
|
2525
2094
|
!!removedItemCoordinates?.state && removedItemCoordinates.state.currentIndex > -1;
|
|
2526
2095
|
|
|
2527
|
-
//
|
|
2528
|
-
// Written only if it either already exists or matches the filter
|
|
2529
|
-
// of the paginator.
|
|
2096
|
+
// Stored only if already present or it matches the paginator's filter.
|
|
2530
2097
|
if (this._itemIndex.has(id) || this.matchesFilter(ingestedItem)) {
|
|
2531
2098
|
this._itemIndex.setOne(ingestedItem);
|
|
2532
2099
|
}
|
|
2533
2100
|
|
|
2534
|
-
//
|
|
2101
|
+
// No longer matches the filter: it was removed above.
|
|
2535
2102
|
if (!this.matchesFilter(ingestedItem)) {
|
|
2536
|
-
// left the result set, not just this list
|
|
2103
|
+
// It left the result set, not just this list.
|
|
2537
2104
|
this.shrinkOffsetAfterRemoval(removedItemCoordinates);
|
|
2538
|
-
// Throttled: the removal
|
|
2539
|
-
//
|
|
2105
|
+
// Throttled: the removal deferred its emit, so publish the settled window once. Suspended
|
|
2106
|
+
// (coalescing batch): `removeItemAtCoordinates` recorded it and `batch()` emits on exit.
|
|
2540
2107
|
if (!this.isWindowPublishSuspended && this.isStateThrottled && itemHasBeenRemoved)
|
|
2541
2108
|
this.scheduleWindowPublish();
|
|
2542
2109
|
return itemHasBeenRemoved;
|
|
@@ -2547,15 +2114,13 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2547
2114
|
const onlyLogicalIntervals =
|
|
2548
2115
|
this.itemIntervals.length <= 2 &&
|
|
2549
2116
|
this.itemIntervals.every((itv) => isLogicalInterval(itv));
|
|
2550
|
-
//
|
|
2551
|
-
// using the OLD bounds.
|
|
2117
|
+
// Decide with the old bounds whether the new snapshot still belongs to the same interval.
|
|
2552
2118
|
const stillBelongsToPreviousAnchoredInterval =
|
|
2553
2119
|
previousInterval &&
|
|
2554
|
-
//
|
|
2555
|
-
//
|
|
2120
|
+
// Only logical intervals exist and the item was in one: keep it there so it does not
|
|
2121
|
+
// disappear on update.
|
|
2556
2122
|
((onlyLogicalIntervals && isLogicalInterval(previousInterval)) ||
|
|
2557
|
-
//
|
|
2558
|
-
// within that interval's sort bounds.
|
|
2123
|
+
// Anchored: reuse only while the new snapshot is within the interval's sort bounds.
|
|
2559
2124
|
(!isLogicalInterval(previousInterval) &&
|
|
2560
2125
|
this.belongsToInterval(ingestedItem, previousInterval)));
|
|
2561
2126
|
|
|
@@ -2566,11 +2131,11 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2566
2131
|
const { liveHeadLogical, liveTailLogical } = this;
|
|
2567
2132
|
|
|
2568
2133
|
if (!targetInterval) {
|
|
2569
|
-
// No anchored interval
|
|
2570
|
-
//
|
|
2571
|
-
//
|
|
2134
|
+
// No anchored interval contains the new snapshot: place it relative to the loaded intervals
|
|
2135
|
+
// (logical head or tail, the head-anchored window it slid out of, or nowhere if its page is
|
|
2136
|
+
// unloaded).
|
|
2572
2137
|
if (this._itemIntervals.size === 0) {
|
|
2573
|
-
// No pages
|
|
2138
|
+
// No pages yet: keep it in the logical head.
|
|
2574
2139
|
targetInterval = {
|
|
2575
2140
|
id: LOGICAL_HEAD_INTERVAL_ID,
|
|
2576
2141
|
itemIds: [this.getItemId(ingestedItem)],
|
|
@@ -2586,7 +2151,7 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2586
2151
|
const tailEdges = tailInterval && this.getIntervalPaginationEdges(tailInterval);
|
|
2587
2152
|
|
|
2588
2153
|
if (headEdges && this.aIsMoreHeadwardThanB(ingestedItem, headEdges.head)) {
|
|
2589
|
-
//
|
|
2154
|
+
// Before the loaded head: logical head.
|
|
2590
2155
|
targetInterval = liveHeadLogical
|
|
2591
2156
|
? this.insertItemIdIntoInterval(liveHeadLogical, ingestedItem)
|
|
2592
2157
|
: {
|
|
@@ -2594,13 +2159,10 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2594
2159
|
itemIds: [this.getItemId(ingestedItem)],
|
|
2595
2160
|
};
|
|
2596
2161
|
} else if (tailEdges && this.aIsMoreTailwardThanB(ingestedItem, tailEdges.tail)) {
|
|
2597
|
-
//
|
|
2598
|
-
//
|
|
2599
|
-
//
|
|
2600
|
-
//
|
|
2601
|
-
// channel look like a deletion; its rank is then approximate until the next page settles
|
|
2602
|
-
// it. A floating middle window has unloaded pages on both sides, so there it really is
|
|
2603
|
-
// on another page.
|
|
2162
|
+
// After the loaded tail: normally the item moved to an unloaded page, so it waits in the
|
|
2163
|
+
// logical tail. Not when it slid out of a head-anchored window (the "first N items"): it
|
|
2164
|
+
// is still one of them, and exiling it looked like a deletion. Its rank is approximate
|
|
2165
|
+
// until the next page settles it.
|
|
2604
2166
|
const slidOutOfHeadAnchoredWindow =
|
|
2605
2167
|
!!previousInterval &&
|
|
2606
2168
|
!isLogicalInterval(previousInterval) &&
|
|
@@ -2617,9 +2179,8 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2617
2179
|
itemIds: [this.getItemId(ingestedItem)],
|
|
2618
2180
|
};
|
|
2619
2181
|
} else {
|
|
2620
|
-
//
|
|
2621
|
-
//
|
|
2622
|
-
// this item won't be visible again until the relevant page is fetched.
|
|
2182
|
+
// Inside the global bounds but on an unloaded page: it stays invisible until that page is
|
|
2183
|
+
// fetched.
|
|
2623
2184
|
if (
|
|
2624
2185
|
!this.isWindowPublishSuspended &&
|
|
2625
2186
|
this.isStateThrottled &&
|
|
@@ -2630,15 +2191,11 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2630
2191
|
}
|
|
2631
2192
|
}
|
|
2632
2193
|
} else {
|
|
2633
|
-
// Found an anchored interval whose bounds contain the new snapshot.
|
|
2634
2194
|
targetInterval = this.insertItemIdIntoInterval(targetInterval, ingestedItem);
|
|
2635
2195
|
}
|
|
2636
2196
|
|
|
2637
|
-
//
|
|
2638
|
-
//
|
|
2639
|
-
// that same interval, restore it as the active interval. Otherwise the re-added item is
|
|
2640
|
-
// never emitted to state.items below — the emit is gated on _activeIntervalId — so it
|
|
2641
|
-
// silently disappears from the visible list until the interval is reloaded.
|
|
2197
|
+
// Removing the previous snapshot may have dropped the (now empty) active interval. Re-adding
|
|
2198
|
+
// the item into it restores it as active: the emit below is gated on `_activeIntervalId`.
|
|
2642
2199
|
const removedIntervalId = removedItemCoordinates?.interval?.interval.id;
|
|
2643
2200
|
if (
|
|
2644
2201
|
!this._activeIntervalId &&
|
|
@@ -2652,10 +2209,8 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2652
2209
|
);
|
|
2653
2210
|
}
|
|
2654
2211
|
|
|
2655
|
-
//
|
|
2656
|
-
// `
|
|
2657
|
-
// the already-pruned interval, and the emit after it projects from that same interval. No-op
|
|
2658
|
-
// unless a cap is configured — see {@link pruneTailToLimit}.
|
|
2212
|
+
// Prune before committing: `targetInterval` is still the uncommitted copy, so the
|
|
2213
|
+
// `commitInterval` below stores the pruned interval (see {@link pruneTailToLimit}).
|
|
2659
2214
|
const prunedNow = this.pruneTailToLimit(targetInterval);
|
|
2660
2215
|
|
|
2661
2216
|
const addedNewInterval = !this._itemIntervals.has(targetInterval.id);
|
|
@@ -2665,7 +2220,6 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2665
2220
|
this.setIntervals(this.sortIntervals(this.itemIntervals));
|
|
2666
2221
|
}
|
|
2667
2222
|
|
|
2668
|
-
// emit new state if active interval impacted by ingestion
|
|
2669
2223
|
if (
|
|
2670
2224
|
this._activeIntervalId &&
|
|
2671
2225
|
[targetInterval.id, removedItemCoordinates?.interval?.interval.id].includes(
|
|
@@ -2673,37 +2227,29 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2673
2227
|
)
|
|
2674
2228
|
) {
|
|
2675
2229
|
if (this.isWindowPublishSuspended) {
|
|
2676
|
-
// Coalescing batch: record the change; batch() emits the settled window once on exit.
|
|
2230
|
+
// Coalescing batch: record the change; `batch()` emits the settled window once on exit.
|
|
2677
2231
|
this._suspendedWindowDirty = true;
|
|
2678
2232
|
} else if (this.isStateThrottled) {
|
|
2679
2233
|
this.scheduleWindowPublish();
|
|
2680
2234
|
} else {
|
|
2681
2235
|
const items = this.items ?? [];
|
|
2682
|
-
|
|
2683
|
-
|
|
2684
|
-
* discrepancies once active intervals are switched:
|
|
2685
|
-
* 1. state.items [a,b,c] intervals [a,b,c], [d]
|
|
2686
|
-
* 2. a changed and is moved to another interval state.items is now [a,b,c], intervals [b,c,], [d, a]
|
|
2687
|
-
* 3. jumping / changing active interval to [d,a] - state.items is now [d,a], intervals [b,c], [d,a]
|
|
2688
|
-
*/
|
|
2236
|
+
// With `lockItemOrder`, `state.items` can keep an item the intervals moved elsewhere, so
|
|
2237
|
+
// switching the active interval then shows a different list.
|
|
2689
2238
|
if (keepOrderInState) {
|
|
2690
|
-
//
|
|
2239
|
+
// The item was visible: reinsert it at its old index.
|
|
2691
2240
|
const nextView = items.slice();
|
|
2692
2241
|
const insertAt = Math.min(originalIndexInState, nextView.length);
|
|
2693
2242
|
nextView.splice(insertAt, 0, ingestedItem);
|
|
2694
2243
|
this.state.partialNext({
|
|
2695
|
-
// This branch republishes the
|
|
2696
|
-
//
|
|
2697
|
-
// every survivor's relative position — which is the whole point of `lockItemOrder`.
|
|
2244
|
+
// This branch republishes the last published array rather than re-projecting, so IDs a
|
|
2245
|
+
// prune just removed would resurrect: drop them, keeping survivors' relative positions.
|
|
2698
2246
|
items: prunedNow
|
|
2699
2247
|
? this.retainIntervalMembers(nextView, targetInterval)
|
|
2700
2248
|
: nextView,
|
|
2701
2249
|
...this.consumePendingPrunePaginationState(),
|
|
2702
2250
|
});
|
|
2703
2251
|
} else {
|
|
2704
|
-
|
|
2705
|
-
* Select a correct interval from which the state.items array is derived
|
|
2706
|
-
*/
|
|
2252
|
+
// Derive from the active interval (the one the item left, or the target).
|
|
2707
2253
|
this.state.partialNext({
|
|
2708
2254
|
items: this.intervalToItems(
|
|
2709
2255
|
this._activeIntervalId === removedItemCoordinates?.interval?.interval.id &&
|
|
@@ -2721,22 +2267,10 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2721
2267
|
}
|
|
2722
2268
|
|
|
2723
2269
|
/**
|
|
2724
|
-
*
|
|
2725
|
-
*
|
|
2726
|
-
*
|
|
2727
|
-
*
|
|
2728
|
-
* notifications fold into a single flush, so sibling holders of the same ids (e.g. a thread /
|
|
2729
|
-
* pinned paginator sharing the entity) re-project once, not once per item. Inert for single-home
|
|
2730
|
-
* paginators (channels, reminders, user groups) whose index is over a private store with no
|
|
2731
|
-
* sibling subscribers — there it is a plain passthrough.
|
|
2732
|
-
* - **This paginator's own active window** (`coalesce: true`): every `ingestItem` / `removeItem`
|
|
2733
|
-
* inside `fn` records that the window changed instead of publishing it, then `batch` emits the
|
|
2734
|
-
* settled window exactly once on exit via {@link flushWindowPublish}. This is deterministic and
|
|
2735
|
-
* independent of state throttling — unlike leaving it off, where an un-throttled paginator emits
|
|
2736
|
-
* once per item and a throttled one merely coalesces within its 500ms window. Use it for one-shot
|
|
2737
|
-
* operations (reconciliation, reload re-ingest) that must settle in a single update. Omit it in WS
|
|
2738
|
-
* event handlers, where per-event publishes should ride the throttle so successive events coalesce
|
|
2739
|
-
* across its trailing edge rather than each forcing a synchronous emit.
|
|
2270
|
+
* Runs `fn` as one batched mutation: per-item store notifications fold into one flush, so sibling
|
|
2271
|
+
* holders of the same IDs re-project once. With `coalesce: true` the active window also emits
|
|
2272
|
+
* exactly once on exit ({@link flushWindowPublish}), independent of throttling: for one-shot
|
|
2273
|
+
* operations. Omit it in WS event handlers so events ride the throttle.
|
|
2740
2274
|
*/
|
|
2741
2275
|
batch(fn: () => void, { coalesce = false }: { coalesce?: boolean } = {}): void {
|
|
2742
2276
|
if (!coalesce) {
|
|
@@ -2746,10 +2280,6 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2746
2280
|
this.withSingleWindowPublish(() => this._itemIndex.batch(fn), { exit: 'sync' });
|
|
2747
2281
|
}
|
|
2748
2282
|
|
|
2749
|
-
// ---------------------------------------------------------------------------
|
|
2750
|
-
// Remove / contains
|
|
2751
|
-
// ---------------------------------------------------------------------------
|
|
2752
|
-
|
|
2753
2283
|
protected removeItemAtCoordinates(coords: ItemCoordinates): ItemCoordinates {
|
|
2754
2284
|
const { state: stateLocation, interval: intervalLocation } = coords;
|
|
2755
2285
|
|
|
@@ -2757,15 +2287,12 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2757
2287
|
state: { currentIndex: -1, insertionIndex: -1 },
|
|
2758
2288
|
};
|
|
2759
2289
|
|
|
2760
|
-
// 1) Remove from interval, if present
|
|
2761
2290
|
if (intervalLocation && intervalLocation.currentIndex > -1) {
|
|
2762
2291
|
const updatedInterval = this.removeItemIdFromInterval(intervalLocation);
|
|
2763
2292
|
const { interval } = updatedInterval;
|
|
2764
2293
|
if (interval.itemIds.length === 0) {
|
|
2765
|
-
// Drop empty interval
|
|
2766
2294
|
this.dropInterval(interval.id);
|
|
2767
2295
|
|
|
2768
|
-
// If it was active -> clear active
|
|
2769
2296
|
if (this.isActiveInterval(interval)) {
|
|
2770
2297
|
this.setActiveInterval(undefined);
|
|
2771
2298
|
}
|
|
@@ -2775,7 +2302,6 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2775
2302
|
result.interval = updatedInterval;
|
|
2776
2303
|
}
|
|
2777
2304
|
|
|
2778
|
-
// 2) Remove from visible state.items, if present
|
|
2779
2305
|
if (stateLocation && stateLocation.currentIndex > -1) {
|
|
2780
2306
|
if (this.isWindowPublishSuspended) {
|
|
2781
2307
|
this._suspendedWindowDirty = true;
|
|
@@ -2785,7 +2311,7 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2785
2311
|
this.state.partialNext({ items: newItems });
|
|
2786
2312
|
}
|
|
2787
2313
|
|
|
2788
|
-
//
|
|
2314
|
+
// Keep `insertionIndex` consistent after the removal.
|
|
2789
2315
|
if (stateLocation.insertionIndex > stateLocation.currentIndex) {
|
|
2790
2316
|
stateLocation.insertionIndex--;
|
|
2791
2317
|
}
|
|
@@ -2813,13 +2339,9 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2813
2339
|
}
|
|
2814
2340
|
|
|
2815
2341
|
/**
|
|
2816
|
-
*
|
|
2817
|
-
*
|
|
2818
|
-
*
|
|
2819
|
-
*
|
|
2820
|
-
* If we are removing the last item from the currently active interval, we do not search for a new active interval.
|
|
2821
|
-
* If the number of items approach 0 in an active interval, we expect from the UI to load new pages to populate
|
|
2822
|
-
* the active interval.
|
|
2342
|
+
* In the returned coordinates `currentIndex === -1` means not found and `insertionIndex === -1`
|
|
2343
|
+
* that none was determined. Removing the last item of the active interval does not activate
|
|
2344
|
+
* another one: the UI is expected to load pages to repopulate it.
|
|
2823
2345
|
*/
|
|
2824
2346
|
removeItem({ id, item: inputItem }: { id?: string; item?: T }): ItemCoordinates {
|
|
2825
2347
|
const noAction = { state: { currentIndex: -1, insertionIndex: -1 } };
|
|
@@ -2833,7 +2355,7 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2833
2355
|
const result = this.removeItemAtCoordinates(coords);
|
|
2834
2356
|
this._itemIndex.remove(this.getItemId(item));
|
|
2835
2357
|
this.shrinkOffsetAfterRemoval(result);
|
|
2836
|
-
// Throttled:
|
|
2358
|
+
// Throttled: the removal deferred its emit, so publish the settled window once.
|
|
2837
2359
|
if (!this.isWindowPublishSuspended && this.isStateThrottled)
|
|
2838
2360
|
this.scheduleWindowPublish();
|
|
2839
2361
|
return result;
|
|
@@ -2855,8 +2377,6 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2855
2377
|
? valueOrFactory(currentItems)
|
|
2856
2378
|
: valueOrFactory;
|
|
2857
2379
|
|
|
2858
|
-
// If the references between the two values are the same, just return the
|
|
2859
|
-
// current state; otherwise trigger a state change.
|
|
2860
2380
|
if (currentItems === newItems) {
|
|
2861
2381
|
return current;
|
|
2862
2382
|
}
|
|
@@ -2886,19 +2406,10 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2886
2406
|
}
|
|
2887
2407
|
|
|
2888
2408
|
/**
|
|
2889
|
-
* Records the
|
|
2890
|
-
*
|
|
2891
|
-
*
|
|
2892
|
-
*
|
|
2893
|
-
* hydrate (`mergeNewestPage`). Leaving `_lastQueryShape` undefined afterwards makes the next
|
|
2894
|
-
* query look like a shape change, so `executeQuery` takes its first-page branch and publishes
|
|
2895
|
-
* `getStateBeforeFirstQuery()` (items `undefined`) BEFORE the request. A response with items
|
|
2896
|
-
* rebuilds the window from the surviving intervals, so that case merely churns; an empty one — a
|
|
2897
|
-
* tailward query on a thread whose replies are all loaded — has nothing to rebuild from and the
|
|
2898
|
-
* loaded window is lost.
|
|
2899
|
-
*
|
|
2900
|
-
* Only meaningful with items in hand: an empty window has no shape to continue from, and the
|
|
2901
|
-
* flags already say there is nothing more to fetch.
|
|
2409
|
+
* Records the query shape of the loaded window so the next pagination continues it. Data that
|
|
2410
|
+
* arrives without a query (`setItems`, `mergeNewestPage`) would otherwise make the next query a
|
|
2411
|
+
* first page that publishes `items: undefined` first, and an empty response then loses the
|
|
2412
|
+
* window. Needs items: an empty window has no shape to continue from.
|
|
2902
2413
|
*/
|
|
2903
2414
|
protected recordLoadedWindowQueryShape() {
|
|
2904
2415
|
if (
|
|
@@ -2909,33 +2420,19 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2909
2420
|
}
|
|
2910
2421
|
}
|
|
2911
2422
|
|
|
2912
|
-
// ---------------------------------------------------------------------------
|
|
2913
|
-
// Debounce & query execution
|
|
2914
|
-
// ---------------------------------------------------------------------------
|
|
2915
|
-
|
|
2916
2423
|
setDebounceOptions = ({ debounceMs }: PaginatorDebounceOptions) => {
|
|
2917
2424
|
this._executeQueryDebounced = debounce(this.executeQuery.bind(this), debounceMs);
|
|
2918
2425
|
};
|
|
2919
2426
|
|
|
2920
|
-
/**
|
|
2921
|
-
* Rebuilds the state-publish throttles for a new interval, or drops them when the interval is unset.
|
|
2922
|
-
*
|
|
2923
|
-
* This exists because `stateThrottleMs` is read *once*: the throttles capture the interval in their
|
|
2924
|
-
* closures, so assigning `config.stateThrottleMs` afterwards does nothing at all — an unthrottled
|
|
2925
|
-
* paginator never gains a throttle, and a throttled one keeps its original interval. Anything
|
|
2926
|
-
* changing the value at runtime (declarative configuration registered after construction, or
|
|
2927
|
-
* `client.config.reset()`) has to come through here.
|
|
2928
|
-
*
|
|
2929
|
-
* Pending publishes are flushed first, so a swap cannot swallow a trailing-edge emit that was
|
|
2930
|
-
* already scheduled.
|
|
2931
|
-
*/
|
|
2427
|
+
/** Changes `stateThrottleMs` at runtime. The config controller rebuilds the throttles. */
|
|
2932
2428
|
setStateThrottleOptions = ({ stateThrottleMs }: { stateThrottleMs?: number }) => {
|
|
2933
|
-
// Released surface. It no longer has to pair the write with the rebuild — the controller's
|
|
2934
|
-
// `onChanged` does that for whichever route the value arrives by, including a declarative change.
|
|
2935
2429
|
this.updateConfig({ stateThrottleMs } as Partial<BasePaginatorConfig<T, Q>>);
|
|
2936
2430
|
};
|
|
2937
2431
|
|
|
2938
|
-
/**
|
|
2432
|
+
/**
|
|
2433
|
+
* Rebuilds the state-publish throttles for a new interval, or drops them when it is unset.
|
|
2434
|
+
* Pending publishes are flushed first so a swap cannot swallow a scheduled trailing-edge emit.
|
|
2435
|
+
*/
|
|
2939
2436
|
private rebuildStatePublishThrottles(stateThrottleMs?: number) {
|
|
2940
2437
|
this.flushPendingPublishes();
|
|
2941
2438
|
|
|
@@ -2944,8 +2441,7 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2944
2441
|
|
|
2945
2442
|
if (!stateThrottleMs) return;
|
|
2946
2443
|
|
|
2947
|
-
//
|
|
2948
|
-
// trailing edge re-projects the active window fresh, so a burst emits ~once per interval.
|
|
2444
|
+
// The trailing edge re-projects the active window, so a burst emits about once per interval.
|
|
2949
2445
|
this._windowPublishThrottle = throttle(
|
|
2950
2446
|
() => this.flushWindowPublish(),
|
|
2951
2447
|
stateThrottleMs,
|
|
@@ -2954,8 +2450,6 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2954
2450
|
trailing: true,
|
|
2955
2451
|
},
|
|
2956
2452
|
);
|
|
2957
|
-
// Interval view publishes ride their own throttle so they coalesce like `state.items` but land on
|
|
2958
|
-
// an independent trailing edge (see {@link _viewPublishThrottle}).
|
|
2959
2453
|
this._viewPublishThrottle = throttle(
|
|
2960
2454
|
() => this.flushIntervalViewPublish(),
|
|
2961
2455
|
stateThrottleMs,
|
|
@@ -2964,27 +2458,10 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2964
2458
|
}
|
|
2965
2459
|
|
|
2966
2460
|
/**
|
|
2967
|
-
*
|
|
2968
|
-
*
|
|
2461
|
+
* Rebuilds the configuration from defaults, options and the declarative slice, dropping earlier
|
|
2462
|
+
* `updateConfig` changes.
|
|
2969
2463
|
*
|
|
2970
|
-
*
|
|
2971
|
-
* so the two share one code path and cannot drift. Both read-once fields are routed through their
|
|
2972
|
-
* rebuild setters, because assigning them would be silently discarded.
|
|
2973
|
-
*
|
|
2974
|
-
* Structural wiring is untouched here because it never reaches `config` in the first place:
|
|
2975
|
-
* `itemIndex` and `createItemIndex` are destructured out of the constructor's options and resolved
|
|
2976
|
-
* once into {@link _itemIndex}, so there is nothing in the derived config for a re-derivation to drop.
|
|
2977
|
-
*
|
|
2978
|
-
* Subclass behaviour overrides are folded in through {@link getBehaviourOverrides} rather than written
|
|
2979
|
-
* afterwards, so one re-derivation is one `configState` publish carrying a complete config. It used to
|
|
2980
|
-
* be a second write from an `initializeConfig` override, and the claim that both writes carried a
|
|
2981
|
-
* complete config was wrong: the base derivation knows nothing of the overlay, so it published the
|
|
2982
|
-
* config with `doRequest`, `deriveCursor` and `itemOrderComparator` **stripped**, and the subclass then
|
|
2983
|
-
* put them back. A `PinnedMessagePaginator` re-derivation emitted three notifications, of which the
|
|
2984
|
-
* first had no request function at all — a subscriber that paginated during that synchronous window
|
|
2985
|
-
* would have found none.
|
|
2986
|
-
*
|
|
2987
|
-
* Applied last, so the overlay still wins over constructor options exactly as the second write did.
|
|
2464
|
+
* @param declarativeConfig - The declarative slice. Leave it out to rebuild without one.
|
|
2988
2465
|
*/
|
|
2989
2466
|
initializeConfig(declarativeConfig?: DeclarativePaginatorConfig): void {
|
|
2990
2467
|
this.configController.initialize(
|
|
@@ -2993,16 +2470,9 @@ export abstract class BasePaginator<T, Q> {
|
|
|
2993
2470
|
}
|
|
2994
2471
|
|
|
2995
2472
|
/**
|
|
2996
|
-
* Behaviour a subclass installs that
|
|
2997
|
-
* closed over `this
|
|
2998
|
-
*
|
|
2999
|
-
* Folded into the single derivation in {@link initializeConfig}, which is why an override must return
|
|
3000
|
-
* **stable references**: rebuilding the closures on each call makes every derived config differ from
|
|
3001
|
-
* the last, defeating the guard above and republishing on every unrelated re-derivation. Memoize them
|
|
3002
|
-
* — their inputs are fixed at construction.
|
|
3003
|
-
*
|
|
3004
|
-
* Called only after construction. The base constructor builds `configState` directly rather than
|
|
3005
|
-
* through `initializeConfig`, so an override is never invoked before its own fields are initialized.
|
|
2473
|
+
* Behaviour a subclass installs that options cannot express (a comparator, `deriveCursor` or
|
|
2474
|
+
* `doRequest` closed over `this`). Applied last in `initializeConfig`. Must return stable
|
|
2475
|
+
* references (memoize them), or every derivation republishes. Called only after construction.
|
|
3006
2476
|
*/
|
|
3007
2477
|
protected getBehaviourOverrides(): Partial<BasePaginatorConfig<T, Q>> {
|
|
3008
2478
|
return {};
|
|
@@ -3024,7 +2494,7 @@ export abstract class BasePaginator<T, Q> {
|
|
|
3024
2494
|
}: { direction?: PaginationDirection } & Pick<PaginationQueryParams<Q>, 'reset'>) =>
|
|
3025
2495
|
!this.isLoading &&
|
|
3026
2496
|
(reset === 'yes' ||
|
|
3027
|
-
//
|
|
2497
|
+
// No direction: a jump query.
|
|
3028
2498
|
typeof direction === 'undefined' ||
|
|
3029
2499
|
(direction === 'tailward' && this.hasMoreTail) ||
|
|
3030
2500
|
(direction === 'headward' && this.hasMoreHead));
|
|
@@ -3032,10 +2502,9 @@ export abstract class BasePaginator<T, Q> {
|
|
|
3032
2502
|
isFirstPageQuery = (
|
|
3033
2503
|
params: { queryShape?: unknown } & Pick<PaginationQueryParams<Q>, 'reset'>,
|
|
3034
2504
|
): boolean => {
|
|
3035
|
-
//
|
|
3036
|
-
//
|
|
3037
|
-
//
|
|
3038
|
-
// `shouldResetStateBeforeQuery` reports a first page for it too.
|
|
2505
|
+
// No loaded window: first page. Items without a loaded page (a live event ingested one into a
|
|
2506
|
+
// never-queried list) have no recorded query shape, so `shouldResetStateBeforeQuery` reports a
|
|
2507
|
+
// first page for them too.
|
|
3039
2508
|
if (typeof this.items === 'undefined') return true;
|
|
3040
2509
|
if (params.reset === 'yes') return true;
|
|
3041
2510
|
if (params.reset === 'no') return false;
|
|
@@ -3048,12 +2517,9 @@ export abstract class BasePaginator<T, Q> {
|
|
|
3048
2517
|
...this.initialState,
|
|
3049
2518
|
isLoading: true,
|
|
3050
2519
|
};
|
|
3051
|
-
//
|
|
3052
|
-
//
|
|
3053
|
-
//
|
|
3054
|
-
// re-derived per page in postQueryReconcile, because the offset only grows tailward from here and
|
|
3055
|
-
// would then read as "more headward" even for a list that started at the head. Cursor pagination
|
|
3056
|
-
// learns hasMoreHead from the query response, so leave the optimistic default for it.
|
|
2520
|
+
// Offset pagination: the head is loaded exactly when the window starts at offset 0, so
|
|
2521
|
+
// `hasMoreHead` is anchored here, not re-derived per page (the growing offset would read as
|
|
2522
|
+
// "more headward"). Cursor pagination learns it from the response.
|
|
3057
2523
|
if (!this.isCursorPagination) {
|
|
3058
2524
|
state.hasMoreHead = (this.config.initialOffset ?? 0) > 0;
|
|
3059
2525
|
}
|
|
@@ -3064,6 +2530,11 @@ export abstract class BasePaginator<T, Q> {
|
|
|
3064
2530
|
return false;
|
|
3065
2531
|
}
|
|
3066
2532
|
|
|
2533
|
+
/** The page size a query's results are measured against when deriving the head/tail flags. */
|
|
2534
|
+
protected getRequestedPageSize(_queryShape: Q | undefined): number {
|
|
2535
|
+
return this.pageSize;
|
|
2536
|
+
}
|
|
2537
|
+
|
|
3067
2538
|
protected getStateAfterQuery(
|
|
3068
2539
|
stateUpdate: Partial<PaginatorState<T>>,
|
|
3069
2540
|
|
|
@@ -3095,12 +2566,6 @@ export abstract class BasePaginator<T, Q> {
|
|
|
3095
2566
|
try {
|
|
3096
2567
|
return await this.query(params);
|
|
3097
2568
|
} catch (e) {
|
|
3098
|
-
const isOfflineSupportEnabledWithItems =
|
|
3099
|
-
this.isOfflineSupportEnabled && (this.items ?? []).length > 0;
|
|
3100
|
-
if (!isOfflineSupportEnabledWithItems) {
|
|
3101
|
-
this.state.partialNext({ lastQueryError: e as Error });
|
|
3102
|
-
}
|
|
3103
|
-
|
|
3104
2569
|
if (remainingRetries > 0) {
|
|
3105
2570
|
await sleep(DEFAULT_QUERY_CHANNELS_MS_BETWEEN_RETRIES);
|
|
3106
2571
|
return await this.runQueryRetryable({
|
|
@@ -3108,6 +2573,14 @@ export abstract class BasePaginator<T, Q> {
|
|
|
3108
2573
|
retryCount: remainingRetries - 1,
|
|
3109
2574
|
});
|
|
3110
2575
|
}
|
|
2576
|
+
|
|
2577
|
+
// run only once all retries are exhausted
|
|
2578
|
+
const isOfflineSupportEnabledWithItems =
|
|
2579
|
+
this.isOfflineSupportEnabled && (this.items ?? []).length > 0;
|
|
2580
|
+
if (!isOfflineSupportEnabledWithItems) {
|
|
2581
|
+
this.state.partialNext({ lastQueryError: e as Error });
|
|
2582
|
+
}
|
|
2583
|
+
|
|
3111
2584
|
if (this.config.throwErrors) {
|
|
3112
2585
|
this.state.partialNext({ isLoading: false });
|
|
3113
2586
|
throw e;
|
|
@@ -3117,16 +2590,21 @@ export abstract class BasePaginator<T, Q> {
|
|
|
3117
2590
|
}
|
|
3118
2591
|
|
|
3119
2592
|
/**
|
|
3120
|
-
*
|
|
2593
|
+
* Runs a pagination query and reconciles its result into the paginator state.
|
|
3121
2594
|
*
|
|
3122
2595
|
* @param params - Query parameters.
|
|
3123
2596
|
* @param params.direction - Direction to paginate in (headward or tailward).
|
|
3124
|
-
* @param params.keepPreviousItems - Keep already-loaded items instead of clearing them on a
|
|
2597
|
+
* @param params.keepPreviousItems - Keep already-loaded items instead of clearing them on a
|
|
2598
|
+
* first-page query.
|
|
3125
2599
|
* @param params.queryShape - Explicit query shape overriding the one derived from current state.
|
|
3126
|
-
* @param params.
|
|
3127
|
-
* @param params.
|
|
3128
|
-
* @param params.
|
|
2600
|
+
* @param params.requestOptions - Request options outside the query shape.
|
|
2601
|
+
* @param params.reset - 'yes' forces a first page, 'no' continues, else the query shape decides.
|
|
2602
|
+
* @param params.retryCount - Number of retries after a failure.
|
|
2603
|
+
* @param params.silent - Skip the `isLoading: true` publish of a non-first-page or
|
|
2604
|
+
* `keepPreviousItems` query.
|
|
3129
2605
|
* @param params.updateState - Whether to write the query results back to state.
|
|
2606
|
+
* @returns The reconciled result (`targetInterval` is `null` when nothing was ingested, e.g. a
|
|
2607
|
+
* failed request or an empty page), or nothing when the query did not run.
|
|
3130
2608
|
*/
|
|
3131
2609
|
async executeQuery({
|
|
3132
2610
|
direction,
|
|
@@ -3140,30 +2618,24 @@ export abstract class BasePaginator<T, Q> {
|
|
|
3140
2618
|
}: PaginationQueryParams<Q> = {}): Promise<ExecuteQueryReturnValue<T> | void> {
|
|
3141
2619
|
if (!this.canExecuteQuery({ direction, reset })) return;
|
|
3142
2620
|
|
|
3143
|
-
// A forced reset
|
|
3144
|
-
//
|
|
3145
|
-
//
|
|
3146
|
-
//
|
|
3147
|
-
//
|
|
3148
|
-
// Clearing the interval storage here also stops the incoming page from merging into stale
|
|
3149
|
-
// intervals. Only a forced reset clears it: a first page reached through ordinary shape-change
|
|
3150
|
-
// detection (cursor pagination looks like a new shape every page) must keep the cache so
|
|
3151
|
-
// adjacent pages merge; filter/sort changes clear it via `resetState()` in their setters.
|
|
2621
|
+
// A forced reset happens before the request is built: `getNextQueryShape()` reads the
|
|
2622
|
+
// offset/cursor from state. Only a forced reset clears the interval storage: a first page
|
|
2623
|
+
// reached through shape-change detection (cursor pagination looks like a new shape every page)
|
|
2624
|
+
// keeps it so adjacent pages merge. Filter/sort setters clear it via `resetState()`.
|
|
3152
2625
|
const isForcedReset = reset === 'yes' && !keepPreviousItems;
|
|
3153
2626
|
if (isForcedReset) {
|
|
3154
2627
|
this.clearItemStorage();
|
|
3155
2628
|
this.state.next(this.getStateBeforeFirstQuery());
|
|
3156
2629
|
} else if (reset === 'yes' && !forcedQueryShape) {
|
|
3157
|
-
// A `keepPreviousItems` refresh
|
|
3158
|
-
//
|
|
3159
|
-
// page loads. Reset only the pagination position; `getNextQueryShape()` below reads it from state.
|
|
2630
|
+
// A `keepPreviousItems` refresh restarts from page 1 without clearing the loaded window:
|
|
2631
|
+
// reset only the pagination position that `getNextQueryShape()` reads.
|
|
3160
2632
|
this.state.partialNext({
|
|
3161
2633
|
cursor: this.config.initialCursor,
|
|
3162
2634
|
offset: this.config.initialOffset ?? 0,
|
|
3163
2635
|
});
|
|
3164
2636
|
}
|
|
3165
2637
|
|
|
3166
|
-
// A non-destructive refresh
|
|
2638
|
+
// A non-destructive refresh asks for the whole loaded list at once (the server may return less).
|
|
3167
2639
|
const isRefresh = reset === 'yes' && keepPreviousItems && !forcedQueryShape;
|
|
3168
2640
|
const pageSize = isRefresh
|
|
3169
2641
|
? Math.max(this.pageSize, this.items?.length ?? 0)
|
|
@@ -3175,17 +2647,10 @@ export abstract class BasePaginator<T, Q> {
|
|
|
3175
2647
|
|
|
3176
2648
|
if (isFirstPage && !keepPreviousItems) {
|
|
3177
2649
|
const state = this.getStateBeforeFirstQuery();
|
|
3178
|
-
// Publish the loading flag
|
|
3179
|
-
// `isLoading`, so
|
|
3180
|
-
//
|
|
3181
|
-
//
|
|
3182
|
-
// requests. A UI that loads both ends at once does exactly that: an empty list sits within the
|
|
3183
|
-
// scroll threshold of its top AND its bottom, so the scroll handler calls `toTail` and `toHead`
|
|
3184
|
-
// one line apart.
|
|
3185
|
-
//
|
|
3186
|
-
// Only the flag: `state` carries `items: undefined`, so publishing all of it here would blank
|
|
3187
|
-
// a list that offline data is about to fill — the reason the full publish waits for the preload.
|
|
3188
|
-
// A forced reset published it (loading included) synchronously above, so it needs nothing.
|
|
2650
|
+
// Publish the loading flag before the offline preload is awaited: `canExecuteQuery` gates on
|
|
2651
|
+
// `isLoading`, so a second call in the same tick (`toTail` and `toHead` on an empty list)
|
|
2652
|
+
// would issue an identical request. Only the flag: `state` has `items: undefined`, which
|
|
2653
|
+
// would blank a list the offline data is about to fill. A forced reset already published it.
|
|
3189
2654
|
if (!isForcedReset) {
|
|
3190
2655
|
this.state.partialNext({ isLoading: true });
|
|
3191
2656
|
}
|
|
@@ -3199,14 +2664,13 @@ export abstract class BasePaginator<T, Q> {
|
|
|
3199
2664
|
retryCount,
|
|
3200
2665
|
})) ?? state.items;
|
|
3201
2666
|
}
|
|
3202
|
-
// A forced reset already published this state
|
|
3203
|
-
//
|
|
2667
|
+
// A forced reset already published this state: publish again only when the offline preload
|
|
2668
|
+
// produced items.
|
|
3204
2669
|
if (!isForcedReset || items !== undefined) {
|
|
3205
2670
|
this.state.next({ ...state, items });
|
|
3206
2671
|
}
|
|
3207
2672
|
} else if (!silent) {
|
|
3208
|
-
// Non-first-page
|
|
3209
|
-
// freshly fetched page is merged into the still-loaded intervals in postQueryReconcile.
|
|
2673
|
+
// Non-first-page or `keepPreviousItems` refresh: surface loading without blanking the list.
|
|
3210
2674
|
this.state.partialNext({ isLoading: true });
|
|
3211
2675
|
}
|
|
3212
2676
|
|
|
@@ -3223,7 +2687,7 @@ export abstract class BasePaginator<T, Q> {
|
|
|
3223
2687
|
isFirstPage,
|
|
3224
2688
|
keepPreviousItems,
|
|
3225
2689
|
queryShape,
|
|
3226
|
-
requestedPageSize: this.
|
|
2690
|
+
requestedPageSize: this.getRequestedPageSize(queryShape),
|
|
3227
2691
|
results,
|
|
3228
2692
|
updateState,
|
|
3229
2693
|
});
|
|
@@ -3250,26 +2714,20 @@ export abstract class BasePaginator<T, Q> {
|
|
|
3250
2714
|
return { stateCandidate: stateUpdate, targetInterval: null };
|
|
3251
2715
|
}
|
|
3252
2716
|
|
|
3253
|
-
//
|
|
3254
|
-
//
|
|
3255
|
-
// - new contract uses tailward/headward
|
|
3256
|
-
//
|
|
3257
|
-
// Internal SDK paginators already return tailward/headward, so this fallback is
|
|
3258
|
-
// only to keep non-migrated external subclasses working during transition.
|
|
2717
|
+
// Custom subclasses may still return the deprecated `next`/`prev` instead of
|
|
2718
|
+
// `tailward`/`headward`.
|
|
3259
2719
|
const { items, headward, tailward, next, prev } = results;
|
|
3260
2720
|
const resolvedHeadward = headward ?? prev;
|
|
3261
2721
|
const resolvedTailward = tailward ?? next;
|
|
3262
2722
|
|
|
3263
2723
|
stateUpdate.lastQueryError = undefined;
|
|
3264
|
-
// Filtering is a
|
|
3265
|
-
//
|
|
3266
|
-
// paginator synchronously (MessagePaginator.seedFirstPageSync) before read-state hydration.
|
|
2724
|
+
// Filtering is synchronous, so reconciliation runs in a single tick (synchronous seeds rely on
|
|
2725
|
+
// it).
|
|
3267
2726
|
const filteredItems = this.filterQueryResults(items);
|
|
3268
2727
|
stateUpdate.items = filteredItems;
|
|
3269
2728
|
|
|
3270
2729
|
const isJumpQuery = !!queryShape && this.isJumpQueryShape(queryShape);
|
|
3271
|
-
//
|
|
3272
|
-
// have to be read before the ingest below adds the page to it.
|
|
2730
|
+
// Read the kept window's IDs before the ingest below adds the refreshed page to it.
|
|
3273
2731
|
const keptItemIds =
|
|
3274
2732
|
isFirstPage && keepPreviousItems && !this.isCursorPagination && this.items?.length
|
|
3275
2733
|
? new Set(this.items.map((item) => this.getItemId(item)))
|
|
@@ -3277,14 +2735,14 @@ export abstract class BasePaginator<T, Q> {
|
|
|
3277
2735
|
const interval = this.ingestPage({
|
|
3278
2736
|
page: stateUpdate.items,
|
|
3279
2737
|
policy: isJumpQuery ? 'strict-overlap-only' : 'auto',
|
|
3280
|
-
//
|
|
2738
|
+
// The first page is always the head.
|
|
3281
2739
|
isHead: isJumpQuery
|
|
3282
|
-
? undefined //
|
|
2740
|
+
? undefined // unknown for a jump
|
|
3283
2741
|
: isFirstPage ||
|
|
3284
2742
|
(direction === 'headward' ? requestedPageSize > items.length : undefined),
|
|
3285
|
-
//
|
|
2743
|
+
// Even a first page compares the requested vs returned page size.
|
|
3286
2744
|
isTail: isJumpQuery
|
|
3287
|
-
? undefined //
|
|
2745
|
+
? undefined // unknown for a jump
|
|
3288
2746
|
: isFirstPage || direction === 'tailward'
|
|
3289
2747
|
? requestedPageSize > items.length
|
|
3290
2748
|
: undefined,
|
|
@@ -3294,29 +2752,13 @@ export abstract class BasePaginator<T, Q> {
|
|
|
3294
2752
|
this.setActiveInterval(interval, { updateState: false });
|
|
3295
2753
|
stateUpdate.items = this.intervalToItems(interval);
|
|
3296
2754
|
} else if (updateState && !items.length && (keepPreviousItems || !isFirstPage)) {
|
|
3297
|
-
// An empty page must
|
|
3298
|
-
//
|
|
3299
|
-
// (leaving the active interval untouched), so `stateUpdate.items` still holds the empty
|
|
3300
|
-
// `filteredItems` here and committing that would blank the list. This happens when a refresh
|
|
3301
|
-
// finds nothing, or when a paginate hits the dataset edge. Preserve the current view instead.
|
|
3302
|
-
// A genuine reset (isFirstPage without keepPreviousItems) still blanks, so an emptied dataset
|
|
3303
|
-
// shows empty.
|
|
2755
|
+
// An empty page must not wipe the loaded items on a `keepPreviousItems` refresh or an
|
|
2756
|
+
// incremental query (`ingestPage` returns null for it). A genuine reset still blanks.
|
|
3304
2757
|
stateUpdate.items = this.items;
|
|
3305
2758
|
}
|
|
3306
2759
|
|
|
3307
|
-
|
|
3308
|
-
|
|
3309
|
-
* Therefore, the BasePaginator.cursorSource can be 'derived' | 'query'
|
|
3310
|
-
* - derived - the BasePaginator applies the default client-side logic based on the pagination options (id_lt, id_gt, id_around...)
|
|
3311
|
-
* - query - BasePaginator.query() resp. BasePaginator.config.doRequest (called inside query()) is expected to provide the cursor and abide by the rules that when the wall is hit in
|
|
3312
|
-
* a given direction, the cursor will be set to null.
|
|
3313
|
-
*
|
|
3314
|
-
* The 'derived' calculation will perform the following steps:
|
|
3315
|
-
* 1. After ingesting into the parent interval determine the cursor candidate values from the first and the last item in the interval.
|
|
3316
|
-
* 2. Decide, whether the candidates can be set based on the requested vs real page size
|
|
3317
|
-
* 3. If the page size from the response is smaller that the requested page size, then in the given direction
|
|
3318
|
-
* the cursor will be set to null.
|
|
3319
|
-
*/
|
|
2760
|
+
// The cursor comes from `config.deriveCursor` (derived from the ingested interval) or from the
|
|
2761
|
+
// query response (`headward`/`tailward`, falsy meaning the edge was hit).
|
|
3320
2762
|
if (this.isCursorPagination) {
|
|
3321
2763
|
if (this.config.deriveCursor && interval) {
|
|
3322
2764
|
const { cursor, hasMoreTail, hasMoreHead } = this.config.deriveCursor({
|
|
@@ -3332,6 +2774,21 @@ export abstract class BasePaginator<T, Q> {
|
|
|
3332
2774
|
stateUpdate.cursor = cursor;
|
|
3333
2775
|
stateUpdate.hasMoreTail = hasMoreTail;
|
|
3334
2776
|
stateUpdate.hasMoreHead = hasMoreHead;
|
|
2777
|
+
} else if (this.config.deriveCursor && direction && !isFirstPage) {
|
|
2778
|
+
// Nothing was ingested, so there is no interval to derive from: only the direction
|
|
2779
|
+
// paginated in is resolved and the other side keeps its cursor.
|
|
2780
|
+
stateUpdate.cursor =
|
|
2781
|
+
direction === 'headward'
|
|
2782
|
+
? {
|
|
2783
|
+
headward: resolvedHeadward || null,
|
|
2784
|
+
tailward: this.cursor?.tailward ?? null,
|
|
2785
|
+
}
|
|
2786
|
+
: {
|
|
2787
|
+
headward: this.cursor?.headward ?? null,
|
|
2788
|
+
tailward: resolvedTailward || null,
|
|
2789
|
+
};
|
|
2790
|
+
if (direction === 'headward') stateUpdate.hasMoreHead = !!resolvedHeadward;
|
|
2791
|
+
else stateUpdate.hasMoreTail = !!resolvedTailward;
|
|
3335
2792
|
} else {
|
|
3336
2793
|
stateUpdate.cursor = {
|
|
3337
2794
|
tailward: resolvedTailward || null,
|
|
@@ -3344,7 +2801,8 @@ export abstract class BasePaginator<T, Q> {
|
|
|
3344
2801
|
// todo: we could keep the offset in two directions (initial tailward offset would be taken from config.initialOffset)
|
|
3345
2802
|
const startOffset = this.offset ?? 0;
|
|
3346
2803
|
stateUpdate.offset = startOffset + items.length;
|
|
3347
|
-
// After a `keepPreviousItems` refresh whose page connects to the kept window, continue from
|
|
2804
|
+
// After a `keepPreviousItems` refresh whose page connects to the kept window, continue from
|
|
2805
|
+
// the window's end instead of re-fetching it.
|
|
3348
2806
|
const lastPageItem = items[items.length - 1];
|
|
3349
2807
|
if (
|
|
3350
2808
|
interval &&
|
|
@@ -3357,12 +2815,11 @@ export abstract class BasePaginator<T, Q> {
|
|
|
3357
2815
|
startOffset + this.intervalToItems(interval).length,
|
|
3358
2816
|
);
|
|
3359
2817
|
}
|
|
3360
|
-
// Only hasMoreTail depends on the page result
|
|
3361
|
-
//
|
|
3362
|
-
// the offset only grows tailward from here, so leave hasMoreHead untouched.
|
|
2818
|
+
// Only `hasMoreTail` depends on the page result: `hasMoreHead` was anchored at the reset
|
|
2819
|
+
// ({@link getStateBeforeFirstQuery}).
|
|
3363
2820
|
stateUpdate.hasMoreTail = items.length >= this.pageSize;
|
|
3364
|
-
//
|
|
3365
|
-
//
|
|
2821
|
+
// A `keepPreviousItems` first page never publishes `getStateBeforeFirstQuery()`, so anchor
|
|
2822
|
+
// its `hasMoreHead` from the start offset here.
|
|
3366
2823
|
if (isFirstPage) stateUpdate.hasMoreHead = (this.config.initialOffset ?? 0) > 0;
|
|
3367
2824
|
}
|
|
3368
2825
|
|
|
@@ -3382,14 +2839,12 @@ export abstract class BasePaginator<T, Q> {
|
|
|
3382
2839
|
interval.hasMoreTail = resolvedHasMoreTail;
|
|
3383
2840
|
interval.isHead = resolvedHasMoreHead === false;
|
|
3384
2841
|
interval.isTail = resolvedHasMoreTail === false;
|
|
3385
|
-
// `isHead` is decided here
|
|
2842
|
+
// `isHead` is decided here, not at ingest: reflect a flip in `anchoredHead`.
|
|
3386
2843
|
this.syncAnchoredHeadAfterHeadFlip(interval, wasHead);
|
|
3387
2844
|
} else if (!items.length && direction) {
|
|
3388
|
-
// An empty directional response means the dataset edge was reached
|
|
3389
|
-
//
|
|
3390
|
-
//
|
|
3391
|
-
// (e.g. `jumpToTheLatestMessage` would never see the head as loaded, and a "scroll to latest"
|
|
3392
|
-
// affordance would never clear).
|
|
2845
|
+
// An empty directional response means the dataset edge was reached, but `ingestPage` returns
|
|
2846
|
+
// no interval for an empty page: flag the active interval, or its `isHead`/`isTail` stay
|
|
2847
|
+
// stale and the head never reads as loaded.
|
|
3393
2848
|
const activeInterval = this._activeIntervalId
|
|
3394
2849
|
? this._itemIntervals.get(this._activeIntervalId)
|
|
3395
2850
|
: undefined;
|
|
@@ -3398,7 +2853,6 @@ export abstract class BasePaginator<T, Q> {
|
|
|
3398
2853
|
const wasHead = activeInterval.isHead;
|
|
3399
2854
|
activeInterval.isHead = true;
|
|
3400
2855
|
activeInterval.hasMoreHead = false;
|
|
3401
|
-
// The active page just reached the dataset head; reflect the flip in `anchoredHead`.
|
|
3402
2856
|
this.syncAnchoredHeadAfterHeadFlip(activeInterval, wasHead);
|
|
3403
2857
|
} else if (direction === 'tailward') {
|
|
3404
2858
|
activeInterval.isTail = true;
|
|
@@ -3408,7 +2862,10 @@ export abstract class BasePaginator<T, Q> {
|
|
|
3408
2862
|
}
|
|
3409
2863
|
|
|
3410
2864
|
const state = this.getStateAfterQuery(stateUpdate, isFirstPage);
|
|
2865
|
+
// A caller that commits its own state (`updateState: false`) must not be left with the
|
|
2866
|
+
// `isLoading` that `executeQuery` published.
|
|
3411
2867
|
if (updateState) this.state.next(state);
|
|
2868
|
+
else if (this.isLoading) this.state.partialNext({ isLoading: false });
|
|
3412
2869
|
// Only the first page is cached and a later page cannot change it.
|
|
3413
2870
|
if (isFirstPage) this.populateOfflineDbAfterQuery({ items: state.items, queryShape });
|
|
3414
2871
|
|
|
@@ -3418,10 +2875,6 @@ export abstract class BasePaginator<T, Q> {
|
|
|
3418
2875
|
};
|
|
3419
2876
|
}
|
|
3420
2877
|
|
|
3421
|
-
// ---------------------------------------------------------------------------
|
|
3422
|
-
// Public API: navigation
|
|
3423
|
-
// ---------------------------------------------------------------------------
|
|
3424
|
-
|
|
3425
2878
|
cancelScheduledQuery() {
|
|
3426
2879
|
this._executeQueryDebounced.cancel();
|
|
3427
2880
|
}
|
|
@@ -3431,22 +2884,15 @@ export abstract class BasePaginator<T, Q> {
|
|
|
3431
2884
|
this.setIntervals([]);
|
|
3432
2885
|
this.setActiveInterval(undefined);
|
|
3433
2886
|
this.clearIntervalViews();
|
|
3434
|
-
// Nothing is loaded
|
|
3435
|
-
//
|
|
3436
|
-
// (a filter/sort setter that resets, `ChannelManager.resetPaginatorStates()` on disconnect)
|
|
3437
|
-
// would be treated as a continuation — ingested without `isHead`, leaving any live-updated
|
|
3438
|
-
// logical interval unreconciled.
|
|
2887
|
+
// Nothing is loaded, so the next query is a first page again. A stale shape would make a
|
|
2888
|
+
// re-query with an unchanged shape a continuation, ingested without `isHead`.
|
|
3439
2889
|
this._lastQueryShape = undefined;
|
|
3440
2890
|
}
|
|
3441
2891
|
|
|
3442
2892
|
/**
|
|
3443
|
-
* Releases this paginator's hold on its item content
|
|
3444
|
-
*
|
|
3445
|
-
*
|
|
3446
|
-
* receiving change notifications, and its items never garbage-collect. Call on teardown of the
|
|
3447
|
-
* owner: a discard, not a reset (the owner is not reused; a re-appearing id gets a fresh instance;
|
|
3448
|
-
* leftover interval/state caches die with the paginator when it is dropped). Also cancels any
|
|
3449
|
-
* pending throttled window/view publish, so nothing emits after teardown.
|
|
2893
|
+
* Releases this paginator's hold on its item content (unlinks every member ID from the shared
|
|
2894
|
+
* store, which otherwise pins a discarded owner) and cancels pending throttled publishes. A
|
|
2895
|
+
* teardown, not a reset: the owner is not reused.
|
|
3450
2896
|
*/
|
|
3451
2897
|
dispose(): void {
|
|
3452
2898
|
this._windowPublishThrottle?.cancelTimer();
|