stream-chat 10.0.0-rc.9 → 10.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -6
- package/dist/cjs/index.browser.js +21650 -19790
- package/dist/cjs/index.browser.js.map +4 -4
- package/dist/cjs/index.node.js +21690 -19798
- package/dist/cjs/index.node.js.map +4 -4
- package/dist/esm/index.mjs +21755 -19895
- package/dist/esm/index.mjs.map +4 -4
- package/dist/types/ChannelManager.d.ts +216 -135
- package/dist/types/CooldownTimer.d.ts +13 -27
- package/dist/types/EventHandlerPipeline.d.ts +18 -38
- package/dist/types/LiveLocationManager.d.ts +24 -52
- package/dist/types/api-client.d.ts +17 -5
- package/dist/types/channel.d.ts +432 -470
- package/dist/types/channel_state.d.ts +68 -112
- package/dist/types/client.d.ts +321 -435
- package/dist/types/client_state.d.ts +1 -3
- package/dist/types/configuration/ConfigController.d.ts +31 -125
- package/dist/types/configuration/InstanceConfigurationRegistry.d.ts +32 -124
- 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 +64 -79
- package/dist/types/configuration/utils/applyInstanceConfiguration.d.ts +14 -36
- 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 +45 -0
- package/dist/types/connection/ConnectionRecoveryManager.d.ts +84 -0
- package/dist/types/connection/index.d.ts +4 -0
- package/dist/types/connection/networkConnection/NetworkConnectionObserver.d.ts +82 -0
- package/dist/types/connection/networkConnection/index.d.ts +3 -0
- package/dist/types/connection/networkConnection/reporters.d.ts +20 -0
- package/dist/types/connection/networkConnection/types.d.ts +40 -0
- package/dist/types/connection/wsConnection/StableWSConnection.d.ts +137 -0
- package/dist/types/connection/wsConnection/WSConnection.d.ts +105 -0
- package/dist/types/connection/wsConnection/WSConnectionFallback.d.ts +47 -0
- package/dist/types/connection/wsConnection/config.d.ts +31 -0
- package/dist/types/connection/wsConnection/index.d.ts +4 -0
- package/dist/types/connection/wsConnection/types.d.ts +46 -0
- package/dist/types/constants.d.ts +2 -0
- package/dist/types/custom_types.d.ts +0 -2
- package/dist/types/entityStore/EntityStore.d.ts +226 -65
- package/dist/types/entityStore/StoreBackedItemIndex.d.ts +19 -33
- package/dist/types/entityStore/index.d.ts +0 -1
- package/dist/types/errors.d.ts +16 -19
- package/dist/types/formatMessageMemo.d.ts +5 -0
- package/dist/types/gen/chat/ChannelApi.d.ts +5 -1
- package/dist/types/gen/chat/ChatApi.d.ts +149 -105
- package/dist/types/gen/models/index.d.ts +2528 -690
- package/dist/types/gen/models/timestamp-guard.d.ts +22 -0
- package/dist/types/gen/moderation/ModerationApi.d.ts +33 -14
- package/dist/types/index.d.ts +10 -6
- package/dist/types/{i18n/languageNames.d.ts → languageNames.d.ts} +9 -24
- package/dist/types/logger.d.ts +1 -3
- package/dist/types/messageComposer/CustomDataManager.d.ts +7 -1
- package/dist/types/messageComposer/LocationComposer.d.ts +7 -1
- package/dist/types/messageComposer/attachmentIdentity.d.ts +24 -0
- package/dist/types/messageComposer/attachmentManager.d.ts +52 -24
- package/dist/types/messageComposer/attachmentUtils.d.ts +23 -0
- package/dist/types/messageComposer/configuration/configuration.d.ts +2 -5
- package/dist/types/messageComposer/configuration/types.d.ts +38 -50
- package/dist/types/messageComposer/index.d.ts +1 -0
- package/dist/types/messageComposer/linkPreviewsManager.d.ts +12 -9
- package/dist/types/messageComposer/messageComposer.d.ts +60 -128
- package/dist/types/messageComposer/middleware/attachmentManager/postUpload/attachmentEnrichment.d.ts +10 -1
- package/dist/types/messageComposer/middleware/messageComposer/attachments.d.ts +4 -0
- package/dist/types/messageComposer/middleware/messageComposer/commandInjection.d.ts +5 -0
- package/dist/types/messageComposer/middleware/messageComposer/index.d.ts +2 -0
- package/dist/types/messageComposer/middleware/messageComposer/pollOnly.d.ts +6 -0
- package/dist/types/messageComposer/middleware/messageComposer/userDataInjection.d.ts +5 -0
- 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/commandUtils.d.ts +4 -0
- package/dist/types/messageComposer/middleware/textComposer/commands.d.ts +11 -2
- package/dist/types/messageComposer/middleware/textComposer/mentions.d.ts +19 -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 +15 -5
- package/dist/types/messageComposer/textComposer.d.ts +14 -7
- package/dist/types/messageComposer/types.d.ts +27 -7
- package/dist/types/messageDelivery/MessageDeliveryReporter.d.ts +27 -80
- package/dist/types/messageDelivery/MessageReceiptsTracker.d.ts +40 -73
- package/dist/types/messageOperations/FailedSendCache.d.ts +29 -0
- package/dist/types/messageOperations/MessageOperationStatePolicy.d.ts +16 -22
- package/dist/types/messageOperations/MessageOperations.d.ts +63 -34
- package/dist/types/messageOperations/applyReactionLocally.d.ts +15 -0
- package/dist/types/messageOperations/createMessageOperations.d.ts +9 -0
- package/dist/types/messageOperations/index.d.ts +6 -4
- package/dist/types/messageOperations/reflectReactionEvent.d.ts +16 -0
- package/dist/types/messageOperations/sendOrdering.d.ts +14 -0
- package/dist/types/messageOperations/settlePendingAttachmentUploads.d.ts +20 -0
- package/dist/types/messageOperations/types.d.ts +43 -14
- package/dist/types/middleware.d.ts +10 -0
- package/dist/types/moderation.d.ts +21 -14
- package/dist/types/notifications/NotificationManager.d.ts +10 -23
- package/dist/types/notifications/types.d.ts +21 -57
- package/dist/types/offline-support/offline_support_api.d.ts +150 -528
- package/dist/types/offline-support/offline_sync_manager.d.ts +21 -42
- package/dist/types/offline-support/queueableOperations.d.ts +35 -37
- package/dist/types/offline-support/types.d.ts +40 -186
- package/dist/types/pagination/FilterBuilder.d.ts +1 -18
- 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 +4 -5
- package/dist/types/pagination/cursorDerivation/linearPaginationFlags.d.ts +19 -5
- package/dist/types/pagination/index.d.ts +1 -0
- package/dist/types/pagination/paginators/BasePaginator.d.ts +604 -550
- package/dist/types/pagination/paginators/ChannelPaginator.d.ts +123 -106
- package/dist/types/pagination/paginators/MessageIntervalPaginator.d.ts +576 -334
- package/dist/types/pagination/paginators/MessagePaginator.d.ts +237 -131
- package/dist/types/pagination/paginators/PinnedMessagePaginator.d.ts +15 -26
- package/dist/types/pagination/paginators/ReminderPaginator.d.ts +4 -3
- package/dist/types/pagination/paginators/ThreadPaginator.d.ts +44 -0
- package/dist/types/pagination/paginators/UserGroupPaginator.d.ts +5 -8
- package/dist/types/pagination/paginators/index.d.ts +1 -0
- 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 +34 -8
- package/dist/types/poll_manager.d.ts +12 -2
- package/dist/types/poll_optimistic_votes.d.ts +57 -0
- package/dist/types/reminders/Reminder.d.ts +11 -11
- package/dist/types/reminders/ReminderManager.d.ts +13 -25
- package/dist/types/search/BaseSearchSource.d.ts +10 -8
- package/dist/types/search/ChannelSearchSource.d.ts +16 -0
- package/dist/types/search/MessageSearchSource.d.ts +17 -0
- package/dist/types/search/SearchController.d.ts +26 -28
- package/dist/types/search/types.d.ts +6 -10
- package/dist/types/signing.d.ts +12 -3
- package/dist/types/thread.d.ts +63 -129
- package/dist/types/thread_manager.d.ts +95 -66
- package/dist/types/token_manager.d.ts +8 -13
- package/dist/types/types.d.ts +81 -199
- package/dist/types/types.utility.d.ts +3 -3
- package/dist/types/upload-utils.d.ts +5 -10
- package/dist/types/uploadManager.d.ts +31 -11
- package/dist/types/utils/FixedSizeQueueCache.d.ts +8 -11
- package/dist/types/utils/WithSubscriptions.d.ts +6 -16
- package/dist/types/utils/abort.d.ts +17 -0
- package/dist/types/utils/concurrency.d.ts +12 -20
- 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 +33 -57
- package/dist/types/utils.d.ts +72 -91
- package/package.json +14 -40
- package/src/ChannelManager.ts +494 -303
- package/src/CooldownTimer.ts +28 -38
- package/src/EventHandlerPipeline.ts +22 -45
- package/src/LiveLocationManager.ts +37 -76
- package/src/api-client.ts +113 -50
- package/src/campaign.ts +1 -1
- package/src/channel.ts +1067 -1276
- package/src/channel_batch_updater.ts +1 -1
- package/src/channel_state.ts +73 -168
- package/src/client.ts +744 -974
- package/src/client_state.ts +3 -8
- package/src/configuration/ConfigController.ts +42 -158
- package/src/configuration/InstanceConfigurationRegistry.ts +43 -172
- package/src/configuration/index.ts +1 -1
- package/src/configuration/keys.ts +13 -32
- package/src/configuration/shape.ts +169 -59
- package/src/configuration/types.ts +69 -92
- package/src/configuration/utils/applyInstanceConfiguration.ts +22 -54
- 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 +111 -0
- package/src/connection/ConnectionRecoveryManager.ts +257 -0
- package/src/connection/index.ts +4 -0
- package/src/connection/networkConnection/NetworkConnectionObserver.ts +204 -0
- package/src/connection/networkConnection/index.ts +3 -0
- package/src/connection/networkConnection/reporters.ts +58 -0
- package/src/connection/networkConnection/types.ts +45 -0
- package/src/{connection.ts → connection/wsConnection/StableWSConnection.ts} +230 -232
- package/src/connection/wsConnection/WSConnection.ts +270 -0
- package/src/connection/wsConnection/WSConnectionFallback.ts +250 -0
- package/src/connection/wsConnection/config.ts +73 -0
- package/src/connection/wsConnection/index.ts +4 -0
- package/src/connection/wsConnection/types.ts +48 -0
- package/src/constants.ts +6 -5
- package/src/custom_types.ts +0 -1
- package/src/entityStore/EntityStore.ts +415 -79
- package/src/entityStore/StoreBackedItemIndex.ts +37 -41
- package/src/entityStore/index.ts +0 -1
- package/src/errors.ts +39 -20
- package/src/formatMessageMemo.ts +17 -0
- package/src/gen/chat/ChannelApi.ts +122 -36
- package/src/gen/chat/ChatApi.ts +578 -1540
- package/src/gen/models/index.ts +2498 -3383
- package/src/gen/models/timestamp-guard.ts +27 -0
- package/src/gen/moderation/ModerationApi.ts +170 -367
- package/src/index.ts +22 -10
- package/src/languageNames.ts +88 -0
- package/src/logger.ts +1 -3
- package/src/messageComposer/CustomDataManager.ts +19 -6
- package/src/messageComposer/LocationComposer.ts +19 -23
- package/src/messageComposer/MessageComposerEffectHandlers.ts +1 -2
- package/src/messageComposer/attachmentIdentity.ts +54 -0
- package/src/messageComposer/attachmentManager.ts +170 -185
- package/src/messageComposer/attachmentUtils.ts +44 -0
- package/src/messageComposer/configuration/configuration.ts +15 -8
- package/src/messageComposer/configuration/types.ts +38 -50
- package/src/messageComposer/fileUtils.ts +1 -1
- package/src/messageComposer/index.ts +1 -0
- package/src/messageComposer/linkPreviewsManager.ts +18 -21
- package/src/messageComposer/messageComposer.ts +223 -174
- package/src/messageComposer/middleware/attachmentManager/postUpload/AttachmentPostUploadMiddlewareExecutor.ts +1 -1
- package/src/messageComposer/middleware/attachmentManager/postUpload/attachmentEnrichment.ts +46 -33
- package/src/messageComposer/middleware/attachmentManager/postUpload/uploadErrorHandler.ts +4 -1
- package/src/messageComposer/middleware/attachmentManager/preUpload/blockedUploadNotification.ts +1 -1
- package/src/messageComposer/middleware/messageComposer/MessageComposerMiddlewareExecutor.ts +6 -0
- package/src/messageComposer/middleware/messageComposer/attachments.ts +76 -5
- package/src/messageComposer/middleware/messageComposer/commandInjection.ts +10 -4
- package/src/messageComposer/middleware/messageComposer/customData.ts +17 -5
- package/src/messageComposer/middleware/messageComposer/index.ts +2 -0
- package/src/messageComposer/middleware/messageComposer/linkPreviews.ts +22 -12
- package/src/messageComposer/middleware/messageComposer/pollOnly.ts +9 -1
- package/src/messageComposer/middleware/messageComposer/textComposer.ts +1 -1
- package/src/messageComposer/middleware/messageComposer/userDataInjection.ts +12 -12
- 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 +8 -6
- package/src/messageComposer/middleware/textComposer/commandUtils.ts +10 -3
- 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 +21 -9
- package/src/messageComposer/textComposer.ts +37 -57
- package/src/messageComposer/types.ts +39 -11
- package/src/messageDelivery/MessageDeliveryReporter.ts +86 -125
- package/src/messageDelivery/MessageReceiptsTracker.ts +88 -101
- package/src/messageOperations/FailedSendCache.ts +85 -0
- package/src/messageOperations/MessageOperationStatePolicy.ts +121 -112
- package/src/messageOperations/MessageOperations.ts +297 -175
- package/src/{entityStore → messageOperations}/applyReactionLocally.ts +9 -28
- package/src/messageOperations/createMessageOperations.ts +176 -0
- package/src/messageOperations/index.ts +6 -14
- package/src/messageOperations/reflectReactionEvent.ts +43 -0
- package/src/messageOperations/sendOrdering.ts +25 -0
- package/src/messageOperations/settlePendingAttachmentUploads.ts +98 -0
- package/src/messageOperations/types.ts +51 -13
- package/src/middleware.ts +13 -5
- package/src/moderation.ts +25 -21
- package/src/notifications/NotificationManager.ts +19 -28
- package/src/notifications/types.ts +21 -57
- package/src/offline-support/offline_support_api.ts +226 -669
- package/src/offline-support/offline_sync_manager.ts +51 -80
- package/src/offline-support/queueableOperations.ts +98 -73
- package/src/offline-support/types.ts +43 -186
- package/src/pagination/FilterBuilder.ts +1 -22
- package/src/pagination/ItemIndex.ts +4 -12
- package/src/pagination/cursorDerivation/aroundPaginationFlags.ts +29 -0
- package/src/pagination/cursorDerivation/createdAtAroundPaginationFlags.ts +15 -63
- package/src/pagination/cursorDerivation/idAroundPaginationFlags.ts +11 -39
- package/src/pagination/cursorDerivation/linearPaginationFlags.ts +53 -33
- package/src/pagination/filterCompiler.ts +11 -25
- package/src/pagination/index.ts +1 -0
- package/src/pagination/paginators/BasePaginator.ts +1415 -1041
- package/src/pagination/paginators/ChannelPaginator.ts +479 -217
- package/src/pagination/paginators/MessageIntervalPaginator.ts +1351 -772
- package/src/pagination/paginators/MessagePaginator.ts +513 -233
- package/src/pagination/paginators/PinnedMessagePaginator.ts +32 -40
- package/src/pagination/paginators/ReminderPaginator.ts +21 -16
- package/src/pagination/paginators/ThreadPaginator.ts +170 -0
- package/src/pagination/paginators/UserGroupPaginator.ts +16 -19
- package/src/pagination/paginators/index.ts +1 -0
- 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 +177 -98
- package/src/poll_manager.ts +24 -22
- package/src/poll_optimistic_votes.ts +335 -0
- package/src/reminders/Reminder.ts +16 -12
- package/src/reminders/ReminderManager.ts +22 -55
- package/src/reminders/ReminderTimer.ts +1 -2
- package/src/search/BaseSearchSource.ts +19 -25
- package/src/search/ChannelSearchSource.ts +43 -1
- package/src/search/MessageSearchSource.ts +77 -13
- package/src/search/SearchController.ts +39 -36
- package/src/search/types.ts +6 -10
- package/src/segment.ts +1 -1
- package/src/signing.ts +23 -3
- package/src/thread.ts +418 -703
- package/src/thread_manager.ts +300 -234
- package/src/token_manager.ts +12 -22
- package/src/types.ts +102 -216
- package/src/types.utility.ts +3 -3
- package/src/upload-utils.ts +5 -10
- package/src/uploadManager.ts +64 -18
- package/src/utils/FixedSizeQueueCache.ts +18 -21
- package/src/utils/WithSubscriptions.ts +6 -16
- package/src/utils/abort.ts +45 -0
- 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 +40 -60
- package/src/utils.ts +181 -174
- package/codegen/i18n/callSites.ts +0 -126
- package/codegen/i18n/generate.ts +0 -226
- package/codegen/i18n/guards.ts +0 -178
- package/codegen/i18n/index.ts +0 -29
- package/codegen/i18n/stringMaps.ts +0 -91
- package/codegen/i18n/types.ts +0 -100
- package/dist/cjs/i18n.browser.js +0 -1131
- package/dist/cjs/i18n.browser.js.map +0 -7
- package/dist/cjs/i18n.node.js +0 -1160
- package/dist/cjs/i18n.node.js.map +0 -7
- package/dist/esm/i18n-codegen.mjs +0 -409
- package/dist/esm/i18n-codegen.mjs.map +0 -7
- package/dist/esm/i18n.mjs +0 -1098
- package/dist/esm/i18n.mjs.map +0 -7
- package/dist/types/ConnectionRecoveryManager.d.ts +0 -156
- package/dist/types/connection.d.ts +0 -139
- package/dist/types/entityStore/applyReactionLocally.d.ts +0 -32
- package/dist/types/i18n/Streami18n.d.ts +0 -168
- package/dist/types/i18n/TranslationBuilder.d.ts +0 -70
- package/dist/types/i18n/TranslationStore.d.ts +0 -57
- package/dist/types/i18n/dayjs.d.ts +0 -104
- package/dist/types/i18n/formatters.d.ts +0 -91
- package/dist/types/i18n/index.d.ts +0 -15
- package/dist/types/i18n/translator.d.ts +0 -29
- package/dist/types/i18n/types.d.ts +0 -262
- package/dist/types/i18n-codegen/callSites.d.ts +0 -10
- package/dist/types/i18n-codegen/generate.d.ts +0 -15
- package/dist/types/i18n-codegen/guards.d.ts +0 -61
- package/dist/types/i18n-codegen/index.d.ts +0 -29
- package/dist/types/i18n-codegen/stringMaps.d.ts +0 -14
- package/dist/types/i18n-codegen/types.d.ts +0 -94
- package/dist/types/insights.d.ts +0 -56
- package/dist/types/messageOperations/optimistic.d.ts +0 -118
- package/dist/types/messageOperations/persistence.d.ts +0 -21
- package/dist/types/pagination/utility.queryChannel.d.ts +0 -26
- package/dist/types/store.d.ts +0 -125
- package/src/ConnectionRecoveryManager.ts +0 -293
- package/src/i18n/Streami18n.ts +0 -520
- package/src/i18n/TranslationBuilder.ts +0 -176
- package/src/i18n/TranslationStore.ts +0 -96
- package/src/i18n/dayjs.ts +0 -228
- package/src/i18n/formatters.ts +0 -461
- package/src/i18n/index.ts +0 -15
- package/src/i18n/languageNames.ts +0 -103
- package/src/i18n/translator.ts +0 -76
- package/src/i18n/types.ts +0 -375
- package/src/insights.ts +0 -82
- package/src/messageOperations/optimistic.ts +0 -257
- package/src/messageOperations/persistence.ts +0 -40
- package/src/pagination/utility.queryChannel.ts +0 -84
- package/src/store.ts +0 -304
|
@@ -1,13 +1,15 @@
|
|
|
1
1
|
import type {
|
|
2
2
|
AnyInterval,
|
|
3
3
|
BasePaginatorConfig,
|
|
4
|
-
|
|
4
|
+
CursorDeriveContext,
|
|
5
5
|
CursorDeriveResult,
|
|
6
|
+
DoRequestResponse,
|
|
7
|
+
ExecuteQueryReturnValue,
|
|
6
8
|
Interval,
|
|
7
9
|
PaginationDirection,
|
|
8
10
|
PaginationQueryParams,
|
|
9
|
-
PaginatorCursor,
|
|
10
11
|
PaginatorState,
|
|
12
|
+
QueryPagePlacement,
|
|
11
13
|
} from './BasePaginator';
|
|
12
14
|
import {
|
|
13
15
|
BasePaginator,
|
|
@@ -18,21 +20,25 @@ import {
|
|
|
18
20
|
ZERO_PAGE_CURSOR,
|
|
19
21
|
} from './BasePaginator';
|
|
20
22
|
import type {
|
|
23
|
+
ChannelStateResponse,
|
|
24
|
+
GetRepliesResponse,
|
|
21
25
|
LocalMessage,
|
|
22
26
|
MessagePaginationParams,
|
|
23
|
-
MessageResponse,
|
|
24
27
|
PinnedMessagePaginationOptions,
|
|
25
|
-
ReactionResponse,
|
|
26
28
|
SortParamRequest,
|
|
29
|
+
StreamResponse,
|
|
30
|
+
TimestampNS,
|
|
27
31
|
UserResponse,
|
|
28
32
|
} from '../../types';
|
|
29
33
|
import type { Channel } from '../../channel';
|
|
34
|
+
import type { Thread } from '../../thread';
|
|
35
|
+
import { ChannelWatchStatus } from '../../channel_state';
|
|
30
36
|
import { CORE_NOTIFICATION_TYPE } from '../../notifications';
|
|
31
|
-
import { StateStore } from '
|
|
37
|
+
import { StateStore } from '@stream-io/state-store';
|
|
32
38
|
import {
|
|
33
|
-
computeOwnReactions,
|
|
34
39
|
formatMessage,
|
|
35
40
|
generateUUIDv4,
|
|
41
|
+
isThreadOnlyReply,
|
|
36
42
|
toDeletedMessage,
|
|
37
43
|
} from '../../utils';
|
|
38
44
|
import { makeComparator } from '../sortCompiler';
|
|
@@ -44,7 +50,10 @@ import type { EntityStoreChangeBatch } from '../../entityStore/EntityStore';
|
|
|
44
50
|
import { StoreBackedItemIndex } from '../../entityStore/StoreBackedItemIndex';
|
|
45
51
|
import { deriveCreatedAtAroundPaginationFlags } from '../cursorDerivation';
|
|
46
52
|
import { deriveIdAroundPaginationFlags } from '../cursorDerivation/idAroundPaginationFlags';
|
|
47
|
-
import {
|
|
53
|
+
import {
|
|
54
|
+
deriveLinearPaginationFlags,
|
|
55
|
+
getLinearQueryDirection,
|
|
56
|
+
} from '../cursorDerivation/linearPaginationFlags';
|
|
48
57
|
|
|
49
58
|
export type MessageFocusReason =
|
|
50
59
|
| 'jump-to-message'
|
|
@@ -65,20 +74,19 @@ export type MessageFocusSignalState = {
|
|
|
65
74
|
|
|
66
75
|
export type JumpToMessageOptions = {
|
|
67
76
|
pageSize?: number;
|
|
68
|
-
/**
|
|
69
|
-
* Optional reason attached to emitted focus signal.
|
|
70
|
-
* Defaults to `jump-to-message`.
|
|
71
|
-
*/
|
|
77
|
+
/** Reason attached to the emitted focus signal. Defaults to `jump-to-message`. */
|
|
72
78
|
focusReason?: MessageFocusReason;
|
|
73
|
-
/**
|
|
74
|
-
* TTL for the emitted focus signal in milliseconds.
|
|
75
|
-
* Defaults to `3000`.
|
|
76
|
-
*/
|
|
79
|
+
/** TTL of the emitted focus signal in milliseconds. Defaults to `3000`. */
|
|
77
80
|
focusSignalTtlMs?: number;
|
|
81
|
+
/** Suppresses the focus signal after a successful jump. */
|
|
82
|
+
suppressFocusSignal?: boolean;
|
|
78
83
|
/**
|
|
79
|
-
*
|
|
84
|
+
* Also watches the channel (so it receives events) when it is not watched yet. The request that
|
|
85
|
+
* loads the interval around the message asks to watch too, so it stays one request, and a message
|
|
86
|
+
* already loaded is loaded again. Ignored for a thread's reply list (its request cannot watch)
|
|
87
|
+
* and when the paginator's `doRequest` loads the messages.
|
|
80
88
|
*/
|
|
81
|
-
|
|
89
|
+
watchChannel?: boolean;
|
|
82
90
|
};
|
|
83
91
|
|
|
84
92
|
export type MessagePaginatorSort = SortParamRequest[];
|
|
@@ -102,11 +110,12 @@ export type MessagePaginatorState = PaginatorState<LocalMessage>;
|
|
|
102
110
|
export type MessageQueryShape = MessagePaginationParams | PinnedMessagePaginationOptions;
|
|
103
111
|
|
|
104
112
|
/**
|
|
105
|
-
*
|
|
106
|
-
*
|
|
107
|
-
* But we always paginate within the same list without changing the sorting params.
|
|
108
|
-
* It is currently not possible to change the sorting params.
|
|
113
|
+
* Whether a query asks for no messages (`limit: 0`). Its empty page says nothing about the channel,
|
|
114
|
+
* so it must not be read as an empty one.
|
|
109
115
|
*/
|
|
116
|
+
const isQueryForNoMessages = (limit: number) => limit === 0;
|
|
117
|
+
|
|
118
|
+
/** Query shapes are cursors within one list (the sort cannot change), so a change never resets it. */
|
|
110
119
|
const hasPaginationQueryShapeChanged: PaginationQueryShapeChangeIdentifier<
|
|
111
120
|
MessageQueryShape
|
|
112
121
|
> = () => false;
|
|
@@ -116,16 +125,10 @@ const dataFieldFilterResolver: FieldToDataResolver<LocalMessage> = {
|
|
|
116
125
|
resolve: (message, path) => resolveDotPathValue(message, path),
|
|
117
126
|
};
|
|
118
127
|
|
|
119
|
-
/**
|
|
120
|
-
* A message's `created_at` as the comparable wire timestamp (unix nanoseconds), or `null` when it
|
|
121
|
-
* is absent or not a finite number.
|
|
122
|
-
*
|
|
123
|
-
* Accepts `null`/`undefined` so callers holding an optional message (e.g.
|
|
124
|
-
* `MessagePaginator.lastMessage`) do not each repeat the guard.
|
|
125
|
-
*/
|
|
128
|
+
/** A message's `created_at` (unix nanoseconds), or `null` when absent or not finite. */
|
|
126
129
|
export const getMessageCreatedAtTimestamp = (
|
|
127
130
|
message: LocalMessage | null | undefined,
|
|
128
|
-
):
|
|
131
|
+
): TimestampNS | null => {
|
|
129
132
|
const timestamp = message?.created_at;
|
|
130
133
|
return typeof timestamp === 'number' && Number.isFinite(timestamp) ? timestamp : null;
|
|
131
134
|
};
|
|
@@ -135,140 +138,189 @@ export type MessagePaginatorOptions = {
|
|
|
135
138
|
id?: string;
|
|
136
139
|
itemIndex?: ItemIndexApi<LocalMessage>;
|
|
137
140
|
parentMessageId?: string;
|
|
138
|
-
/**
|
|
139
|
-
* Sort passed to backend message/replies query.
|
|
140
|
-
* Does not affect in-memory item ordering.
|
|
141
|
-
*/
|
|
141
|
+
/** Sort sent to the backend messages/replies query. Does not affect in-memory ordering. */
|
|
142
142
|
requestSort?: MessagePaginatorSort;
|
|
143
143
|
/**
|
|
144
144
|
* @deprecated Use `requestSort` instead.
|
|
145
145
|
*/
|
|
146
146
|
sort?: MessagePaginatorSort;
|
|
147
|
-
/**
|
|
148
|
-
* In-memory ordering for items exposed by paginator state.
|
|
149
|
-
*/
|
|
147
|
+
/** In-memory ordering of the items exposed by paginator state. */
|
|
150
148
|
itemOrder?: MessagePaginatorSort;
|
|
149
|
+
/** The thread whose replies this paginator lists; without it, it lists the channel's messages. */
|
|
150
|
+
thread?: Thread;
|
|
151
151
|
paginatorOptions?: PaginatorOptions<LocalMessage, MessageQueryShape>;
|
|
152
152
|
};
|
|
153
153
|
|
|
154
154
|
/**
|
|
155
|
-
* Options for {@link MessageIntervalPaginator.
|
|
156
|
-
*
|
|
157
|
-
*
|
|
158
|
-
*
|
|
159
|
-
*
|
|
160
|
-
*
|
|
161
|
-
* newest / oldest message" are its bounds by `created_at`. With NO options, `mergeNewestPage` prunes
|
|
162
|
-
* any loaded message that falls WITHIN `page`'s `created_at` span but is absent from it —
|
|
163
|
-
* unconditionally safe (a message that arrived live during the caller's fetch is always strictly
|
|
164
|
-
* newer than `page`'s newest message, so it can never fall in that span). `candidateIds` widens the
|
|
165
|
-
* reconcilable window at the TOP edge; `requestedLimit` only tunes the `hasMoreTail` affordance and
|
|
166
|
-
* can never remove a message:
|
|
155
|
+
* Options for {@link MessageIntervalPaginator.reconcileNewestMessages} that enable reconciling
|
|
156
|
+
* messages hard-deleted while the client received no events (no event reaches other clients). With
|
|
157
|
+
* no options it prunes loaded messages inside `page`'s `created_at` span that are absent from it,
|
|
158
|
+
* which is always safe: a live arrival is newer than `page`'s newest message.
|
|
159
|
+
* `headIntervalItemIdsAtRequest` widens reconciliation at the top edge; `requestedLimit` says
|
|
160
|
+
* whether the page reached the channel start.
|
|
167
161
|
*/
|
|
168
|
-
export type
|
|
162
|
+
export type ReconcileNewestMessagesOptions = {
|
|
169
163
|
/**
|
|
170
|
-
* The `limit` the caller passed to the query that produced `page`.
|
|
171
|
-
*
|
|
172
|
-
*
|
|
173
|
-
*
|
|
174
|
-
*
|
|
175
|
-
* {@link MessageIntervalPaginator.
|
|
176
|
-
*
|
|
177
|
-
*
|
|
178
|
-
* start.
|
|
164
|
+
* The `limit` the caller passed to the query that produced `page`. Compared to `page.length`, it
|
|
165
|
+
* says whether `page` reached the channel start (see
|
|
166
|
+
* {@link MessageIntervalPaginator.pageReachedChannelStart}, which ignores a limit above
|
|
167
|
+
* `pageSize`), deciding `hasMoreTail`, whether `page` can be separated from the head interval by
|
|
168
|
+
* a gap, and whether a reload asks the server about messages deleted below the page (see
|
|
169
|
+
* {@link MessageIntervalPaginator.removeIdsTailwardOfPageIfNothingOlder}). On its own it never
|
|
170
|
+
* removes a message. Pass the limit actually sent: a larger one makes a short page look like the
|
|
171
|
+
* channel start, welding it to the head interval across a real gap.
|
|
179
172
|
*/
|
|
180
173
|
requestedLimit?: number;
|
|
181
174
|
/**
|
|
182
|
-
*
|
|
183
|
-
*
|
|
184
|
-
*
|
|
185
|
-
*
|
|
186
|
-
*
|
|
187
|
-
*
|
|
175
|
+
* The IDs of the head interval's server-confirmed items when the request for `page` went out,
|
|
176
|
+
* taken with {@link MessageIntervalPaginator.getHeadIntervalItemIdsAtRequest} before the request
|
|
177
|
+
* is awaited. Only these prove what `page` says about the head interval:
|
|
178
|
+
*
|
|
179
|
+
* - deletion: at or above `page`'s newest message, and for an empty `page`, only this snapshot
|
|
180
|
+
* tells a just-deleted message from one that arrived live, or was sent, during the request;
|
|
181
|
+
* - contiguity: `page` starts inside the head interval only if its oldest message the head
|
|
182
|
+
* interval could hold is in this snapshot (see `isSeparatedFromHeadByGap`).
|
|
183
|
+
*
|
|
184
|
+
* Only the head interval receives live messages, so only its IDs are needed.
|
|
188
185
|
*/
|
|
189
|
-
|
|
186
|
+
headIntervalItemIdsAtRequest?: ReadonlySet<string>;
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
/** An external query prepared by {@link MessageIntervalPaginator.prepareExternalQuery}. */
|
|
190
|
+
export type PreparedExternalQuery = {
|
|
191
|
+
messagePaginationParams: MessagePaginationParams;
|
|
192
|
+
isNewestPage: boolean;
|
|
193
|
+
placePage: (page: LocalMessage[]) => boolean;
|
|
190
194
|
};
|
|
191
195
|
|
|
192
196
|
/**
|
|
193
|
-
*
|
|
197
|
+
* What one of the message paginator's own queries got back, before its page is extracted (see
|
|
198
|
+
* {@link MessageIntervalPaginator.fetchQueryResponse}), by where it came from.
|
|
194
199
|
*/
|
|
195
|
-
export type
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
};
|
|
200
|
+
export type MessageQueryResponse =
|
|
201
|
+
| {
|
|
202
|
+
/** what a custom `doRequest` returned: the page, used as is */
|
|
203
|
+
doRequestResponse: DoRequestResponse<LocalMessage>;
|
|
204
|
+
source: 'doRequest';
|
|
205
|
+
}
|
|
206
|
+
| {
|
|
207
|
+
/** the replies endpoint's response for a thread's reply list */
|
|
208
|
+
repliesResponse: GetRepliesResponse;
|
|
209
|
+
source: 'replies';
|
|
210
|
+
}
|
|
211
|
+
| {
|
|
212
|
+
/** the response of a channel query: its messages, and the rest, applied once they are placed */
|
|
213
|
+
channelResponse: StreamResponse<ChannelStateResponse>;
|
|
214
|
+
source: 'channel';
|
|
215
|
+
/** whether the query watched the channel, which applying the response records */
|
|
216
|
+
watch: boolean;
|
|
217
|
+
};
|
|
213
218
|
|
|
214
219
|
/**
|
|
215
|
-
*
|
|
216
|
-
*
|
|
220
|
+
* A message list with a configurable backend request sort and a stable in-memory item order.
|
|
221
|
+
* Ingested items are filtered only by local predicates (`filterQueryResults`).
|
|
217
222
|
*/
|
|
218
223
|
export class MessageIntervalPaginator extends BasePaginator<
|
|
219
224
|
LocalMessage,
|
|
220
|
-
MessageQueryShape
|
|
225
|
+
MessageQueryShape,
|
|
226
|
+
MessageQueryResponse
|
|
221
227
|
> {
|
|
228
|
+
/**
|
|
229
|
+
* Holder name of this list's index in the message store. A getter, so a subclass's value is in
|
|
230
|
+
* place while the base constructor builds the index.
|
|
231
|
+
*/
|
|
232
|
+
protected get holderName() {
|
|
233
|
+
return 'message-interval-paginator';
|
|
234
|
+
}
|
|
235
|
+
|
|
222
236
|
declare state: StateStore<MessagePaginatorState>;
|
|
223
237
|
private readonly _id: string;
|
|
224
|
-
|
|
225
|
-
|
|
238
|
+
/** The channel this list belongs to. A thread's reply list holds its parent channel. */
|
|
239
|
+
readonly channel: Channel;
|
|
240
|
+
/** See {@link MessagePaginatorOptions.thread}. */
|
|
241
|
+
readonly thread?: Thread;
|
|
242
|
+
/** Set when this is a thread's reply list, to the parent message's ID. */
|
|
243
|
+
readonly parentMessageId?: string;
|
|
226
244
|
readonly messageFocusSignal: StateStore<MessageFocusSignalState>;
|
|
227
245
|
private clearMessageFocusSignalTimeoutId: ReturnType<typeof setTimeout> | null = null;
|
|
228
246
|
private messageFocusSignalToken = 0;
|
|
229
247
|
protected _requestSort = DEFAULT_BACKEND_SORT;
|
|
230
248
|
protected _itemOrder: MessagePaginatorSort = DEFAULT_BACKEND_SORT;
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
249
|
+
/** The pending {@link removeIdsTailwardOfPageIfNothingOlder} (kept so tests can await it). */
|
|
250
|
+
private _pendingTailwardOfPageRemoval?: Promise<void>;
|
|
251
|
+
/**
|
|
252
|
+
* The ID of the newest server-confirmed message of the interval whose head mark was cleared last
|
|
253
|
+
* (see {@link unmarkedHeadInterval}). Forgotten once a newest page is reconciled with no head
|
|
254
|
+
* interval loaded, and when the loaded intervals are cleared.
|
|
255
|
+
*/
|
|
256
|
+
private unmarkedHeadEdgeId: string | undefined;
|
|
234
257
|
sortComparator: (a: LocalMessage, b: LocalMessage) => number;
|
|
235
258
|
/**
|
|
236
|
-
*
|
|
237
|
-
*
|
|
259
|
+
* Whether a message belongs in intervals and state. Keep it consistent with `filterQueryResults`
|
|
260
|
+
* and with the page the linear cursor flag derivation reads (see {@link deriveCursorFromPage}).
|
|
238
261
|
*/
|
|
239
262
|
shouldIncludeMessageInInterval(message: LocalMessage): boolean {
|
|
240
263
|
return !message.shadowed;
|
|
241
264
|
}
|
|
242
265
|
|
|
243
266
|
/**
|
|
244
|
-
*
|
|
245
|
-
*
|
|
246
|
-
*
|
|
247
|
-
*
|
|
248
|
-
*
|
|
267
|
+
* Reconciles the held messages that changed in the entity store.
|
|
268
|
+
*
|
|
269
|
+
* @internal
|
|
270
|
+
* @param batch - The change batch from the store.
|
|
271
|
+
* @param batch.changedIds - IDs of the watched messages that changed.
|
|
249
272
|
*/
|
|
250
273
|
onEntitiesChanged({ changedIds }: EntityStoreChangeBatch): void {
|
|
251
274
|
this.reconcileChangedIds(changedIds);
|
|
252
275
|
}
|
|
253
276
|
|
|
254
277
|
/**
|
|
255
|
-
*
|
|
256
|
-
*
|
|
257
|
-
*
|
|
278
|
+
* Drops a message from this paginator's intervals after the entity store removed it.
|
|
279
|
+
*
|
|
280
|
+
* @internal
|
|
281
|
+
* @param id - ID of the removed message.
|
|
282
|
+
* @param message - The removed message.
|
|
258
283
|
*/
|
|
284
|
+
onEntityRemoved(id: string, message: unknown): void {
|
|
285
|
+
this.removeItem({ id, item: message as LocalMessage });
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** Entity-store subscriber flush after an optimistic (local-user) write: skips the throttle. */
|
|
259
289
|
flushState(): void {
|
|
260
290
|
this.flushPendingPublishes();
|
|
261
291
|
}
|
|
262
292
|
|
|
293
|
+
/** UI-driven "hold off on pruning" signal ({@link setPruningSuspended}). Off by default. */
|
|
294
|
+
protected get isPruningSuspended(): boolean {
|
|
295
|
+
return this._pruningSuspended;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
private _pruningSuspended = false;
|
|
299
|
+
|
|
300
|
+
/**
|
|
301
|
+
* Holds off dropping the oldest loaded messages, so pruning does not pull content from under a user
|
|
302
|
+
* reading near them: the interval may grow past `maxLoadedItems` until they scroll back. A plain
|
|
303
|
+
* field, not a `StateStore`: nothing observes it and a scroll-driven signal must not cost a render.
|
|
304
|
+
*/
|
|
305
|
+
setPruningSuspended = (suspended: boolean) => {
|
|
306
|
+
this._pruningSuspended = suspended;
|
|
307
|
+
};
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* A message anchors pagination once the server has acknowledged it. This keeps an unsent message
|
|
311
|
+
* out of both halves of a prune and stops its ID from becoming the tailward cursor (`id_lt`).
|
|
312
|
+
*/
|
|
313
|
+
protected isPaginationAnchorable(item: LocalMessage | undefined): boolean {
|
|
314
|
+
return !!item && this.isServerConfirmedMessage(item);
|
|
315
|
+
}
|
|
316
|
+
|
|
263
317
|
protected get intervalItemIdsAreHeadFirst(): boolean {
|
|
264
|
-
//
|
|
265
|
-
// Pagination "head" (newest side) is therefore at the END of the `itemIds` array.
|
|
318
|
+
// Intervals hold messages in `created_at` ascending order: the head (newest) is at the END.
|
|
266
319
|
return false;
|
|
267
320
|
}
|
|
268
321
|
|
|
269
322
|
protected get intervalSortDirection(): 'asc' | 'desc' {
|
|
270
|
-
//
|
|
271
|
-
// should come first => reverse interval ordering.
|
|
323
|
+
// `itemOrderComparator` is `created_at` ascending but newer head edges must come first.
|
|
272
324
|
return 'desc';
|
|
273
325
|
}
|
|
274
326
|
|
|
@@ -282,6 +334,7 @@ export class MessageIntervalPaginator extends BasePaginator<
|
|
|
282
334
|
sort,
|
|
283
335
|
itemOrder,
|
|
284
336
|
paginatorOptions,
|
|
337
|
+
thread,
|
|
285
338
|
}: MessagePaginatorOptions,
|
|
286
339
|
builtInDefaults: Partial<BasePaginatorConfig<LocalMessage, MessageQueryShape>> = {},
|
|
287
340
|
) {
|
|
@@ -291,12 +344,9 @@ export class MessageIntervalPaginator extends BasePaginator<
|
|
|
291
344
|
{
|
|
292
345
|
itemIndex,
|
|
293
346
|
...paginatorOptions,
|
|
294
|
-
//
|
|
295
|
-
//
|
|
296
|
-
//
|
|
297
|
-
// sync. When the store is unavailable (e.g. a detached paginator in a test) the index falls
|
|
298
|
-
// back to a private store and behaves exactly like a plain per-instance index. Overridable per
|
|
299
|
-
// instance via `paginatorOptions.createItemIndex` or an explicit `itemIndex`.
|
|
347
|
+
// Backed by the client's message store: a message held in several lists has one canonical
|
|
348
|
+
// copy and updates fan out to all holders. Without a store (e.g. a detached paginator in a
|
|
349
|
+
// test) the index is private. Overridable via `paginatorOptions.createItemIndex`/`itemIndex`.
|
|
300
350
|
createItemIndex:
|
|
301
351
|
paginatorOptions?.createItemIndex ??
|
|
302
352
|
((owner) =>
|
|
@@ -304,11 +354,10 @@ export class MessageIntervalPaginator extends BasePaginator<
|
|
|
304
354
|
store: channel.getClient?.().messageStore,
|
|
305
355
|
owner: owner as MessageIntervalPaginator,
|
|
306
356
|
getEntityId: owner.getItemId.bind(owner),
|
|
357
|
+
holderName: (owner as MessageIntervalPaginator).holderName,
|
|
307
358
|
})),
|
|
308
359
|
},
|
|
309
|
-
// SDK
|
|
310
|
-
// and the zero cursor were previously spread into the caller's options, where they outranked
|
|
311
|
-
// every `client.config.set({ messagePaginator: … })`.
|
|
360
|
+
// SDK defaults: a declarative registration (`client.config.set({ messagePaginator })`) wins.
|
|
312
361
|
{
|
|
313
362
|
hasPaginationQueryShapeChanged,
|
|
314
363
|
initialCursor: ZERO_PAGE_CURSOR,
|
|
@@ -317,6 +366,7 @@ export class MessageIntervalPaginator extends BasePaginator<
|
|
|
317
366
|
},
|
|
318
367
|
);
|
|
319
368
|
this.channel = channel;
|
|
369
|
+
this.thread = thread;
|
|
320
370
|
this.parentMessageId = parentMessageId;
|
|
321
371
|
this._id = id ?? `message-paginator-${generateUUIDv4()}`;
|
|
322
372
|
this._requestSort = resolvedRequestSort;
|
|
@@ -338,12 +388,8 @@ export class MessageIntervalPaginator extends BasePaginator<
|
|
|
338
388
|
}
|
|
339
389
|
|
|
340
390
|
/**
|
|
341
|
-
* Memoized
|
|
342
|
-
*
|
|
343
|
-
* are stable.
|
|
344
|
-
*
|
|
345
|
-
* Safe to build once: both close over `this` and read `_itemOrder`, which is assigned in the
|
|
346
|
-
* constructor and has no setter.
|
|
391
|
+
* Memoized: `initializeConfig` folds it in and skips the publish when nothing moved, which needs
|
|
392
|
+
* stable references. Safe to build once: `_itemOrder` is set in the constructor, with no setter.
|
|
347
393
|
*/
|
|
348
394
|
private intervalBehaviour?: Partial<
|
|
349
395
|
BasePaginatorConfig<LocalMessage, MessageQueryShape>
|
|
@@ -354,7 +400,7 @@ export class MessageIntervalPaginator extends BasePaginator<
|
|
|
354
400
|
> {
|
|
355
401
|
if (!this.intervalBehaviour) {
|
|
356
402
|
this.intervalBehaviour = {
|
|
357
|
-
deriveCursor:
|
|
403
|
+
deriveCursor: (ctx) => this.deriveCursorFromPage(ctx),
|
|
358
404
|
itemOrderComparator: makeComparator<LocalMessage>({
|
|
359
405
|
sort: this._itemOrder,
|
|
360
406
|
resolvePathValue: resolveDotPathValue,
|
|
@@ -370,12 +416,8 @@ export class MessageIntervalPaginator extends BasePaginator<
|
|
|
370
416
|
}
|
|
371
417
|
|
|
372
418
|
/**
|
|
373
|
-
*
|
|
374
|
-
*
|
|
375
|
-
*
|
|
376
|
-
* Contributed to the base derivation rather than written after it — see
|
|
377
|
-
* {@link BasePaginator.getBehaviourOverrides}. That is what keeps one re-derivation to one publish,
|
|
378
|
-
* and stops the intermediate publish that had these two stripped.
|
|
419
|
+
* Installs cursor derivation and item ordering on `config` through the base derivation
|
|
420
|
+
* ({@link BasePaginator.getBehaviourOverrides}), so one re-derivation is one publish.
|
|
379
421
|
*/
|
|
380
422
|
protected override getBehaviourOverrides(): Partial<
|
|
381
423
|
BasePaginatorConfig<LocalMessage, MessageQueryShape>
|
|
@@ -384,9 +426,8 @@ export class MessageIntervalPaginator extends BasePaginator<
|
|
|
384
426
|
}
|
|
385
427
|
|
|
386
428
|
/**
|
|
387
|
-
* The constructor's route to the same overlay.
|
|
388
|
-
*
|
|
389
|
-
* own fields were initialized.
|
|
429
|
+
* The constructor's route to the same overlay. It calls the private builder, not the overridable
|
|
430
|
+
* hook, which would run a subclass override before its fields are initialized.
|
|
390
431
|
*/
|
|
391
432
|
protected installIntervalBehaviour(): void {
|
|
392
433
|
this.updateConfig(this.buildIntervalBehaviour());
|
|
@@ -408,25 +449,23 @@ export class MessageIntervalPaginator extends BasePaginator<
|
|
|
408
449
|
return this._itemOrder ?? this._requestSort ?? DEFAULT_BACKEND_SORT;
|
|
409
450
|
}
|
|
410
451
|
|
|
411
|
-
/**
|
|
412
|
-
* Even though we do not send filters object to the server, we need to have filters for client-side item ingestion logic.
|
|
413
|
-
*/
|
|
452
|
+
/** Not sent to the server: drives client-side item ingestion. */
|
|
414
453
|
buildMatchFilters = (): MessagePaginatorFilter => ({
|
|
415
454
|
cid: this.channel.cid,
|
|
416
455
|
...(this.parentMessageId ? { parent_id: this.parentMessageId } : {}),
|
|
417
456
|
});
|
|
418
457
|
|
|
419
|
-
// invoked inside BasePaginator.executeQuery() to keep it as a query descriptor;
|
|
420
458
|
protected getNextQueryShape({
|
|
421
459
|
direction,
|
|
422
460
|
}: Omit<
|
|
423
461
|
PaginationQueryParams<MessageQueryShape>,
|
|
424
462
|
'isFirstPageQuery'
|
|
425
463
|
>): MessageQueryShape {
|
|
464
|
+
// no server-known message at that edge: no cursor, so the query returns the newest page
|
|
465
|
+
const cursorId = direction ? this.cursor?.[direction] : undefined;
|
|
426
466
|
return {
|
|
427
467
|
limit: this.pageSize,
|
|
428
|
-
[direction === 'tailward' ? 'id_lt' : 'id_gt']:
|
|
429
|
-
direction && this.cursor?.[direction],
|
|
468
|
+
...(cursorId && { [direction === 'tailward' ? 'id_lt' : 'id_gt']: cursorId }),
|
|
430
469
|
};
|
|
431
470
|
}
|
|
432
471
|
|
|
@@ -437,131 +476,334 @@ export class MessageIntervalPaginator extends BasePaginator<
|
|
|
437
476
|
direction?: PaginationDirection;
|
|
438
477
|
items: LocalMessage[];
|
|
439
478
|
}) => {
|
|
440
|
-
|
|
479
|
+
// Newer side is the pagination head for messages.
|
|
480
|
+
const { head, tail } = this.getPagePaginationEdges(items);
|
|
481
|
+
if (!head || !tail) {
|
|
441
482
|
return {
|
|
442
483
|
tailward: undefined,
|
|
443
484
|
headward: undefined,
|
|
444
485
|
};
|
|
445
486
|
}
|
|
446
487
|
|
|
447
|
-
|
|
448
|
-
const end = items[items.length - 1];
|
|
449
|
-
|
|
450
|
-
// Newer side is the pagination head for messages. Which bound is considered "head"
|
|
451
|
-
// is determined by intervalItemIdsAreHeadFirst (see BasePaginator.getIntervalPaginationEdges).
|
|
452
|
-
const head = this.intervalItemIdsAreHeadFirst ? start : end;
|
|
453
|
-
const tail = this.intervalItemIdsAreHeadFirst ? end : start;
|
|
454
|
-
|
|
455
|
-
// if there is no direction, then we are jumping, and we want to set both directions in the cursor
|
|
488
|
+
// Without a direction this is a jump: set both cursors.
|
|
456
489
|
return {
|
|
457
490
|
tailward: !direction || direction === 'tailward' ? this.getItemId(tail) : undefined,
|
|
458
491
|
headward: !direction || direction === 'headward' ? this.getItemId(head) : undefined,
|
|
459
492
|
};
|
|
460
493
|
};
|
|
461
494
|
|
|
462
|
-
|
|
495
|
+
/**
|
|
496
|
+
* Runs the query pipeline (see `BasePaginator.executeQuery`). A query that goes to the channel —
|
|
497
|
+
* not a thread's reply list, not a custom `doRequest` — runs as a tracked query of the channel
|
|
498
|
+
* (`Channel.runTrackedQuery`), so the channel store keeps the channel until the query ends. A
|
|
499
|
+
* disposed channel's query is not tracked: its fetch step is refused, and fails as any failed
|
|
500
|
+
* request does.
|
|
501
|
+
*/
|
|
502
|
+
override executeQuery(
|
|
503
|
+
params: PaginationQueryParams<MessageQueryShape> = {},
|
|
504
|
+
): Promise<ExecuteQueryReturnValue<LocalMessage> | void> {
|
|
505
|
+
const queriesChannel =
|
|
506
|
+
!this.parentMessageId && !this.config.doRequest && !this.channel.pendingDisposal;
|
|
507
|
+
if (!queriesChannel) return super.executeQuery(params);
|
|
508
|
+
return this.channel.runTrackedQuery(() => super.executeQuery(params));
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
/**
|
|
512
|
+
* The fetching step of the query pipeline: requests a page through a custom `doRequest`, the
|
|
513
|
+
* replies endpoint for a thread's reply list, or the channel query otherwise, which takes in what
|
|
514
|
+
* the response says about the channel itself and leaves the rest for the last step (see
|
|
515
|
+
* `Channel.requestChannelState`). Reads `requestOptions.watch`: `true` also watches the channel
|
|
516
|
+
* with the request. Ignored for a thread's reply list and with `doRequest`.
|
|
517
|
+
*/
|
|
518
|
+
protected override fetchQueryResponse = async ({
|
|
463
519
|
direction,
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
> => {
|
|
467
|
-
|
|
468
|
-
if (!this._nextQueryShape) {
|
|
469
|
-
this._nextQueryShape = this.getNextQueryShape({ direction });
|
|
470
|
-
}
|
|
520
|
+
queryShape,
|
|
521
|
+
requestOptions,
|
|
522
|
+
}: PaginationQueryParams<MessageQueryShape>): Promise<MessageQueryResponse> => {
|
|
523
|
+
const options = queryShape ?? this.getNextQueryShape({ direction });
|
|
471
524
|
|
|
472
|
-
const options = this._nextQueryShape;
|
|
473
|
-
let items: LocalMessage[];
|
|
474
|
-
let tailward: string | undefined;
|
|
475
|
-
let headward: string | undefined;
|
|
476
525
|
if (this.config.doRequest) {
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
!direction || direction === 'tailward'
|
|
482
|
-
? (result.cursor?.tailward ?? undefined)
|
|
483
|
-
: undefined;
|
|
484
|
-
headward =
|
|
485
|
-
!direction || direction === 'headward'
|
|
486
|
-
? (result.cursor?.headward ?? undefined)
|
|
487
|
-
: undefined;
|
|
488
|
-
} else {
|
|
489
|
-
const { messages } = this.parentMessageId
|
|
490
|
-
? await this.channel.getClient().getReplies({
|
|
491
|
-
parent_id: this.parentMessageId,
|
|
492
|
-
...options,
|
|
493
|
-
sort: this.requestSort,
|
|
494
|
-
})
|
|
495
|
-
: await this.channel.query({
|
|
496
|
-
messages: options as MessagePaginationParams,
|
|
497
|
-
// todo: why do we query for watchers?
|
|
498
|
-
// watchers: { limit: this.pageSize },
|
|
499
|
-
});
|
|
500
|
-
items = this.getCanonicalQueryItems(messages.map(formatMessage));
|
|
501
|
-
const cursor = this.getCursorFromQueryResults({ direction, items });
|
|
502
|
-
tailward = cursor.tailward;
|
|
503
|
-
headward = cursor.headward;
|
|
526
|
+
return {
|
|
527
|
+
doRequestResponse: await this.config.doRequest(options),
|
|
528
|
+
source: 'doRequest',
|
|
529
|
+
};
|
|
504
530
|
}
|
|
505
|
-
|
|
506
|
-
|
|
531
|
+
if (this.parentMessageId) {
|
|
532
|
+
const repliesResponse = await this.channel
|
|
533
|
+
.getClient()
|
|
534
|
+
.getReplies(
|
|
535
|
+
{ parent_id: this.parentMessageId },
|
|
536
|
+
{ ...options, sort: this.getRepliesRequestSort(options) },
|
|
537
|
+
);
|
|
538
|
+
return { repliesResponse, source: 'replies' };
|
|
539
|
+
}
|
|
540
|
+
const watch = requestOptions?.watch === true;
|
|
541
|
+
const channelResponse = await this.channel.requestChannelState(
|
|
542
|
+
{
|
|
543
|
+
messages: options as MessagePaginationParams,
|
|
544
|
+
...(watch && { watch: true }),
|
|
545
|
+
// todo: why do we query for watchers?
|
|
546
|
+
// watchers: { limit: this.pageSize },
|
|
547
|
+
},
|
|
548
|
+
undefined,
|
|
549
|
+
);
|
|
550
|
+
return { channelResponse, source: 'channel', watch };
|
|
507
551
|
};
|
|
508
552
|
|
|
509
553
|
/**
|
|
510
|
-
*
|
|
511
|
-
* `
|
|
554
|
+
* The extracting step of the query pipeline: the messages in item order and their cursors, which
|
|
555
|
+
* a custom `doRequest` reports and which are derived from the messages otherwise.
|
|
556
|
+
*/
|
|
557
|
+
protected override extractQueryPage(
|
|
558
|
+
response: MessageQueryResponse,
|
|
559
|
+
{ direction }: PaginationQueryParams<MessageQueryShape>,
|
|
560
|
+
): PaginationQueryReturnValue<LocalMessage> {
|
|
561
|
+
if (response.source === 'doRequest') {
|
|
562
|
+
const { cursor, items } = response.doRequestResponse;
|
|
563
|
+
// Without a direction this is a jump: set both cursors.
|
|
564
|
+
return {
|
|
565
|
+
headward: !direction || direction === 'headward' ? cursor?.headward : undefined,
|
|
566
|
+
items: this.getCanonicalQueryItems(items),
|
|
567
|
+
tailward: !direction || direction === 'tailward' ? cursor?.tailward : undefined,
|
|
568
|
+
};
|
|
569
|
+
}
|
|
570
|
+
const messages =
|
|
571
|
+
response.source === 'replies'
|
|
572
|
+
? response.repliesResponse.messages
|
|
573
|
+
: (response.channelResponse.messages ?? []);
|
|
574
|
+
const items = this.getCanonicalQueryItems(messages.map(formatMessage));
|
|
575
|
+
return { items, ...this.getCursorFromQueryResults({ direction, items }) };
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
/**
|
|
579
|
+
* The last step of the query pipeline: the rest of a channel query's response, applied once its
|
|
580
|
+
* page is placed (see `Channel.applyChannelStateFromResponse`). The other sources return nothing
|
|
581
|
+
* else.
|
|
582
|
+
*/
|
|
583
|
+
protected override applyQueryResponseRest(
|
|
584
|
+
response: MessageQueryResponse,
|
|
585
|
+
_placeParams: QueryPagePlacement<MessageQueryShape>,
|
|
586
|
+
) {
|
|
587
|
+
if (response.source === 'channel') {
|
|
588
|
+
// Not the latest message set the offline database stores: `watch()` and the channel list
|
|
589
|
+
// store that.
|
|
590
|
+
this.channel.applyChannelStateFromResponse(response.channelResponse, {
|
|
591
|
+
isLatestMessageSet: false,
|
|
592
|
+
watch: response.watch,
|
|
593
|
+
});
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
/**
|
|
598
|
+
* Whether this paginator is active: the thread it lists is active (see `Thread.activate()`), or,
|
|
599
|
+
* without a thread, its channel is (see `Channel.activate()`). A page from a query an active
|
|
600
|
+
* paginator did not run leaves its active interval active; an inactive paginator shows a fresh
|
|
601
|
+
* newest page instead, also one separated from the loaded messages by a gap (see
|
|
602
|
+
* {@link reconcileNewestMessages}).
|
|
603
|
+
*/
|
|
604
|
+
private isActivePaginator(): boolean {
|
|
605
|
+
return (this.thread ?? this.channel).active;
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
/**
|
|
609
|
+
* Places a page from an external query — one this paginator did not run, whose page the caller
|
|
610
|
+
* chose — in the intervals it belongs to, never removing anything loaded. Bringing the loaded
|
|
611
|
+
* newest messages up to date with a fresh newest page, removals included, is
|
|
612
|
+
* {@link reconcileNewestMessages}'s job instead.
|
|
613
|
+
*
|
|
614
|
+
* External queries are a channel query (`watch()`, see {@link prepareExternalQuery}), the
|
|
615
|
+
* channel list's query (`client.hydrateChannels`), and the channel state the pinned list's first
|
|
616
|
+
* page comes with. `messagePaginationParams` are the
|
|
617
|
+
* options the page was queried with; they decide where it goes:
|
|
618
|
+
*
|
|
619
|
+
* - The newest page: when no interval is active yet (nothing loaded, or only live messages), its
|
|
620
|
+
* interval becomes the active one, as the channel's first page. When the active interval is the
|
|
621
|
+
* newest interval, the page lands in it.
|
|
622
|
+
* - Any other page — a page at a cursor or around a message, or the newest page while an older
|
|
623
|
+
* interval is active — is only stored, as a separate interval merged only with an interval it
|
|
624
|
+
* overlaps.
|
|
625
|
+
*
|
|
626
|
+
* The active interval stays active: changing it is this paginator's own methods' job
|
|
627
|
+
* (`jumpToMessage()` and the like). The exception is an inactive paginator (see
|
|
628
|
+
* {@link isActivePaginator}), where the newest page is shown as when no interval is
|
|
629
|
+
* active. A newest
|
|
630
|
+
* page for loaded messages goes to {@link reconcileNewestMessages} instead
|
|
631
|
+
* (`prepareExternalQuery`, the channel list's query). When a page lands in the active interval,
|
|
632
|
+
* overlaps it, or takes in an active interval of live messages only, that interval is shown again
|
|
633
|
+
* with the page. The paginator's own queries are left alone too: a running one keeps its loading
|
|
634
|
+
* flag, and its last query error and query shape stay.
|
|
512
635
|
*
|
|
513
|
-
*
|
|
514
|
-
*
|
|
515
|
-
*
|
|
516
|
-
* the `last_read_message_id` / `last_delivered_message_id`. `postQueryReconcile` is fully
|
|
517
|
-
* synchronous (filtering is a local predicate), so seeding here guarantees the paginator is
|
|
518
|
-
* populated before the reconcile runs. First-page reconciliation also takes the unread snapshot.
|
|
636
|
+
* It runs synchronously, so a caller can apply the rest of the response right after with the page
|
|
637
|
+
* in place, as it has to: read and delivery positions that come without a message id are looked
|
|
638
|
+
* up among the loaded messages.
|
|
519
639
|
*
|
|
520
|
-
*
|
|
521
|
-
* (`messages: { id_around }` / `{ created_at_around }`), so the original pagination options are
|
|
522
|
-
* threaded through as the query shape. For an around/jump open this lets `postQueryReconcile`
|
|
523
|
-
* apply jump semantics (no forced head/tail; cursor flags derived from the around position)
|
|
524
|
-
* instead of wrongly flagging the window as the head (newest) page.
|
|
640
|
+
* Returns whether it showed the page as a first page.
|
|
525
641
|
*/
|
|
526
|
-
|
|
527
|
-
|
|
642
|
+
placeExternalQueryPage(
|
|
643
|
+
page: LocalMessage[],
|
|
528
644
|
requestedPageSize: number,
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
) {
|
|
645
|
+
messagePaginationParams?: MessagePaginationParams,
|
|
646
|
+
): boolean {
|
|
532
647
|
const queryShape: MessageQueryShape = {
|
|
533
|
-
...
|
|
648
|
+
...messagePaginationParams,
|
|
534
649
|
limit: requestedPageSize,
|
|
535
650
|
};
|
|
536
651
|
const isJump = this.isJumpQueryShape(queryShape);
|
|
652
|
+
const isNewestPage = this.isHeadPageQueryShape(queryShape);
|
|
653
|
+
// In item order, as `extractQueryPage()` hands its pages over, so the page's edges are its
|
|
654
|
+
// first and last item.
|
|
655
|
+
const items = this.getCanonicalQueryItems(page);
|
|
656
|
+
const { head: headItem, tail: tailItem } = this.getPagePaginationEdges(items);
|
|
657
|
+
// the first page of a list not loaded yet, or the newest page
|
|
658
|
+
const isFirstPage = typeof this.items === 'undefined' || isNewestPage;
|
|
659
|
+
const activeInterval = this.itemIntervals.find((interval) =>
|
|
660
|
+
this.isActiveInterval(interval),
|
|
661
|
+
);
|
|
662
|
+
// only live messages, with no page loaded yet, count as no active interval, as does any
|
|
663
|
+
// interval of an inactive paginator
|
|
664
|
+
const hasActiveInterval =
|
|
665
|
+
!!activeInterval && !isLogicalInterval(activeInterval) && this.isActivePaginator();
|
|
666
|
+
// The newest page lands in the active interval when that is the newest interval; any other page
|
|
667
|
+
// has no known place relative to the active interval, so it is stored as a separate interval.
|
|
668
|
+
const landsInActiveInterval = isNewestPage && this.isActiveIntervalAtHead;
|
|
669
|
+
const showsPage = isNewestPage && (!hasActiveInterval || landsInActiveInterval);
|
|
670
|
+
const placed = this.placePage(
|
|
671
|
+
{
|
|
672
|
+
startsSeparateInterval: !landsInActiveInterval,
|
|
673
|
+
// A jump/around page spans both directions; a page at a cursor pages the way its cursor
|
|
674
|
+
// points, and a plain latest page paginates tailward (older).
|
|
675
|
+
direction: isJump
|
|
676
|
+
? undefined
|
|
677
|
+
: (getLinearQueryDirection(queryShape) ?? 'tailward'),
|
|
678
|
+
isFirstPage,
|
|
679
|
+
queryShape,
|
|
680
|
+
requestedPageSize,
|
|
681
|
+
results: {
|
|
682
|
+
items,
|
|
683
|
+
headward: isJump ? headItem?.id : undefined,
|
|
684
|
+
tailward: tailItem?.id,
|
|
685
|
+
},
|
|
686
|
+
updateState: showsPage,
|
|
687
|
+
},
|
|
688
|
+
{ endsQuery: false },
|
|
689
|
+
);
|
|
690
|
+
// A stored page that took in a live-only active interval (only live messages, no page) carries
|
|
691
|
+
// on as the active interval: its live messages are still shown, with what the page added.
|
|
692
|
+
const tookInActiveInterval =
|
|
693
|
+
!!activeInterval &&
|
|
694
|
+
!this.itemIntervals.some((interval) => this.isActiveInterval(interval));
|
|
695
|
+
const intervalTakingOver = tookInActiveInterval ? placed.targetInterval : null;
|
|
696
|
+
if (intervalTakingOver) {
|
|
697
|
+
this.setActiveInterval(intervalTakingOver, { updateState: false });
|
|
698
|
+
// placing did not publish it: the interval it took in becomes the active one only here
|
|
699
|
+
const { cursor, hasMoreHead, hasMoreTail } = placed.stateCandidate;
|
|
700
|
+
this.publishActiveInterval({ cursor, hasMoreHead, hasMoreTail });
|
|
701
|
+
}
|
|
702
|
+
if (showsPage) {
|
|
703
|
+
// shown without a query of this paginator, so its next query has to continue this interval
|
|
704
|
+
this.recordLoadedIntervalQueryShape();
|
|
705
|
+
}
|
|
706
|
+
return showsPage && isFirstPage;
|
|
707
|
+
}
|
|
537
708
|
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
709
|
+
/**
|
|
710
|
+
* Whether messages are loaded for {@link reconcileNewestMessages} to bring up to date. A list
|
|
711
|
+
* loaded empty has none (no interval, not even live messages), so a fresh newest page is placed
|
|
712
|
+
* as a first page instead ({@link placeExternalQueryPage}); reconciling would find nothing to
|
|
713
|
+
* merge it into and drop it.
|
|
714
|
+
*/
|
|
715
|
+
get canReconcileNewestMessages(): boolean {
|
|
716
|
+
return typeof this.items !== 'undefined' && this.itemIntervals.length > 0;
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
/**
|
|
720
|
+
* The snapshot a newest page is reconciled against (see
|
|
721
|
+
* {@link ReconcileNewestMessagesOptions.headIntervalItemIdsAtRequest}): the IDs of the head
|
|
722
|
+
* interval's server-confirmed messages. Take it right before the request goes out. Unsent messages
|
|
723
|
+
* are left out: one confirmed during the request proves neither that the page connects to the
|
|
724
|
+
* head interval nor, when the page lacks it, that it was deleted. `undefined` while no head
|
|
725
|
+
* interval is loaded.
|
|
726
|
+
*
|
|
727
|
+
* @internal
|
|
728
|
+
*/
|
|
729
|
+
getHeadIntervalItemIdsAtRequest(): ReadonlySet<string> | undefined {
|
|
730
|
+
const head = this.anchoredHeadInterval;
|
|
731
|
+
if (!head) return undefined;
|
|
732
|
+
return new Set(head.itemIds.filter((id) => this.isServerConfirmedItemId(id)));
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
/**
|
|
736
|
+
* Whether the loaded message with this ID is server-confirmed
|
|
737
|
+
* (see {@link isServerConfirmedMessage}).
|
|
738
|
+
*/
|
|
739
|
+
private isServerConfirmedItemId(id: string): boolean {
|
|
740
|
+
const message = this.getItem(id);
|
|
741
|
+
return !!message && this.isServerConfirmedMessage(message);
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
/**
|
|
745
|
+
* Prepares an external query for a page of these messages: the watch query the channel sends
|
|
746
|
+
* (`channel.watch()`, `channel.reload()`) with the `messages` options its caller gave. Call it
|
|
747
|
+
* before sending the query, and place the returned page with `placePage` before the response's
|
|
748
|
+
* read state is applied: the read state is resolved against the loaded messages.
|
|
749
|
+
*
|
|
750
|
+
* - `messagePaginationParams`: the options to send as the query's `messages`, with `limit` set to
|
|
751
|
+
* the page size when not given.
|
|
752
|
+
* - `isNewestPage`: whether the query asks for the newest page — no cursor, not around a message,
|
|
753
|
+
* and some messages.
|
|
754
|
+
* - `placePage`: places the returned page. The newest page goes to
|
|
755
|
+
* {@link placeExternalNewestPage}, reconciled against the messages loaded when the query was
|
|
756
|
+
* prepared; any other page is placed by {@link placeExternalQueryPage}. A query for no messages
|
|
757
|
+
* (`limit: 0`) places nothing. Returns whether it showed a first page.
|
|
758
|
+
*/
|
|
759
|
+
prepareExternalQuery(messages?: MessagePaginationParams): PreparedExternalQuery {
|
|
760
|
+
const messagePaginationParams: MessagePaginationParams = {
|
|
761
|
+
...messages,
|
|
762
|
+
limit: messages?.limit ?? this.pageSize,
|
|
763
|
+
};
|
|
764
|
+
const limit = messagePaginationParams.limit ?? this.pageSize;
|
|
765
|
+
if (isQueryForNoMessages(limit)) {
|
|
766
|
+
return { messagePaginationParams, isNewestPage: false, placePage: () => false };
|
|
551
767
|
}
|
|
552
768
|
|
|
553
|
-
this.
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
769
|
+
const isNewestPage = this.isHeadPageQueryShape(messagePaginationParams);
|
|
770
|
+
const headIntervalItemIdsAtRequest = isNewestPage
|
|
771
|
+
? this.getHeadIntervalItemIdsAtRequest()
|
|
772
|
+
: undefined;
|
|
773
|
+
return {
|
|
774
|
+
messagePaginationParams,
|
|
775
|
+
isNewestPage,
|
|
776
|
+
placePage: (page) =>
|
|
777
|
+
isNewestPage
|
|
778
|
+
? this.placeExternalNewestPage(page, {
|
|
779
|
+
headIntervalItemIdsAtRequest,
|
|
780
|
+
requestedLimit: limit,
|
|
781
|
+
})
|
|
782
|
+
: this.placeExternalQueryPage(page, limit, messagePaginationParams),
|
|
783
|
+
};
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
/**
|
|
787
|
+
* Places the newest page of an external query (a channel query, the channel list's query): it
|
|
788
|
+
* reconciles the loaded newest messages ({@link reconcileNewestMessages}), or is placed as a
|
|
789
|
+
* first page when none are loaded ({@link placeExternalQueryPage}). A query for no messages
|
|
790
|
+
* (`requestedLimit: 0`) places nothing. Returns whether it showed a first page.
|
|
791
|
+
*
|
|
792
|
+
* @internal
|
|
793
|
+
*/
|
|
794
|
+
placeExternalNewestPage(
|
|
795
|
+
page: LocalMessage[],
|
|
796
|
+
{
|
|
797
|
+
headIntervalItemIdsAtRequest,
|
|
798
|
+
requestedLimit,
|
|
799
|
+
}: ReconcileNewestMessagesOptions & { requestedLimit: number },
|
|
800
|
+
): boolean {
|
|
801
|
+
if (isQueryForNoMessages(requestedLimit)) return false;
|
|
802
|
+
if (!this.canReconcileNewestMessages) {
|
|
803
|
+
return this.placeExternalQueryPage(page, requestedLimit);
|
|
804
|
+
}
|
|
805
|
+
this.reconcileNewestMessages(page, { headIntervalItemIdsAtRequest, requestedLimit });
|
|
806
|
+
return false;
|
|
565
807
|
}
|
|
566
808
|
|
|
567
809
|
isJumpQueryShape(queryShape: MessageQueryShape): boolean {
|
|
@@ -571,6 +813,30 @@ export class MessageIntervalPaginator extends BasePaginator<
|
|
|
571
813
|
);
|
|
572
814
|
}
|
|
573
815
|
|
|
816
|
+
/** Only a query without a cursor and not around a message returns the newest page. */
|
|
817
|
+
protected override isHeadPageQueryShape(
|
|
818
|
+
queryShape: MessageQueryShape | undefined,
|
|
819
|
+
): boolean {
|
|
820
|
+
return (
|
|
821
|
+
!queryShape ||
|
|
822
|
+
(!this.isJumpQueryShape(queryShape) && !getLinearQueryDirection(queryShape))
|
|
823
|
+
);
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
/** A jump sends its own `limit`: head/tail flags are derived against it, not `pageSize`. */
|
|
827
|
+
protected override getRequestedPageSize(
|
|
828
|
+
queryShape: MessageQueryShape | undefined,
|
|
829
|
+
): number {
|
|
830
|
+
return queryShape && this.isJumpQueryShape(queryShape)
|
|
831
|
+
? (queryShape.limit ?? this.pageSize)
|
|
832
|
+
: this.pageSize;
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
/**
|
|
836
|
+
* Makes the interval holding the message the active one, querying the page around it when it is
|
|
837
|
+
* not loaded. Resolves `false` when the message cannot be shown, or when a later claim on the
|
|
838
|
+
* active interval (see `claimActiveInterval`) was made before the page arrived.
|
|
839
|
+
*/
|
|
574
840
|
jumpToMessage = async (
|
|
575
841
|
messageId: string,
|
|
576
842
|
{
|
|
@@ -578,11 +844,16 @@ export class MessageIntervalPaginator extends BasePaginator<
|
|
|
578
844
|
focusSignalTtlMs,
|
|
579
845
|
pageSize,
|
|
580
846
|
suppressFocusSignal,
|
|
847
|
+
watchChannel,
|
|
581
848
|
}: JumpToMessageOptions = {},
|
|
582
849
|
): Promise<boolean> => {
|
|
850
|
+
const watch =
|
|
851
|
+
!!watchChannel &&
|
|
852
|
+
!this.parentMessageId &&
|
|
853
|
+
!this.config.doRequest &&
|
|
854
|
+
this.channel.watchStatus !== ChannelWatchStatus.Watching;
|
|
583
855
|
let localMessage = this.getItem(messageId);
|
|
584
856
|
let interval: AnyInterval | undefined;
|
|
585
|
-
let state: Partial<PaginatorState<LocalMessage>> | undefined;
|
|
586
857
|
if (localMessage) {
|
|
587
858
|
interval = this.locateIntervalForItem(localMessage);
|
|
588
859
|
if (
|
|
@@ -590,11 +861,8 @@ export class MessageIntervalPaginator extends BasePaginator<
|
|
|
590
861
|
!isLogicalInterval(interval) &&
|
|
591
862
|
!interval.itemIds.includes(messageId)
|
|
592
863
|
) {
|
|
593
|
-
//
|
|
594
|
-
//
|
|
595
|
-
// grew across the target's position without merging). Prefer the interval that actually
|
|
596
|
-
// holds the id so the jump activates the window the message really lives in - otherwise, if
|
|
597
|
-
// the range-matched interval happens to be active, the jump becomes a no-op.
|
|
864
|
+
// The range match can return an interval that spans the target without holding it (a
|
|
865
|
+
// neighbour grew across its position): use the one that holds the ID, or the jump may no-op.
|
|
598
866
|
interval = this.itemIntervals.find(
|
|
599
867
|
(candidate) =>
|
|
600
868
|
!isLogicalInterval(candidate) && candidate.itemIds.includes(messageId),
|
|
@@ -602,18 +870,21 @@ export class MessageIntervalPaginator extends BasePaginator<
|
|
|
602
870
|
}
|
|
603
871
|
}
|
|
604
872
|
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
};
|
|
612
|
-
} else if (!localMessage || !interval || isLogicalInterval(interval)) {
|
|
873
|
+
// a loaded message needs no request, unless the jump is also to watch the channel
|
|
874
|
+
if (!watch && localMessage && interval && !isLogicalInterval(interval)) {
|
|
875
|
+
// showing a loaded interval claims the active interval, as a query for one does
|
|
876
|
+
this.claimActiveInterval();
|
|
877
|
+
this.showLoadedInterval(interval);
|
|
878
|
+
} else {
|
|
613
879
|
const result = await this.executeQuery({
|
|
614
|
-
|
|
880
|
+
claimsActiveInterval: true,
|
|
881
|
+
// Always send a limit: the replies endpoint ignores `id_around` without one.
|
|
882
|
+
queryShape: { id_around: messageId, limit: pageSize ?? this.pageSize },
|
|
883
|
+
...(watch && { requestOptions: { watch: true } }),
|
|
615
884
|
updateState: false,
|
|
616
885
|
});
|
|
886
|
+
// a later claim decides the active interval, and the page stays stored
|
|
887
|
+
if (result?.isSuperseded) return false;
|
|
617
888
|
localMessage = this.getItem(messageId);
|
|
618
889
|
if (!localMessage || !result || !result.targetInterval) {
|
|
619
890
|
this.channel.getClient().notifications.addError({
|
|
@@ -624,24 +895,22 @@ export class MessageIntervalPaginator extends BasePaginator<
|
|
|
624
895
|
return false;
|
|
625
896
|
}
|
|
626
897
|
interval = result.targetInterval;
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
898
|
+
this.showInterval(
|
|
899
|
+
interval,
|
|
900
|
+
isLogicalInterval(interval)
|
|
901
|
+
? result.stateCandidate
|
|
902
|
+
: {
|
|
903
|
+
...result.stateCandidate,
|
|
904
|
+
hasMoreHead: interval.hasMoreHead,
|
|
905
|
+
hasMoreTail: interval.hasMoreTail,
|
|
906
|
+
// Falls back to the interval-derived cursor when the stateCandidate is partial.
|
|
907
|
+
cursor:
|
|
908
|
+
result.stateCandidate.cursor ?? this.getCursorFromInterval(interval),
|
|
909
|
+
items: this.intervalToItems(interval),
|
|
910
|
+
},
|
|
911
|
+
);
|
|
639
912
|
}
|
|
640
913
|
|
|
641
|
-
if (!this.isActiveInterval(interval)) {
|
|
642
|
-
this.setActiveInterval(interval, { updateState: false });
|
|
643
|
-
}
|
|
644
|
-
if (state) this.state.partialNext(state);
|
|
645
914
|
if (!suppressFocusSignal) {
|
|
646
915
|
this.emitMessageFocusSignal({
|
|
647
916
|
messageId,
|
|
@@ -652,21 +921,52 @@ export class MessageIntervalPaginator extends BasePaginator<
|
|
|
652
921
|
return true;
|
|
653
922
|
};
|
|
654
923
|
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
924
|
+
/**
|
|
925
|
+
* Shows a loaded interval as it is: its items, its own pagination flags and the cursor continuing
|
|
926
|
+
* it. Claiming the active interval is the caller's choice (see `claimActiveInterval`).
|
|
927
|
+
*/
|
|
928
|
+
protected showLoadedInterval(interval: Interval) {
|
|
929
|
+
this.showInterval(interval, {
|
|
930
|
+
hasMoreHead: interval.hasMoreHead,
|
|
931
|
+
hasMoreTail: interval.hasMoreTail,
|
|
932
|
+
cursor: this.getCursorFromInterval(interval),
|
|
933
|
+
items: this.intervalToItems(interval),
|
|
934
|
+
});
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
/** Makes `interval` the active interval and publishes `state` for it in one update. */
|
|
938
|
+
private showInterval(
|
|
939
|
+
interval: AnyInterval,
|
|
940
|
+
state: Partial<PaginatorState<LocalMessage>>,
|
|
941
|
+
) {
|
|
942
|
+
if (!this.isActiveInterval(interval)) {
|
|
943
|
+
this.setActiveInterval(interval, { updateState: false });
|
|
661
944
|
}
|
|
945
|
+
this.state.partialNext(state);
|
|
946
|
+
// shown without a query of this paginator, so its next query has to continue this interval
|
|
947
|
+
this.recordLoadedIntervalQueryShape();
|
|
948
|
+
}
|
|
662
949
|
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
950
|
+
/**
|
|
951
|
+
* Shows the interval holding the latest message and jumps to that message. Without a loaded head
|
|
952
|
+
* interval (see {@link latestHeadInterval}), the newest page is queried first: no cursor, so it
|
|
953
|
+
* holds the latest message however many pages are missing. The page merges with an interval it
|
|
954
|
+
* overlaps and is an interval of its own otherwise, and is shown either way. Resolves `false` when
|
|
955
|
+
* the latest message cannot be shown, or when a later claim on the active interval (see
|
|
956
|
+
* `claimActiveInterval`) was made before the page arrived: that page is then only stored.
|
|
957
|
+
*/
|
|
958
|
+
jumpToTheLatestMessage = async (options?: JumpToMessageOptions): Promise<boolean> => {
|
|
959
|
+
if (!this.latestHeadInterval) {
|
|
960
|
+
const result = await this.executeQuery({
|
|
961
|
+
claimsActiveInterval: true,
|
|
962
|
+
queryShape: { limit: this.pageSize },
|
|
963
|
+
updateState: false,
|
|
964
|
+
});
|
|
965
|
+
// a later claim decides the active interval, and the page stays stored
|
|
966
|
+
if (result?.isSuperseded) return false;
|
|
668
967
|
}
|
|
669
968
|
|
|
969
|
+
const latestMessageId = this.latestHeadInterval?.itemIds.slice(-1)[0];
|
|
670
970
|
if (!latestMessageId) {
|
|
671
971
|
this.channel.getClient().notifications.addError({
|
|
672
972
|
message: 'Jump to latest message unsuccessful',
|
|
@@ -684,203 +984,554 @@ export class MessageIntervalPaginator extends BasePaginator<
|
|
|
684
984
|
};
|
|
685
985
|
|
|
686
986
|
/**
|
|
687
|
-
*
|
|
688
|
-
*
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
987
|
+
* The head interval when it is the newest loaded interval, so its newest message is the latest
|
|
988
|
+
* one; `undefined` while no head interval is loaded or live messages newer than it are.
|
|
989
|
+
*/
|
|
990
|
+
private get latestHeadInterval(): Interval | undefined {
|
|
991
|
+
const newest = this.itemIntervals[0];
|
|
992
|
+
return newest && !isLogicalInterval(newest) && newest.isHead ? newest : undefined;
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
/**
|
|
996
|
+
* Reconciles the loaded newest messages with a fresh newest page, without issuing a query: they
|
|
997
|
+
* are brought up to date in place — messages added and updated, those the page proves were
|
|
998
|
+
* hard-deleted removed — rather than blanked and reloaded. The page comes from an external query
|
|
999
|
+
* (a reload, a channel-list query, connection recovery). In an active paginator (see
|
|
1000
|
+
* {@link isActivePaginator}) the active interval stays active, the head interval included
|
|
1001
|
+
* (changing it is `jumpToTheLatestMessage()`'s job); in an inactive one, the head interval is
|
|
1002
|
+
* shown.
|
|
692
1003
|
*
|
|
693
|
-
*
|
|
694
|
-
*
|
|
695
|
-
* items are appended and every already loaded item (including older pages already paged in) is
|
|
696
|
-
* kept. The tail boundary (`hasMoreTail`/`cursor.tailward`) is set from whether the page reached
|
|
697
|
-
* the channel start ({@link pageReachedChannelStart}): a bounded page that came back short means
|
|
698
|
-
* no more older, otherwise "load older" stays enabled and the cursor re-anchors to the true loaded
|
|
699
|
-
* oldest (which also clears a stale offline-DB cursor). Then destructive reconciliation
|
|
700
|
-
* ({@link reconcileHeadAgainstPage}) removes any loaded message
|
|
701
|
-
* that the authoritative page proves was hard-deleted while offline (see that method + the
|
|
702
|
-
* {@link MergeNewestPageOptions} for the exact, safe window).
|
|
1004
|
+
* Where the page goes depends on the head interval, the loaded interval reaching the newest
|
|
1005
|
+
* message:
|
|
703
1006
|
*
|
|
704
|
-
*
|
|
705
|
-
*
|
|
706
|
-
*
|
|
707
|
-
*
|
|
708
|
-
*
|
|
709
|
-
* gap and older history load again when paginating older. No separate reconciliation is needed:
|
|
710
|
-
* the rebuilt window IS the server truth, so any hard-deleted message is simply absent from it.
|
|
1007
|
+
* 1. NO HEAD INTERVAL (only live messages, a jumped-to interval, or a cleared head mark, see
|
|
1008
|
+
* {@link unmarkHead}) - the page becomes the head interval, merging with the intervals it
|
|
1009
|
+
* overlaps, live messages included, minus what it proves was hard-deleted. It is shown if the
|
|
1010
|
+
* live messages it absorbed were active; an active interval that it overlaps grows. A
|
|
1011
|
+
* page separated by a gap from the interval whose head mark was cleared is placed as in 2.
|
|
711
1012
|
*
|
|
712
|
-
*
|
|
713
|
-
*
|
|
714
|
-
*
|
|
715
|
-
*
|
|
716
|
-
* — given a pre-fetch snapshot via `options.candidateIds` — is reconciled as "the channel has no
|
|
717
|
-
* messages" (every server-confirmed loaded message removed).
|
|
1013
|
+
* 2. SEPARATED BY A GAP (see {@link isSeparatedFromHeadByGap}) - merging would weld the two
|
|
1014
|
+
* across the gap, hiding the messages in between, so the page takes the place of the head
|
|
1015
|
+
* interval (see {@link placeNewestPageAcrossGap}): stored beside the active interval when that
|
|
1016
|
+
* is an older interval, shown in place of the loaded intervals otherwise.
|
|
718
1017
|
*
|
|
719
|
-
*
|
|
720
|
-
*
|
|
1018
|
+
* 3. OTHERWISE - the page merges into the head interval, which keeps every loaded message and
|
|
1019
|
+
* drops what the page proves was hard-deleted (see {@link reconcileHeadAgainstPage}). An
|
|
1020
|
+
* active head interval gets its tail boundary from the page (see {@link showHeadInterval});
|
|
1021
|
+
* otherwise the active interval stays active, and grows into the head interval if the page
|
|
1022
|
+
* overlaps it.
|
|
1023
|
+
*
|
|
1024
|
+
* Only a gap drops loaded intervals, never an older active interval, and with nothing loaded it
|
|
1025
|
+
* does nothing: placing a first page is {@link placeQueryPage}'s job. An empty page changes
|
|
1026
|
+
* nothing on its own but, given a pre-fetch snapshot (`options.headIntervalItemIdsAtRequest`), is
|
|
1027
|
+
* reconciled as "the channel has no messages": every server-confirmed message of the head interval
|
|
1028
|
+
* is removed.
|
|
1029
|
+
*
|
|
1030
|
+
* The query shape of the loaded interval is recorded on every exit (see
|
|
1031
|
+
* `recordLoadedIntervalQueryShape`): an interval left without one loses itself on the next
|
|
1032
|
+
* pagination.
|
|
1033
|
+
*
|
|
1034
|
+
* @param page - The fetched newest interval (may be empty). `created_at` order is normalized on
|
|
1035
|
+
* ingest.
|
|
1036
|
+
* @param options - See {@link ReconcileNewestMessagesOptions}. Omit to prune only within the
|
|
1037
|
+
* page's own span.
|
|
721
1038
|
*/
|
|
722
|
-
|
|
1039
|
+
reconcileNewestMessages = (
|
|
1040
|
+
page: LocalMessage[],
|
|
1041
|
+
options?: ReconcileNewestMessagesOptions,
|
|
1042
|
+
) => {
|
|
1043
|
+
// The page came back, so whatever the last query failure was, it is no longer the truth: a
|
|
1044
|
+
// failed "load older" would otherwise keep a UI's error surface latched through a successful
|
|
1045
|
+
// refresh. Placing a page clears it in `placeQueryPage`.
|
|
1046
|
+
if (this.state.getLatestValue().lastQueryError) {
|
|
1047
|
+
this.state.partialNext({ lastQueryError: undefined });
|
|
1048
|
+
}
|
|
1049
|
+
this._reconcileNewestMessages(page, options);
|
|
1050
|
+
this.recordLoadedIntervalQueryShape();
|
|
1051
|
+
};
|
|
1052
|
+
|
|
1053
|
+
private _reconcileNewestMessages = (
|
|
1054
|
+
page: LocalMessage[],
|
|
1055
|
+
options?: ReconcileNewestMessagesOptions,
|
|
1056
|
+
) => {
|
|
723
1057
|
const headInterval = this.itemIntervals[0] as Interval | undefined;
|
|
724
1058
|
if (!headInterval?.isHead) {
|
|
725
|
-
//
|
|
726
|
-
//
|
|
727
|
-
//
|
|
728
|
-
//
|
|
729
|
-
//
|
|
730
|
-
//
|
|
731
|
-
// by convention and could be a logical tail and no anchored head, whose presence would mean
|
|
732
|
-
// this window is anchored with an older island merely in view. Keeps both neighbouring no-op
|
|
733
|
-
// contracts, so nothing loaded has no logical head (seeding is `postQueryReconcile`'s job).
|
|
1059
|
+
// The newest messages are not loaded as an interval: only live content arrived (e.g. the first
|
|
1060
|
+
// query came back empty and the user's reply went to the logical head), only a jumped-to
|
|
1061
|
+
// interval is loaded, or the head mark was cleared (see `unmarkHead`). The page becomes the
|
|
1062
|
+
// head interval, and `ingestPage` merges into it the intervals it overlaps, live messages
|
|
1063
|
+
// included, else the newest messages could never be reached. With nothing loaded, placing
|
|
1064
|
+
// a first page is `placeQueryPage`'s job.
|
|
734
1065
|
const logicalHead = this.liveHeadLogical;
|
|
735
1066
|
const hasAnchoredHead = this.itemIntervals.some(
|
|
736
1067
|
(interval) => !isLogicalInterval(interval) && interval.isHead,
|
|
737
1068
|
);
|
|
738
|
-
if (!
|
|
1069
|
+
if (!this.itemIntervals.length || hasAnchoredHead || !page?.length) return;
|
|
1070
|
+
|
|
1071
|
+
// The interval that reached the newest message until its head mark was cleared is judged as
|
|
1072
|
+
// the head interval is, gap included. The page becomes the head interval either way, so that
|
|
1073
|
+
// interval is judged only once.
|
|
1074
|
+
const unmarkedHead = this.unmarkedHeadInterval;
|
|
1075
|
+
this.unmarkedHeadEdgeId = undefined;
|
|
1076
|
+
if (unmarkedHead && this.isSeparatedFromHeadByGap(unmarkedHead, page, options)) {
|
|
1077
|
+
this.placeNewestPageAcrossGap(page, unmarkedHead, options);
|
|
1078
|
+
return;
|
|
1079
|
+
}
|
|
739
1080
|
|
|
740
|
-
// Take over the view
|
|
741
|
-
//
|
|
742
|
-
// branch below enforces).
|
|
743
|
-
const takeOverView =
|
|
1081
|
+
// Take over the view if the live content being absorbed is active, or the paginator is
|
|
1082
|
+
// inactive. An active interval elsewhere (an interval jumped to) stays active, with the
|
|
1083
|
+
// page anchored as the head interval (the rule the jumped away branch below enforces).
|
|
1084
|
+
const takeOverView =
|
|
1085
|
+
!this.isActivePaginator() ||
|
|
1086
|
+
(!!logicalHead && this.isActiveInterval(logicalHead));
|
|
744
1087
|
|
|
745
1088
|
const anchored = this.ingestPage({ page, isHead: true, setActive: false });
|
|
746
|
-
if (!anchored
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
headward: null,
|
|
759
|
-
tailward: hasMoreTail ? (anchored.itemIds[0] ?? null) : null,
|
|
760
|
-
},
|
|
761
|
-
});
|
|
1089
|
+
if (!anchored) return;
|
|
1090
|
+
// The page may have merged into an interval that stopped reaching the newest message (see
|
|
1091
|
+
// `unmarkHead`); remove from it, as from the head, what the page proves was hard-deleted.
|
|
1092
|
+
this.reconcileHeadAgainstPage(page, options);
|
|
1093
|
+
if (!takeOverView) {
|
|
1094
|
+
// The page merged into the active interval, which now reaches the head: show what it gained.
|
|
1095
|
+
if (this.isActiveInterval(anchored)) {
|
|
1096
|
+
this.publishActiveIntervalGrownIntoHead();
|
|
1097
|
+
}
|
|
1098
|
+
return;
|
|
1099
|
+
}
|
|
1100
|
+
this.showHeadInterval(page, options);
|
|
762
1101
|
return;
|
|
763
1102
|
}
|
|
764
|
-
//
|
|
765
|
-
// (overlap branch only): did we believe we were at the channel start, and how much was loaded.
|
|
1103
|
+
// Inputs for removeIdsTailwardOfPageIfNothingOlder, captured before the merge overwrites state.
|
|
766
1104
|
const wasAtChannelStart = !this.state.getLatestValue().hasMoreTail;
|
|
767
1105
|
const preMergeLoadedCount = headInterval.itemIds.length;
|
|
768
|
-
// If the caller jumped to a separate (older) window, that window is active and the head is merely
|
|
769
|
-
// still-loaded underneath. Don't MERGE the fresh page or switch the view (that would yank them to
|
|
770
|
-
// the newest) — but STILL prune offline hard-deletes out of the hidden head, otherwise returning to
|
|
771
|
-
// it later (scroll-to-latest) surfaces ghosts that were deleted while jumped away. Reconciliation
|
|
772
|
-
// targets the head interval regardless of which interval is active, and removing a hidden-head ghost
|
|
773
|
-
// leaves the active island's items untouched.
|
|
774
|
-
if (!this.isActiveInterval(headInterval)) {
|
|
775
|
-
this.reconcileHeadAgainstPage(page, options);
|
|
776
|
-
return;
|
|
777
|
-
}
|
|
778
1106
|
|
|
779
1107
|
if (!page?.length) {
|
|
780
|
-
//
|
|
781
|
-
//
|
|
782
|
-
// arrived live during the fetch is excluded by the snapshot).
|
|
1108
|
+
// An empty page never blanks the list: only with a pre-fetch snapshot is it read as "channel
|
|
1109
|
+
// emptied" (the snapshot excludes messages that arrived live during the fetch).
|
|
783
1110
|
this.reconcileHeadAgainstPage([], options);
|
|
784
1111
|
return;
|
|
785
1112
|
}
|
|
786
1113
|
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
if (!overlapsLoadedHead) {
|
|
791
|
-
// Disjoint window: rebuild from the fetched page as a fresh newest slice. Clearing
|
|
792
|
-
// the stale intervals first ensures `ingestPage` builds a single head interval instead of
|
|
793
|
-
// merging across the gap so reanchoring the cursor to this page's oldest item keeps the next
|
|
794
|
-
// "load older" contiguous.
|
|
795
|
-
this.setIntervals([]);
|
|
796
|
-
this.setActiveInterval(undefined);
|
|
797
|
-
const resetInterval = this.ingestPage({
|
|
798
|
-
page,
|
|
799
|
-
isHead: true,
|
|
800
|
-
// Disjoint means the previously loaded head was entirely OLDER than this newest window, so
|
|
801
|
-
// there is always older data to load (the gap + the prior history) - keep hasMoreTail true.
|
|
802
|
-
isTail: false,
|
|
803
|
-
setActive: false,
|
|
804
|
-
});
|
|
805
|
-
if (!resetInterval) return;
|
|
806
|
-
this.setActiveInterval(resetInterval, { updateState: false });
|
|
807
|
-
this.state.partialNext({
|
|
808
|
-
items: this.intervalToItems(resetInterval),
|
|
809
|
-
cursor: this.getCursorFromInterval(resetInterval),
|
|
810
|
-
hasMoreHead: resetInterval.hasMoreHead,
|
|
811
|
-
hasMoreTail: resetInterval.hasMoreTail,
|
|
812
|
-
});
|
|
1114
|
+
if (this.isSeparatedFromHeadByGap(headInterval, page, options)) {
|
|
1115
|
+
this.placeNewestPageAcrossGap(page, headInterval, options);
|
|
813
1116
|
return;
|
|
814
1117
|
}
|
|
815
1118
|
|
|
816
|
-
//
|
|
817
|
-
|
|
818
|
-
if (!
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
// may be truncated. See {@link pageReachedChannelStart} (no hardcoded max page size, per-paginator).
|
|
824
|
-
// This decides only the "load older" AFFORDANCE — it never removes a message (reconciliation stays
|
|
825
|
-
// window-only below). isTail mirrors it: `true` only when we RELIABLY reached the start, which also
|
|
826
|
-
// clears a stale offline-DB `isTail:true` and stops `intervalsOverlap` welding a far page across a
|
|
827
|
-
// gap. The tail cursor anchors to the oldest loaded id so "load older" stays contiguous.
|
|
828
|
-
const hasMoreTail = !this.pageReachedChannelStart(page, options);
|
|
829
|
-
interval.hasMoreTail = hasMoreTail;
|
|
830
|
-
interval.isTail = !hasMoreTail;
|
|
1119
|
+
// Another interval is shown; the head interval is still reconciled, so returning to it
|
|
1120
|
+
// (scroll-to-latest) shows neither ghosts nor stale newest messages.
|
|
1121
|
+
if (!this.isActiveInterval(headInterval)) {
|
|
1122
|
+
this.reconcileHeadAgainstPage(page, options);
|
|
1123
|
+
this.mergePageIntoInactiveHead(page, options);
|
|
1124
|
+
return;
|
|
1125
|
+
}
|
|
831
1126
|
|
|
832
|
-
|
|
833
|
-
this.
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
// Tailward = the oldest loaded id (interval item ids are created_at asc), null once we reached
|
|
839
|
-
// the channel start.
|
|
840
|
-
cursor: {
|
|
841
|
-
headward: null,
|
|
842
|
-
tailward: hasMoreTail ? (interval.itemIds[0] ?? null) : null,
|
|
843
|
-
},
|
|
1127
|
+
// the head interval is active: merge in place, keeping every loaded message
|
|
1128
|
+
const interval = this.ingestPage({
|
|
1129
|
+
page,
|
|
1130
|
+
isHead: true,
|
|
1131
|
+
setActive: false,
|
|
1132
|
+
targetIntervalId: headInterval.id,
|
|
844
1133
|
});
|
|
1134
|
+
if (!interval) return;
|
|
1135
|
+
this.showHeadInterval(page, options);
|
|
845
1136
|
|
|
846
|
-
|
|
847
|
-
// collect the below-window leftovers it cannot decide from the page alone.
|
|
848
|
-
const belowWindow = this.reconcileHeadAgainstPage(page, options);
|
|
1137
|
+
const idsTailwardOfPage = this.reconcileHeadAgainstPage(page, options);
|
|
849
1138
|
|
|
850
|
-
//
|
|
851
|
-
//
|
|
852
|
-
//
|
|
1139
|
+
// Messages tailward of the page may be deleted or just older than the page reached. Only a reload
|
|
1140
|
+
// of the whole head interval (`requestedLimit >= loaded`, not the small list hydrate) that was at
|
|
1141
|
+
// the channel start can settle them, by asking the server; otherwise they are kept.
|
|
853
1142
|
const requestedLimit = options?.requestedLimit;
|
|
854
1143
|
if (
|
|
855
|
-
|
|
1144
|
+
idsTailwardOfPage.length &&
|
|
856
1145
|
wasAtChannelStart &&
|
|
857
1146
|
typeof requestedLimit === 'number' &&
|
|
858
1147
|
requestedLimit >= preMergeLoadedCount
|
|
859
1148
|
) {
|
|
860
|
-
this.
|
|
861
|
-
|
|
1149
|
+
this._pendingTailwardOfPageRemoval = this.removeIdsTailwardOfPageIfNothingOlder(
|
|
1150
|
+
idsTailwardOfPage,
|
|
862
1151
|
this.getItemId(page[0]),
|
|
863
1152
|
);
|
|
864
1153
|
}
|
|
865
1154
|
};
|
|
866
1155
|
|
|
867
1156
|
/**
|
|
868
|
-
*
|
|
869
|
-
*
|
|
1157
|
+
* Shows the head interval a fresh newest page merged into, with no newer messages to load. It has
|
|
1158
|
+
* older ones unless the page reached the channel start (see {@link pageReachedChannelStart});
|
|
1159
|
+
* `isTail` follows, which also clears a stale offline-DB `isTail: true` that would let
|
|
1160
|
+
* `intervalsOverlap` weld a far page across a gap.
|
|
1161
|
+
*/
|
|
1162
|
+
private showHeadInterval(
|
|
1163
|
+
page: LocalMessage[],
|
|
1164
|
+
options?: ReconcileNewestMessagesOptions,
|
|
1165
|
+
) {
|
|
1166
|
+
// read here, as reconciling replaces the interval object a caller holds
|
|
1167
|
+
const interval = this.anchoredHeadInterval;
|
|
1168
|
+
if (!interval) return;
|
|
1169
|
+
const hasMoreTail = !this.pageReachedChannelStart(page, options);
|
|
1170
|
+
interval.hasMoreTail = hasMoreTail;
|
|
1171
|
+
interval.isTail = !hasMoreTail;
|
|
1172
|
+
this.setActiveInterval(interval, { updateState: false });
|
|
1173
|
+
const flags = { hasMoreHead: false, hasMoreTail };
|
|
1174
|
+
this.publishActiveInterval({
|
|
1175
|
+
...flags,
|
|
1176
|
+
cursor: this.getCursorFromInterval(interval, flags),
|
|
1177
|
+
});
|
|
1178
|
+
}
|
|
1179
|
+
|
|
1180
|
+
/**
|
|
1181
|
+
* Whether a fresh newest page and the head interval (or the interval whose head mark was cleared,
|
|
1182
|
+
* see {@link unmarkedHeadInterval}) are separated by a gap, with messages between them possibly
|
|
1183
|
+
* not loaded. They are not when the two together form one unbroken stretch of the channel:
|
|
1184
|
+
*
|
|
1185
|
+
* - the page starts inside the head interval (see {@link pageStartsInsideHead});
|
|
1186
|
+
* - the page covers the head interval (see {@link pageCoversHead});
|
|
1187
|
+
* - the page reached the channel start (see {@link pageReachedChannelStart}), so nothing older
|
|
1188
|
+
* than it exists to be missing.
|
|
1189
|
+
*
|
|
1190
|
+
* Sharing a message is not enough on its own: a message the user sent while offline is confirmed
|
|
1191
|
+
* by the server before the reconnect's newest page is requested, so it sits at the top of the
|
|
1192
|
+
* head interval and in the page, with the messages missed below it in neither. For example, the
|
|
1193
|
+
* interval holds m1–m100 and the user's queued "hello"; the server got m101–m210 meanwhile. A page
|
|
1194
|
+
* of 25 holds m187–m210 and "hello": it does not start inside the interval (m187 was never loaded)
|
|
1195
|
+
* nor cover it (m1 is not in it), so it is past a gap. When the user wrote the last 10 loaded
|
|
1196
|
+
* messages and others sent 20 since, a page of 25 holds the user's last 5 and the 20 new ones:
|
|
1197
|
+
* its oldest was loaded, so it starts inside the interval.
|
|
1198
|
+
*
|
|
1199
|
+
* A message missed while the socket was down comes with connection recovery's newest page.
|
|
1200
|
+
*/
|
|
1201
|
+
private isSeparatedFromHeadByGap(
|
|
1202
|
+
head: Interval,
|
|
1203
|
+
page: LocalMessage[],
|
|
1204
|
+
options?: ReconcileNewestMessagesOptions,
|
|
1205
|
+
): boolean {
|
|
1206
|
+
if (this.pageStartsInsideHead(head, page, options)) return false;
|
|
1207
|
+
if (this.pageCoversHead(head, page)) return false;
|
|
1208
|
+
if (this.pageReachedChannelStart(page, options)) return false;
|
|
1209
|
+
return true;
|
|
1210
|
+
}
|
|
1211
|
+
|
|
1212
|
+
/**
|
|
1213
|
+
* Whether the page's oldest message the head interval could hold (see
|
|
1214
|
+
* {@link getPageOldestHoldableMessage}) was in the head interval when the request went out. The
|
|
1215
|
+
* page runs unbroken from that message to the newest and the interval is taken to run unbroken
|
|
1216
|
+
* below it, so nothing between them is missing.
|
|
1217
|
+
*
|
|
1218
|
+
* With a snapshot of the request (`options.headIntervalItemIdsAtRequest`), the message must be
|
|
1219
|
+
* in it and held by no interval other than the head interval: a message that reached the interval
|
|
1220
|
+
* during the request, live or as a send confirmed meanwhile, may sit above messages the interval
|
|
1221
|
+
* never loaded. One no longer loaded at all still counts: if the head interval holds messages
|
|
1222
|
+
* older than it, the interval ran unbroken through it and it was removed (e.g. hard-deleted);
|
|
1223
|
+
* if not, the page covers the interval anyway. Without a snapshot, the message must be in the
|
|
1224
|
+
* head interval and server-confirmed now.
|
|
870
1225
|
*
|
|
871
|
-
*
|
|
872
|
-
*
|
|
873
|
-
*
|
|
874
|
-
*
|
|
1226
|
+
* The interval is not unbroken below a send the server confirmed while the channel received no
|
|
1227
|
+
* events, such as one replayed from the offline queue before the reconnect's newest page is
|
|
1228
|
+
* requested. If that send is exactly the page's oldest (as many newer messages as the page has
|
|
1229
|
+
* room for were sent after it), the page is taken to start inside the interval although messages
|
|
1230
|
+
* below the send were missed. The page and the interval cannot tell this apart from a send
|
|
1231
|
+
* confirmed while events were arriving.
|
|
1232
|
+
*/
|
|
1233
|
+
private pageStartsInsideHead(
|
|
1234
|
+
head: Interval,
|
|
1235
|
+
page: LocalMessage[],
|
|
1236
|
+
options?: ReconcileNewestMessagesOptions,
|
|
1237
|
+
): boolean {
|
|
1238
|
+
const pageOldest = this.getPageOldestHoldableMessage(page);
|
|
1239
|
+
if (!pageOldest) return false;
|
|
1240
|
+
const id = this.getItemId(pageOldest);
|
|
1241
|
+
const idsAtRequest = options?.headIntervalItemIdsAtRequest;
|
|
1242
|
+
if (!idsAtRequest) {
|
|
1243
|
+
return head.itemIds.includes(id) && this.isServerConfirmedItemId(id);
|
|
1244
|
+
}
|
|
1245
|
+
const heldByAnotherInterval = !head.itemIds.includes(id) && !!this.getItem(id);
|
|
1246
|
+
return idsAtRequest.has(id) && !heldByAnotherInterval;
|
|
1247
|
+
}
|
|
1248
|
+
|
|
1249
|
+
/**
|
|
1250
|
+
* Whether the page spans the whole head interval: the interval holds no server-confirmed message
|
|
1251
|
+
* older than the page. What the interval holds beyond the page is newer (it arrived as an event
|
|
1252
|
+
* after the page was produced) or unsent (it carries the device's clock).
|
|
1253
|
+
*/
|
|
1254
|
+
private pageCoversHead(head: Interval, page: LocalMessage[]): boolean {
|
|
1255
|
+
const pageOldest = this.getPageOldestMessage(page);
|
|
1256
|
+
if (!pageOldest) return true;
|
|
1257
|
+
return !head.itemIds.some((id) => {
|
|
1258
|
+
const message = this.getItem(id);
|
|
1259
|
+
return (
|
|
1260
|
+
!!message &&
|
|
1261
|
+
this.isServerConfirmedMessage(message) &&
|
|
1262
|
+
this.aIsMoreTailwardThanB(message, pageOldest)
|
|
1263
|
+
);
|
|
1264
|
+
});
|
|
1265
|
+
}
|
|
1266
|
+
|
|
1267
|
+
/**
|
|
1268
|
+
* The page's oldest message that the head interval could have loaded: server-confirmed and kept
|
|
1269
|
+
* in intervals (see {@link filterQueryResults}). A message the interval filters out, such as a
|
|
1270
|
+
* shadowed one, would never be found in it. {@link pageCoversHead} compares with the page's
|
|
1271
|
+
* oldest message of any kind instead: it only needs the page's span.
|
|
1272
|
+
*/
|
|
1273
|
+
private getPageOldestHoldableMessage(page: LocalMessage[]): LocalMessage | undefined {
|
|
1274
|
+
const holdable = this.filterQueryResults(page).filter((message) =>
|
|
1275
|
+
this.isServerConfirmedMessage(message),
|
|
1276
|
+
);
|
|
1277
|
+
return this.getPageOldestMessage(holdable);
|
|
1278
|
+
}
|
|
1279
|
+
|
|
1280
|
+
/**
|
|
1281
|
+
* The interval whose head mark was cleared last (see {@link unmarkHead}), while it is still
|
|
1282
|
+
* loaded. It reached the newest message until then, so a newest page is judged against it while
|
|
1283
|
+
* no head interval is loaded.
|
|
1284
|
+
*/
|
|
1285
|
+
private get unmarkedHeadInterval(): Interval | undefined {
|
|
1286
|
+
const id = this.unmarkedHeadEdgeId;
|
|
1287
|
+
if (!id) return undefined;
|
|
1288
|
+
return this.itemIntervals.find(
|
|
1289
|
+
(interval): interval is Interval =>
|
|
1290
|
+
!isLogicalInterval(interval) && interval.itemIds.includes(id),
|
|
1291
|
+
);
|
|
1292
|
+
}
|
|
1293
|
+
|
|
1294
|
+
/**
|
|
1295
|
+
* Remembers the interval by a message that stays in it: a server-confirmed one, as an unsent one
|
|
1296
|
+
* may be deleted or retried; the raw newest item only when the interval holds none.
|
|
1297
|
+
*/
|
|
1298
|
+
protected override unmarkHead(interval: Interval) {
|
|
1299
|
+
const edge =
|
|
1300
|
+
this.getServerKnownEdges(interval).head ??
|
|
1301
|
+
this.getIntervalPaginationEdges(interval)?.head;
|
|
1302
|
+
this.unmarkedHeadEdgeId = edge ? this.getItemId(edge) : undefined;
|
|
1303
|
+
super.unmarkHead(interval);
|
|
1304
|
+
}
|
|
1305
|
+
|
|
1306
|
+
protected override clearItemStorage() {
|
|
1307
|
+
this.unmarkedHeadEdgeId = undefined;
|
|
1308
|
+
super.clearItemStorage();
|
|
1309
|
+
}
|
|
1310
|
+
|
|
1311
|
+
override resetState() {
|
|
1312
|
+
this.unmarkedHeadEdgeId = undefined;
|
|
1313
|
+
super.resetState();
|
|
1314
|
+
}
|
|
1315
|
+
|
|
1316
|
+
private getPageOldestMessage(page: LocalMessage[]): LocalMessage | undefined {
|
|
1317
|
+
return this.getPagePaginationEdges(this.getCanonicalQueryItems(page)).tail;
|
|
1318
|
+
}
|
|
1319
|
+
|
|
1320
|
+
/**
|
|
1321
|
+
* Places a fresh newest page separated by a gap from `headInterval` (the head interval, or the
|
|
1322
|
+
* interval whose head mark was cleared, see {@link isSeparatedFromHeadByGap}). The page becomes
|
|
1323
|
+
* the head interval either way, and the intervals nothing brought up to date are dropped, as a
|
|
1324
|
+
* message deleted meanwhile would come back with them:
|
|
875
1325
|
*
|
|
876
|
-
*
|
|
877
|
-
*
|
|
878
|
-
*
|
|
879
|
-
*
|
|
1326
|
+
* - an active interval other than the head interval (see {@link getActiveIntervalApartFromHead})
|
|
1327
|
+
* stays active, and the page is stored beside it (see
|
|
1328
|
+
* {@link storeNewestPageBesideActiveInterval});
|
|
1329
|
+
* - otherwise the page replaces the loaded intervals and is shown (see
|
|
1330
|
+
* {@link replaceIntervalsWithNewestPage}).
|
|
1331
|
+
*/
|
|
1332
|
+
private placeNewestPageAcrossGap(
|
|
1333
|
+
page: LocalMessage[],
|
|
1334
|
+
headInterval: Interval,
|
|
1335
|
+
options?: ReconcileNewestMessagesOptions,
|
|
1336
|
+
) {
|
|
1337
|
+
const activeInterval = this.getActiveIntervalApartFromHead(headInterval);
|
|
1338
|
+
if (activeInterval) {
|
|
1339
|
+
this.storeNewestPageBesideActiveInterval(page, activeInterval, options);
|
|
1340
|
+
} else {
|
|
1341
|
+
this.replaceIntervalsWithNewestPage(page, options);
|
|
1342
|
+
}
|
|
1343
|
+
}
|
|
1344
|
+
|
|
1345
|
+
/**
|
|
1346
|
+
* The active loaded interval when it is not `headInterval`, such as an interval jumped to;
|
|
1347
|
+
* `undefined` when `headInterval` or live messages only are active, and in an inactive paginator
|
|
1348
|
+
* (see {@link isActivePaginator}).
|
|
1349
|
+
*/
|
|
1350
|
+
private getActiveIntervalApartFromHead(headInterval: Interval): Interval | undefined {
|
|
1351
|
+
if (!this.isActivePaginator()) return undefined;
|
|
1352
|
+
return this.itemIntervals.find(
|
|
1353
|
+
(interval): interval is Interval =>
|
|
1354
|
+
!isLogicalInterval(interval) &&
|
|
1355
|
+
this.isActiveInterval(interval) &&
|
|
1356
|
+
interval.id !== headInterval.id,
|
|
1357
|
+
);
|
|
1358
|
+
}
|
|
1359
|
+
|
|
1360
|
+
/**
|
|
1361
|
+
* Replaces the loaded intervals with a fresh newest page separated from the head interval by a gap
|
|
1362
|
+
* (see {@link placeNewestPageAcrossGap}) and shows it. The page's interval keeps the loaded
|
|
1363
|
+
* messages that must not be lost (see {@link getMessagesKeptAcrossGap}) and has older messages
|
|
1364
|
+
* to load.
|
|
1365
|
+
*/
|
|
1366
|
+
private replaceIntervalsWithNewestPage(
|
|
1367
|
+
page: LocalMessage[],
|
|
1368
|
+
options?: ReconcileNewestMessagesOptions,
|
|
1369
|
+
) {
|
|
1370
|
+
const keptMessages = this.getMessagesKeptAcrossGap(page, this.itemIntervals);
|
|
1371
|
+
// one publish, once the page's interval is in place and reconciled, so subscribers read it whole
|
|
1372
|
+
this.batch(
|
|
1373
|
+
() => {
|
|
1374
|
+
this.clearItemStorage();
|
|
1375
|
+
this.ingestPageAsHeadInterval(page, keptMessages, options);
|
|
1376
|
+
this.showHeadInterval(page, options);
|
|
1377
|
+
},
|
|
1378
|
+
{ coalesce: true },
|
|
1379
|
+
);
|
|
1380
|
+
}
|
|
1381
|
+
|
|
1382
|
+
/**
|
|
1383
|
+
* Stores a fresh newest page separated from the head interval by a gap (see
|
|
1384
|
+
* {@link placeNewestPageAcrossGap}) as the head interval, beside `activeInterval`, which stays
|
|
1385
|
+
* active and shown as it is. Every other loaded interval is dropped and loads again on
|
|
1386
|
+
* demand. The page's interval keeps the messages of the dropped intervals that must not be lost
|
|
1387
|
+
* (see {@link getMessagesKeptAcrossGap}) and has older messages to load.
|
|
1388
|
+
*
|
|
1389
|
+
* The active interval keeps all its messages, unsent ones included, so nothing moves in the
|
|
1390
|
+
* shown list, and it is not brought up to date: a message deleted or edited meanwhile stays as it was
|
|
1391
|
+
* loaded. It can load newer messages, up to the head interval it then joins.
|
|
1392
|
+
*/
|
|
1393
|
+
private storeNewestPageBesideActiveInterval(
|
|
1394
|
+
page: LocalMessage[],
|
|
1395
|
+
activeInterval: Interval,
|
|
1396
|
+
options?: ReconcileNewestMessagesOptions,
|
|
1397
|
+
) {
|
|
1398
|
+
const droppedIntervals = this.itemIntervals.filter(
|
|
1399
|
+
(interval) => interval.id !== activeInterval.id,
|
|
1400
|
+
);
|
|
1401
|
+
const keptMessages = this.getMessagesKeptAcrossGap(page, droppedIntervals);
|
|
1402
|
+
const keepingIds = new Set(
|
|
1403
|
+
[...page, ...keptMessages].map((message) => this.getItemId(message)),
|
|
1404
|
+
);
|
|
1405
|
+
// one publish, once the page's interval is in place and reconciled, so subscribers read it whole
|
|
1406
|
+
this.batch(
|
|
1407
|
+
() => {
|
|
1408
|
+
this.dropIntervals(droppedIntervals, { keepingIds });
|
|
1409
|
+
this.unmarkedHeadEdgeId = undefined;
|
|
1410
|
+
// Not the head interval: a head mark would weld the page to it (`intervalsOverlap` joins
|
|
1411
|
+
// anything beyond a head interval's head edge).
|
|
1412
|
+
activeInterval.isHead = false;
|
|
1413
|
+
const pageInterval = this.ingestPageAsHeadInterval(page, keptMessages, options);
|
|
1414
|
+
if (pageInterval && this.isActiveInterval(pageInterval)) {
|
|
1415
|
+
// the page overlapped the active interval, which grew into the head interval
|
|
1416
|
+
this.publishActiveIntervalGrownIntoHead();
|
|
1417
|
+
return;
|
|
1418
|
+
}
|
|
1419
|
+
this.markActiveIntervalBelowHead(activeInterval);
|
|
1420
|
+
},
|
|
1421
|
+
{ coalesce: true },
|
|
1422
|
+
);
|
|
1423
|
+
}
|
|
1424
|
+
|
|
1425
|
+
/**
|
|
1426
|
+
* Ingests a fresh newest page placed across a gap, with `keptMessages`, as the head interval,
|
|
1427
|
+
* which has older messages to load, and removes from it what the page proves was hard-deleted (see
|
|
1428
|
+
* {@link reconcileHeadAgainstPage}). Returns the interval the page landed in.
|
|
1429
|
+
*/
|
|
1430
|
+
private ingestPageAsHeadInterval(
|
|
1431
|
+
page: LocalMessage[],
|
|
1432
|
+
keptMessages: LocalMessage[],
|
|
1433
|
+
options?: ReconcileNewestMessagesOptions,
|
|
1434
|
+
): Interval | null {
|
|
1435
|
+
const pageInterval = this.ingestPage({
|
|
1436
|
+
page: [...page, ...keptMessages],
|
|
1437
|
+
isHead: true,
|
|
1438
|
+
isTail: false,
|
|
1439
|
+
setActive: false,
|
|
1440
|
+
});
|
|
1441
|
+
this.reconcileHeadAgainstPage(page, options);
|
|
1442
|
+
return pageInterval;
|
|
1443
|
+
}
|
|
1444
|
+
|
|
1445
|
+
/**
|
|
1446
|
+
* Drops `intervals` from storage and releases their messages, except those with `keepingIds`,
|
|
1447
|
+
* which the caller ingests again.
|
|
1448
|
+
*/
|
|
1449
|
+
private dropIntervals(
|
|
1450
|
+
intervals: AnyInterval[],
|
|
1451
|
+
{ keepingIds }: { keepingIds: ReadonlySet<string> },
|
|
1452
|
+
) {
|
|
1453
|
+
for (const interval of intervals) {
|
|
1454
|
+
this.dropInterval(interval.id);
|
|
1455
|
+
for (const id of interval.itemIds) {
|
|
1456
|
+
if (!keepingIds.has(id)) this._itemIndex.remove(id);
|
|
1457
|
+
}
|
|
1458
|
+
}
|
|
1459
|
+
}
|
|
1460
|
+
|
|
1461
|
+
/**
|
|
1462
|
+
* Marks the active interval, which does not reach the newest message, as able to load newer
|
|
1463
|
+
* messages. Publishes the flag and cursor only when they changed, so the interval shown stays as
|
|
1464
|
+
* it is.
|
|
1465
|
+
*/
|
|
1466
|
+
private markActiveIntervalBelowHead(interval: Interval) {
|
|
1467
|
+
interval.hasMoreHead = true;
|
|
1468
|
+
const cursor = this.getCursorFromInterval(interval);
|
|
1469
|
+
const shown = this.state.getLatestValue();
|
|
1470
|
+
if (shown.hasMoreHead && shown.cursor?.headward === cursor.headward) return;
|
|
1471
|
+
this.state.partialNext({ hasMoreHead: true, cursor });
|
|
1472
|
+
}
|
|
1473
|
+
|
|
1474
|
+
/**
|
|
1475
|
+
* The messages of `intervals`, missing from a newest page placed across a gap, that the page's
|
|
1476
|
+
* interval keeps:
|
|
1477
|
+
*
|
|
1478
|
+
* - unsent messages (see {@link isServerConfirmedMessage});
|
|
1479
|
+
* - messages from the page's oldest on: those that arrived during the request stay, and
|
|
1480
|
+
* reconciling removes those the page proves were hard-deleted.
|
|
1481
|
+
*/
|
|
1482
|
+
private getMessagesKeptAcrossGap(
|
|
1483
|
+
page: LocalMessage[],
|
|
1484
|
+
intervals: AnyInterval[],
|
|
1485
|
+
): LocalMessage[] {
|
|
1486
|
+
const pageIds = new Set(page.map((message) => this.getItemId(message)));
|
|
1487
|
+
const pageOldest = this.getPageOldestMessage(page);
|
|
1488
|
+
const isOlderThanPage = (message: LocalMessage) =>
|
|
1489
|
+
!!pageOldest && this.aIsMoreTailwardThanB(message, pageOldest);
|
|
1490
|
+
return intervals
|
|
1491
|
+
.flatMap((interval) => this.intervalToItems(interval))
|
|
1492
|
+
.filter(
|
|
1493
|
+
(message) =>
|
|
1494
|
+
!pageIds.has(this.getItemId(message)) &&
|
|
1495
|
+
(!this.isServerConfirmedMessage(message) || !isOlderThanPage(message)),
|
|
1496
|
+
);
|
|
1497
|
+
}
|
|
1498
|
+
|
|
1499
|
+
/**
|
|
1500
|
+
* Merges a fresh newest page, not separated by a gap, into the head interval while another
|
|
1501
|
+
* interval is shown. That interval stays active and grows into the head interval if the page
|
|
1502
|
+
* overlaps it. In an inactive paginator (see {@link isActivePaginator}), the head interval is
|
|
1503
|
+
* shown instead.
|
|
1504
|
+
*/
|
|
1505
|
+
private mergePageIntoInactiveHead(
|
|
1506
|
+
page: LocalMessage[],
|
|
1507
|
+
options?: ReconcileNewestMessagesOptions,
|
|
1508
|
+
) {
|
|
1509
|
+
const interval = this.ingestPage({ page, isHead: true, setActive: false });
|
|
1510
|
+
if (!interval) return;
|
|
1511
|
+
if (!this.isActivePaginator()) {
|
|
1512
|
+
this.showHeadInterval(page, options);
|
|
1513
|
+
} else if (this.isActiveInterval(interval)) {
|
|
1514
|
+
this.publishActiveIntervalGrownIntoHead();
|
|
1515
|
+
}
|
|
1516
|
+
}
|
|
1517
|
+
|
|
1518
|
+
/** Publishes the active interval once a newest page grew it into the head interval. */
|
|
1519
|
+
private publishActiveIntervalGrownIntoHead() {
|
|
1520
|
+
this.publishActiveInterval({
|
|
1521
|
+
hasMoreHead: false,
|
|
1522
|
+
cursor: { headward: null, tailward: this.cursor?.tailward ?? null },
|
|
1523
|
+
});
|
|
1524
|
+
}
|
|
1525
|
+
|
|
1526
|
+
/**
|
|
1527
|
+
* Whether `page` proves it reached the channel's oldest message: the request was bounded by this
|
|
1528
|
+
* paginator's own `pageSize` and `page` came back shorter. A larger over-request (e.g.
|
|
1529
|
+
* `channel.reload`) may have been server-capped and never proves it. Gates `hasMoreTail` and the
|
|
1530
|
+
* gap rule ({@link isSeparatedFromHeadByGap}), never removing a message.
|
|
880
1531
|
*/
|
|
881
1532
|
private pageReachedChannelStart(
|
|
882
1533
|
page: LocalMessage[],
|
|
883
|
-
options?:
|
|
1534
|
+
options?: ReconcileNewestMessagesOptions,
|
|
884
1535
|
): boolean {
|
|
885
1536
|
const requestedLimit = options?.requestedLimit;
|
|
886
1537
|
return (
|
|
@@ -891,28 +1542,30 @@ export class MessageIntervalPaginator extends BasePaginator<
|
|
|
891
1542
|
}
|
|
892
1543
|
|
|
893
1544
|
/**
|
|
894
|
-
*
|
|
895
|
-
*
|
|
896
|
-
*
|
|
897
|
-
* older than `
|
|
898
|
-
*
|
|
899
|
-
*
|
|
1545
|
+
* Settles the loaded messages {@link reconcileHeadAgainstPage} found tailward of the page (older
|
|
1546
|
+
* than `pageTailId`, the page's oldest, and absent from it): from the page alone a hard-deleted
|
|
1547
|
+
* oldest message looks like one the page was too short to include. It asks the server whether
|
|
1548
|
+
* anything is older than `pageTailId`. When nothing is, those messages were deleted: they are
|
|
1549
|
+
* removed and the head interval becomes the tail. A failed request, or a head interval replaced
|
|
1550
|
+
* while waiting, keeps them. The caller decides when this runs.
|
|
900
1551
|
*/
|
|
901
|
-
private async
|
|
902
|
-
|
|
903
|
-
|
|
1552
|
+
private async removeIdsTailwardOfPageIfNothingOlder(
|
|
1553
|
+
idsTailwardOfPage: string[],
|
|
1554
|
+
pageTailId: string,
|
|
904
1555
|
): Promise<void> {
|
|
905
|
-
const
|
|
906
|
-
//
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
this.
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
1556
|
+
const headIdBeforeRequest = (this.itemIntervals[0] as Interval | undefined)?.id;
|
|
1557
|
+
// A failed request proves nothing, so it counts as "something older exists".
|
|
1558
|
+
const hasMessagesOlderThanPage = await this.hasMessagesOlderThan(pageTailId).catch(
|
|
1559
|
+
() => true,
|
|
1560
|
+
);
|
|
1561
|
+
if (hasMessagesOlderThanPage) return;
|
|
1562
|
+
// A jump, a reset or another newest page may have replaced the head interval meanwhile.
|
|
1563
|
+
const headAfterRequest = this.itemIntervals[0] as Interval | undefined;
|
|
1564
|
+
if (!headAfterRequest?.isHead || headAfterRequest.id !== headIdBeforeRequest) return;
|
|
1565
|
+
this.removeReconciledItems(idsTailwardOfPage);
|
|
1566
|
+
headAfterRequest.hasMoreTail = false;
|
|
1567
|
+
headAfterRequest.isTail = true;
|
|
1568
|
+
if (this.isActiveInterval(headAfterRequest)) {
|
|
916
1569
|
this.state.partialNext({
|
|
917
1570
|
hasMoreTail: false,
|
|
918
1571
|
cursor: { headward: null, tailward: null },
|
|
@@ -926,16 +1579,15 @@ export class MessageIntervalPaginator extends BasePaginator<
|
|
|
926
1579
|
const { messages } = this.parentMessageId
|
|
927
1580
|
? await this.channel
|
|
928
1581
|
.getClient()
|
|
929
|
-
.getReplies({ parent_id: this.parentMessageId,
|
|
1582
|
+
.getReplies({ parent_id: this.parentMessageId }, pagination)
|
|
930
1583
|
: await this.channel.query({ messages: pagination });
|
|
931
1584
|
return Array.isArray(messages) && messages.length > 0;
|
|
932
1585
|
}
|
|
933
1586
|
|
|
934
1587
|
/**
|
|
935
|
-
* Whether a loaded message is server-confirmed
|
|
936
|
-
*
|
|
937
|
-
*
|
|
938
|
-
* so a legitimately-unsent message is never mistaken for a hard delete.
|
|
1588
|
+
* Whether a loaded message is server-confirmed, so it may be reconciled away when absent from an
|
|
1589
|
+
* authoritative page. Optimistic (`sending`), `failed` and client-side `error` messages are not, so
|
|
1590
|
+
* an unsent message is never mistaken for a hard delete.
|
|
939
1591
|
*/
|
|
940
1592
|
protected isServerConfirmedMessage(message: LocalMessage): boolean {
|
|
941
1593
|
return (
|
|
@@ -946,56 +1598,87 @@ export class MessageIntervalPaginator extends BasePaginator<
|
|
|
946
1598
|
}
|
|
947
1599
|
|
|
948
1600
|
/**
|
|
949
|
-
*
|
|
950
|
-
* `
|
|
951
|
-
|
|
1601
|
+
* Whether this list holds `message`: it passes the filter and, in a channel's main list (no
|
|
1602
|
+
* `parentMessageId`), is not a reply only its thread lists (see `isThreadOnlyReply`).
|
|
1603
|
+
*/
|
|
1604
|
+
private isListedMessage(message: LocalMessage): boolean {
|
|
1605
|
+
if (!this.matchesFilter(message)) return false;
|
|
1606
|
+
return !!this.parentMessageId || !isThreadOnlyReply(message);
|
|
1607
|
+
}
|
|
1608
|
+
|
|
1609
|
+
/**
|
|
1610
|
+
* The failed messages a reload restores with {@link restoreFailedMessages}: those of the shown
|
|
1611
|
+
* interval and the head interval, and those of `persisted` (e.g. the offline database's rows of
|
|
1612
|
+
* the channel) this list holds (see {@link isListedMessage}). The loaded copy wins, as it is at
|
|
1613
|
+
* least as fresh. Take them before the reload's request.
|
|
952
1614
|
*
|
|
953
|
-
*
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
1615
|
+
* @internal
|
|
1616
|
+
*/
|
|
1617
|
+
getFailedMessagesToRestore(persisted: LocalMessage[] = []): LocalMessage[] {
|
|
1618
|
+
const failedById = new Map<string, LocalMessage>();
|
|
1619
|
+
const listed = persisted.filter((message) => this.isListedMessage(message));
|
|
1620
|
+
const loaded = [...(this.items ?? []), ...this.anchoredHeadItems];
|
|
1621
|
+
for (const message of [...listed, ...loaded]) {
|
|
1622
|
+
if (message.status === 'failed') failedById.set(this.getItemId(message), message);
|
|
1623
|
+
}
|
|
1624
|
+
return [...failedById.values()];
|
|
1625
|
+
}
|
|
1626
|
+
|
|
1627
|
+
/**
|
|
1628
|
+
* Ingests again each failed message taken before a reload (see
|
|
1629
|
+
* {@link getFailedMessagesToRestore}) that no interval holds after it, so a reload never loses the
|
|
1630
|
+
* user's unsent work. One an interval holds is left as it is: it may have been resent.
|
|
957
1631
|
*
|
|
958
|
-
*
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
1632
|
+
* @internal
|
|
1633
|
+
*/
|
|
1634
|
+
restoreFailedMessages(failedMessages: LocalMessage[]) {
|
|
1635
|
+
const isNoLongerLoaded = (message: LocalMessage) =>
|
|
1636
|
+
!this.findIntervalHoldingItem(message);
|
|
1637
|
+
const toRestore = failedMessages.filter(isNoLongerLoaded);
|
|
1638
|
+
if (!toRestore.length) return;
|
|
1639
|
+
this.batch(
|
|
1640
|
+
() => {
|
|
1641
|
+
for (const message of toRestore) this.ingestItem(message);
|
|
1642
|
+
},
|
|
1643
|
+
{ coalesce: true },
|
|
1644
|
+
);
|
|
1645
|
+
}
|
|
1646
|
+
|
|
1647
|
+
/**
|
|
1648
|
+
* Destructive half of {@link reconcileNewestMessages}: removes loaded head-interval messages
|
|
1649
|
+
* that `page` (the fresh newest interval) proves were hard-deleted while the client received no
|
|
1650
|
+
* events, by `created_at`:
|
|
965
1651
|
*
|
|
966
|
-
*
|
|
967
|
-
*
|
|
968
|
-
*
|
|
969
|
-
*
|
|
970
|
-
*
|
|
971
|
-
* omits any real delete).
|
|
1652
|
+
* - within `page`'s span: a server-confirmed message absent from `page` was deleted (a live
|
|
1653
|
+
* arrival is newer than `page`'s newest, so this needs no snapshot);
|
|
1654
|
+
* - at or above `page`'s newest, and for an empty `page`: only IDs in the pre-fetch
|
|
1655
|
+
* `headIntervalItemIdsAtRequest` snapshot, which tells a just-deleted message from a live
|
|
1656
|
+
* arrival or a send confirmed during the request.
|
|
972
1657
|
*
|
|
973
|
-
*
|
|
974
|
-
*
|
|
975
|
-
* the
|
|
1658
|
+
* Messages below `page`'s oldest are kept (a hard-deleted oldest looks like a server-capped
|
|
1659
|
+
* over-request) and returned for {@link removeIdsTailwardOfPageIfNothingOlder}. Removal goes through
|
|
1660
|
+
* {@link removeItem}, so the index, intervals, message store and any subclass bookkeeping (e.g.
|
|
1661
|
+
* the latest message of {@link MessagePaginator}) stay correct.
|
|
976
1662
|
*
|
|
977
|
-
* @returns
|
|
978
|
-
* from it) for the caller's reached-start probe. Empty for the no-head / empty-page paths.
|
|
1663
|
+
* @returns The below-interval leftover IDs. Empty for the no-head and empty-page paths.
|
|
979
1664
|
*/
|
|
980
1665
|
protected reconcileHeadAgainstPage(
|
|
981
1666
|
page: LocalMessage[],
|
|
982
|
-
options?:
|
|
1667
|
+
options?: ReconcileNewestMessagesOptions,
|
|
983
1668
|
): string[] {
|
|
984
1669
|
const headInterval = this.itemIntervals[0] as Interval | undefined;
|
|
985
1670
|
if (!headInterval?.isHead) return [];
|
|
986
1671
|
|
|
987
1672
|
const loadedIds = headInterval.itemIds;
|
|
988
|
-
const
|
|
1673
|
+
const headIntervalItemIdsAtRequest = options?.headIntervalItemIdsAtRequest;
|
|
989
1674
|
|
|
990
|
-
// Empty page
|
|
991
|
-
//
|
|
1675
|
+
// Empty page: the channel has no messages. Only IDs from the pre-fetch snapshot are removed, so a
|
|
1676
|
+
// message that landed during the fetch survives.
|
|
992
1677
|
if (!page.length) {
|
|
993
|
-
if (!
|
|
994
|
-
const toRemove = loadedIds.filter(
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
return !!message && this.isServerConfirmedMessage(message);
|
|
998
|
-
});
|
|
1678
|
+
if (!headIntervalItemIdsAtRequest) return [];
|
|
1679
|
+
const toRemove = loadedIds.filter(
|
|
1680
|
+
(id) => headIntervalItemIdsAtRequest.has(id) && this.isServerConfirmedItemId(id),
|
|
1681
|
+
);
|
|
999
1682
|
this.removeReconciledItems(toRemove);
|
|
1000
1683
|
return [];
|
|
1001
1684
|
}
|
|
@@ -1004,57 +1687,36 @@ export class MessageIntervalPaginator extends BasePaginator<
|
|
|
1004
1687
|
const newestReturnedTs = getMessageCreatedAtTimestamp(page[page.length - 1]);
|
|
1005
1688
|
const oldestReturnedTs = getMessageCreatedAtTimestamp(page[0]);
|
|
1006
1689
|
|
|
1007
|
-
//
|
|
1008
|
-
|
|
1009
|
-
// are collected into `belowWindow` and returned instead, for the reached-start probe to settle.
|
|
1010
|
-
const windowLowTs = oldestReturnedTs ?? Number.POSITIVE_INFINITY;
|
|
1690
|
+
// Nothing below the page's oldest is removed here: those go to `idsTailwardOfPage`.
|
|
1691
|
+
const pageTailTs = oldestReturnedTs ?? Number.POSITIVE_INFINITY;
|
|
1011
1692
|
|
|
1012
1693
|
const toRemove: string[] = [];
|
|
1013
|
-
const
|
|
1694
|
+
const idsTailwardOfPage: string[] = [];
|
|
1014
1695
|
for (const id of loadedIds) {
|
|
1015
|
-
if (pageIds.has(id)) continue;
|
|
1696
|
+
if (pageIds.has(id)) continue;
|
|
1016
1697
|
const message = this.getItem(id);
|
|
1017
|
-
if (!message || !this.isServerConfirmedMessage(message)) continue;
|
|
1698
|
+
if (!message || !this.isServerConfirmedMessage(message)) continue;
|
|
1018
1699
|
const ts = getMessageCreatedAtTimestamp(message);
|
|
1019
|
-
if (ts === null) continue; // no server timestamp (optimistic)
|
|
1700
|
+
if (ts === null) continue; // no server timestamp (optimistic)
|
|
1020
1701
|
|
|
1021
1702
|
if (newestReturnedTs !== null && ts >= newestReturnedTs) {
|
|
1022
|
-
// At
|
|
1023
|
-
//
|
|
1024
|
-
//
|
|
1025
|
-
|
|
1026
|
-
if (candidateIds?.has(id)) toRemove.push(id);
|
|
1703
|
+
// At or above the page's newest, a hard-deleted newest message, a live arrival and a send
|
|
1704
|
+
// confirmed during the request look the same: remove only IDs from the pre-fetch snapshot,
|
|
1705
|
+
// which holds none of the latter two.
|
|
1706
|
+
if (headIntervalItemIdsAtRequest?.has(id)) toRemove.push(id);
|
|
1027
1707
|
continue;
|
|
1028
1708
|
}
|
|
1029
|
-
//
|
|
1030
|
-
//
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
else belowWindow.push(id);
|
|
1709
|
+
// Within the page's span a live arrival cannot be here, so absence means a hard delete. At or
|
|
1710
|
+
// below the page's oldest the page cannot decide: return it for the caller to settle.
|
|
1711
|
+
if (ts > pageTailTs) toRemove.push(id);
|
|
1712
|
+
else idsTailwardOfPage.push(id);
|
|
1034
1713
|
}
|
|
1035
1714
|
|
|
1036
1715
|
this.removeReconciledItems(toRemove);
|
|
1037
|
-
return
|
|
1716
|
+
return idsTailwardOfPage;
|
|
1038
1717
|
}
|
|
1039
1718
|
|
|
1040
|
-
/**
|
|
1041
|
-
* Remove a set of reconciled (hard-deleted) ids from this paginator's loaded state in one coalesced
|
|
1042
|
-
* batch. Each id goes through {@link removeItem}, which drops it from THREE places — not a single
|
|
1043
|
-
* interval:
|
|
1044
|
-
*
|
|
1045
|
-
* 1. the item index — unlinks this paginator's membership from the shared entity store (GC'ing the
|
|
1046
|
-
* content if this was the last holder);
|
|
1047
|
-
* 2. the interval that holds it — located by id, so it is NOT head-specific in general; in practice
|
|
1048
|
-
* it is always the head interval, because the sole caller ({@link reconcileHeadAgainstPage})
|
|
1049
|
-
* sources these ids from `headInterval.itemIds` and an item has single-interval membership;
|
|
1050
|
-
* 3. the active window (`state.items`) if visible — blanking to `[]` when the window empties, per
|
|
1051
|
-
* {@link flushWindowPublish}.
|
|
1052
|
-
*
|
|
1053
|
-
* The coalesced batch collapses all of that into a single `state.items` publish. Then mirror the
|
|
1054
|
-
* removal into the offline DB (see {@link purgeReconciledFromOfflineDb}) so a cold start does not
|
|
1055
|
-
* re-seed the ghosts from SQLite. No-op for an empty set, so an unaffected merge does not touch
|
|
1056
|
-
* state a second time.
|
|
1057
|
-
*/
|
|
1719
|
+
/** Removes reconciled IDs in one coalesced batch (one publish), then mirrors it offline. */
|
|
1058
1720
|
private removeReconciledItems(ids: string[]) {
|
|
1059
1721
|
if (!ids.length) return;
|
|
1060
1722
|
this.batch(
|
|
@@ -1067,26 +1729,15 @@ export class MessageIntervalPaginator extends BasePaginator<
|
|
|
1067
1729
|
}
|
|
1068
1730
|
|
|
1069
1731
|
/**
|
|
1070
|
-
*
|
|
1071
|
-
*
|
|
1072
|
-
*
|
|
1073
|
-
* page), so without this the ghosts survive in SQLite and a cold start would re-seed them after the
|
|
1074
|
-
* in-memory list already dropped them.
|
|
1075
|
-
*
|
|
1076
|
-
* Owned by the state layer, NOT the SDK: the SDK only supplies the platform `offlineDb`
|
|
1077
|
-
* implementation and never orchestrates DB writes for reconciliation. Fire-and-forget and
|
|
1078
|
-
* best-effort — the in-memory removal is the source of truth for the live list, so a failed/absent
|
|
1079
|
-
* DB write is no worse than before (the ghost merely re-appears on a cold start until the next
|
|
1080
|
-
* reconcile). No-op when offline support is off (`client.offlineDb` undefined). The ids are already
|
|
1081
|
-
* server-confirmed (the reconcile excludes pending/failed/optimistic), so a plain hard delete —
|
|
1082
|
-
* without the pending-task teardown of a local failed message — is correct.
|
|
1732
|
+
* Mirrors a reconciliation into the offline DB: a hard delete done while offline reaches it via no
|
|
1733
|
+
* event and the reconnect query upserts (never removing absent rows), so a cold start would re-seed
|
|
1734
|
+
* the ghosts. Fire-and-forget, no-op without offline support.
|
|
1083
1735
|
*/
|
|
1084
1736
|
private purgeReconciledFromOfflineDb(ids: string[]) {
|
|
1085
1737
|
const offlineDb = this.channel.getClient?.()?.offlineDb;
|
|
1086
1738
|
if (!offlineDb) return;
|
|
1087
|
-
// The offline DB owns the batching (single transaction); we just hand it the reconciled ids.
|
|
1088
1739
|
offlineDb.hardDeleteMessages({ ids }).catch(() => {
|
|
1089
|
-
//
|
|
1740
|
+
// Best effort: the live list is already correct.
|
|
1090
1741
|
});
|
|
1091
1742
|
}
|
|
1092
1743
|
|
|
@@ -1094,15 +1745,12 @@ export class MessageIntervalPaginator extends BasePaginator<
|
|
|
1094
1745
|
lastReadAt,
|
|
1095
1746
|
messages,
|
|
1096
1747
|
}: {
|
|
1097
|
-
lastReadAt:
|
|
1748
|
+
lastReadAt: TimestampNS;
|
|
1098
1749
|
messages: LocalMessage[];
|
|
1099
1750
|
}): { firstUnreadMessageId: string | null; lastReadMessageId: string | null } => {
|
|
1100
|
-
// Messages are
|
|
1101
|
-
//
|
|
1102
|
-
//
|
|
1103
|
-
//
|
|
1104
|
-
// If the page starts after lastReadAt, the entire page is unread and the first message is
|
|
1105
|
-
// used as unread anchor (legacy "whole channel is unread" behavior for this queried window).
|
|
1751
|
+
// Messages are chronological: `lastReadMessageId` is the newest with `created_at <= lastReadAt`,
|
|
1752
|
+
// `firstUnreadMessageId` the first with `created_at > lastReadAt`. If the page starts after
|
|
1753
|
+
// `lastReadAt`, the whole page is unread and its first message is the unread anchor.
|
|
1106
1754
|
const lastReadTimestamp = lastReadAt;
|
|
1107
1755
|
if (!Number.isFinite(lastReadTimestamp) || !messages.length) {
|
|
1108
1756
|
return { firstUnreadMessageId: null, lastReadMessageId: null };
|
|
@@ -1167,20 +1815,15 @@ export class MessageIntervalPaginator extends BasePaginator<
|
|
|
1167
1815
|
|
|
1168
1816
|
this.messageFocusSignal.next({ signal });
|
|
1169
1817
|
|
|
1170
|
-
//
|
|
1171
|
-
//
|
|
1172
|
-
// panel when a "view in channel" jump resolves), so measuring the highlight lifetime from the
|
|
1173
|
-
// moment the jump resolved would burn it while the message is still off-screen. The consumer
|
|
1174
|
-
// starts the countdown via `scheduleMessageFocusSignalClear` once the message is actually
|
|
1175
|
-
// viewed.
|
|
1818
|
+
// The auto-dismiss countdown does not start here: the message list may not be visible yet (e.g.
|
|
1819
|
+
// covered by a thread panel), so the consumer starts it via `scheduleMessageFocusSignalClear`.
|
|
1176
1820
|
return signal;
|
|
1177
1821
|
};
|
|
1178
1822
|
|
|
1179
1823
|
/**
|
|
1180
|
-
* Starts the auto-
|
|
1181
|
-
*
|
|
1182
|
-
*
|
|
1183
|
-
* signal has already been cleared or superseded (guarded by `token`).
|
|
1824
|
+
* Starts the auto-dismiss countdown for the active focus signal. Call it once the focused message
|
|
1825
|
+
* is viewed, so the highlight lasts from when the user could see it. No-op if the signal was
|
|
1826
|
+
* cleared or superseded (guarded by `token`).
|
|
1184
1827
|
*/
|
|
1185
1828
|
scheduleMessageFocusSignalClear = ({
|
|
1186
1829
|
token,
|
|
@@ -1220,19 +1863,14 @@ export class MessageIntervalPaginator extends BasePaginator<
|
|
|
1220
1863
|
}
|
|
1221
1864
|
|
|
1222
1865
|
/**
|
|
1223
|
-
* Partial truncation for `channel.truncated`
|
|
1224
|
-
*
|
|
1225
|
-
*
|
|
1226
|
-
*
|
|
1227
|
-
*
|
|
1228
|
-
*
|
|
1229
|
-
* its `tail` (oldest) and `head` (newest) edges, so only the single interval that *straddles* the
|
|
1230
|
-
* cutoff is scanned member-by-member — the rest are kept or dropped wholesale. The straddling
|
|
1231
|
-
* interval becomes the new global tail (nothing older than the cutoff exists anymore), so its
|
|
1232
|
-
* `isTail`/`hasMoreTail` are set; intervals entirely newer keep their flags (unloaded older
|
|
1233
|
-
* messages may still sit between them and the cutoff). The active window is re-emitted once.
|
|
1866
|
+
* Partial truncation for `channel.truncated` with a `truncated_at`: drops every loaded message
|
|
1867
|
+
* strictly older than the cutoff across all intervals (a full truncation uses
|
|
1868
|
+
* {@link MessageIntervalPaginator.clearStateAndCache}). Only the interval straddling the cutoff is
|
|
1869
|
+
* scanned member by member and becomes the new global tail; intervals entirely newer keep their
|
|
1870
|
+
* flags, since unloaded older messages may sit between them and the cutoff. The active interval is
|
|
1871
|
+
* re-emitted once.
|
|
1234
1872
|
*/
|
|
1235
|
-
truncate
|
|
1873
|
+
truncate({ truncatedAt }: { truncatedAt: TimestampNS }) {
|
|
1236
1874
|
const cutoff = truncatedAt;
|
|
1237
1875
|
if (!Number.isFinite(cutoff)) return;
|
|
1238
1876
|
|
|
@@ -1251,8 +1889,7 @@ export class MessageIntervalPaginator extends BasePaginator<
|
|
|
1251
1889
|
} else if (isOld(edges.head)) {
|
|
1252
1890
|
removedIds.push(...interval.itemIds); // newest edge < cutoff → whole interval is older
|
|
1253
1891
|
} else {
|
|
1254
|
-
//
|
|
1255
|
-
// binary-search rather than scanning every member.
|
|
1892
|
+
// Items are chronological, so the old ones come first: binary-search the split.
|
|
1256
1893
|
const ids = interval.itemIds;
|
|
1257
1894
|
const splitIndex = lowerBound(
|
|
1258
1895
|
ids.length,
|
|
@@ -1271,37 +1908,46 @@ export class MessageIntervalPaginator extends BasePaginator<
|
|
|
1271
1908
|
if (!removedIds.length) return;
|
|
1272
1909
|
for (const id of removedIds) this._itemIndex.remove(id);
|
|
1273
1910
|
|
|
1274
|
-
// No re-sort
|
|
1275
|
-
//
|
|
1276
|
-
// tailward items — an interval's head edge (the intervalComparator sort key) never changes.
|
|
1911
|
+
// No re-sort: intervals keep their order and truncation only removes tailward items, so the head
|
|
1912
|
+
// edge (the interval sort key) never changes.
|
|
1277
1913
|
this.setIntervals(survivingIntervals);
|
|
1278
1914
|
|
|
1279
|
-
//
|
|
1915
|
+
// `setIntervals` does not emit: re-emit the active interval once.
|
|
1280
1916
|
const active = this._activeIntervalId
|
|
1281
1917
|
? this._itemIntervals.get(this._activeIntervalId)
|
|
1282
1918
|
: undefined;
|
|
1283
|
-
if (active
|
|
1284
|
-
|
|
1919
|
+
if (active) {
|
|
1920
|
+
// `setActiveInterval` does not emit for a logical interval, so its survivors are emitted here.
|
|
1921
|
+
if (isLogicalInterval(active)) {
|
|
1922
|
+
this.state.partialNext({ items: this.intervalToItems(active) });
|
|
1923
|
+
} else {
|
|
1924
|
+
this.setActiveInterval(active);
|
|
1925
|
+
}
|
|
1285
1926
|
return;
|
|
1286
1927
|
}
|
|
1287
1928
|
|
|
1288
|
-
// The active
|
|
1289
|
-
//
|
|
1290
|
-
// anchored interval) rather than emitting an empty page, which would blank the message list.
|
|
1929
|
+
// The active interval was truncated away: activate the tail-most (oldest) surviving anchored
|
|
1930
|
+
// interval rather than blank the message list.
|
|
1291
1931
|
const anchoredSurvivors = this.itemIntervals.filter(
|
|
1292
1932
|
(itv): itv is Interval => !isLogicalInterval(itv),
|
|
1293
1933
|
);
|
|
1294
1934
|
|
|
1295
|
-
// If the active interval was truncated, we move to the neareast interval - which is the tail now
|
|
1296
1935
|
const fallback = this.getTailIntervalFromSortedIntervals(anchoredSurvivors);
|
|
1297
1936
|
if (fallback) {
|
|
1298
1937
|
this.setActiveInterval(fallback);
|
|
1299
1938
|
} else {
|
|
1300
|
-
// Nothing loaded survived the truncation.
|
|
1301
|
-
|
|
1939
|
+
// Nothing loaded survived the truncation. Drop the stale active id too: the next ingested
|
|
1940
|
+
// message lands in a logical head interval, which is only activated (and published) when no
|
|
1941
|
+
// interval is active.
|
|
1942
|
+
this.setActiveInterval(undefined);
|
|
1943
|
+
this.state.partialNext({ items: [], hasMoreTail: false });
|
|
1302
1944
|
}
|
|
1303
|
-
}
|
|
1945
|
+
}
|
|
1304
1946
|
|
|
1947
|
+
/**
|
|
1948
|
+
* Deletes `userId`'s loaded messages (removes them on a hard delete) and marks the quotes of them
|
|
1949
|
+
* as deleted. Returns the messages it deleted, as they were before.
|
|
1950
|
+
*/
|
|
1305
1951
|
applyMessageDeletionForUser = ({
|
|
1306
1952
|
userId,
|
|
1307
1953
|
hardDelete = false,
|
|
@@ -1309,58 +1955,56 @@ export class MessageIntervalPaginator extends BasePaginator<
|
|
|
1309
1955
|
}: {
|
|
1310
1956
|
userId: string;
|
|
1311
1957
|
hardDelete?: boolean;
|
|
1312
|
-
deletedAt:
|
|
1313
|
-
}) => {
|
|
1314
|
-
const loadedMessages = this.
|
|
1958
|
+
deletedAt: TimestampNS;
|
|
1959
|
+
}): LocalMessage[] => {
|
|
1960
|
+
const loadedMessages = this._itemIndex.values();
|
|
1961
|
+
const deletedMessages: LocalMessage[] = [];
|
|
1315
1962
|
|
|
1316
|
-
//
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1963
|
+
// Coalesce: one emit for this interval and one shared-store flush for the sibling holders.
|
|
1964
|
+
this.batch(
|
|
1965
|
+
() => {
|
|
1966
|
+
for (const message of loadedMessages) {
|
|
1967
|
+
if (message.user?.id === userId) {
|
|
1968
|
+
deletedMessages.push(message);
|
|
1969
|
+
if (hardDelete) {
|
|
1970
|
+
this.removeItem({ id: message.id });
|
|
1971
|
+
} else {
|
|
1972
|
+
this.ingestItem(
|
|
1973
|
+
toDeletedMessage({
|
|
1974
|
+
message,
|
|
1975
|
+
hardDelete,
|
|
1976
|
+
deletedAt,
|
|
1977
|
+
}) as LocalMessage,
|
|
1978
|
+
);
|
|
1979
|
+
}
|
|
1980
|
+
continue;
|
|
1981
|
+
}
|
|
1982
|
+
|
|
1983
|
+
if (
|
|
1984
|
+
message.quoted_message?.user?.id === userId &&
|
|
1985
|
+
message.quoted_message.type !== 'deleted'
|
|
1986
|
+
) {
|
|
1987
|
+
this.ingestItem({
|
|
1988
|
+
...message,
|
|
1989
|
+
quoted_message: toDeletedMessage({
|
|
1990
|
+
message: formatMessage(message.quoted_message),
|
|
1327
1991
|
hardDelete,
|
|
1328
1992
|
deletedAt,
|
|
1329
1993
|
}) as LocalMessage,
|
|
1330
|
-
);
|
|
1994
|
+
});
|
|
1331
1995
|
}
|
|
1332
|
-
continue;
|
|
1333
|
-
}
|
|
1334
|
-
|
|
1335
|
-
if (
|
|
1336
|
-
message.quoted_message?.user?.id === userId &&
|
|
1337
|
-
message.quoted_message.type !== 'deleted'
|
|
1338
|
-
) {
|
|
1339
|
-
this.ingestItem({
|
|
1340
|
-
...message,
|
|
1341
|
-
quoted_message: toDeletedMessage({
|
|
1342
|
-
message: formatMessage(message.quoted_message),
|
|
1343
|
-
hardDelete,
|
|
1344
|
-
deletedAt,
|
|
1345
|
-
}) as LocalMessage,
|
|
1346
|
-
});
|
|
1347
1996
|
}
|
|
1348
|
-
}
|
|
1349
|
-
|
|
1997
|
+
},
|
|
1998
|
+
{ coalesce: true },
|
|
1999
|
+
);
|
|
2000
|
+
return deletedMessages;
|
|
1350
2001
|
};
|
|
1351
2002
|
|
|
1352
|
-
/**
|
|
1353
|
-
* Ensures quoted-message snapshots across loaded paginator cache are in sync
|
|
1354
|
-
* with the provided message.
|
|
1355
|
-
*
|
|
1356
|
-
* Scans cached messages and updates any item where `quoted_message_id`
|
|
1357
|
-
* matches `message.id`.
|
|
1358
|
-
*/
|
|
2003
|
+
/** Updates the quoted-message snapshot of every cached message that quotes `message`. */
|
|
1359
2004
|
reflectQuotedMessageUpdate = (message: LocalMessage) => {
|
|
1360
2005
|
const cachedMessages = this._itemIndex.values();
|
|
1361
2006
|
|
|
1362
|
-
//
|
|
1363
|
-
// to a single flush instead of one per re-ingested quoting message.
|
|
2007
|
+
// Several cached messages may quote it: coalesce the shared-store fan-out into one flush.
|
|
1364
2008
|
this.batch(() => {
|
|
1365
2009
|
for (const cachedMessage of cachedMessages) {
|
|
1366
2010
|
if (cachedMessage.quoted_message_id !== message.id) continue;
|
|
@@ -1374,22 +2018,18 @@ export class MessageIntervalPaginator extends BasePaginator<
|
|
|
1374
2018
|
};
|
|
1375
2019
|
|
|
1376
2020
|
/**
|
|
1377
|
-
*
|
|
1378
|
-
*
|
|
1379
|
-
*
|
|
1380
|
-
*
|
|
1381
|
-
* Batched: a user rename can affect many messages, so this patches the shared item index and
|
|
1382
|
-
* re-emits the active window a single time (if it held an affected message) rather than one
|
|
1383
|
-
* `ingestItem` re-emit per message.
|
|
2021
|
+
* Reflects an updated `user` onto every cached message authored by that user (not
|
|
2022
|
+
* `quoted_message.user`). Patches the shared item index in one batch and re-emits the active
|
|
2023
|
+
* interval once, if it held an affected message.
|
|
1384
2024
|
*/
|
|
1385
|
-
reflectUserUpdate
|
|
2025
|
+
reflectUserUpdate(user: UserResponse) {
|
|
1386
2026
|
const activeIds = new Set((this.items ?? []).map((m) => this.getItemId(m)));
|
|
1387
2027
|
let activeAffected = false;
|
|
1388
|
-
//
|
|
1389
|
-
// holders into a single flush. This paginator's own active window is re-emitted once below.
|
|
2028
|
+
// A rename can touch many messages: coalesce the shared-store fan-out into one flush.
|
|
1390
2029
|
this.batch(() => {
|
|
1391
2030
|
for (const message of this._itemIndex.values()) {
|
|
1392
2031
|
if (message.user?.id !== user.id) continue;
|
|
2032
|
+
if (message.user === user) continue;
|
|
1393
2033
|
this._itemIndex.setOne({ ...message, user });
|
|
1394
2034
|
if (activeIds.has(this.getItemId(message))) activeAffected = true;
|
|
1395
2035
|
}
|
|
@@ -1399,124 +2039,92 @@ export class MessageIntervalPaginator extends BasePaginator<
|
|
|
1399
2039
|
items: (this.items ?? []).map((m) => this.getItem(this.getItemId(m)) ?? m),
|
|
1400
2040
|
});
|
|
1401
2041
|
}
|
|
1402
|
-
}
|
|
2042
|
+
}
|
|
1403
2043
|
|
|
1404
2044
|
/**
|
|
1405
|
-
*
|
|
1406
|
-
*
|
|
1407
|
-
*
|
|
1408
|
-
*
|
|
1409
|
-
*
|
|
1410
|
-
* `channel.state.messages` / `channel.state.threads` caches (the same logic backs the thread
|
|
1411
|
-
* paginator via `Thread.messagePaginator`).
|
|
1412
|
-
*
|
|
1413
|
-
* `own_reactions` is seeded from the currently cached item (so another user's reaction keeps ours),
|
|
1414
|
-
* falling back to the event's own_reactions when the message is not loaded — matching the legacy
|
|
1415
|
-
* behavior where `_updateMessage` only mutated a message that existed locally.
|
|
1416
|
-
*
|
|
1417
|
-
* @param params - The reaction event payload.
|
|
1418
|
-
* @param params.message - The reaction event's message, carrying the
|
|
1419
|
-
* server-computed `reaction_groups` / `latest_reactions`. Ingested as-is except for `own_reactions`.
|
|
1420
|
-
* @param params.reaction - The reaction from the event. Only added to/removed from
|
|
1421
|
-
* `own_reactions` when its `user_id` is the current user; otherwise the current user's
|
|
1422
|
-
* `own_reactions` are left untouched.
|
|
1423
|
-
* @param [params.removed=false] - `true` for `reaction.deleted` (remove the reaction from
|
|
1424
|
-
* `own_reactions`); `false` for `reaction.new` / `reaction.updated` (add it).
|
|
1425
|
-
* @param [params.enforceUnique=false] - When adding, first clear the current user's existing
|
|
1426
|
-
* `own_reactions` so only the incoming one remains (used by `reaction.updated`, where a user's
|
|
1427
|
-
* reaction replaces their previous one).
|
|
1428
|
-
*
|
|
1429
|
-
* TODO(reactive-store): reflect reactions ONCE at the store level, not per-paginator. Both the
|
|
1430
|
-
* channel handler (channel.ts) and the thread handler (thread.ts) call this on every reaction.*
|
|
1431
|
-
* event, so a message held in more than one collection (a show_in_channel reply, or the thread
|
|
1432
|
-
* parent) is reflected TWICE: two writes to the same canonical slot, each fanning out to the
|
|
1433
|
-
* other holder (double re-projection) and minting a fresh ref that defeats the reconcile
|
|
1434
|
-
* ref-equality bail. Idempotent (counts come wholesale from the event) so the result is correct,
|
|
1435
|
-
* just wasteful. The store already fans out to every holder, so reflect once (by id, if held) and
|
|
1436
|
-
* retire the per-collection reflect calls + parent path + enforce_unique branch.
|
|
2045
|
+
* The last loaded message created at or before `timestamp` (a floor), or `null` when it precedes
|
|
2046
|
+
* every loaded message. With `exactTsMatch`, only a message created exactly at `timestamp` matches.
|
|
2047
|
+
* Searches the loaded intervals from the head down (each already sorted, O(log n) per interval):
|
|
2048
|
+
* the first holding a message at or before `timestamp` holds the answer. Used by the receipts
|
|
2049
|
+
* tracker to resolve read/delivered cursors.
|
|
1437
2050
|
*/
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
const baseOwnReactions = existing?.own_reactions ?? formatted.own_reactions ?? [];
|
|
1452
|
-
const own_reactions = computeOwnReactions({
|
|
1453
|
-
current: baseOwnReactions,
|
|
1454
|
-
enforceUnique,
|
|
1455
|
-
reaction,
|
|
1456
|
-
removed,
|
|
1457
|
-
userId: this.channel.getClient().userId,
|
|
1458
|
-
});
|
|
1459
|
-
this.ingestItem({ ...formatted, own_reactions });
|
|
2051
|
+
findItemByTimestamp = (
|
|
2052
|
+
timestamp: TimestampNS,
|
|
2053
|
+
exactTsMatch = false,
|
|
2054
|
+
): LocalMessage | null => {
|
|
2055
|
+
for (const interval of this.sortIntervals(this.itemIntervals)) {
|
|
2056
|
+
const found = this.findItemByTimestampIn(
|
|
2057
|
+
this.intervalToItems(interval),
|
|
2058
|
+
timestamp,
|
|
2059
|
+
exactTsMatch,
|
|
2060
|
+
);
|
|
2061
|
+
if (found !== undefined) return found;
|
|
2062
|
+
}
|
|
2063
|
+
return null;
|
|
1460
2064
|
};
|
|
1461
2065
|
|
|
1462
2066
|
/**
|
|
1463
|
-
*
|
|
1464
|
-
*
|
|
1465
|
-
* lower-bound search), or the newest loaded message when the timestamp is beyond it. Used by the
|
|
1466
|
-
* receipts tracker to resolve read/delivered cursors. Searches the newest loaded window — where
|
|
1467
|
-
* read cursors live — which is already sorted, so this is O(log n) with no re-sort.
|
|
2067
|
+
* {@link findItemByTimestamp} within one interval (`items` ascending by `created_at`). `undefined`
|
|
2068
|
+
* when every item is newer than `timestamp`, so an older interval has to be searched.
|
|
1468
2069
|
*/
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
if (!items.length) return
|
|
1475
|
-
//
|
|
1476
|
-
//
|
|
1477
|
-
//
|
|
1478
|
-
// been reached. A ceil match (first message >= target) would over-count it — e.g. a participant
|
|
1479
|
-
// whose read cursor predates every loaded message would be reported as having read the oldest one.
|
|
1480
|
-
// `lowerBound` returns the first index whose created_at is strictly greater than the target, so
|
|
1481
|
-
// the floor is the item immediately before it.
|
|
2070
|
+
private findItemByTimestampIn(
|
|
2071
|
+
items: LocalMessage[],
|
|
2072
|
+
timestamp: TimestampNS,
|
|
2073
|
+
exactTsMatch: boolean,
|
|
2074
|
+
): LocalMessage | null | undefined {
|
|
2075
|
+
if (!items.length) return undefined;
|
|
2076
|
+
// A floor, not a ceil: a cursor is the timestamp of the last message a participant reached, so a
|
|
2077
|
+
// ceil would count the oldest loaded message as read by a cursor that predates all of them.
|
|
2078
|
+
// `lowerBound` finds the first index strictly after the target.
|
|
1482
2079
|
const firstAfter = lowerBound(items.length, (i) => {
|
|
1483
2080
|
const t = getMessageCreatedAtTimestamp(items[i]);
|
|
1484
2081
|
return t === null || t > timestamp;
|
|
1485
2082
|
});
|
|
1486
|
-
if (firstAfter === 0) return
|
|
2083
|
+
if (firstAfter === 0) return undefined; // target precedes every message in this interval
|
|
1487
2084
|
const found = items[firstAfter - 1];
|
|
1488
2085
|
const foundTimestamp = getMessageCreatedAtTimestamp(found);
|
|
1489
|
-
// A message without a
|
|
1490
|
-
// server timestamp) cannot be located by timestamp.
|
|
2086
|
+
// A message without a server timestamp (e.g. optimistic) cannot be located.
|
|
1491
2087
|
if (foundTimestamp === null) return null;
|
|
1492
2088
|
if (!exactTsMatch) return found;
|
|
1493
2089
|
return foundTimestamp === timestamp ? found : null;
|
|
1494
|
-
}
|
|
2090
|
+
}
|
|
1495
2091
|
|
|
1496
|
-
filterQueryResults
|
|
1497
|
-
items.filter(this.shouldIncludeMessageInInterval.bind(this));
|
|
2092
|
+
override filterQueryResults(items: LocalMessage[]) {
|
|
2093
|
+
return items.filter(this.shouldIncludeMessageInInterval.bind(this));
|
|
2094
|
+
}
|
|
2095
|
+
|
|
2096
|
+
/**
|
|
2097
|
+
* The sort of a replies request. A page newer than a cursor (`id_gt`, `created_at_after`, ...)
|
|
2098
|
+
* must hold the replies right after the cursor, so it is requested oldest first: newest first
|
|
2099
|
+
* returns the newest replies and skips the ones in between. The page is put in item order
|
|
2100
|
+
* afterwards, so the request sort only decides which replies the page holds.
|
|
2101
|
+
*/
|
|
2102
|
+
private getRepliesRequestSort(options: MessageQueryShape): MessagePaginatorSort {
|
|
2103
|
+
if (getLinearQueryDirection(options) !== 'headward') return this.requestSort;
|
|
2104
|
+
return this.requestSort.map((sort) => ({ ...sort, direction: 1 }));
|
|
2105
|
+
}
|
|
1498
2106
|
|
|
1499
2107
|
private getCanonicalQueryItems(items: LocalMessage[]): LocalMessage[] {
|
|
1500
2108
|
return [...items].sort(this.itemOrderComparator);
|
|
1501
2109
|
}
|
|
1502
|
-
}
|
|
1503
2110
|
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
//
|
|
1514
|
-
//
|
|
1515
|
-
//
|
|
2111
|
+
/**
|
|
2112
|
+
* The cursor and more-messages flags after a page is placed (`deriveCursor`). A page around a
|
|
2113
|
+
* point counts the messages the server returned on each side of it. Any other page is compared
|
|
2114
|
+
* with the interval's outermost server-known messages (see {@link getServerKnownEdges}): a page
|
|
2115
|
+
* never holds an unsent message, so one at an edge must not hide that the page reached the edge.
|
|
2116
|
+
*/
|
|
2117
|
+
private deriveCursorFromPage(
|
|
2118
|
+
ctx: CursorDeriveContext<LocalMessage, MessageQueryShape>,
|
|
2119
|
+
): CursorDeriveResult {
|
|
2120
|
+
// The interval is built from the filtered page but `ctx.page` is the raw response. The linear
|
|
2121
|
+
// derivation compares the page's length with the requested size and its edges with the
|
|
2122
|
+
// interval's server-known edges, so the locally filtered messages (e.g. shadowed) are dropped for
|
|
2123
|
+
// it, or it would wrongly conclude the page is not at the bounds.
|
|
1516
2124
|
const pageWithPermittedMessages: LocalMessage[] = [];
|
|
1517
2125
|
let filteredLocallyCount = 0;
|
|
1518
2126
|
for (const message of ctx.page) {
|
|
1519
|
-
if (!
|
|
2127
|
+
if (!this.shouldIncludeMessageInInterval(message)) {
|
|
1520
2128
|
filteredLocallyCount++;
|
|
1521
2129
|
} else {
|
|
1522
2130
|
pageWithPermittedMessages.push(message);
|
|
@@ -1527,11 +2135,7 @@ const makeDeriveCursor =
|
|
|
1527
2135
|
0,
|
|
1528
2136
|
ctx.requestedPageSize - filteredLocallyCount,
|
|
1529
2137
|
);
|
|
1530
|
-
|
|
1531
|
-
if (
|
|
1532
|
-
ctx.interval &&
|
|
1533
|
-
ctx.interval.itemIds.length + filteredLocallyCount < ctx.page.length
|
|
1534
|
-
) {
|
|
2138
|
+
if (ctx.interval.itemIds.length + filteredLocallyCount < ctx.page.length) {
|
|
1535
2139
|
console.error(
|
|
1536
2140
|
'error',
|
|
1537
2141
|
'Corrupted message set state: parent set size < returned page size',
|
|
@@ -1543,48 +2147,23 @@ const makeDeriveCursor =
|
|
|
1543
2147
|
};
|
|
1544
2148
|
}
|
|
1545
2149
|
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
tailward: !hasMoreTail ? null : (ctx.interval?.itemIds[0] ?? null),
|
|
1556
|
-
};
|
|
1557
|
-
return { cursor, hasMoreHead, hasMoreTail };
|
|
2150
|
+
// A page around a point is judged by how many messages the server returned on each side of it,
|
|
2151
|
+
// so it is read as returned: a message filtered locally, the target included, still shows the
|
|
2152
|
+
// server had it, and dropping it would make its side look exhausted.
|
|
2153
|
+
const aroundDerivationCtx = ctx;
|
|
2154
|
+
const linearDerivationCtx = {
|
|
2155
|
+
...ctx,
|
|
2156
|
+
intervalEdges: this.getServerKnownEdges(ctx.interval),
|
|
2157
|
+
page: pageWithPermittedMessages,
|
|
2158
|
+
requestedPageSize: requestedPageSizeAfterAdjustment,
|
|
1558
2159
|
};
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
page: pageWithPermittedMessages,
|
|
1570
|
-
requestedPageSize: requestedPageSizeAfterAdjustment,
|
|
1571
|
-
}),
|
|
1572
|
-
);
|
|
1573
|
-
} else if (ctx.queryShape?.id_around) {
|
|
1574
|
-
return injectCursor(
|
|
1575
|
-
deriveIdAroundPaginationFlags({
|
|
1576
|
-
...ctx,
|
|
1577
|
-
page: pageWithPermittedMessages,
|
|
1578
|
-
requestedPageSize: requestedPageSizeAfterAdjustment,
|
|
1579
|
-
}),
|
|
1580
|
-
);
|
|
1581
|
-
} else {
|
|
1582
|
-
return injectCursor(
|
|
1583
|
-
deriveLinearPaginationFlags({
|
|
1584
|
-
...ctx,
|
|
1585
|
-
page: pageWithPermittedMessages,
|
|
1586
|
-
requestedPageSize: requestedPageSizeAfterAdjustment,
|
|
1587
|
-
}),
|
|
1588
|
-
);
|
|
1589
|
-
}
|
|
1590
|
-
};
|
|
2160
|
+
const flags = (ctx.queryShape as MessagePaginationParams)?.created_at_around
|
|
2161
|
+
? deriveCreatedAtAroundPaginationFlags<LocalMessage, MessagePaginationParams>(
|
|
2162
|
+
aroundDerivationCtx,
|
|
2163
|
+
)
|
|
2164
|
+
: ctx.queryShape?.id_around
|
|
2165
|
+
? deriveIdAroundPaginationFlags(aroundDerivationCtx)
|
|
2166
|
+
: deriveLinearPaginationFlags(linearDerivationCtx);
|
|
2167
|
+
return { ...flags, cursor: this.getCursorFromInterval(ctx.interval, flags) };
|
|
2168
|
+
}
|
|
2169
|
+
}
|