stream-chat 10.0.0-rc.8 → 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 +22095 -22290
- package/dist/cjs/index.browser.js.map +4 -4
- package/dist/cjs/index.node.js +22143 -22298
- package/dist/cjs/index.node.js.map +4 -4
- package/dist/esm/index.mjs +22093 -22288
- package/dist/esm/index.mjs.map +4 -4
- package/dist/types/ChannelManager.d.ts +216 -135
- package/dist/types/CooldownTimer.d.ts +16 -27
- package/dist/types/EventHandlerPipeline.d.ts +18 -38
- package/dist/types/LiveLocationManager.d.ts +25 -47
- package/dist/types/api-client.d.ts +17 -5
- package/dist/types/channel.d.ts +435 -500
- package/dist/types/channel_state.d.ts +72 -112
- package/dist/types/client.d.ts +323 -440
- 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 +3 -1
- 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 +2540 -698
- package/dist/types/gen/models/timestamp-guard.d.ts +22 -0
- package/dist/types/gen/moderation/ModerationApi.d.ts +37 -14
- package/dist/types/index.d.ts +10 -5
- 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 +8 -2
- 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 -123
- 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 +20 -19
- 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 +43 -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 -185
- 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 -327
- 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 +8 -13
- package/dist/types/pagination/utility.search.d.ts +3 -8
- package/dist/types/poll.d.ts +35 -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 +17 -7
- 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 +67 -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 -197
- 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 +45 -0
- package/dist/types/utils.d.ts +74 -93
- package/package.json +14 -40
- package/src/ChannelManager.ts +494 -303
- package/src/CooldownTimer.ts +46 -59
- package/src/EventHandlerPipeline.ts +22 -45
- package/src/LiveLocationManager.ts +99 -91
- package/src/api-client.ts +113 -50
- package/src/campaign.ts +1 -1
- package/src/channel.ts +1098 -1351
- package/src/channel_batch_updater.ts +1 -1
- package/src/channel_state.ts +81 -174
- package/src/client.ts +755 -970
- 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 -231
- 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 +7 -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 -1752
- package/src/gen/models/index.ts +2566 -3440
- package/src/gen/models/timestamp-guard.ts +27 -0
- package/src/gen/moderation/ModerationApi.ts +183 -406
- package/src/index.ts +32 -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 +49 -9
- 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 +234 -179
- 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/sharedLocation.ts +7 -2
- 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 -124
- package/src/messageDelivery/MessageReceiptsTracker.ts +122 -139
- package/src/messageOperations/FailedSendCache.ts +85 -0
- package/src/messageOperations/MessageOperationStatePolicy.ts +124 -116
- package/src/messageOperations/MessageOperations.ts +297 -175
- package/src/{entityStore → messageOperations}/applyReactionLocally.ts +13 -25
- 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 +231 -681
- package/src/offline-support/offline_sync_manager.ts +51 -90
- package/src/offline-support/queueableOperations.ts +98 -73
- package/src/offline-support/types.ts +43 -185
- 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 +17 -62
- 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 +481 -219
- package/src/pagination/paginators/MessageIntervalPaginator.ts +1362 -775
- package/src/pagination/paginators/MessagePaginator.ts +521 -240
- 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 +18 -15
- 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 +17 -24
- package/src/pagination/utility.search.ts +4 -11
- package/src/poll.ts +183 -102
- package/src/poll_manager.ts +24 -22
- package/src/poll_optimistic_votes.ts +335 -0
- package/src/reminders/Reminder.ts +33 -16
- package/src/reminders/ReminderManager.ts +23 -56
- package/src/reminders/ReminderTimer.ts +6 -6
- 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 +430 -712
- package/src/thread_manager.ts +300 -234
- package/src/token_manager.ts +12 -22
- package/src/types.ts +102 -214
- 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 +64 -0
- package/src/utils.ts +227 -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 -26
- package/dist/types/gen/model-decoders/decoders.d.ts +0 -3
- package/dist/types/gen/model-decoders/event-decoder-mapping.d.ts +0 -6
- 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/gen/model-decoders/decoders.ts +0 -2710
- package/src/gen/model-decoders/event-decoder-mapping.ts +0 -198
- 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 -249
- package/src/messageOperations/persistence.ts +0 -40
- package/src/pagination/utility.queryChannel.ts +0 -84
- package/src/store.ts +0 -304
package/src/thread.ts
CHANGED
|
@@ -1,43 +1,31 @@
|
|
|
1
|
-
import { StateStore } from '
|
|
2
|
-
import {
|
|
3
|
-
computeOwnReactions,
|
|
4
|
-
formatMessage,
|
|
5
|
-
localMessageToNewMessagePayload,
|
|
6
|
-
} from './utils';
|
|
1
|
+
import { StateStore } from '@stream-io/state-store';
|
|
2
|
+
import { formatMessage } from './utils';
|
|
7
3
|
import type {
|
|
8
4
|
DraftResponse,
|
|
9
|
-
|
|
5
|
+
EventPayload,
|
|
10
6
|
LocalMessage,
|
|
11
7
|
MarkReadRequest,
|
|
12
8
|
MarkReadResponse,
|
|
13
9
|
MessageResponse,
|
|
14
|
-
ReactionRequest,
|
|
15
10
|
ReadStateResponse,
|
|
16
|
-
SendReactionRequest,
|
|
17
11
|
SortParamRequest,
|
|
18
12
|
StreamResponse,
|
|
19
13
|
ThreadStateResponse,
|
|
14
|
+
TimestampNS,
|
|
20
15
|
UserResponse,
|
|
21
16
|
} from './types';
|
|
22
17
|
import { isDoesNotExistError } from './errors';
|
|
23
|
-
import type {
|
|
24
|
-
|
|
25
|
-
DeleteMessageWithStateUpdateParams,
|
|
26
|
-
SendMessageWithStateUpdateParams,
|
|
27
|
-
UpdateMessageWithStateUpdateParams,
|
|
28
|
-
} from './channel';
|
|
18
|
+
import type { Channel } from './channel';
|
|
19
|
+
import { ChannelWatchStatus } from './channel_state';
|
|
29
20
|
import type { StreamChat } from './client';
|
|
30
21
|
import type { CustomThreadData } from './custom_types';
|
|
31
22
|
import { MessageComposer } from './messageComposer';
|
|
32
|
-
import {
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
deleteReactionOptimistically,
|
|
36
|
-
MessageOperations,
|
|
37
|
-
} from './messageOperations';
|
|
23
|
+
import { createMessageOperations } from './messageOperations';
|
|
24
|
+
import type { MessageOperations } from './messageOperations';
|
|
25
|
+
import { nowNs } from './utils/time';
|
|
38
26
|
import { WithSubscriptions } from './utils/WithSubscriptions';
|
|
39
27
|
import { MessagePaginator } from './pagination';
|
|
40
|
-
import type {
|
|
28
|
+
import type { PaginatorCursor, ReconcileNewestMessagesOptions } from './pagination';
|
|
41
29
|
import { applyInstanceConfiguration } from './configuration/utils/applyInstanceConfiguration';
|
|
42
30
|
import { ConfigController } from './configuration/ConfigController';
|
|
43
31
|
import { deepFreezeConfig } from './configuration/utils/deepFreezeConfig';
|
|
@@ -49,32 +37,41 @@ import {
|
|
|
49
37
|
} from './configuration/utils/declarativeSlices';
|
|
50
38
|
import type { PipelineEvent } from './EventHandlerPipeline';
|
|
51
39
|
|
|
40
|
+
const getCursorFromReplies = (
|
|
41
|
+
replies: LocalMessage[],
|
|
42
|
+
reachesTail: boolean,
|
|
43
|
+
): PaginatorCursor => {
|
|
44
|
+
const oldest = replies.reduce<LocalMessage | undefined>(
|
|
45
|
+
(acc, reply) => (!acc || reply.created_at < acc.created_at ? reply : acc),
|
|
46
|
+
undefined,
|
|
47
|
+
);
|
|
48
|
+
return { headward: null, tailward: reachesTail ? null : (oldest?.id ?? null) };
|
|
49
|
+
};
|
|
50
|
+
|
|
52
51
|
export type ThreadState = {
|
|
53
|
-
/**
|
|
54
|
-
* Determines if the thread is currently opened and on-screen. When the thread is active,
|
|
55
|
-
* all new messages are immediately marked as read.
|
|
56
|
-
*/
|
|
52
|
+
/** Whether the thread is open and on-screen. While active, new messages are marked read. */
|
|
57
53
|
active: boolean;
|
|
58
54
|
channel: Channel;
|
|
59
|
-
|
|
55
|
+
/** Unix nanoseconds, as the API sends it. */
|
|
56
|
+
createdAt: TimestampNS;
|
|
60
57
|
custom: CustomThreadData;
|
|
61
|
-
|
|
58
|
+
/** Unix nanoseconds, as the API sends it. */
|
|
59
|
+
deletedAt: TimestampNS | null;
|
|
62
60
|
isLoading: boolean;
|
|
63
61
|
isStateStale: boolean;
|
|
64
|
-
/**
|
|
65
|
-
* Thread is identified by and has a one-to-one relation with its parent message.
|
|
66
|
-
* We use parent message id as a thread id.
|
|
67
|
-
*/
|
|
62
|
+
/** A thread maps one-to-one to its parent message, whose ID is the thread ID. */
|
|
68
63
|
parentMessage: LocalMessage;
|
|
69
64
|
participants: ThreadStateResponse['thread_participants'];
|
|
70
65
|
read: ThreadReadState;
|
|
71
66
|
replyCount: number;
|
|
72
67
|
title: string;
|
|
73
|
-
|
|
68
|
+
/** Unix nanoseconds, as the API sends it. */
|
|
69
|
+
updatedAt: TimestampNS | null;
|
|
74
70
|
};
|
|
75
71
|
|
|
76
72
|
export type ThreadUserReadState = {
|
|
77
|
-
|
|
73
|
+
/** Unix nanoseconds, as the API sends it. */
|
|
74
|
+
lastReadAt: TimestampNS;
|
|
78
75
|
unreadMessageCount: number;
|
|
79
76
|
user: UserResponse;
|
|
80
77
|
lastReadMessageId?: string;
|
|
@@ -83,6 +80,12 @@ export type ThreadUserReadState = {
|
|
|
83
80
|
|
|
84
81
|
export type ThreadReadState = Record<string, ThreadUserReadState | undefined>;
|
|
85
82
|
|
|
83
|
+
const timestampOr = (
|
|
84
|
+
value: TimestampNS | undefined,
|
|
85
|
+
fallback: TimestampNS,
|
|
86
|
+
): TimestampNS =>
|
|
87
|
+
typeof value === 'number' && Number.isFinite(value) ? value : fallback;
|
|
88
|
+
|
|
86
89
|
const DEFAULT_PAGE_LIMIT = 50;
|
|
87
90
|
const DEFAULT_SORT: SortParamRequest[] = [{ field: 'created_at', direction: -1 }];
|
|
88
91
|
const DEFAULT_ITEM_ORDER: SortParamRequest[] = [{ field: 'created_at', direction: 1 }];
|
|
@@ -98,27 +101,21 @@ export type ThreadConfig = {
|
|
|
98
101
|
};
|
|
99
102
|
};
|
|
100
103
|
|
|
101
|
-
/**
|
|
102
|
-
* Empty because every field of `ThreadConfig` is optional — a thread's own configuration is one handler
|
|
103
|
-
* wide. Declared and frozen anyway, so the entity carries the same defaults layer as every other
|
|
104
|
-
* configurable class rather than a special case.
|
|
105
|
-
*/
|
|
104
|
+
/** Empty: every field of `ThreadConfig` is optional. */
|
|
106
105
|
export const DEFAULT_THREAD_CONFIG: ThreadConfig = deepFreezeConfig({});
|
|
107
106
|
|
|
108
107
|
export class Thread extends WithSubscriptions {
|
|
109
|
-
/** The shared configuration machinery — see {@link ConfigController}. */
|
|
110
108
|
private readonly configController = new ConfigController<ThreadConfig>({
|
|
111
109
|
defaults: DEFAULT_THREAD_CONFIG,
|
|
112
110
|
});
|
|
113
111
|
public readonly state: StateStore<ThreadState>;
|
|
114
112
|
public readonly id: string;
|
|
115
113
|
public readonly messageComposer: MessageComposer;
|
|
116
|
-
public readonly messagePaginator: MessagePaginator;
|
|
117
114
|
public readonly messageOperations: MessageOperations;
|
|
115
|
+
public readonly messagePaginator: MessagePaginator;
|
|
118
116
|
|
|
119
117
|
private client: StreamChat;
|
|
120
118
|
private failedRepliesMap: Map<string, LocalMessage> = new Map();
|
|
121
|
-
/** How many consumers have called `activate()` without a matching `deactivate()`. */
|
|
122
119
|
private _activeRefCount = 0;
|
|
123
120
|
|
|
124
121
|
constructor({
|
|
@@ -136,48 +133,12 @@ export class Thread extends WithSubscriptions {
|
|
|
136
133
|
}) {
|
|
137
134
|
super();
|
|
138
135
|
if (threadData) {
|
|
139
|
-
if (!threadData.channel) {
|
|
140
|
-
throw new Error('Thread channel is required when threadData is provided');
|
|
141
|
-
}
|
|
142
|
-
if (!threadData.parent_message) {
|
|
143
|
-
throw new Error('Thread parent_message is required when threadData is provided');
|
|
144
|
-
}
|
|
145
|
-
const threadChannel = client.channel(
|
|
146
|
-
threadData.channel.type,
|
|
147
|
-
threadData.channel.id,
|
|
148
|
-
{ custom: threadData.channel.custom },
|
|
149
|
-
);
|
|
150
|
-
threadChannel._hydrateMembers({
|
|
151
|
-
members: threadData.channel.members ?? [],
|
|
152
|
-
overrideCurrentState: false,
|
|
153
|
-
});
|
|
154
|
-
|
|
155
136
|
this.state = new StateStore<ThreadState>({
|
|
156
|
-
// local only
|
|
157
137
|
active: false,
|
|
158
138
|
isLoading: false,
|
|
159
139
|
isStateStale: false,
|
|
160
|
-
|
|
161
|
-
channel:
|
|
162
|
-
createdAt: new Date(threadData.created_at),
|
|
163
|
-
// rest
|
|
164
|
-
deletedAt: threadData.deleted_at ? new Date(threadData.deleted_at) : null,
|
|
165
|
-
parentMessage: formatMessage(threadData.parent_message),
|
|
166
|
-
participants: threadData.thread_participants,
|
|
167
|
-
read: formatReadState(
|
|
168
|
-
!threadData.read || threadData.read.length === 0
|
|
169
|
-
? getPlaceholderReadResponse(client.userId)
|
|
170
|
-
: threadData.read,
|
|
171
|
-
),
|
|
172
|
-
// Use the parent message's reply_count, not the top-level threadData.reply_count. The
|
|
173
|
-
// thread endpoints (getThread/queryThreads) return a top level reply_count that EXCLUDES
|
|
174
|
-
// soft-deleted replies, while parent_message.reply_count (and the channel's own copy)
|
|
175
|
-
// INCLUDE them so the top level value renders fewer replies than the channel badge shows.
|
|
176
|
-
// parent_message.reply_count is the authoritative, channel consistent count.
|
|
177
|
-
replyCount: threadData.parent_message.reply_count ?? 0,
|
|
178
|
-
updatedAt: threadData.updated_at ? new Date(threadData.updated_at) : null,
|
|
179
|
-
title: threadData.title,
|
|
180
|
-
custom: threadData.custom ?? {},
|
|
140
|
+
...formatThreadState(threadData, client.userId),
|
|
141
|
+
channel: ensureThreadChannel(client, threadData),
|
|
181
142
|
});
|
|
182
143
|
|
|
183
144
|
this.id = threadData.parent_message_id;
|
|
@@ -193,9 +154,8 @@ export class Thread extends WithSubscriptions {
|
|
|
193
154
|
}
|
|
194
155
|
|
|
195
156
|
const formattedParentMessage = formatMessage(parentMessage);
|
|
196
|
-
const createdAt = parentMessage.created_at
|
|
197
|
-
|
|
198
|
-
: new Date();
|
|
157
|
+
const createdAt = timestampOr(parentMessage.created_at, nowNs());
|
|
158
|
+
const replyCount = parentMessage.reply_count ?? 0;
|
|
199
159
|
|
|
200
160
|
this.state = new StateStore<ThreadState>({
|
|
201
161
|
active: false,
|
|
@@ -204,13 +164,17 @@ export class Thread extends WithSubscriptions {
|
|
|
204
164
|
custom: {},
|
|
205
165
|
deletedAt: formattedParentMessage.deleted_at ?? null,
|
|
206
166
|
isLoading: false,
|
|
207
|
-
|
|
167
|
+
// Loads its data once when opened. A parent without replies in a watched channel has nothing
|
|
168
|
+
// on the server yet (`getThread` would answer 404); in an unwatched channel `reply_count` may
|
|
169
|
+
// miss newer replies, so it loads.
|
|
170
|
+
isStateStale:
|
|
171
|
+
replyCount > 0 || channel.watchStatus !== ChannelWatchStatus.Watching,
|
|
208
172
|
parentMessage: formattedParentMessage,
|
|
209
173
|
participants: [],
|
|
210
174
|
read: formatReadState(getPlaceholderReadResponse(client.userId)),
|
|
211
|
-
replyCount
|
|
175
|
+
replyCount,
|
|
212
176
|
title: '',
|
|
213
|
-
updatedAt: parentMessage.updated_at
|
|
177
|
+
updatedAt: parentMessage.updated_at ?? null,
|
|
214
178
|
});
|
|
215
179
|
|
|
216
180
|
this.id = parentMessage.id;
|
|
@@ -218,11 +182,9 @@ export class Thread extends WithSubscriptions {
|
|
|
218
182
|
|
|
219
183
|
this.client = client;
|
|
220
184
|
|
|
221
|
-
// Read
|
|
222
|
-
// options — the reply paginator's `unreadReferencePolicy` and initial cursor are read once.
|
|
185
|
+
// Read up front: the reply paginator takes `unreadReferencePolicy` as a constructor argument.
|
|
223
186
|
const declarativeConfig = client.config.getConfig('thread') ?? undefined;
|
|
224
|
-
//
|
|
225
|
-
// the per-parent slice overrides it (thread replies default to a smaller page than a channel).
|
|
187
|
+
// The general `messagePaginator` key applies to replies; the thread's own slice overrides it.
|
|
226
188
|
const messagePaginatorConfig = mergeDeclarativePaginatorConfig(
|
|
227
189
|
client.config.getConfig('messagePaginator') ?? undefined,
|
|
228
190
|
declarativeConfig?.messagePaginator,
|
|
@@ -231,39 +193,36 @@ export class Thread extends WithSubscriptions {
|
|
|
231
193
|
this.messagePaginator = new MessagePaginator(
|
|
232
194
|
{
|
|
233
195
|
channel: this.channel,
|
|
196
|
+
thread: this,
|
|
234
197
|
parentMessageId: this.id,
|
|
235
198
|
requestSort: DEFAULT_SORT,
|
|
236
199
|
itemOrder: DEFAULT_ITEM_ORDER,
|
|
237
|
-
//
|
|
200
|
+
// A constructor argument, not paginator configuration.
|
|
238
201
|
unreadReferencePolicy: messagePaginatorConfig?.unreadReferencePolicy,
|
|
239
202
|
paginatorOptions: {
|
|
240
203
|
declarativeConfig: toDeclarativePaginatorConfig(messagePaginatorConfig),
|
|
241
204
|
},
|
|
242
205
|
},
|
|
243
|
-
//
|
|
244
|
-
//
|
|
245
|
-
// overrides it, which would not be true of a construction argument.
|
|
206
|
+
// SDK default page size. Overridable through `client.config.set`
|
|
207
|
+
// (`messagePaginator.pageSize`).
|
|
246
208
|
{ pageSize: DEFAULT_PAGE_LIMIT },
|
|
247
209
|
);
|
|
248
210
|
|
|
249
|
-
//
|
|
250
|
-
//
|
|
251
|
-
// first reply page instantly, without a network fetch on open. `latest_replies` is the most
|
|
252
|
-
// recent window of replies, so it reaches the head (nothing newer to load); it reaches the
|
|
253
|
-
// tail only when it already contains every reply. Threads built from a bare parent message
|
|
254
|
-
// carry no replies to seed and fall back to a paginator fetch on first open.
|
|
211
|
+
// Seeds the first reply page without a fetch. `latest_replies` is the newest interval: it
|
|
212
|
+
// reaches the head, and the tail only if it holds every reply.
|
|
255
213
|
if (threadData?.latest_replies?.length) {
|
|
214
|
+
const replies = threadData.latest_replies.map(formatMessage);
|
|
215
|
+
const isLastPage = holdsEveryReply(replies, threadData);
|
|
256
216
|
this.messagePaginator.setItems({
|
|
257
|
-
valueOrFactory:
|
|
217
|
+
valueOrFactory: replies,
|
|
218
|
+
cursor: getCursorFromReplies(replies, isLastPage),
|
|
258
219
|
isFirstPage: true,
|
|
259
|
-
isLastPage
|
|
220
|
+
isLastPage,
|
|
260
221
|
});
|
|
261
222
|
}
|
|
262
223
|
|
|
263
|
-
//
|
|
264
|
-
|
|
265
|
-
// newest reply is not among `latest_replies` still reports the correct latest-activity timestamp.
|
|
266
|
-
this.messagePaginator.seedLastMessageAt(threadData?.last_message_at);
|
|
224
|
+
// Floor for `latestMessageAt`, for when the newest reply is not among `latest_replies`.
|
|
225
|
+
this.messagePaginator.setQueriedLatestMessageAt(threadData?.last_message_at);
|
|
267
226
|
|
|
268
227
|
this.messageComposer = new MessageComposer({
|
|
269
228
|
client,
|
|
@@ -271,119 +230,19 @@ export class Thread extends WithSubscriptions {
|
|
|
271
230
|
compositionContext: this,
|
|
272
231
|
});
|
|
273
232
|
|
|
274
|
-
this.messageOperations =
|
|
275
|
-
...createMessageOperationsPersistence({ channel: this.channel }),
|
|
276
|
-
ingest: (m) => {
|
|
277
|
-
const store = this.channel.getClient().messageStore;
|
|
278
|
-
// See the matching comment in `Channel`: the reply paginator's filter demands
|
|
279
|
-
// `parent_id === this.id`, so an operation on this thread's PARENT message — edited or deleted
|
|
280
|
-
// from inside the open thread, which is how the UI SDKs route it — is not something the reply
|
|
281
|
-
// paginator can hold. The store reaches it (a subscribed thread seeds its parent there) and
|
|
282
|
-
// fans the change out to the channel list too.
|
|
283
|
-
if (this.messagePaginator.matchesFilter(m)) {
|
|
284
|
-
this.messagePaginator.ingestItem(m);
|
|
285
|
-
} else if (store.has(m.id)) {
|
|
286
|
-
store.upsert(m);
|
|
287
|
-
}
|
|
288
|
-
store.flushSubscribers(m.id);
|
|
289
|
-
},
|
|
290
|
-
// Mirrors `ingest`'s routing: a message this paginator does not hold can still be held by the
|
|
291
|
-
// client-global store (a thread parent, a message displayed by another collection), and the
|
|
292
|
-
// policy uses this both for its freshness comparison and to decide whether there is anything to
|
|
293
|
-
// update optimistically at all. Reading only the paginator would make those two disagree.
|
|
294
|
-
get: (id) =>
|
|
295
|
-
this.messagePaginator.getItem(id) ??
|
|
296
|
-
this.channel.getClient().messageStore.get(id),
|
|
297
|
-
remove: (id) => {
|
|
298
|
-
this.messagePaginator.removeItem({ id });
|
|
299
|
-
// A reply with `show_in_channel` is held by the channel list as well, so removing it from the
|
|
300
|
-
// reply paginator alone leaves a ghost there until the `message.deleted` event arrives. Both
|
|
301
|
-
// calls are no-ops when the paginator does not hold the id, which is the same reason the SDK's
|
|
302
|
-
// own `removeMessage` removes from the channel unconditionally.
|
|
303
|
-
this.channel.messagePaginator.removeItem({ id });
|
|
304
|
-
this.channel.pinnedMessagesPaginator.removeItem({ id });
|
|
305
|
-
},
|
|
306
|
-
normalizeOutgoingMessage: (m) => ({
|
|
307
|
-
...m,
|
|
308
|
-
parent_id: this.id,
|
|
309
|
-
}),
|
|
310
|
-
handlers: () => {
|
|
311
|
-
const { requestHandlers } = this.channel.configState.getLatestValue();
|
|
312
|
-
const deleteMessageRequest = requestHandlers?.deleteMessageRequest;
|
|
313
|
-
const sendMessageRequest = requestHandlers?.sendMessageRequest;
|
|
314
|
-
const retrySendMessageRequest = requestHandlers?.retrySendMessageRequest;
|
|
315
|
-
const updateMessageRequest = requestHandlers?.updateMessageRequest;
|
|
316
|
-
return {
|
|
317
|
-
delete: deleteMessageRequest
|
|
318
|
-
? (p) =>
|
|
319
|
-
deleteMessageRequest({
|
|
320
|
-
localMessage: p.localMessage,
|
|
321
|
-
options: p.options,
|
|
322
|
-
})
|
|
323
|
-
: undefined,
|
|
324
|
-
send: sendMessageRequest
|
|
325
|
-
? (p) =>
|
|
326
|
-
sendMessageRequest({
|
|
327
|
-
localMessage: p.localMessage,
|
|
328
|
-
message: p.message,
|
|
329
|
-
options: p.options,
|
|
330
|
-
})
|
|
331
|
-
: undefined,
|
|
332
|
-
retry: retrySendMessageRequest
|
|
333
|
-
? (p) =>
|
|
334
|
-
retrySendMessageRequest({
|
|
335
|
-
localMessage: p.localMessage,
|
|
336
|
-
message: p.message,
|
|
337
|
-
options: p.options,
|
|
338
|
-
})
|
|
339
|
-
: undefined,
|
|
340
|
-
update: updateMessageRequest
|
|
341
|
-
? (p) =>
|
|
342
|
-
updateMessageRequest({
|
|
343
|
-
localMessage: p.localMessage,
|
|
344
|
-
options: p.options,
|
|
345
|
-
})
|
|
346
|
-
: undefined,
|
|
347
|
-
};
|
|
348
|
-
},
|
|
349
|
-
defaults: {
|
|
350
|
-
delete: async (id, o) => {
|
|
351
|
-
const result = await this.channel.getClient().deleteMessage({ id, ...o });
|
|
352
|
-
return { message: result.message };
|
|
353
|
-
},
|
|
354
|
-
send: async (m, o) => {
|
|
355
|
-
const result = await this.channel.sendMessage({ message: m, ...o });
|
|
356
|
-
return { message: result.message };
|
|
357
|
-
},
|
|
358
|
-
update: async (m, o) => {
|
|
359
|
-
const result = await this.channel.getClient().updateMessage({
|
|
360
|
-
id: m.id,
|
|
361
|
-
message: localMessageToNewMessagePayload(m),
|
|
362
|
-
...o,
|
|
363
|
-
});
|
|
364
|
-
return { message: result.message };
|
|
365
|
-
},
|
|
366
|
-
},
|
|
367
|
-
});
|
|
233
|
+
this.messageOperations = createMessageOperations(this);
|
|
368
234
|
|
|
369
|
-
//
|
|
370
|
-
// configured through its constructor above; this re-applies the mutable half the way a reset does.
|
|
235
|
+
// Same derivation path as `config.reset()`. Idempotent: re-applies what the constructors set.
|
|
371
236
|
this.initializeConfig(declarativeConfig);
|
|
372
237
|
}
|
|
373
238
|
|
|
374
239
|
/**
|
|
375
|
-
* Derives this thread's configuration
|
|
376
|
-
*
|
|
377
|
-
* Called by the constructor and by `client.config.reset()`. The thread owns only its own
|
|
378
|
-
* `requestHandlers`; the paginator derives its own configuration.
|
|
240
|
+
* Derives this thread's configuration, and its reply paginator's, from the declarative slice.
|
|
241
|
+
* Called by the constructor and by `client.config.reset()`.
|
|
379
242
|
*/
|
|
380
243
|
initializeConfig(declarativeConfig?: ThreadDeclarativeConfig): void {
|
|
381
|
-
// Only the thread's own slice
|
|
382
|
-
//
|
|
383
|
-
//
|
|
384
|
-
// Replaces rather than merges: a handler dropped from the declarative tree must disappear. The
|
|
385
|
-
// controller skips a write that changes nothing, which matters because `alsoWatch` re-runs this for
|
|
386
|
-
// any of three keys and `useThreadRequestHandlers` subscribes to the store.
|
|
244
|
+
// Only the thread's own slice: the paginator and operations keys go to those objects below.
|
|
245
|
+
// Replaces rather than merges, so a handler dropped from the declarative tree disappears.
|
|
387
246
|
this.configController.initialize({
|
|
388
247
|
requestHandlers: declarativeConfig?.requestHandlers,
|
|
389
248
|
});
|
|
@@ -397,8 +256,7 @@ export class Thread extends WithSubscriptions {
|
|
|
397
256
|
),
|
|
398
257
|
);
|
|
399
258
|
|
|
400
|
-
//
|
|
401
|
-
// key the channel does, with its own per-parent override.
|
|
259
|
+
// Takes the shared `messageOperations` key like the channel does, with its own override.
|
|
402
260
|
this.messageOperations.initializeConfig(
|
|
403
261
|
mergeDeclarativeMessageOperationsConfig(
|
|
404
262
|
this.client.config.getConfig('messageOperations') ?? undefined,
|
|
@@ -407,23 +265,19 @@ export class Thread extends WithSubscriptions {
|
|
|
407
265
|
);
|
|
408
266
|
}
|
|
409
267
|
|
|
410
|
-
/**
|
|
411
|
-
* Resolved configuration as a store, so consumers can react to it — the shape every configurable class
|
|
412
|
-
* exposes.
|
|
413
|
-
*/
|
|
414
268
|
get configState(): StateStore<ThreadConfig> {
|
|
415
269
|
return this.configController.state;
|
|
416
270
|
}
|
|
417
271
|
|
|
418
|
-
/**
|
|
419
|
-
* This thread's resolved configuration. `Readonly` because the value is the store's live object —
|
|
420
|
-
* assigning to a field of it would change state without notifying anyone. Use {@link updateConfig}.
|
|
421
|
-
*/
|
|
422
272
|
get config(): Readonly<ThreadConfig> {
|
|
423
273
|
return this.configController.value;
|
|
424
274
|
}
|
|
425
275
|
|
|
426
|
-
/**
|
|
276
|
+
/**
|
|
277
|
+
* Merges a partial configuration into the resolved config.
|
|
278
|
+
*
|
|
279
|
+
* @param config - The fields to change.
|
|
280
|
+
*/
|
|
427
281
|
updateConfig(config: Partial<ThreadConfig>): void {
|
|
428
282
|
this.configController.patch(config);
|
|
429
283
|
}
|
|
@@ -440,48 +294,45 @@ export class Thread extends WithSubscriptions {
|
|
|
440
294
|
return ownUnreadCountSelector(this.client.userId)(this.state.getLatestValue());
|
|
441
295
|
}
|
|
442
296
|
|
|
297
|
+
/** See {@link Thread.activate}. */
|
|
298
|
+
get active() {
|
|
299
|
+
return this.state.getLatestValue().active;
|
|
300
|
+
}
|
|
301
|
+
|
|
443
302
|
/**
|
|
444
|
-
* Declares that a consumer is displaying this thread
|
|
303
|
+
* Declares that a consumer is displaying this thread and returns the function that ends it (as
|
|
304
|
+
* `channel.activate()`). Refcounted: the thread stays active until the last release, and each
|
|
305
|
+
* release is idempotent. `active` selects the threads reloaded on reconnect, so release it.
|
|
445
306
|
*
|
|
446
|
-
*
|
|
447
|
-
*
|
|
448
|
-
* hence the refcount, matching `channel.activate()`. A thread held by more than one mount stays
|
|
449
|
-
* active until the last holder releases it.
|
|
307
|
+
* The first activation keeps the thread in `client.threads` for the session, subscribed and
|
|
308
|
+
* resolvable through `client.threads.get(id)` after release.
|
|
450
309
|
*/
|
|
451
|
-
public activate = () => {
|
|
310
|
+
public activate = (): (() => void) => {
|
|
452
311
|
this._activeRefCount += 1;
|
|
453
312
|
if (this._activeRefCount === 1) {
|
|
313
|
+
this.client.threads.register(this);
|
|
454
314
|
this.state.partialNext({ active: true });
|
|
455
315
|
}
|
|
456
|
-
};
|
|
457
316
|
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
}
|
|
317
|
+
let released = false;
|
|
318
|
+
return () => {
|
|
319
|
+
if (released) return;
|
|
320
|
+
released = true;
|
|
321
|
+
this._activeRefCount -= 1;
|
|
322
|
+
if (this._activeRefCount === 0) {
|
|
323
|
+
this.state.partialNext({ active: false });
|
|
324
|
+
}
|
|
325
|
+
};
|
|
468
326
|
};
|
|
469
327
|
|
|
470
328
|
/**
|
|
471
|
-
* Re-queries
|
|
472
|
-
*
|
|
473
|
-
*
|
|
474
|
-
*
|
|
475
|
-
*
|
|
476
|
-
*
|
|
477
|
-
*
|
|
478
|
-
* neither of which covers a thread constructed directly and never registered (the common path in
|
|
479
|
-
* the React Native SDK, which resolves `threadsById[id] ?? new Thread(...)`). Reading the paginator
|
|
480
|
-
* is true for managed and unmanaged threads alike. An overlap merge keeps them anyway (the
|
|
481
|
-
* reconcile's provenance guard never prunes a non-server message); only a disjoint rebuild can drop
|
|
482
|
-
* them, so any that actually fell out are re-ingested below.
|
|
483
|
-
*
|
|
484
|
-
* Rethrows, except for a not-found answer on a thread that never had replies (see the catch).
|
|
329
|
+
* Re-queries the replies, sized to the loaded interval, and reconciles them in place (the thread
|
|
330
|
+
* analogue of {@link Channel.reload}; recovery calls it for active threads). The thread applies
|
|
331
|
+
* the response to itself ({@link Thread.hydrateState}), whether or not it is registered in
|
|
332
|
+
* `client.threads`. Failed replies are kept: those loaded in the reply paginator or in the
|
|
333
|
+
* offline DB before the request that are no longer loaded after it are ingested again (the
|
|
334
|
+
* offline DB read is best effort). Rethrows, except for a not-found answer on a thread that never
|
|
335
|
+
* had replies.
|
|
485
336
|
*/
|
|
486
337
|
public reload = async () => {
|
|
487
338
|
if (this.state.getLatestValue().isLoading) {
|
|
@@ -491,45 +342,40 @@ export class Thread extends WithSubscriptions {
|
|
|
491
342
|
this.state.partialNext({ isLoading: true });
|
|
492
343
|
|
|
493
344
|
try {
|
|
494
|
-
const
|
|
495
|
-
const loadedReplyCount = loadedReplies.length;
|
|
345
|
+
const loadedReplyCount = this.messagePaginator.items?.length ?? 0;
|
|
496
346
|
const requestedReplyLimit =
|
|
497
347
|
Math.max(loadedReplyCount, this.messagePaginator.pageSize ?? 0) || undefined;
|
|
498
|
-
const
|
|
499
|
-
|
|
500
|
-
const
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
this.
|
|
348
|
+
const offlineDb = this.client.offlineDb;
|
|
349
|
+
// best effort: a failing read must not fail the reload
|
|
350
|
+
const failedInDb = offlineDb
|
|
351
|
+
? await offlineDb.getFailedMessages({ cid: this.channel.cid }).catch(() => [])
|
|
352
|
+
: [];
|
|
353
|
+
// after the read: a reply that fails meanwhile is loaded by then
|
|
354
|
+
const failedBefore = this.messagePaginator.getFailedMessagesToRestore(failedInDb);
|
|
355
|
+
const headIntervalItemIdsAtRequest =
|
|
356
|
+
this.messagePaginator.getHeadIntervalItemIdsAtRequest();
|
|
357
|
+
const { thread: threadData } = await this.client.getThread(
|
|
358
|
+
{ message_id: this.id },
|
|
359
|
+
{
|
|
360
|
+
participant_limit: DEFAULT_THREAD_PARTICIPANT_LIMIT,
|
|
361
|
+
watch: true,
|
|
362
|
+
reply_limit: requestedReplyLimit,
|
|
363
|
+
},
|
|
364
|
+
);
|
|
365
|
+
this.channel.watchStatus = ChannelWatchStatus.Watching;
|
|
366
|
+
this.hydrateState(threadData, {
|
|
505
367
|
reconcile: {
|
|
506
368
|
requestedLimit: requestedReplyLimit,
|
|
507
|
-
|
|
369
|
+
headIntervalItemIdsAtRequest,
|
|
508
370
|
},
|
|
509
371
|
});
|
|
510
|
-
|
|
511
|
-
if (failedBefore.length) {
|
|
512
|
-
// Membership is checked against the visible window, NOT `getItem`: that reads the item
|
|
513
|
-
// index, which can still hold a message the rebuild dropped from the loaded window — so an
|
|
514
|
-
// index-based guard skips the re-ingest on exactly the path that needs it.
|
|
515
|
-
const visible = new Set((this.messagePaginator.items ?? []).map((r) => r.id));
|
|
516
|
-
this.messagePaginator.batch(
|
|
517
|
-
() => {
|
|
518
|
-
for (const failed of failedBefore) {
|
|
519
|
-
if (!visible.has(failed.id)) this.messagePaginator.ingestItem(failed);
|
|
520
|
-
}
|
|
521
|
-
},
|
|
522
|
-
{ coalesce: true },
|
|
523
|
-
);
|
|
524
|
-
}
|
|
372
|
+
this.messagePaginator.restoreFailedMessages(failedBefore);
|
|
525
373
|
} catch (error) {
|
|
526
374
|
const notFound =
|
|
527
375
|
isDoesNotExistError(error as Error) ||
|
|
528
376
|
(error as { status?: number })?.status === 404;
|
|
529
377
|
const neverExisted = notFound && this.state.getLatestValue().replyCount === 0;
|
|
530
|
-
//
|
|
531
|
-
// being whether the parent message has any replies or not. A thread with all hard
|
|
532
|
-
// deleted replies will simply not throw.
|
|
378
|
+
// Not found while the parent has no replies: the thread was never created, not an error.
|
|
533
379
|
if (neverExisted) return;
|
|
534
380
|
|
|
535
381
|
throw error;
|
|
@@ -538,107 +384,71 @@ export class Thread extends WithSubscriptions {
|
|
|
538
384
|
}
|
|
539
385
|
};
|
|
540
386
|
|
|
387
|
+
/**
|
|
388
|
+
* Updates the thread's state and its channel's members and custom data, and merges the replies
|
|
389
|
+
* into the loaded interval (with `reconcile`) or replaces it (without).
|
|
390
|
+
*/
|
|
541
391
|
public hydrateState = (
|
|
542
|
-
|
|
543
|
-
options?: { reconcile?:
|
|
392
|
+
threadData: ThreadStateResponse,
|
|
393
|
+
options?: { reconcile?: ReconcileNewestMessagesOptions },
|
|
544
394
|
) => {
|
|
545
|
-
if (
|
|
546
|
-
|
|
547
|
-
return;
|
|
395
|
+
if (threadData.parent_message_id !== this.id) {
|
|
396
|
+
throw new Error("Cannot hydrate thread's state from another thread's response");
|
|
548
397
|
}
|
|
549
398
|
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
"Cannot hydrate thread's state using thread with different threadId",
|
|
553
|
-
);
|
|
554
|
-
}
|
|
399
|
+
const serverState = formatThreadState(threadData, this.client.userId);
|
|
400
|
+
const reconcile = options?.reconcile;
|
|
555
401
|
|
|
556
|
-
|
|
557
|
-
createdAt,
|
|
558
|
-
custom,
|
|
559
|
-
title,
|
|
560
|
-
deletedAt,
|
|
561
|
-
parentMessage,
|
|
562
|
-
participants,
|
|
563
|
-
read,
|
|
564
|
-
replyCount,
|
|
565
|
-
updatedAt,
|
|
566
|
-
} = thread.state.getLatestValue();
|
|
567
|
-
|
|
568
|
-
// Preserve pending (failed) replies so they survive the hydrate. The messagePaginator is now
|
|
569
|
-
// the sole reply source, so we merge the incoming newest page into it and re-ingest the
|
|
570
|
-
// pending replies (mirrors the previous state.replies concat behavior).
|
|
402
|
+
// Failed replies survive the hydrate: they are re-ingested after the incoming page is merged.
|
|
571
403
|
const pendingReplies = Array.from(this.failedRepliesMap.values());
|
|
572
404
|
|
|
573
|
-
this.
|
|
574
|
-
|
|
575
|
-
createdAt,
|
|
576
|
-
custom,
|
|
577
|
-
deletedAt,
|
|
578
|
-
parentMessage,
|
|
579
|
-
participants,
|
|
580
|
-
read,
|
|
581
|
-
replyCount,
|
|
582
|
-
updatedAt,
|
|
583
|
-
isStateStale: false,
|
|
584
|
-
});
|
|
405
|
+
ensureThreadChannel(this.client, threadData);
|
|
406
|
+
this.state.partialNext({ ...serverState, isStateStale: false });
|
|
585
407
|
|
|
586
|
-
if (
|
|
587
|
-
this.client.messageStore.upsert(parentMessage);
|
|
408
|
+
if (this.hasSubscriptions) {
|
|
409
|
+
this.client.messageStore.upsert(serverState.parentMessage);
|
|
588
410
|
}
|
|
589
411
|
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
412
|
+
const incomingReplies = (threadData.latest_replies ?? []).map(formatMessage);
|
|
413
|
+
if (!reconcile) this.messagePaginator.clearStateAndCache();
|
|
414
|
+
// The response's newest reply time replaces what was known, so latestMessageAt is right even
|
|
415
|
+
// when the merged page lacks the newest reply, or that reply was hard-deleted.
|
|
416
|
+
this.messagePaginator.setQueriedLatestMessageAt(threadData.last_message_at);
|
|
417
|
+
if (typeof this.messagePaginator.items === 'undefined') {
|
|
418
|
+
// Nothing loaded yet (e.g. a thread opened from a message): `reconcileNewestMessages` no-ops
|
|
419
|
+
// without a loaded interval and would drop the fetched replies, so set them as the constructor
|
|
420
|
+
// does.
|
|
421
|
+
const isLastPage = holdsEveryReply(incomingReplies, threadData);
|
|
422
|
+
this.messagePaginator.setItems({
|
|
423
|
+
valueOrFactory: incomingReplies,
|
|
424
|
+
cursor: getCursorFromReplies(incomingReplies, isLastPage),
|
|
425
|
+
isFirstPage: true,
|
|
426
|
+
isLastPage,
|
|
427
|
+
});
|
|
428
|
+
} else {
|
|
429
|
+
this.messagePaginator.reconcileNewestMessages(incomingReplies, reconcile);
|
|
430
|
+
}
|
|
594
431
|
pendingReplies.forEach((reply) => this.messagePaginator.ingestItem(reply));
|
|
595
|
-
// Carry the re-queried thread's last-activity floor so lastMessageAt stays fresh even when the
|
|
596
|
-
// merged page does not include the newest reply. Monotonic, so an older value is a no-op.
|
|
597
|
-
this.messagePaginator.seedLastMessageAt(thread.messagePaginator.lastMessageAt);
|
|
598
432
|
};
|
|
599
433
|
|
|
600
434
|
public registerSubscriptions = () => {
|
|
601
435
|
if (this.hasSubscriptions) {
|
|
602
|
-
// Thread is already listening for events and changes
|
|
603
436
|
return;
|
|
604
437
|
}
|
|
605
438
|
|
|
606
439
|
this.addUnsubscribeFunction(this.subscribeThreadSetupStateChange());
|
|
607
440
|
this.addUnsubscribeFunction(this.subscribeParentMessageFromStore());
|
|
608
|
-
this.addUnsubscribeFunction(this.subscribeThreadUpdated());
|
|
609
441
|
this.addUnsubscribeFunction(this.subscribeMarkActiveThreadRead());
|
|
610
442
|
this.addUnsubscribeFunction(this.subscribeReloadActiveStaleThread());
|
|
611
|
-
this.addUnsubscribeFunction(this.
|
|
612
|
-
this.addUnsubscribeFunction(this.subscribeNewReplies());
|
|
613
|
-
this.addUnsubscribeFunction(this.subscribeRepliesRead());
|
|
614
|
-
this.addUnsubscribeFunction(this.subscribeRepliesUnread());
|
|
615
|
-
this.addUnsubscribeFunction(this.subscribeMessageDeleted());
|
|
616
|
-
this.addUnsubscribeFunction(this.subscribeMessageUpdated());
|
|
617
|
-
this.addUnsubscribeFunction(this.subscribeUserMessagesDeleted());
|
|
443
|
+
this.addUnsubscribeFunction(this.subscribeMarkStaleOnStopWatching());
|
|
618
444
|
};
|
|
619
445
|
|
|
620
446
|
/**
|
|
621
|
-
* Subscribes
|
|
622
|
-
*
|
|
623
|
-
*
|
|
624
|
-
*
|
|
625
|
-
*
|
|
626
|
-
*
|
|
627
|
-
* - no *setup function* runs for it — matching how `MessageComposer` already behaves;
|
|
628
|
-
* - it sees the declarative slice **as it stood when the thread was constructed**, because the
|
|
629
|
-
* constructor applies it directly, but no *later* `client.config.set({ thread: … })` or
|
|
630
|
-
* `set({ messagePaginator: … })` reaches it;
|
|
631
|
-
* - it is absent from the registry's `liveInstances`, so `client.config.reset()` skips it, and
|
|
632
|
-
* `hasLiveInstances('thread')` does not count it when deciding whether to warn about a
|
|
633
|
-
* construction-only path registered too late.
|
|
634
|
-
*
|
|
635
|
-
* So read "declarative configuration is unaffected" as *at construction only*. A thread held by a
|
|
636
|
-
* `ThreadManager` that has itself registered is covered — `subscribeManageThreadSubscriptions` calls
|
|
637
|
-
* `registerSubscriptions()` on every thread entering its state — so the common path is fine. A thread
|
|
638
|
-
* constructed directly, or held by an unregistered manager, is not.
|
|
639
|
-
*
|
|
640
|
-
* The alternative — applying the setup function at construction — would break the teardown symmetry
|
|
641
|
-
* `WithSubscriptions` provides, which is why the asymmetry stands.
|
|
447
|
+
* Subscribes to the `'thread'` configuration key. Unlike `Channel`, which subscribes in its
|
|
448
|
+
* constructor, a thread that never registers sees the declarative slice only as of construction:
|
|
449
|
+
* no setup function runs, later `client.config.set` calls miss it and `client.config.reset()`
|
|
450
|
+
* skips it. `ThreadManager` registers the threads it holds (listed, `ensure()`d or active) while
|
|
451
|
+
* its own subscriptions are registered.
|
|
642
452
|
*/
|
|
643
453
|
private subscribeThreadSetupStateChange = () =>
|
|
644
454
|
applyInstanceConfiguration({
|
|
@@ -649,26 +459,25 @@ export class Thread extends WithSubscriptions {
|
|
|
649
459
|
// Read fresh: by the time reset calls this, the declarative store has been cleared.
|
|
650
460
|
reinitializeConfig: () =>
|
|
651
461
|
this.initializeConfig(this.client.config.getConfig('thread') ?? undefined),
|
|
652
|
-
//
|
|
653
|
-
//
|
|
462
|
+
// Also rerun on the shared keys the reply paginator and operations derive from, so the setup
|
|
463
|
+
// function's overrides survive.
|
|
654
464
|
alsoWatch: ['messagePaginator', 'messageOperations'],
|
|
655
465
|
});
|
|
656
466
|
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
}
|
|
467
|
+
public handleThreadUpdated = (event: EventPayload<'thread.updated'>) => {
|
|
468
|
+
if (!event.thread || event.thread.parent_message_id !== this.id) {
|
|
469
|
+
return;
|
|
470
|
+
}
|
|
662
471
|
|
|
663
|
-
|
|
472
|
+
const threadData = event.thread;
|
|
664
473
|
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
474
|
+
this.state.partialNext({
|
|
475
|
+
title: threadData.title,
|
|
476
|
+
updatedAt: threadData.updated_at,
|
|
477
|
+
deletedAt: threadData.deleted_at ?? null,
|
|
478
|
+
custom: threadData.custom ?? {},
|
|
479
|
+
});
|
|
480
|
+
};
|
|
672
481
|
|
|
673
482
|
private subscribeMarkActiveThreadRead = () =>
|
|
674
483
|
this.state.subscribeWithSelector(
|
|
@@ -692,254 +501,194 @@ export class Thread extends WithSubscriptions {
|
|
|
692
501
|
},
|
|
693
502
|
);
|
|
694
503
|
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
504
|
+
/**
|
|
505
|
+
* A watch stopped while the connection stays up (`NotWatching`) ends the channel's events with no
|
|
506
|
+
* reconnect to catch it. A dropped connection (`WasWatching`) is left to recovery.
|
|
507
|
+
*/
|
|
508
|
+
private subscribeMarkStaleOnStopWatching = () =>
|
|
509
|
+
this.channel.state.subscribeWithSelector(
|
|
510
|
+
({ watchStatus }) => ({ watchStatus }),
|
|
511
|
+
({ watchStatus }, previous) => {
|
|
512
|
+
if (
|
|
513
|
+
previous?.watchStatus === ChannelWatchStatus.Watching &&
|
|
514
|
+
watchStatus === ChannelWatchStatus.NotWatching
|
|
515
|
+
) {
|
|
516
|
+
this.state.partialNext({ isStateStale: true });
|
|
517
|
+
}
|
|
518
|
+
},
|
|
519
|
+
);
|
|
709
520
|
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
521
|
+
public handleRepliesUnread = (event: EventPayload<'notification.mark_unread'>) => {
|
|
522
|
+
if (!event.user || event.created_at == null || !event.thread_id) return;
|
|
523
|
+
if (event.thread_id !== this.id) return;
|
|
524
|
+
|
|
525
|
+
const userId = event.user.id;
|
|
526
|
+
const createdAt = event.created_at;
|
|
527
|
+
const user = event.user;
|
|
528
|
+
|
|
529
|
+
this.state.next((current) => ({
|
|
530
|
+
...current,
|
|
531
|
+
read: {
|
|
532
|
+
...current.read,
|
|
533
|
+
[userId]: {
|
|
534
|
+
...current.read[userId],
|
|
535
|
+
lastReadAt: timestampOr(event.last_read_at, createdAt),
|
|
536
|
+
user,
|
|
537
|
+
firstUnreadMessageId: event.first_unread_message_id,
|
|
538
|
+
unreadMessageCount: event.unread_messages ?? 0,
|
|
539
|
+
},
|
|
540
|
+
},
|
|
541
|
+
}));
|
|
542
|
+
};
|
|
714
543
|
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
544
|
+
public handleNewReply = (event: EventPayload<'message.new'>) => {
|
|
545
|
+
if (!this.client.userId || event.message?.parent_id !== this.id) {
|
|
546
|
+
return;
|
|
547
|
+
}
|
|
718
548
|
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
read: {
|
|
722
|
-
...current.read,
|
|
723
|
-
[userId]: {
|
|
724
|
-
...current.read[userId],
|
|
725
|
-
lastReadAt:
|
|
726
|
-
typeof event.last_read_at !== 'undefined'
|
|
727
|
-
? new Date(event.last_read_at)
|
|
728
|
-
: new Date(createdAt),
|
|
729
|
-
user,
|
|
730
|
-
firstUnreadMessageId: event.first_unread_message_id,
|
|
731
|
-
unreadMessageCount: event.unread_messages ?? 0,
|
|
732
|
-
},
|
|
733
|
-
},
|
|
734
|
-
}));
|
|
735
|
-
}).unsubscribe;
|
|
549
|
+
const isOwnMessage = event.message.user?.id === this.client.userId;
|
|
550
|
+
const { active, read } = this.state.getLatestValue();
|
|
736
551
|
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
}
|
|
552
|
+
this.upsertReplyLocally({
|
|
553
|
+
message: event.message,
|
|
554
|
+
timestampChanged: isOwnMessage,
|
|
555
|
+
});
|
|
742
556
|
|
|
743
|
-
|
|
744
|
-
|
|
557
|
+
if (active) {
|
|
558
|
+
this.throttledMarkRead();
|
|
559
|
+
}
|
|
745
560
|
|
|
746
|
-
|
|
747
|
-
message: event.message,
|
|
748
|
-
// MessageRequest from current user could have been added optimistically,
|
|
749
|
-
// so the actual timestamp might differ in the event
|
|
750
|
-
timestampChanged: isOwnMessage,
|
|
751
|
-
});
|
|
561
|
+
const nextRead: ThreadReadState = {};
|
|
752
562
|
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
}
|
|
563
|
+
for (const userId of Object.keys(read)) {
|
|
564
|
+
const userRead = read[userId];
|
|
756
565
|
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
for (const userId of Object.keys(read)) {
|
|
760
|
-
const userRead = read[userId];
|
|
761
|
-
|
|
762
|
-
if (userRead) {
|
|
763
|
-
let nextUserRead: ThreadUserReadState = userRead;
|
|
764
|
-
|
|
765
|
-
if (userId === event.user?.id) {
|
|
766
|
-
// The user who just sent a message to the thread has no unread messages
|
|
767
|
-
// in that thread
|
|
768
|
-
nextUserRead = {
|
|
769
|
-
...nextUserRead,
|
|
770
|
-
lastReadAt: event.created_at ? new Date(event.created_at) : new Date(),
|
|
771
|
-
user: event.user,
|
|
772
|
-
unreadMessageCount: 0,
|
|
773
|
-
};
|
|
774
|
-
} else if (active && userId === this.client.userId) {
|
|
775
|
-
// Do not increment unread count for the current user in an active thread
|
|
776
|
-
} else {
|
|
777
|
-
// Increment unread count for all users except the author of the new message
|
|
778
|
-
nextUserRead = {
|
|
779
|
-
...nextUserRead,
|
|
780
|
-
unreadMessageCount: userRead.unreadMessageCount + 1,
|
|
781
|
-
};
|
|
782
|
-
}
|
|
566
|
+
if (userRead) {
|
|
567
|
+
let nextUserRead: ThreadUserReadState = userRead;
|
|
783
568
|
|
|
784
|
-
|
|
569
|
+
if (userId === event.user?.id) {
|
|
570
|
+
// The sender has no unread messages.
|
|
571
|
+
nextUserRead = {
|
|
572
|
+
...nextUserRead,
|
|
573
|
+
lastReadAt: timestampOr(event.created_at, nowNs()),
|
|
574
|
+
user: event.user,
|
|
575
|
+
unreadMessageCount: 0,
|
|
576
|
+
};
|
|
577
|
+
} else if (active && userId === this.client.userId) {
|
|
578
|
+
// Do not increment unread count for the current user in an active thread
|
|
579
|
+
} else {
|
|
580
|
+
nextUserRead = {
|
|
581
|
+
...nextUserRead,
|
|
582
|
+
unreadMessageCount: userRead.unreadMessageCount + 1,
|
|
583
|
+
};
|
|
785
584
|
}
|
|
786
|
-
}
|
|
787
585
|
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
private subscribeRepliesRead = () =>
|
|
792
|
-
this.client.on('message.read', (event) => {
|
|
793
|
-
if (!event.user || !event.created_at || !event.thread) return;
|
|
794
|
-
if (event.thread.parent_message_id !== this.id) return;
|
|
586
|
+
nextRead[userId] = nextUserRead;
|
|
587
|
+
}
|
|
588
|
+
}
|
|
795
589
|
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
const user = event.user;
|
|
590
|
+
this.state.partialNext({ read: nextRead });
|
|
591
|
+
};
|
|
799
592
|
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
593
|
+
public handleRepliesRead = (event: EventPayload<'message.read'>) => {
|
|
594
|
+
if (!event.user || event.created_at == null || !event.thread) return;
|
|
595
|
+
if (event.thread.parent_message_id !== this.id) return;
|
|
596
|
+
|
|
597
|
+
const userId = event.user.id;
|
|
598
|
+
const createdAt = event.created_at;
|
|
599
|
+
const user = event.user;
|
|
600
|
+
|
|
601
|
+
this.state.next((current) => ({
|
|
602
|
+
...current,
|
|
603
|
+
read: {
|
|
604
|
+
...current.read,
|
|
605
|
+
[userId]: {
|
|
606
|
+
lastReadAt: createdAt,
|
|
607
|
+
user,
|
|
608
|
+
lastReadMessageId: event.last_read_message_id,
|
|
609
|
+
unreadMessageCount: 0,
|
|
810
610
|
},
|
|
811
|
-
}
|
|
812
|
-
})
|
|
611
|
+
},
|
|
612
|
+
}));
|
|
613
|
+
};
|
|
813
614
|
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
const formattedMessage = formatMessage(event.message);
|
|
615
|
+
public handleMessageDeleted = (event: EventPayload<'message.deleted'>) => {
|
|
616
|
+
if (!event.message) return;
|
|
617
|
+
const formattedMessage = formatMessage(event.message);
|
|
818
618
|
|
|
819
|
-
|
|
820
|
-
if (event.
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
// Handle soft delete (updates deleted_at timestamp)
|
|
825
|
-
this.upsertReplyLocally({ message: event.message });
|
|
826
|
-
}
|
|
619
|
+
if (event.message.parent_id === this.id) {
|
|
620
|
+
if (event.hard_delete) {
|
|
621
|
+
this.deleteReplyLocally({ message: event.message });
|
|
622
|
+
} else {
|
|
623
|
+
this.upsertReplyLocally({ message: event.message });
|
|
827
624
|
}
|
|
625
|
+
}
|
|
828
626
|
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
}
|
|
627
|
+
if (event.message.id === this.id) {
|
|
628
|
+
this.updateParentMessageLocally({ message: event.message });
|
|
629
|
+
}
|
|
833
630
|
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
private subscribeMessageUpdated = () => {
|
|
838
|
-
const messageUpdateTypes: EventType[] = ['message.updated', 'message.undeleted'];
|
|
839
|
-
const reactionTypes: EventType[] = [
|
|
840
|
-
'reaction.new',
|
|
841
|
-
'reaction.deleted',
|
|
842
|
-
'reaction.updated',
|
|
843
|
-
];
|
|
844
|
-
|
|
845
|
-
const unsubscribeMessageUpdated = messageUpdateTypes.map(
|
|
846
|
-
(eventType) =>
|
|
847
|
-
this.client.on(eventType, (event: PipelineEvent) => {
|
|
848
|
-
if (!event.message) return;
|
|
849
|
-
// A `message.updated` WS event carries `own_reactions: []`; upserting it verbatim would
|
|
850
|
-
// wipe the current user's reactions on an edit. Preserve them off the copy we already hold
|
|
851
|
-
// — the reply paginator for a reply, `state.parentMessage` for the parent (the parent is
|
|
852
|
-
// not held in any paginator, so it needs the same treatment directly).
|
|
853
|
-
const message =
|
|
854
|
-
event.message.parent_id === this.id
|
|
855
|
-
? {
|
|
856
|
-
...event.message,
|
|
857
|
-
own_reactions:
|
|
858
|
-
this.messagePaginator.getItem(event.message.id)?.own_reactions ??
|
|
859
|
-
event.message.own_reactions,
|
|
860
|
-
}
|
|
861
|
-
: !event.message.parent_id && event.message.id === this.id
|
|
862
|
-
? {
|
|
863
|
-
...event.message,
|
|
864
|
-
own_reactions:
|
|
865
|
-
this.state.getLatestValue().parentMessage?.own_reactions ??
|
|
866
|
-
event.message.own_reactions,
|
|
867
|
-
}
|
|
868
|
-
: event.message;
|
|
869
|
-
this.updateParentMessageOrReplyLocally(message);
|
|
870
|
-
this.messagePaginator.reflectQuotedMessageUpdate(formatMessage(event.message));
|
|
871
|
-
}).unsubscribe,
|
|
872
|
-
);
|
|
631
|
+
this.messagePaginator.reflectQuotedMessageUpdate(formattedMessage);
|
|
632
|
+
};
|
|
873
633
|
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
message,
|
|
885
|
-
reaction,
|
|
886
|
-
removed: eventType === 'reaction.deleted',
|
|
887
|
-
});
|
|
888
|
-
} else if (!message.parent_id && message.id === this.id) {
|
|
889
|
-
// Reaction on the PARENT. The parent isn't in a paginator, so apply the current user's
|
|
890
|
-
// own_reactions delta here (mirroring the reply path's reflectReaction) rather than
|
|
891
|
-
// copying the WS event verbatim — which would drop own_reactions the event omits.
|
|
892
|
-
const own_reactions = computeOwnReactions({
|
|
893
|
-
current:
|
|
894
|
-
this.state.getLatestValue().parentMessage?.own_reactions ??
|
|
895
|
-
message.own_reactions ??
|
|
896
|
-
[],
|
|
897
|
-
enforceUnique: eventType === 'reaction.updated',
|
|
898
|
-
reaction,
|
|
899
|
-
removed: eventType === 'reaction.deleted',
|
|
900
|
-
userId: this.client.userId,
|
|
901
|
-
});
|
|
902
|
-
this.updateParentMessageLocally({ message: { ...message, own_reactions } });
|
|
634
|
+
public handleMessageUpdated = (event: PipelineEvent) => {
|
|
635
|
+
if (!event.message) return;
|
|
636
|
+
// A `message.updated` event carries `own_reactions: []`, which would wipe the current user's
|
|
637
|
+
// reactions: keep them from the held copy (the reply paginator, or `state.parentMessage`).
|
|
638
|
+
const message =
|
|
639
|
+
event.message.parent_id === this.id
|
|
640
|
+
? {
|
|
641
|
+
...event.message,
|
|
642
|
+
own_reactions:
|
|
643
|
+
this.messagePaginator.getItem(event.message.id)?.own_reactions ??
|
|
644
|
+
event.message.own_reactions,
|
|
903
645
|
}
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
646
|
+
: !event.message.parent_id && event.message.id === this.id
|
|
647
|
+
? {
|
|
648
|
+
...event.message,
|
|
649
|
+
own_reactions:
|
|
650
|
+
this.state.getLatestValue().parentMessage?.own_reactions ??
|
|
651
|
+
event.message.own_reactions,
|
|
652
|
+
}
|
|
653
|
+
: event.message;
|
|
654
|
+
this.updateParentMessageOrReplyLocally(message);
|
|
655
|
+
this.messagePaginator.reflectQuotedMessageUpdate(formatMessage(event.message));
|
|
656
|
+
};
|
|
909
657
|
|
|
910
|
-
|
|
658
|
+
public handleReactionChanged = (event: PipelineEvent) => {
|
|
659
|
+
if (!event.message || !event.reaction) return;
|
|
660
|
+
const { message } = event;
|
|
661
|
+
this.messagePaginator.reflectQuotedMessageUpdate(formatMessage(message));
|
|
911
662
|
};
|
|
912
663
|
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
const
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
const deletedAtSource =
|
|
925
|
-
eventType === 'user.deleted' ? event.user.deleted_at : event.created_at;
|
|
926
|
-
this.messagePaginator.applyMessageDeletionForUser({
|
|
927
|
-
userId: event.user.id,
|
|
928
|
-
hardDelete: !!event.hard_delete,
|
|
929
|
-
deletedAt: deletedAtSource ? new Date(deletedAtSource) : new Date(),
|
|
930
|
-
});
|
|
931
|
-
}).unsubscribe,
|
|
932
|
-
);
|
|
664
|
+
public handleUserUpdated = (event: PipelineEvent) => {
|
|
665
|
+
const { user } = event;
|
|
666
|
+
if (!user) return;
|
|
667
|
+
this.messagePaginator.reflectUserUpdate(user);
|
|
668
|
+
|
|
669
|
+
// the parent message might not yet be loaded in channel.messagePaginator
|
|
670
|
+
const parent = this.client.messageStore.get(this.id);
|
|
671
|
+
if (parent?.user?.id === user.id && parent.user !== user) {
|
|
672
|
+
this.client.messageStore.upsert({ ...parent, user });
|
|
673
|
+
}
|
|
674
|
+
};
|
|
933
675
|
|
|
934
|
-
|
|
676
|
+
// Applies a user ban or deletion to this thread's replies.
|
|
677
|
+
public handleUserMessagesDeleted = (event: PipelineEvent) => {
|
|
678
|
+
if (!event.user) return;
|
|
679
|
+
// user.deleted carries the deletion time on the user; user.messages.deleted on the event.
|
|
680
|
+
const deletedAtSource =
|
|
681
|
+
event.type === 'user.deleted' ? event.user.deleted_at : event.created_at;
|
|
682
|
+
this.messagePaginator.applyMessageDeletionForUser({
|
|
683
|
+
userId: event.user.id,
|
|
684
|
+
hardDelete: !!event.hard_delete,
|
|
685
|
+
deletedAt: deletedAtSource ?? nowNs(),
|
|
686
|
+
});
|
|
935
687
|
};
|
|
936
688
|
|
|
937
|
-
//
|
|
938
|
-
//
|
|
939
|
-
//
|
|
940
|
-
// store, which reflects it here through this single subscription (one per thread, not one per
|
|
941
|
-
// message). Seeds the store on first subscribe when no other collection holds the parent yet
|
|
942
|
-
// (e.g. a thread opened from a notification, its parent not in the channel window).
|
|
689
|
+
// `state.parentMessage` and its derived fields project the parent in the client-global message
|
|
690
|
+
// store, so every update to the parent reaches them through this one subscription. Seeds the
|
|
691
|
+
// store when no other collection holds the parent yet (e.g. a thread opened from a notification).
|
|
943
692
|
private subscribeParentMessageFromStore = () => {
|
|
944
693
|
const store = this.client.messageStore;
|
|
945
694
|
const parent = this.state.getLatestValue().parentMessage;
|
|
@@ -951,9 +700,10 @@ export class Thread extends WithSubscriptions {
|
|
|
951
700
|
...current,
|
|
952
701
|
deletedAt: message.deleted_at ?? null,
|
|
953
702
|
parentMessage: message,
|
|
954
|
-
participants:
|
|
955
|
-
normalizeThreadParticipants(message.thread_participants, current.channel.cid) ??
|
|
703
|
+
participants: mergeThreadParticipants(
|
|
956
704
|
current.participants,
|
|
705
|
+
normalizeThreadParticipants(message.thread_participants, current.channel.cid),
|
|
706
|
+
),
|
|
957
707
|
replyCount: message.reply_count ?? current.replyCount,
|
|
958
708
|
}));
|
|
959
709
|
});
|
|
@@ -961,11 +711,9 @@ export class Thread extends WithSubscriptions {
|
|
|
961
711
|
|
|
962
712
|
public unregisterSubscriptions = () => {
|
|
963
713
|
const symbol = super.unregisterSubscriptions();
|
|
964
|
-
//
|
|
965
|
-
//
|
|
966
|
-
//
|
|
967
|
-
// removed thread would otherwise stay pinned by `messageStore.subscribers` and keep its replies
|
|
968
|
-
// alive. `getThread` builds a fresh instance if this thread is re-opened, so this is a discard.
|
|
714
|
+
// Releases the reply paginator's per-ID links on the shared message store (they are not in the
|
|
715
|
+
// subscription list), which would otherwise pin a removed thread and its replies. `getThread`
|
|
716
|
+
// builds a fresh instance if the thread is re-opened.
|
|
969
717
|
this.messagePaginator.dispose();
|
|
970
718
|
this.state.partialNext({ isStateStale: true });
|
|
971
719
|
return symbol;
|
|
@@ -973,8 +721,7 @@ export class Thread extends WithSubscriptions {
|
|
|
973
721
|
|
|
974
722
|
// todo: can be removed with the next breaking change and use MessagePaginator only
|
|
975
723
|
public deleteReplyLocally = ({ message }: { message: MessageResponse }) => {
|
|
976
|
-
//
|
|
977
|
-
// isn't loaded, so it's safe to run unconditionally.
|
|
724
|
+
// A no-op when the reply is not loaded.
|
|
978
725
|
this.messagePaginator.removeItem({ id: message.id });
|
|
979
726
|
};
|
|
980
727
|
|
|
@@ -983,8 +730,7 @@ export class Thread extends WithSubscriptions {
|
|
|
983
730
|
message,
|
|
984
731
|
}: {
|
|
985
732
|
message: MessageResponse | LocalMessage;
|
|
986
|
-
//
|
|
987
|
-
// by created_at on ingest, so a changed timestamp is handled without an explicit flag.
|
|
733
|
+
// Unused: the reply paginator repositions by `created_at` on ingest.
|
|
988
734
|
timestampChanged?: boolean;
|
|
989
735
|
}) => {
|
|
990
736
|
if (message.parent_id !== this.id) {
|
|
@@ -995,13 +741,18 @@ export class Thread extends WithSubscriptions {
|
|
|
995
741
|
|
|
996
742
|
// todo: do we really need to keep the failedRepliesMap?
|
|
997
743
|
if (formattedMessage.status === 'failed') {
|
|
998
|
-
//
|
|
744
|
+
// Kept so a failed reply survives a reload or hydrate.
|
|
999
745
|
this.failedRepliesMap.set(formattedMessage.id, formattedMessage);
|
|
1000
746
|
} else if (this.failedRepliesMap.has(message.id)) {
|
|
1001
747
|
this.failedRepliesMap.delete(message.id);
|
|
1002
748
|
}
|
|
1003
749
|
|
|
1004
|
-
//
|
|
750
|
+
// Already showing this snapshot (a holder sharing the store wrote it first): skip the ingest.
|
|
751
|
+
// TODO: This can probably be generalized as a safeguard up in ingestItem or maybe even EntityStore
|
|
752
|
+
// (so if a collection exists that holds this referential entity already, just use that or maybe
|
|
753
|
+
// even skip ingestion sometimes when it makes sense). But leaving that for a separate change.
|
|
754
|
+
if (this.messagePaginator.getItem(formattedMessage.id) === formattedMessage) return;
|
|
755
|
+
|
|
1005
756
|
this.messagePaginator.ingestItem(formattedMessage);
|
|
1006
757
|
};
|
|
1007
758
|
|
|
@@ -1011,9 +762,7 @@ export class Thread extends WithSubscriptions {
|
|
|
1011
762
|
throw new Error('Message does not belong to this thread');
|
|
1012
763
|
}
|
|
1013
764
|
|
|
1014
|
-
//
|
|
1015
|
-
// fields derived from it) is a projection kept in sync by `subscribeParentMessageFromStore`.
|
|
1016
|
-
// Writing the store fans the change out to every collection holding this id and reflects it here.
|
|
765
|
+
// Written to the message store; `subscribeParentMessageFromStore` projects it into the state.
|
|
1017
766
|
if (this.client.messageStore.has(message.id)) {
|
|
1018
767
|
this.client.messageStore.upsert(formatMessage(message));
|
|
1019
768
|
}
|
|
@@ -1030,105 +779,6 @@ export class Thread extends WithSubscriptions {
|
|
|
1030
779
|
}
|
|
1031
780
|
};
|
|
1032
781
|
|
|
1033
|
-
/**
|
|
1034
|
-
* Sends a message with optimistic local state update.
|
|
1035
|
-
*/
|
|
1036
|
-
async sendMessageWithLocalUpdate({
|
|
1037
|
-
localMessage,
|
|
1038
|
-
message,
|
|
1039
|
-
options,
|
|
1040
|
-
sendMessageRequestFn,
|
|
1041
|
-
}: SendMessageWithStateUpdateParams): Promise<void> {
|
|
1042
|
-
await this.messageOperations.send(
|
|
1043
|
-
{
|
|
1044
|
-
localMessage,
|
|
1045
|
-
message,
|
|
1046
|
-
options,
|
|
1047
|
-
},
|
|
1048
|
-
sendMessageRequestFn,
|
|
1049
|
-
);
|
|
1050
|
-
}
|
|
1051
|
-
|
|
1052
|
-
/**
|
|
1053
|
-
* Retry sending a failed message.
|
|
1054
|
-
*/
|
|
1055
|
-
async retrySendMessageWithLocalUpdate(
|
|
1056
|
-
params: Omit<SendMessageWithStateUpdateParams, 'message'>,
|
|
1057
|
-
) {
|
|
1058
|
-
await this.messageOperations.retry(
|
|
1059
|
-
{
|
|
1060
|
-
localMessage: { ...params.localMessage, type: 'regular' },
|
|
1061
|
-
options: params.options,
|
|
1062
|
-
},
|
|
1063
|
-
params.sendMessageRequestFn,
|
|
1064
|
-
);
|
|
1065
|
-
}
|
|
1066
|
-
|
|
1067
|
-
/**
|
|
1068
|
-
* Updates a message with optimistic local state update.
|
|
1069
|
-
*
|
|
1070
|
-
* The update flows through `messagePaginator`, which is the sole reply source.
|
|
1071
|
-
*/
|
|
1072
|
-
async updateMessageWithLocalUpdate(params: UpdateMessageWithStateUpdateParams) {
|
|
1073
|
-
await this.messageOperations.update(
|
|
1074
|
-
{
|
|
1075
|
-
localMessage: params.localMessage,
|
|
1076
|
-
options: params.options,
|
|
1077
|
-
},
|
|
1078
|
-
params.updateMessageRequestFn,
|
|
1079
|
-
);
|
|
1080
|
-
}
|
|
1081
|
-
|
|
1082
|
-
/**
|
|
1083
|
-
* Deletes a message with local state update.
|
|
1084
|
-
*/
|
|
1085
|
-
async deleteMessageWithLocalUpdate(params: DeleteMessageWithStateUpdateParams) {
|
|
1086
|
-
await this.messageOperations.delete(
|
|
1087
|
-
{
|
|
1088
|
-
localMessage: params.localMessage,
|
|
1089
|
-
options: params.options,
|
|
1090
|
-
},
|
|
1091
|
-
params.deleteMessageRequestFn,
|
|
1092
|
-
);
|
|
1093
|
-
}
|
|
1094
|
-
|
|
1095
|
-
/**
|
|
1096
|
-
* Adds a reaction to a reply with an optimistic local state update — see
|
|
1097
|
-
* {@link addReactionOptimistically}, which `Channel` shares. The request routes through the parent
|
|
1098
|
-
* channel because reactions are channel-level, while the local write is addressed by message id and
|
|
1099
|
-
* so reaches a pure reply no channel collection holds.
|
|
1100
|
-
*/
|
|
1101
|
-
async addReactionWithLocalUpdate({
|
|
1102
|
-
messageId,
|
|
1103
|
-
reaction,
|
|
1104
|
-
options,
|
|
1105
|
-
}: {
|
|
1106
|
-
messageId: string;
|
|
1107
|
-
reaction: ReactionRequest;
|
|
1108
|
-
options?: Pick<SendReactionRequest, 'enforce_unique' | 'skip_push'>;
|
|
1109
|
-
}) {
|
|
1110
|
-
await addReactionOptimistically({
|
|
1111
|
-
channel: this.channel,
|
|
1112
|
-
messageId,
|
|
1113
|
-
options,
|
|
1114
|
-
reaction,
|
|
1115
|
-
});
|
|
1116
|
-
}
|
|
1117
|
-
|
|
1118
|
-
/**
|
|
1119
|
-
* Removes the current user's reaction from a reply with an optimistic local state update — see
|
|
1120
|
-
* {@link deleteReactionOptimistically}, which `Channel` shares.
|
|
1121
|
-
*/
|
|
1122
|
-
async deleteReactionWithLocalUpdate({
|
|
1123
|
-
messageId,
|
|
1124
|
-
type,
|
|
1125
|
-
}: {
|
|
1126
|
-
messageId: string;
|
|
1127
|
-
type: string;
|
|
1128
|
-
}) {
|
|
1129
|
-
await deleteReactionOptimistically({ channel: this.channel, messageId, type });
|
|
1130
|
-
}
|
|
1131
|
-
|
|
1132
782
|
public markRead = async ({ force = false }: { force?: boolean } = {}) => {
|
|
1133
783
|
if (this.ownUnreadCount === 0 && !force) {
|
|
1134
784
|
return null;
|
|
@@ -1159,7 +809,7 @@ const normalizeThreadParticipants = (
|
|
|
1159
809
|
): ThreadStateResponse['thread_participants'] | undefined => {
|
|
1160
810
|
if (!participants) return undefined;
|
|
1161
811
|
|
|
1162
|
-
const now =
|
|
812
|
+
const now = nowNs();
|
|
1163
813
|
|
|
1164
814
|
return participants.map(
|
|
1165
815
|
(participant: MessageThreadParticipant) =>
|
|
@@ -1173,13 +823,81 @@ const normalizeThreadParticipants = (
|
|
|
1173
823
|
);
|
|
1174
824
|
};
|
|
1175
825
|
|
|
826
|
+
/**
|
|
827
|
+
* Adds the participants a parent message lists to the thread's. The message lists only the users who
|
|
828
|
+
* replied, while a thread response also counts the parent's author, so replacing the thread's list
|
|
829
|
+
* with the message's would drop that author.
|
|
830
|
+
*/
|
|
831
|
+
const mergeThreadParticipants = (
|
|
832
|
+
current: ThreadStateResponse['thread_participants'],
|
|
833
|
+
fromMessage: ThreadStateResponse['thread_participants'],
|
|
834
|
+
): ThreadStateResponse['thread_participants'] => {
|
|
835
|
+
if (!fromMessage) return current;
|
|
836
|
+
if (!current?.length) return fromMessage;
|
|
837
|
+
const known = new Set(current.map((participant) => participant.user_id));
|
|
838
|
+
const added = fromMessage.filter((participant) => !known.has(participant.user_id));
|
|
839
|
+
return added.length ? [...current, ...added] : current;
|
|
840
|
+
};
|
|
841
|
+
|
|
842
|
+
/** `participant_limit` of the single-thread requests (`getThreadAndHydrate`, `reload()`). */
|
|
843
|
+
export const DEFAULT_THREAD_PARTICIPANT_LIMIT = 100;
|
|
844
|
+
|
|
845
|
+
/** The thread's channel, with the members and custom data of `threadData` applied. */
|
|
846
|
+
export const ensureThreadChannel = (
|
|
847
|
+
client: StreamChat,
|
|
848
|
+
threadData: ThreadStateResponse,
|
|
849
|
+
) => {
|
|
850
|
+
if (!threadData.channel) {
|
|
851
|
+
throw new Error('Thread channel is required when threadData is provided');
|
|
852
|
+
}
|
|
853
|
+
const channel = client.channelManager.ensure({
|
|
854
|
+
type: threadData.channel.type,
|
|
855
|
+
id: threadData.channel.id,
|
|
856
|
+
data: { custom: threadData.channel.custom },
|
|
857
|
+
});
|
|
858
|
+
channel._hydrateMembers({
|
|
859
|
+
members: threadData.channel.members ?? [],
|
|
860
|
+
overrideCurrentState: false,
|
|
861
|
+
});
|
|
862
|
+
return channel;
|
|
863
|
+
};
|
|
864
|
+
|
|
865
|
+
/** Against the top-level `reply_count`: unlike the parent's, it excludes soft-deleted replies. */
|
|
866
|
+
const holdsEveryReply = (replies: LocalMessage[], threadData: ThreadStateResponse) =>
|
|
867
|
+
replies.length === (threadData.reply_count ?? 0);
|
|
868
|
+
|
|
869
|
+
const formatThreadState = (threadData: ThreadStateResponse, currentUserId?: string) => {
|
|
870
|
+
const parentMessage = threadData.parent_message;
|
|
871
|
+
if (!parentMessage) {
|
|
872
|
+
throw new Error('Thread parent_message is required when threadData is provided');
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
return {
|
|
876
|
+
createdAt: threadData.created_at,
|
|
877
|
+
custom: threadData.custom ?? {},
|
|
878
|
+
deletedAt: threadData.deleted_at ?? null,
|
|
879
|
+
parentMessage: formatMessage(parentMessage),
|
|
880
|
+
participants: threadData.thread_participants,
|
|
881
|
+
read: formatReadState(
|
|
882
|
+
!threadData.read || threadData.read.length === 0
|
|
883
|
+
? getPlaceholderReadResponse(currentUserId)
|
|
884
|
+
: threadData.read,
|
|
885
|
+
),
|
|
886
|
+
// From the parent message: the top-level `threadData.reply_count` excludes soft-deleted
|
|
887
|
+
// replies, the parent's (like the channel's) includes them.
|
|
888
|
+
replyCount: parentMessage.reply_count ?? 0,
|
|
889
|
+
title: threadData.title,
|
|
890
|
+
updatedAt: threadData.updated_at ?? null,
|
|
891
|
+
};
|
|
892
|
+
};
|
|
893
|
+
|
|
1176
894
|
const formatReadState = (read: ReadStateResponse[]): ThreadReadState =>
|
|
1177
895
|
read.reduce<ThreadReadState>((state, userRead) => {
|
|
1178
896
|
state[userRead.user.id] = {
|
|
1179
897
|
user: userRead.user,
|
|
1180
898
|
lastReadMessageId: userRead.last_read_message_id,
|
|
1181
899
|
unreadMessageCount: userRead.unread_messages ?? 0,
|
|
1182
|
-
lastReadAt:
|
|
900
|
+
lastReadAt: userRead.last_read,
|
|
1183
901
|
};
|
|
1184
902
|
return state;
|
|
1185
903
|
}, {});
|
|
@@ -1190,7 +908,7 @@ const getPlaceholderReadResponse = (currentUserId?: string): ReadStateResponse[]
|
|
|
1190
908
|
{
|
|
1191
909
|
user: { id: currentUserId } as UserResponse,
|
|
1192
910
|
unread_messages: 0,
|
|
1193
|
-
last_read:
|
|
911
|
+
last_read: nowNs(),
|
|
1194
912
|
},
|
|
1195
913
|
]
|
|
1196
914
|
: [];
|