stream-chat 10.0.0-rc.2 → 10.0.0-rc.21
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 +11 -8
- package/dist/cjs/index.browser.js +15397 -12090
- package/dist/cjs/index.browser.js.map +4 -4
- package/dist/cjs/index.node.js +15349 -11991
- package/dist/cjs/index.node.js.map +4 -4
- package/dist/esm/index.mjs +15164 -11880
- package/dist/esm/index.mjs.map +4 -4
- package/dist/types/ChannelManager.d.ts +246 -6
- package/dist/types/CooldownTimer.d.ts +22 -8
- package/dist/types/EventHandlerPipeline.d.ts +12 -16
- package/dist/types/LiveLocationManager.d.ts +69 -6
- package/dist/types/api-client.d.ts +22 -9
- package/dist/types/channel.d.ts +550 -300
- package/dist/types/channel_state.d.ts +167 -22
- package/dist/types/client.d.ts +325 -305
- package/dist/types/configuration/ConfigController.d.ts +172 -0
- package/dist/types/configuration/InstanceConfigurationRegistry.d.ts +192 -0
- package/dist/types/configuration/index.d.ts +3 -0
- package/dist/types/configuration/keys.d.ts +31 -0
- package/dist/types/configuration/shape.d.ts +58 -0
- package/dist/types/configuration/types.d.ts +206 -50
- package/dist/types/configuration/utils/applyInstanceConfiguration.d.ts +59 -0
- package/dist/types/configuration/utils/copyConfigPatch.d.ts +1 -0
- package/dist/types/configuration/utils/declarativeSlices.d.ts +24 -0
- package/dist/types/configuration/utils/deepFreezeConfig.d.ts +22 -0
- package/dist/types/configuration/utils/index.d.ts +1 -0
- package/dist/types/configuration/utils/serverAuthority.d.ts +49 -0
- package/dist/types/connection/ConnectionIdManager.d.ts +67 -0
- package/dist/types/connection/ConnectionRecoveryManager.d.ts +164 -0
- package/dist/types/connection/index.d.ts +4 -0
- package/dist/types/connection/networkConnection/NetworkConnectionObserver.d.ts +153 -0
- package/dist/types/connection/networkConnection/index.d.ts +3 -0
- package/dist/types/connection/networkConnection/reporters.d.ts +43 -0
- package/dist/types/connection/networkConnection/types.d.ts +55 -0
- package/dist/types/connection/wsConnection/StableWSConnection.d.ts +204 -0
- package/dist/types/connection/wsConnection/WSConnection.d.ts +168 -0
- package/dist/types/connection/wsConnection/WSConnectionFallback.d.ts +55 -0
- package/dist/types/connection/wsConnection/config.d.ts +51 -0
- package/dist/types/connection/wsConnection/index.d.ts +4 -0
- package/dist/types/connection/wsConnection/types.d.ts +99 -0
- package/dist/types/constants.d.ts +3 -1
- package/dist/types/entityStore/EntityStore.d.ts +160 -40
- package/dist/types/entityStore/StoreBackedItemIndex.d.ts +48 -29
- package/dist/types/entityStore/index.d.ts +0 -1
- package/dist/types/errors.d.ts +24 -4
- package/dist/types/formatMessageMemo.d.ts +5 -0
- package/dist/types/gen/chat/ChannelApi.d.ts +51 -23
- package/dist/types/gen/chat/ChatApi.d.ts +215 -168
- package/dist/types/gen/models/index.d.ts +2164 -557
- package/dist/types/gen/models/timestamp-guard.d.ts +22 -0
- package/dist/types/gen/moderation/ModerationApi.d.ts +39 -32
- package/dist/types/gen-imports.d.ts +1 -0
- package/dist/types/index.d.ts +20 -7
- package/dist/types/languageNames.d.ts +97 -0
- package/dist/types/logger.d.ts +1 -1
- package/dist/types/messageComposer/CustomDataManager.d.ts +7 -1
- package/dist/types/messageComposer/LocationComposer.d.ts +10 -4
- package/dist/types/messageComposer/attachmentIdentity.d.ts +11 -0
- package/dist/types/messageComposer/attachmentManager.d.ts +48 -10
- package/dist/types/messageComposer/attachmentUtils.d.ts +34 -0
- package/dist/types/messageComposer/configuration/commands.configuration.d.ts +1 -3
- package/dist/types/messageComposer/configuration/configuration.d.ts +9 -1
- package/dist/types/messageComposer/configuration/index.d.ts +0 -1
- package/dist/types/messageComposer/configuration/types.d.ts +57 -1
- package/dist/types/messageComposer/index.d.ts +1 -0
- package/dist/types/messageComposer/linkPreviewsManager.d.ts +10 -4
- package/dist/types/messageComposer/messageComposer.d.ts +210 -14
- package/dist/types/messageComposer/middleware/attachmentManager/postUpload/attachmentEnrichment.d.ts +20 -1
- package/dist/types/messageComposer/middleware/messageComposer/attachments.d.ts +11 -0
- package/dist/types/messageComposer/middleware/messageComposer/types.d.ts +2 -2
- package/dist/types/messageComposer/middleware/pollComposer/index.d.ts +1 -0
- package/dist/types/messageComposer/middleware/pollComposer/state.d.ts +3 -2
- package/dist/types/messageComposer/middleware/pollComposer/types.d.ts +9 -2
- package/dist/types/messageComposer/middleware/pollComposer/validation.d.ts +44 -0
- package/dist/types/messageComposer/middleware/textComposer/commands.d.ts +2 -2
- package/dist/types/messageComposer/middleware/textComposer/mentions.d.ts +94 -229
- package/dist/types/messageComposer/pollComposer.d.ts +8 -3
- package/dist/types/messageComposer/textComposer.d.ts +9 -1
- package/dist/types/messageComposer/types.d.ts +7 -3
- package/dist/types/messageDelivery/MessageDeliveryReporter.d.ts +64 -8
- package/dist/types/messageDelivery/MessageReceiptsTracker.d.ts +48 -11
- package/dist/types/messageOperations/FailedSendCache.d.ts +34 -0
- package/dist/types/messageOperations/MessageOperationStatePolicy.d.ts +52 -6
- package/dist/types/messageOperations/MessageOperations.d.ts +94 -11
- package/dist/types/{entityStore → messageOperations}/applyReactionLocally.d.ts +8 -2
- package/dist/types/messageOperations/createMessageOperations.d.ts +11 -0
- package/dist/types/messageOperations/index.d.ts +7 -1
- package/dist/types/messageOperations/reflectReactionEvent.d.ts +24 -0
- package/dist/types/messageOperations/sendOrdering.d.ts +17 -0
- package/dist/types/messageOperations/settlePendingAttachmentUploads.d.ts +28 -0
- package/dist/types/messageOperations/types.d.ts +66 -1
- package/dist/types/middleware.d.ts +8 -0
- package/dist/types/moderation.d.ts +18 -4
- package/dist/types/notifications/NotificationManager.d.ts +43 -2
- package/dist/types/notifications/types.d.ts +55 -42
- package/dist/types/offline-support/offline_support_api.d.ts +128 -12
- package/dist/types/offline-support/offline_sync_manager.d.ts +26 -5
- package/dist/types/offline-support/queueableOperations.d.ts +106 -0
- package/dist/types/offline-support/types.d.ts +77 -28
- package/dist/types/pagination/FilterBuilder.d.ts +1 -18
- package/dist/types/pagination/cursorDerivation/createdAtAroundPaginationFlags.d.ts +2 -1
- package/dist/types/pagination/cursorDerivation/linearPaginationFlags.d.ts +21 -3
- package/dist/types/pagination/filterCompiler.d.ts +5 -0
- package/dist/types/pagination/paginators/BasePaginator.d.ts +331 -7
- package/dist/types/pagination/paginators/ChannelPaginator.d.ts +54 -11
- package/dist/types/pagination/paginators/MessageIntervalPaginator.d.ts +283 -66
- package/dist/types/pagination/paginators/MessagePaginator.d.ts +10 -9
- package/dist/types/pagination/paginators/PinnedMessagePaginator.d.ts +17 -1
- package/dist/types/pagination/paginators/ReminderPaginator.d.ts +8 -8
- package/dist/types/pagination/paginators/ThreadPaginator.d.ts +57 -0
- package/dist/types/pagination/paginators/index.d.ts +1 -0
- package/dist/types/pagination/utility.normalization.d.ts +29 -2
- package/dist/types/poll.d.ts +41 -14
- package/dist/types/poll_manager.d.ts +3 -2
- package/dist/types/poll_optimistic_votes.d.ts +61 -0
- package/dist/types/reminders/Reminder.d.ts +17 -7
- package/dist/types/reminders/ReminderManager.d.ts +34 -6
- package/dist/types/search/BaseSearchSource.d.ts +50 -25
- package/dist/types/search/ChannelMemberSearchSource.d.ts +11 -6
- package/dist/types/search/ChannelSearchSource.d.ts +27 -5
- package/dist/types/search/MessageSearchSource.d.ts +36 -6
- package/dist/types/search/SearchController.d.ts +44 -11
- package/dist/types/search/UserSearchSource.d.ts +11 -5
- package/dist/types/search/types.d.ts +14 -1
- package/dist/types/signing.d.ts +0 -157
- package/dist/types/thread.d.ts +118 -62
- package/dist/types/thread_manager.d.ts +124 -35
- package/dist/types/token_manager.d.ts +5 -8
- package/dist/types/types.d.ts +138 -562
- package/dist/types/types.utility.d.ts +8 -0
- package/dist/types/upload-utils.d.ts +20 -0
- package/dist/types/uploadManager.d.ts +50 -2
- package/dist/types/utils/FixedSizeQueueCache.d.ts +2 -0
- package/dist/types/utils/WithSubscriptions.d.ts +1 -1
- package/dist/types/utils/objectPath.d.ts +49 -0
- package/dist/types/utils/time.d.ts +85 -0
- package/dist/types/utils.d.ts +63 -40
- package/package.json +22 -33
- package/src/ChannelManager.ts +561 -109
- package/src/CooldownTimer.ts +55 -45
- package/src/EventHandlerPipeline.ts +13 -23
- package/src/LiveLocationManager.ts +191 -37
- package/src/api-client.ts +144 -53
- package/src/channel.ts +1573 -1050
- package/src/channel_state.ts +239 -129
- package/src/client.ts +843 -892
- package/src/client_state.ts +2 -2
- package/src/configuration/ConfigController.ts +298 -0
- package/src/configuration/InstanceConfigurationRegistry.ts +430 -0
- package/src/configuration/index.ts +7 -0
- package/src/configuration/keys.ts +86 -0
- package/src/configuration/shape.ts +776 -0
- package/src/configuration/types.ts +218 -60
- package/src/configuration/utils/applyInstanceConfiguration.ts +184 -0
- package/src/configuration/utils/copyConfigPatch.ts +61 -0
- package/src/configuration/utils/declarativeSlices.ts +81 -0
- package/src/configuration/utils/deepFreezeConfig.ts +33 -0
- package/src/configuration/utils/index.ts +5 -0
- package/src/configuration/utils/serverAuthority.ts +146 -0
- package/src/connection/ConnectionIdManager.ts +153 -0
- package/src/connection/ConnectionRecoveryManager.ts +371 -0
- package/src/connection/index.ts +4 -0
- package/src/connection/networkConnection/NetworkConnectionObserver.ts +281 -0
- package/src/connection/networkConnection/index.ts +3 -0
- package/src/connection/networkConnection/reporters.ts +85 -0
- package/src/connection/networkConnection/types.ts +60 -0
- package/src/{connection.ts → connection/wsConnection/StableWSConnection.ts} +242 -151
- package/src/connection/wsConnection/WSConnection.ts +345 -0
- package/src/connection/wsConnection/WSConnectionFallback.ts +259 -0
- package/src/connection/wsConnection/config.ts +108 -0
- package/src/connection/wsConnection/index.ts +4 -0
- package/src/connection/wsConnection/types.ts +101 -0
- package/src/constants.ts +5 -3
- package/src/entityStore/EntityStore.ts +350 -10
- package/src/entityStore/StoreBackedItemIndex.ts +66 -37
- package/src/entityStore/index.ts +0 -1
- package/src/errors.ts +40 -7
- package/src/formatMessageMemo.ts +23 -0
- package/src/gen/chat/ChannelApi.ts +230 -44
- package/src/gen/chat/ChatApi.ts +1047 -1745
- package/src/gen/models/index.ts +2378 -3721
- package/src/gen/models/timestamp-guard.ts +27 -0
- package/src/gen/moderation/ModerationApi.ts +218 -388
- package/src/gen-imports.ts +1 -0
- package/src/index.ts +82 -6
- package/src/languageNames.ts +103 -0
- package/src/logger.ts +1 -1
- package/src/messageComposer/CustomDataManager.ts +10 -1
- package/src/messageComposer/LocationComposer.ts +68 -20
- package/src/messageComposer/attachmentIdentity.ts +39 -0
- package/src/messageComposer/attachmentManager.ts +191 -68
- package/src/messageComposer/attachmentUtils.ts +58 -0
- package/src/messageComposer/configuration/commands.configuration.ts +1 -26
- package/src/messageComposer/configuration/configuration.ts +22 -3
- package/src/messageComposer/configuration/index.ts +0 -1
- package/src/messageComposer/configuration/types.ts +58 -1
- package/src/messageComposer/index.ts +1 -0
- package/src/messageComposer/linkPreviewsManager.ts +16 -10
- package/src/messageComposer/messageComposer.ts +487 -98
- package/src/messageComposer/middleware/attachmentManager/postUpload/AttachmentPostUploadMiddlewareExecutor.ts +1 -1
- package/src/messageComposer/middleware/attachmentManager/postUpload/attachmentEnrichment.ts +58 -33
- package/src/messageComposer/middleware/attachmentManager/postUpload/uploadErrorHandler.ts +7 -2
- package/src/messageComposer/middleware/attachmentManager/preUpload/blockedUploadNotification.ts +3 -2
- package/src/messageComposer/middleware/messageComposer/attachments.ts +98 -1
- package/src/messageComposer/middleware/messageComposer/linkPreviews.ts +20 -10
- package/src/messageComposer/middleware/messageComposer/sharedLocation.ts +7 -2
- package/src/messageComposer/middleware/messageComposer/types.ts +2 -7
- package/src/messageComposer/middleware/messageComposer/userDataInjection.ts +11 -6
- package/src/messageComposer/middleware/pollComposer/index.ts +1 -0
- package/src/messageComposer/middleware/pollComposer/state.ts +43 -11
- package/src/messageComposer/middleware/pollComposer/types.ts +9 -2
- package/src/messageComposer/middleware/pollComposer/validation.ts +76 -0
- package/src/messageComposer/middleware/textComposer/commandUtils.ts +3 -2
- package/src/messageComposer/middleware/textComposer/commands.ts +1 -2
- package/src/messageComposer/middleware/textComposer/mentions.ts +91 -39
- package/src/messageComposer/pollComposer.ts +11 -3
- package/src/messageComposer/textComposer.ts +36 -4
- package/src/messageComposer/types.ts +19 -14
- package/src/messageDelivery/MessageDeliveryReporter.ts +154 -53
- package/src/messageDelivery/MessageReceiptsTracker.ts +136 -64
- package/src/messageOperations/FailedSendCache.ts +90 -0
- package/src/messageOperations/MessageOperationStatePolicy.ts +269 -27
- package/src/messageOperations/MessageOperations.ts +340 -136
- package/src/{entityStore → messageOperations}/applyReactionLocally.ts +10 -3
- package/src/messageOperations/createMessageOperations.ts +192 -0
- package/src/messageOperations/index.ts +7 -0
- package/src/messageOperations/reflectReactionEvent.ts +51 -0
- package/src/messageOperations/sendOrdering.ts +28 -0
- package/src/messageOperations/settlePendingAttachmentUploads.ts +110 -0
- package/src/messageOperations/types.ts +74 -0
- package/src/middleware.ts +11 -0
- package/src/moderation.ts +47 -24
- package/src/notifications/NotificationManager.ts +73 -3
- package/src/notifications/configuration.ts +10 -8
- package/src/notifications/types.ts +58 -42
- package/src/offline-support/offline_support_api.ts +380 -197
- package/src/offline-support/offline_sync_manager.ts +105 -32
- package/src/offline-support/queueableOperations.ts +270 -0
- package/src/offline-support/types.ts +85 -39
- package/src/pagination/FilterBuilder.ts +1 -22
- package/src/pagination/cursorDerivation/createdAtAroundPaginationFlags.ts +11 -7
- package/src/pagination/cursorDerivation/linearPaginationFlags.ts +25 -7
- package/src/pagination/filterCompiler.ts +17 -0
- package/src/pagination/paginators/BasePaginator.ts +731 -81
- package/src/pagination/paginators/ChannelPaginator.ts +210 -102
- package/src/pagination/paginators/MessageIntervalPaginator.ts +703 -193
- package/src/pagination/paginators/MessagePaginator.ts +45 -36
- package/src/pagination/paginators/PinnedMessagePaginator.ts +74 -28
- package/src/pagination/paginators/ReminderPaginator.ts +15 -13
- package/src/pagination/paginators/ThreadPaginator.ts +181 -0
- package/src/pagination/paginators/UserGroupPaginator.ts +8 -1
- package/src/pagination/paginators/index.ts +1 -0
- package/src/pagination/utility.normalization.ts +37 -9
- package/src/poll.ts +189 -112
- package/src/poll_manager.ts +14 -8
- package/src/poll_optimistic_votes.ts +335 -0
- package/src/reminders/Reminder.ts +34 -16
- package/src/reminders/ReminderManager.ts +68 -41
- package/src/reminders/ReminderTimer.ts +7 -6
- package/src/search/BaseSearchSource.ts +133 -40
- package/src/search/ChannelMemberSearchSource.ts +27 -18
- package/src/search/ChannelSearchSource.ts +61 -7
- package/src/search/MessageSearchSource.ts +133 -28
- package/src/search/SearchController.ts +93 -16
- package/src/search/UserSearchSource.ts +27 -13
- package/src/search/types.ts +14 -1
- package/src/signing.ts +1 -315
- package/src/thread.ts +503 -511
- package/src/thread_manager.ts +339 -204
- package/src/token_manager.ts +12 -32
- package/src/types.ts +159 -780
- package/src/types.utility.ts +14 -0
- package/src/upload-utils.ts +53 -0
- package/src/uploadManager.ts +85 -7
- package/src/utils/FixedSizeQueueCache.ts +5 -0
- package/src/utils/WithSubscriptions.ts +1 -1
- package/src/utils/objectPath.ts +67 -0
- package/src/utils/time.ts +104 -0
- package/src/utils.ts +209 -157
- package/dist/types/base64.d.ts +0 -2
- package/dist/types/configuration/InstanceConfigurationService.d.ts +0 -26
- package/dist/types/connection.d.ts +0 -146
- package/dist/types/connection_fallback.d.ts +0 -42
- 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/insights.d.ts +0 -58
- package/dist/types/pagination/utility.queryChannel.d.ts +0 -26
- package/dist/types/permissions.d.ts +0 -55
- package/dist/types/store.d.ts +0 -125
- package/src/base64.ts +0 -78
- package/src/configuration/InstanceConfigurationService.ts +0 -73
- package/src/connection_fallback.ts +0 -215
- package/src/gen/model-decoders/decoders.ts +0 -2680
- package/src/gen/model-decoders/event-decoder-mapping.ts +0 -198
- package/src/insights.ts +0 -83
- package/src/pagination/utility.queryChannel.ts +0 -84
- package/src/permissions.ts +0 -102
- package/src/store.ts +0 -304
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { dateToNs, msToNs } from '../utils/time';
|
|
2
|
+
|
|
1
3
|
export function asArray(v: any): any[] {
|
|
2
4
|
return Array.isArray(v) ? v : [v];
|
|
3
5
|
}
|
|
@@ -6,10 +8,23 @@ export function isISODateString(x: any): x is string {
|
|
|
6
8
|
return typeof x === 'string' && x.includes('T') && !Number.isNaN(Date.parse(x));
|
|
7
9
|
}
|
|
8
10
|
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
11
|
+
/**
|
|
12
|
+
* Brings anything date-shaped into unix **nanoseconds**, the unit item fields carry, so a filter or
|
|
13
|
+
* sort can compare an operand against a value.
|
|
14
|
+
*
|
|
15
|
+
* Nanoseconds rather than milliseconds because the two sides of a comparison come from different
|
|
16
|
+
* places: an item's `created_at` is the wire number, while a filter operand is typed `Date | string`
|
|
17
|
+
* in the generated filter types. Normalizing to ms would have meant halving the pair — a `Date`
|
|
18
|
+
* became ms while a wire number was passed through untouched and *called* ms, so every mixed
|
|
19
|
+
* comparison silently ordered wrong and `normKey` bucketed the two apart.
|
|
20
|
+
*
|
|
21
|
+
* A bare `number` is therefore read as nanoseconds. That is the SDK's unit for a timestamp
|
|
22
|
+
* everywhere else, and it is what a value read off an item will be.
|
|
23
|
+
*/
|
|
24
|
+
export function toEpochNanos(x: any): number | null {
|
|
25
|
+
if (x instanceof Date) return dateToNs(x);
|
|
26
|
+
if (typeof x === 'number' && Number.isFinite(x)) return x; // already the wire unit
|
|
27
|
+
if (isISODateString(x)) return msToNs(Date.parse(x));
|
|
13
28
|
return null;
|
|
14
29
|
}
|
|
15
30
|
|
|
@@ -23,8 +38,8 @@ export function toNumberLike(x: any): number | null {
|
|
|
23
38
|
}
|
|
24
39
|
|
|
25
40
|
export function normalizeComparedValues(a: any, b: any) {
|
|
26
|
-
const Ad =
|
|
27
|
-
Bd =
|
|
41
|
+
const Ad = toEpochNanos(a),
|
|
42
|
+
Bd = toEpochNanos(b);
|
|
28
43
|
if (Ad !== null && Bd !== null) return { kind: 'date', a: Ad, b: Bd };
|
|
29
44
|
|
|
30
45
|
const An = toNumberLike(a),
|
|
@@ -84,11 +99,24 @@ export function tokenize(s: string): string[] {
|
|
|
84
99
|
return normalizeString(s).split(/\s+/).filter(Boolean);
|
|
85
100
|
}
|
|
86
101
|
|
|
87
|
-
|
|
88
|
-
|
|
102
|
+
/**
|
|
103
|
+
* Reads `a.b.c` off an item, for the filter and sort compilers.
|
|
104
|
+
*
|
|
105
|
+
* Descends through **anything indexable** — plain objects, arrays (`items.0.id`, `items.length`) and class
|
|
106
|
+
* instances (a `Reminder`, a `Poll`) — because a filter path legitimately reaches into all three. That is why
|
|
107
|
+
* this is not `getPath` from `src/utils/objectPath.ts`, which deliberately walks plain records only; the two
|
|
108
|
+
* are documented there as non-interchangeable.
|
|
109
|
+
*
|
|
110
|
+
* Stops at `null` / `undefined`, the only values that cannot be indexed. It used to stop at any *falsy*
|
|
111
|
+
* value, which made the result depend on a string's contents rather than on its shape: `name.length`
|
|
112
|
+
* resolved to `2` for `'ab'` and to `undefined` for `''`. A falsy value at the end of a path was never
|
|
113
|
+
* affected — the guard only ever ran against an intermediate — so `{ count: 0 }` on `'count'` has always
|
|
114
|
+
* returned `0`, and sorting and filtering on scalar fields were never wrong.
|
|
115
|
+
*/
|
|
116
|
+
export function resolveDotPathValue(obj: any, path: string): unknown {
|
|
89
117
|
return path
|
|
90
118
|
.split('.')
|
|
91
|
-
.reduce((reduced, key) => (
|
|
119
|
+
.reduce((reduced, key) => (reduced == null ? undefined : reduced[key]), obj);
|
|
92
120
|
}
|
|
93
121
|
|
|
94
122
|
export function isIterableButNotString(v: unknown): v is Iterable<unknown> {
|
package/src/poll.ts
CHANGED
|
@@ -1,20 +1,28 @@
|
|
|
1
|
-
import { StateStore } from '
|
|
1
|
+
import { StateStore } from '@stream-io/state-store';
|
|
2
|
+
import { nowNs } from './utils/time';
|
|
3
|
+
import { CORE_NOTIFICATION_TYPE } from './notifications';
|
|
2
4
|
import type { StreamChat } from './client';
|
|
5
|
+
import { getMaxVotedOptionIds, OptimisticPollVotes } from './poll_optimistic_votes';
|
|
3
6
|
import type {
|
|
7
|
+
CreatePollOptionRequest,
|
|
4
8
|
EventPayload,
|
|
5
9
|
PartialPollUpdate,
|
|
6
|
-
|
|
7
|
-
PollOptionData,
|
|
8
|
-
PollResponse_old,
|
|
10
|
+
PollResponseData,
|
|
9
11
|
PollVoteResponseData,
|
|
10
12
|
QueryVotesFilters,
|
|
11
13
|
QueryVotesOptions,
|
|
12
14
|
RequireLiteral,
|
|
15
|
+
SortParamRequest,
|
|
16
|
+
UpdatePollOptionRequest,
|
|
13
17
|
UpdatePollRequest,
|
|
14
|
-
|
|
18
|
+
UserResponse,
|
|
15
19
|
VotingVisibility,
|
|
16
20
|
} from './types';
|
|
17
|
-
import type {
|
|
21
|
+
import type {
|
|
22
|
+
PollResponseData as Gen_PollResponseData,
|
|
23
|
+
TimestampNS,
|
|
24
|
+
WSEvent,
|
|
25
|
+
} from './gen/models';
|
|
18
26
|
|
|
19
27
|
const isPollUpdatedEvent = (e: WSEvent): e is EventPayload<'poll.updated'> =>
|
|
20
28
|
e.type === 'poll.updated';
|
|
@@ -35,19 +43,20 @@ export const isVoteAnswer = (
|
|
|
35
43
|
export type PollAnswersQueryParams = {
|
|
36
44
|
filter?: QueryVotesFilters;
|
|
37
45
|
options?: QueryVotesOptions;
|
|
38
|
-
sort?:
|
|
46
|
+
sort?: SortParamRequest[];
|
|
39
47
|
};
|
|
40
48
|
|
|
41
49
|
export type PollOptionVotesQueryParams = {
|
|
42
50
|
filter: { option_id: string } & QueryVotesFilters;
|
|
43
51
|
options?: QueryVotesOptions;
|
|
44
|
-
sort?:
|
|
52
|
+
sort?: SortParamRequest[];
|
|
45
53
|
};
|
|
46
54
|
|
|
47
55
|
type OptionId = string;
|
|
48
56
|
|
|
49
|
-
export type PollState = Omit<
|
|
50
|
-
|
|
57
|
+
export type PollState = Omit<PollResponseData, 'own_votes' | 'id'> & {
|
|
58
|
+
/** Unix nanoseconds, matching every API timestamp. */
|
|
59
|
+
lastActivityAt: TimestampNS; // todo: would be ideal to get this from the BE
|
|
51
60
|
maxVotedOptionIds: OptionId[];
|
|
52
61
|
ownVotesByOptionId: Record<OptionId, PollVoteResponseData>;
|
|
53
62
|
ownAnswer?: PollVoteResponseData; // each user can have only one answer
|
|
@@ -62,12 +71,17 @@ export class Poll {
|
|
|
62
71
|
public readonly state: StateStore<PollState>;
|
|
63
72
|
public id: string;
|
|
64
73
|
private client: StreamChat;
|
|
74
|
+
private optimisticVotes: OptimisticPollVotes;
|
|
75
|
+
// Set whenever server data (WS event or rehydration) confirms that the poll is closed,
|
|
76
|
+
// so that a failed optimistic close does not reopen a poll that is actually closed.
|
|
77
|
+
private closeConfirmed = false;
|
|
65
78
|
|
|
66
79
|
constructor({ client, poll }: PollInitOptions) {
|
|
67
80
|
this.client = client;
|
|
68
81
|
this.id = poll.id;
|
|
69
82
|
|
|
70
83
|
this.state = new StateStore<PollState>(this.getInitialStateFromPollResponse(poll));
|
|
84
|
+
this.optimisticVotes = new OptimisticPollVotes({ client: this.client, poll: this });
|
|
71
85
|
}
|
|
72
86
|
|
|
73
87
|
private getInitialStateFromPollResponse = (poll: PollInitOptions['poll']) => {
|
|
@@ -89,22 +103,48 @@ export class Poll {
|
|
|
89
103
|
|
|
90
104
|
return {
|
|
91
105
|
...pollResponseForState,
|
|
92
|
-
lastActivityAt:
|
|
106
|
+
lastActivityAt: nowNs(),
|
|
93
107
|
maxVotedOptionIds: getMaxVotedOptionIds(pollResponseForState.vote_counts_by_option),
|
|
94
108
|
ownAnswer,
|
|
95
109
|
ownVotesByOptionId: getOwnVotesByOptionId(ownVotes),
|
|
96
110
|
};
|
|
97
111
|
};
|
|
98
112
|
|
|
113
|
+
// persists only the server's votes, never the optimistic ones
|
|
99
114
|
private upsertOfflineDb = () => {
|
|
115
|
+
const serverState = this.optimisticVotes.withServerVotes(this.data);
|
|
100
116
|
this.client.offlineDb?.executeQuerySafely(
|
|
101
|
-
(db) => db.upsertPoll({ poll: mapPollStateToResponse(this) }),
|
|
117
|
+
(db) => db.upsertPoll({ poll: mapPollStateToResponse(this, serverState) }),
|
|
102
118
|
{ method: 'upsertPoll' },
|
|
103
119
|
);
|
|
104
120
|
};
|
|
105
121
|
|
|
106
122
|
public reinitializeState = (poll: PollInitOptions['poll']) => {
|
|
107
|
-
|
|
123
|
+
if (poll.is_closed) this.closeConfirmed = true;
|
|
124
|
+
const initialState = this.getInitialStateFromPollResponse(poll);
|
|
125
|
+
this.optimisticVotes.reset(initialState);
|
|
126
|
+
this.state.partialNext(initialState);
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
// Hands the vote state of a WS vote event to the optimistic votes, which decide whether to show it.
|
|
130
|
+
private updateFromVoteEvent = (
|
|
131
|
+
event: EventPayload<'poll.vote_casted' | 'poll.vote_changed' | 'poll.vote_removed'>,
|
|
132
|
+
ownVotesByOptionId: Record<OptionId, PollVoteResponseData>,
|
|
133
|
+
answerState: Pick<PollState, 'latest_answers' | 'ownAnswer'>,
|
|
134
|
+
) => {
|
|
135
|
+
const isOwnVote = event.poll_vote.user_id === this.client.userId;
|
|
136
|
+
const shownVoteState = this.optimisticVotes.handleVoteEvent(event.poll, {
|
|
137
|
+
confirmsOwnVote:
|
|
138
|
+
isOwnVote && !isVoteAnswer(event.poll_vote) && !!event.poll_vote.option_id,
|
|
139
|
+
ownVotesByOptionId,
|
|
140
|
+
});
|
|
141
|
+
this.state.partialNext({
|
|
142
|
+
...answerState,
|
|
143
|
+
answers_count: event.poll.answers_count,
|
|
144
|
+
lastActivityAt: event.created_at,
|
|
145
|
+
...shownVoteState,
|
|
146
|
+
});
|
|
147
|
+
this.upsertOfflineDb();
|
|
108
148
|
};
|
|
109
149
|
|
|
110
150
|
get data(): PollState {
|
|
@@ -116,17 +156,19 @@ export class Poll {
|
|
|
116
156
|
if (!isPollUpdatedEvent(event)) return;
|
|
117
157
|
|
|
118
158
|
const { id: _id, ...pollData } = extractPollData(event.poll);
|
|
159
|
+
if (pollData.is_closed) this.closeConfirmed = true;
|
|
119
160
|
// @ts-expect-error type mismatch
|
|
120
|
-
this.state.partialNext({ ...pollData, lastActivityAt:
|
|
161
|
+
this.state.partialNext({ ...pollData, lastActivityAt: event.created_at });
|
|
121
162
|
this.upsertOfflineDb();
|
|
122
163
|
};
|
|
123
164
|
|
|
124
165
|
public handlePollClosed = (event: EventPayload<'poll.closed'>) => {
|
|
125
166
|
if (event.poll?.id && event.poll.id !== this.id) return;
|
|
126
167
|
if (!isPollClosedEventEvent(event)) return;
|
|
168
|
+
this.closeConfirmed = true;
|
|
127
169
|
this.state.partialNext({
|
|
128
170
|
is_closed: true,
|
|
129
|
-
lastActivityAt:
|
|
171
|
+
lastActivityAt: event.created_at,
|
|
130
172
|
});
|
|
131
173
|
this.upsertOfflineDb();
|
|
132
174
|
};
|
|
@@ -138,8 +180,7 @@ export class Poll {
|
|
|
138
180
|
const isOwnVote = event.poll_vote.user_id === this.client.userId;
|
|
139
181
|
let latestAnswers = [...(currentState.latest_answers as PollVoteResponseData[])];
|
|
140
182
|
let ownAnswer = currentState.ownAnswer;
|
|
141
|
-
const ownVotesByOptionId =
|
|
142
|
-
let maxVotedOptionIds = currentState.maxVotedOptionIds;
|
|
183
|
+
const ownVotesByOptionId = { ...this.optimisticVotes.serverOwnVotes };
|
|
143
184
|
|
|
144
185
|
if (isOwnVote) {
|
|
145
186
|
if (isVoteAnswer(event.poll_vote)) {
|
|
@@ -151,20 +192,12 @@ export class Poll {
|
|
|
151
192
|
|
|
152
193
|
if (isVoteAnswer(event.poll_vote)) {
|
|
153
194
|
latestAnswers = [event.poll_vote, ...latestAnswers];
|
|
154
|
-
} else {
|
|
155
|
-
maxVotedOptionIds = getMaxVotedOptionIds(event.poll.vote_counts_by_option);
|
|
156
195
|
}
|
|
157
196
|
|
|
158
|
-
|
|
159
|
-
this.state.partialNext({
|
|
160
|
-
...pollEnrichData,
|
|
197
|
+
this.updateFromVoteEvent(event, ownVotesByOptionId, {
|
|
161
198
|
latest_answers: latestAnswers,
|
|
162
|
-
lastActivityAt: new Date(event.created_at),
|
|
163
199
|
ownAnswer,
|
|
164
|
-
ownVotesByOptionId,
|
|
165
|
-
maxVotedOptionIds,
|
|
166
200
|
});
|
|
167
|
-
this.upsertOfflineDb();
|
|
168
201
|
};
|
|
169
202
|
|
|
170
203
|
public handleVoteChanged = (event: EventPayload<'poll.vote_changed'>) => {
|
|
@@ -175,8 +208,7 @@ export class Poll {
|
|
|
175
208
|
const isOwnVote = event.poll_vote.user_id === this.client.userId;
|
|
176
209
|
let latestAnswers = [...(currentState.latest_answers as PollVoteResponseData[])];
|
|
177
210
|
let ownAnswer = currentState.ownAnswer;
|
|
178
|
-
let ownVotesByOptionId =
|
|
179
|
-
let maxVotedOptionIds = currentState.maxVotedOptionIds;
|
|
211
|
+
let ownVotesByOptionId = this.optimisticVotes.serverOwnVotes;
|
|
180
212
|
|
|
181
213
|
if (isOwnVote) {
|
|
182
214
|
if (isVoteAnswer(event.poll_vote)) {
|
|
@@ -207,24 +239,15 @@ export class Poll {
|
|
|
207
239
|
if (ownAnswer?.id === event.poll_vote.id) {
|
|
208
240
|
ownAnswer = undefined;
|
|
209
241
|
}
|
|
210
|
-
maxVotedOptionIds = getMaxVotedOptionIds(event.poll.vote_counts_by_option);
|
|
211
242
|
}
|
|
212
243
|
} else if (isVoteAnswer(event.poll_vote)) {
|
|
213
244
|
latestAnswers = [event.poll_vote, ...latestAnswers];
|
|
214
|
-
} else {
|
|
215
|
-
maxVotedOptionIds = getMaxVotedOptionIds(event.poll.vote_counts_by_option);
|
|
216
245
|
}
|
|
217
246
|
|
|
218
|
-
|
|
219
|
-
this.state.partialNext({
|
|
220
|
-
...pollEnrichData,
|
|
247
|
+
this.updateFromVoteEvent(event, ownVotesByOptionId, {
|
|
221
248
|
latest_answers: latestAnswers,
|
|
222
|
-
lastActivityAt: new Date(event.created_at),
|
|
223
249
|
ownAnswer,
|
|
224
|
-
ownVotesByOptionId,
|
|
225
|
-
maxVotedOptionIds,
|
|
226
250
|
});
|
|
227
|
-
this.upsertOfflineDb();
|
|
228
251
|
};
|
|
229
252
|
|
|
230
253
|
public handleVoteRemoved = (event: EventPayload<'poll.vote_removed'>) => {
|
|
@@ -234,36 +257,80 @@ export class Poll {
|
|
|
234
257
|
const isOwnVote = event.poll_vote.user_id === this.client.userId;
|
|
235
258
|
let latestAnswers = [...(currentState.latest_answers as PollVoteResponseData[])];
|
|
236
259
|
let ownAnswer = currentState.ownAnswer;
|
|
237
|
-
const ownVotesByOptionId = { ...
|
|
238
|
-
let maxVotedOptionIds = currentState.maxVotedOptionIds;
|
|
260
|
+
const ownVotesByOptionId = { ...this.optimisticVotes.serverOwnVotes };
|
|
239
261
|
|
|
240
262
|
if (isVoteAnswer(event.poll_vote)) {
|
|
241
263
|
latestAnswers = latestAnswers.filter((answer) => answer.id !== event.poll_vote.id);
|
|
242
264
|
if (isOwnVote) {
|
|
243
265
|
ownAnswer = undefined;
|
|
244
266
|
}
|
|
245
|
-
} else {
|
|
246
|
-
|
|
247
|
-
if (isOwnVote && event.poll_vote.option_id) {
|
|
248
|
-
delete ownVotesByOptionId[event.poll_vote.option_id];
|
|
249
|
-
}
|
|
267
|
+
} else if (isOwnVote && event.poll_vote.option_id) {
|
|
268
|
+
delete ownVotesByOptionId[event.poll_vote.option_id];
|
|
250
269
|
}
|
|
251
270
|
|
|
252
|
-
|
|
253
|
-
this.state.partialNext({
|
|
254
|
-
...pollEnrichData,
|
|
271
|
+
this.updateFromVoteEvent(event, ownVotesByOptionId, {
|
|
255
272
|
latest_answers: latestAnswers,
|
|
256
|
-
|
|
273
|
+
ownAnswer,
|
|
274
|
+
});
|
|
275
|
+
};
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* Puts an updated user (new name or image) into the votes, answers and creator this poll keeps,
|
|
279
|
+
* so voter avatars show it. Each vote is replaced, not edited in place, and everything goes out in
|
|
280
|
+
* one state update; nothing is published when the poll doesn't contain the user. An option whose
|
|
281
|
+
* votes don't contain the user keeps its array, so what renders it doesn't re-render. The offline
|
|
282
|
+
* DB gets the updated poll, as with the other poll events.
|
|
283
|
+
*/
|
|
284
|
+
public handleUserUpdated = (user: UserResponse) => {
|
|
285
|
+
const currentState = this.data;
|
|
286
|
+
let changed = false;
|
|
287
|
+
const withUser = <V extends PollVoteResponseData>(vote: V): V => {
|
|
288
|
+
if (vote.user?.id !== user.id || vote.user === user) return vote;
|
|
289
|
+
changed = true;
|
|
290
|
+
return { ...vote, user };
|
|
291
|
+
};
|
|
292
|
+
// the same array when none of its votes is the user's
|
|
293
|
+
const withUserAll = (votes?: PollVoteResponseData[]) => {
|
|
294
|
+
if (!votes) return votes;
|
|
295
|
+
const next = votes.map(withUser);
|
|
296
|
+
return next.some((vote, index) => vote !== votes[index]) ? next : votes;
|
|
297
|
+
};
|
|
298
|
+
|
|
299
|
+
const latestVotesByOption = Object.fromEntries(
|
|
300
|
+
Object.entries(currentState.latest_votes_by_option ?? {}).map(
|
|
301
|
+
([optionId, votes]) => [
|
|
302
|
+
optionId,
|
|
303
|
+
withUserAll(votes as PollVoteResponseData[]) ?? [],
|
|
304
|
+
],
|
|
305
|
+
),
|
|
306
|
+
);
|
|
307
|
+
const latestAnswers = withUserAll(
|
|
308
|
+
currentState.latest_answers as PollVoteResponseData[],
|
|
309
|
+
);
|
|
310
|
+
const ownVotesByOptionId = Object.fromEntries(
|
|
311
|
+
Object.entries(currentState.ownVotesByOptionId).map(([optionId, vote]) => [
|
|
312
|
+
optionId,
|
|
313
|
+
withUser(vote),
|
|
314
|
+
]),
|
|
315
|
+
);
|
|
316
|
+
const ownAnswer = currentState.ownAnswer && withUser(currentState.ownAnswer);
|
|
317
|
+
const createdByChanged =
|
|
318
|
+
currentState.created_by?.id === user.id && currentState.created_by !== user;
|
|
319
|
+
|
|
320
|
+
if (!changed && !createdByChanged) return;
|
|
321
|
+
this.state.partialNext({
|
|
322
|
+
...(createdByChanged && { created_by: user }),
|
|
323
|
+
latest_answers: latestAnswers ?? [],
|
|
324
|
+
latest_votes_by_option: latestVotesByOption,
|
|
257
325
|
ownAnswer,
|
|
258
326
|
ownVotesByOptionId,
|
|
259
|
-
maxVotedOptionIds,
|
|
260
327
|
});
|
|
261
328
|
this.upsertOfflineDb();
|
|
262
329
|
};
|
|
263
330
|
|
|
264
331
|
query = async (id: string) => {
|
|
265
332
|
const { poll } = await this.client.getPoll({ poll_id: id });
|
|
266
|
-
this.state.partialNext({ ...poll, lastActivityAt:
|
|
333
|
+
this.state.partialNext({ ...poll, lastActivityAt: nowNs() });
|
|
267
334
|
return poll;
|
|
268
335
|
};
|
|
269
336
|
|
|
@@ -271,28 +338,51 @@ export class Poll {
|
|
|
271
338
|
await this.client.updatePoll({ ...data, id: this.id as string });
|
|
272
339
|
|
|
273
340
|
partialUpdate = async (partialPollObject: PartialPollUpdate) =>
|
|
274
|
-
await this.client.updatePollPartial(
|
|
275
|
-
poll_id: this.id as string,
|
|
276
|
-
|
|
277
|
-
|
|
341
|
+
await this.client.updatePollPartial(
|
|
342
|
+
{ poll_id: this.id as string },
|
|
343
|
+
partialPollObject,
|
|
344
|
+
);
|
|
278
345
|
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
346
|
+
/**
|
|
347
|
+
* Closes the poll. The poll is marked as closed optimistically and the change is
|
|
348
|
+
* reverted if the request fails, unless the server confirmed the close meanwhile.
|
|
349
|
+
* Does nothing if the poll is already closed.
|
|
350
|
+
*/
|
|
351
|
+
close = async () => {
|
|
352
|
+
if (this.data.is_closed) return;
|
|
353
|
+
|
|
354
|
+
this.closeConfirmed = false;
|
|
355
|
+
this.state.partialNext({ is_closed: true });
|
|
356
|
+
|
|
357
|
+
try {
|
|
358
|
+
return await this.client.updatePollPartial(
|
|
359
|
+
{ poll_id: this.id as string },
|
|
360
|
+
{ set: { is_closed: true } },
|
|
361
|
+
);
|
|
362
|
+
} catch (error) {
|
|
363
|
+
if (!this.closeConfirmed) {
|
|
364
|
+
this.state.partialNext({ is_closed: false });
|
|
365
|
+
}
|
|
366
|
+
throw error;
|
|
367
|
+
}
|
|
368
|
+
};
|
|
284
369
|
|
|
285
370
|
delete = async () => await this.client.deletePoll({ poll_id: this.id as string });
|
|
286
371
|
|
|
287
|
-
createOption = async (option:
|
|
288
|
-
await this.client.createPollOption({ poll_id: this.id as string,
|
|
372
|
+
createOption = async (option: CreatePollOptionRequest) =>
|
|
373
|
+
await this.client.createPollOption({ poll_id: this.id as string }, option);
|
|
289
374
|
|
|
290
|
-
updateOption = async (option:
|
|
291
|
-
await this.client.updatePollOption({ poll_id: this.id as string,
|
|
375
|
+
updateOption = async (option: UpdatePollOptionRequest) =>
|
|
376
|
+
await this.client.updatePollOption({ poll_id: this.id as string }, option);
|
|
292
377
|
|
|
293
378
|
deleteOption = async (option_id: string) =>
|
|
294
379
|
await this.client.deletePollOption({ poll_id: this.id as string, option_id });
|
|
295
380
|
|
|
381
|
+
/**
|
|
382
|
+
* Casts a vote for an option. The vote is shown right away through a local placeholder vote,
|
|
383
|
+
* which the server's vote replaces once the WS events of all pending vote changes arrived.
|
|
384
|
+
* If the request fails, the change is reverted.
|
|
385
|
+
*/
|
|
296
386
|
castVote = async (optionId: string, messageId: string) => {
|
|
297
387
|
const { max_votes_allowed, ownVotesByOptionId } = this.data;
|
|
298
388
|
|
|
@@ -307,31 +397,28 @@ export class Poll {
|
|
|
307
397
|
context: { messageId, optionId },
|
|
308
398
|
},
|
|
309
399
|
options: {
|
|
310
|
-
type:
|
|
400
|
+
type: CORE_NOTIFICATION_TYPE.pollCastVoteLimit,
|
|
311
401
|
},
|
|
312
402
|
});
|
|
313
403
|
return;
|
|
314
404
|
}
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
poll_id: this.id as string,
|
|
318
|
-
vote: { option_id: optionId },
|
|
319
|
-
});
|
|
405
|
+
|
|
406
|
+
return await this.optimisticVotes.castVote(optionId, messageId);
|
|
320
407
|
};
|
|
321
408
|
|
|
409
|
+
/**
|
|
410
|
+
* Removes a vote. The vote is removed right away and restored if the request fails. Vote
|
|
411
|
+
* requests are sent in order, so removing a vote whose cast is not confirmed yet uses the vote
|
|
412
|
+
* id from the cast's response; if that cast failed, there is nothing to remove.
|
|
413
|
+
*/
|
|
322
414
|
removeVote = async (voteId: string, messageId: string) =>
|
|
323
|
-
await this.
|
|
324
|
-
message_id: messageId,
|
|
325
|
-
poll_id: this.id as string,
|
|
326
|
-
vote_id: voteId,
|
|
327
|
-
});
|
|
415
|
+
await this.optimisticVotes.removeVote(voteId, messageId);
|
|
328
416
|
|
|
329
417
|
addAnswer = async (answerText: string, messageId: string) =>
|
|
330
|
-
await this.client.castPollVote(
|
|
331
|
-
message_id: messageId,
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
});
|
|
418
|
+
await this.client.castPollVote(
|
|
419
|
+
{ message_id: messageId, poll_id: this.id as string },
|
|
420
|
+
{ vote: { answer_text: answerText } },
|
|
421
|
+
);
|
|
335
422
|
|
|
336
423
|
removeAnswer = async (answerId: string, messageId: string) =>
|
|
337
424
|
await this.client.deletePollVote({
|
|
@@ -341,36 +428,20 @@ export class Poll {
|
|
|
341
428
|
});
|
|
342
429
|
|
|
343
430
|
queryAnswers = async (params: PollAnswersQueryParams) =>
|
|
344
|
-
await this.client.queryPollVotes(
|
|
345
|
-
poll_id: this.id as string,
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
431
|
+
await this.client.queryPollVotes(
|
|
432
|
+
{ poll_id: this.id as string },
|
|
433
|
+
{
|
|
434
|
+
sort: params.sort,
|
|
435
|
+
filter: { ...(params.filter ?? {}), is_answer: true },
|
|
436
|
+
...(params.options ?? {}),
|
|
437
|
+
},
|
|
438
|
+
);
|
|
350
439
|
|
|
351
440
|
queryOptionVotes = async (params: PollOptionVotesQueryParams) =>
|
|
352
|
-
await this.client.queryPollVotes(
|
|
353
|
-
poll_id: this.id as string,
|
|
354
|
-
sort: params.sort,
|
|
355
|
-
|
|
356
|
-
...(params.options ?? {}),
|
|
357
|
-
});
|
|
358
|
-
}
|
|
359
|
-
|
|
360
|
-
function getMaxVotedOptionIds(
|
|
361
|
-
voteCountsByOption: PollResponse_old['vote_counts_by_option'],
|
|
362
|
-
) {
|
|
363
|
-
let maxVotes = 0;
|
|
364
|
-
let winningOptions: string[] = [];
|
|
365
|
-
for (const [id, count] of Object.entries(voteCountsByOption ?? {})) {
|
|
366
|
-
if (count > maxVotes) {
|
|
367
|
-
winningOptions = [id];
|
|
368
|
-
maxVotes = count;
|
|
369
|
-
} else if (count === maxVotes) {
|
|
370
|
-
winningOptions.push(id);
|
|
371
|
-
}
|
|
372
|
-
}
|
|
373
|
-
return winningOptions;
|
|
441
|
+
await this.client.queryPollVotes(
|
|
442
|
+
{ poll_id: this.id as string },
|
|
443
|
+
{ sort: params.sort, filter: params.filter, ...(params.options ?? {}) },
|
|
444
|
+
);
|
|
374
445
|
}
|
|
375
446
|
|
|
376
447
|
function getOwnVotesByOptionId(ownVotes: PollVoteResponseData[]) {
|
|
@@ -398,7 +469,10 @@ export function extractPollData(pollResponse: Gen_PollResponseData): UpdatePollR
|
|
|
398
469
|
};
|
|
399
470
|
}
|
|
400
471
|
|
|
401
|
-
export function mapPollStateToResponse(
|
|
472
|
+
export function mapPollStateToResponse(
|
|
473
|
+
poll: Poll,
|
|
474
|
+
state: PollState = poll.data,
|
|
475
|
+
): PollResponseData {
|
|
402
476
|
const {
|
|
403
477
|
lastActivityAt: _lastActivityAt,
|
|
404
478
|
|
|
@@ -406,11 +480,11 @@ export function mapPollStateToResponse(poll: Poll): PollResponse_old {
|
|
|
406
480
|
ownVotesByOptionId,
|
|
407
481
|
ownAnswer,
|
|
408
482
|
...restState
|
|
409
|
-
} =
|
|
483
|
+
} = state;
|
|
410
484
|
const ownVotes = [
|
|
411
485
|
...Object.values(ownVotesByOptionId),
|
|
412
486
|
...(ownAnswer ? [ownAnswer] : []),
|
|
413
|
-
].sort((a, b) => a.created_at
|
|
487
|
+
].sort((a, b) => a.created_at - b.created_at);
|
|
414
488
|
|
|
415
489
|
return {
|
|
416
490
|
...restState,
|
|
@@ -421,7 +495,10 @@ export function mapPollStateToResponse(poll: Poll): PollResponse_old {
|
|
|
421
495
|
|
|
422
496
|
export function extractPollEnrichedData(
|
|
423
497
|
pollResponse: Gen_PollResponseData,
|
|
424
|
-
):
|
|
498
|
+
): Pick<
|
|
499
|
+
Gen_PollResponseData,
|
|
500
|
+
'answers_count' | 'latest_votes_by_option' | 'vote_count' | 'vote_counts_by_option'
|
|
501
|
+
> {
|
|
425
502
|
return {
|
|
426
503
|
answers_count: pollResponse.answers_count,
|
|
427
504
|
latest_votes_by_option: pollResponse.latest_votes_by_option,
|
package/src/poll_manager.ts
CHANGED
|
@@ -3,10 +3,10 @@ import type {
|
|
|
3
3
|
CreatePollRequest,
|
|
4
4
|
LocalMessage,
|
|
5
5
|
MessageResponse,
|
|
6
|
-
|
|
7
|
-
PollSort,
|
|
6
|
+
PollResponseData,
|
|
8
7
|
QueryPollsFilters,
|
|
9
8
|
QueryPollsOptions,
|
|
9
|
+
SortParamRequest,
|
|
10
10
|
} from './types';
|
|
11
11
|
import { Poll } from './poll';
|
|
12
12
|
import { formatMessage } from './utils';
|
|
@@ -44,6 +44,7 @@ export class PollManager extends WithSubscriptions {
|
|
|
44
44
|
this.addUnsubscribeFunction(this.subscribeVoteCasted());
|
|
45
45
|
this.addUnsubscribeFunction(this.subscribeVoteChanged());
|
|
46
46
|
this.addUnsubscribeFunction(this.subscribeVoteRemoved());
|
|
47
|
+
this.addUnsubscribeFunction(this.subscribeUserUpdated());
|
|
47
48
|
};
|
|
48
49
|
|
|
49
50
|
public createPoll = async (poll: CreatePollRequest) => {
|
|
@@ -78,7 +79,7 @@ export class PollManager extends WithSubscriptions {
|
|
|
78
79
|
|
|
79
80
|
public queryPolls = async (
|
|
80
81
|
filter: QueryPollsFilters,
|
|
81
|
-
sort:
|
|
82
|
+
sort: SortParamRequest[] = [],
|
|
82
83
|
options: QueryPollsOptions = {},
|
|
83
84
|
) => {
|
|
84
85
|
const { polls, next } = await this.client.queryPolls({
|
|
@@ -107,18 +108,15 @@ export class PollManager extends WithSubscriptions {
|
|
|
107
108
|
if (!message.poll) {
|
|
108
109
|
continue;
|
|
109
110
|
}
|
|
110
|
-
const pollResponse = message.poll as
|
|
111
|
+
const pollResponse = message.poll as PollResponseData;
|
|
111
112
|
this.setOrOverwriteInCache(pollResponse, overwriteState);
|
|
112
113
|
}
|
|
113
114
|
};
|
|
114
115
|
|
|
115
116
|
private setOrOverwriteInCache = (
|
|
116
|
-
pollResponse:
|
|
117
|
+
pollResponse: PollResponseData,
|
|
117
118
|
overwriteState?: boolean,
|
|
118
119
|
) => {
|
|
119
|
-
if (!this.client._cacheEnabled()) {
|
|
120
|
-
return;
|
|
121
|
-
}
|
|
122
120
|
const pollFromCache = this.fromState(pollResponse.id);
|
|
123
121
|
if (!pollFromCache) {
|
|
124
122
|
const poll = new Poll({ client: this.client, poll: pollResponse });
|
|
@@ -163,6 +161,14 @@ export class PollManager extends WithSubscriptions {
|
|
|
163
161
|
}
|
|
164
162
|
}).unsubscribe;
|
|
165
163
|
|
|
164
|
+
// votes carry a copy of their voter, so a changed name or image reaches the polls only from here
|
|
165
|
+
private subscribeUserUpdated = () =>
|
|
166
|
+
this.client.on('user.updated', (event) => {
|
|
167
|
+
const { user } = event;
|
|
168
|
+
if (!user?.id) return;
|
|
169
|
+
for (const poll of this.pollCache.values()) poll.handleUserUpdated(user);
|
|
170
|
+
}).unsubscribe;
|
|
171
|
+
|
|
166
172
|
private subscribeMessageNew = () =>
|
|
167
173
|
this.client.on('message.new', (event) => {
|
|
168
174
|
const { message } = event;
|