stream-chat 9.53.0 → 9.54.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/index.browser.js +362 -79
- package/dist/cjs/index.browser.js.map +3 -3
- package/dist/cjs/index.node.js +362 -79
- package/dist/cjs/index.node.js.map +3 -3
- package/dist/esm/index.mjs +362 -79
- package/dist/esm/index.mjs.map +3 -3
- package/dist/types/client.d.ts +5 -73
- package/dist/types/connection.d.ts +12 -0
- package/dist/types/poll.d.ts +22 -4
- package/dist/types/poll_optimistic_votes.d.ts +63 -0
- package/dist/types/types.d.ts +36 -9
- package/dist/types/utils.d.ts +1 -3
- package/package.json +6 -1
- package/src/client.ts +3 -3
- package/src/connection.ts +47 -2
- package/src/messageComposer/middleware/messageComposer/linkPreviews.ts +20 -10
- package/src/poll.ts +95 -61
- package/src/poll_optimistic_votes.ts +321 -0
- package/src/thread.ts +11 -4
- package/src/types.ts +41 -9
package/src/poll.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { StateStore } from './store';
|
|
2
2
|
import type { StreamChat } from './client';
|
|
3
|
+
import { getMaxVotedOptionIds, OptimisticPollVotes } from './poll_optimistic_votes';
|
|
3
4
|
import type {
|
|
4
5
|
Event,
|
|
5
6
|
PartialPollUpdate,
|
|
@@ -90,12 +91,17 @@ export class Poll {
|
|
|
90
91
|
public readonly state: StateStore<PollState>;
|
|
91
92
|
public id: string;
|
|
92
93
|
private client: StreamChat;
|
|
94
|
+
private optimisticVotes: OptimisticPollVotes;
|
|
95
|
+
// Set whenever server data (WS event or rehydration) confirms that the poll is closed,
|
|
96
|
+
// so that a failed optimistic close does not reopen a poll that is actually closed.
|
|
97
|
+
private closeConfirmed = false;
|
|
93
98
|
|
|
94
99
|
constructor({ client, poll }: PollInitOptions) {
|
|
95
100
|
this.client = client;
|
|
96
101
|
this.id = poll.id;
|
|
97
102
|
|
|
98
103
|
this.state = new StateStore<PollState>(this.getInitialStateFromPollResponse(poll));
|
|
104
|
+
this.optimisticVotes = new OptimisticPollVotes({ client: this.client, poll: this });
|
|
99
105
|
}
|
|
100
106
|
|
|
101
107
|
private getInitialStateFromPollResponse = (poll: PollInitOptions['poll']) => {
|
|
@@ -127,15 +133,45 @@ export class Poll {
|
|
|
127
133
|
};
|
|
128
134
|
};
|
|
129
135
|
|
|
136
|
+
// persists only the server's votes, never the optimistic ones
|
|
130
137
|
private upsertOfflineDb = () => {
|
|
138
|
+
const serverState = this.optimisticVotes.withServerVotes(this.data);
|
|
131
139
|
this.client.offlineDb?.executeQuerySafely(
|
|
132
|
-
(db) => db.upsertPoll({ poll: mapPollStateToResponse(this) }),
|
|
140
|
+
(db) => db.upsertPoll({ poll: mapPollStateToResponse(this, serverState) }),
|
|
133
141
|
{ method: 'upsertPoll' },
|
|
134
142
|
);
|
|
135
143
|
};
|
|
136
144
|
|
|
137
145
|
public reinitializeState = (poll: PollInitOptions['poll']) => {
|
|
138
|
-
|
|
146
|
+
if (poll.is_closed) this.closeConfirmed = true;
|
|
147
|
+
const initialState = this.getInitialStateFromPollResponse(poll);
|
|
148
|
+
this.optimisticVotes.reset(initialState);
|
|
149
|
+
this.state.partialNext(initialState);
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
// Hands the vote state of a WS vote event to the optimistic votes, which decide whether to show it.
|
|
153
|
+
private updateFromVoteEvent = (
|
|
154
|
+
event: Event & {
|
|
155
|
+
created_at: string;
|
|
156
|
+
poll: PollResponse;
|
|
157
|
+
poll_vote: PollVote | PollAnswer;
|
|
158
|
+
},
|
|
159
|
+
ownVotesByOptionId: Record<OptionId, PollVote>,
|
|
160
|
+
answerState: Pick<PollState, 'latest_answers' | 'ownAnswer'>,
|
|
161
|
+
) => {
|
|
162
|
+
const isOwnVote = event.poll_vote.user_id === this.client.userID;
|
|
163
|
+
const shownVoteState = this.optimisticVotes.handleVoteEvent(event.poll, {
|
|
164
|
+
confirmsOwnVote:
|
|
165
|
+
isOwnVote && !isVoteAnswer(event.poll_vote) && !!event.poll_vote.option_id,
|
|
166
|
+
ownVotesByOptionId,
|
|
167
|
+
});
|
|
168
|
+
this.state.partialNext({
|
|
169
|
+
...answerState,
|
|
170
|
+
answers_count: event.poll.answers_count,
|
|
171
|
+
lastActivityAt: new Date(event.created_at),
|
|
172
|
+
...shownVoteState,
|
|
173
|
+
});
|
|
174
|
+
this.upsertOfflineDb();
|
|
139
175
|
};
|
|
140
176
|
|
|
141
177
|
get data(): PollState {
|
|
@@ -147,14 +183,24 @@ export class Poll {
|
|
|
147
183
|
if (!isPollUpdatedEvent(event)) return;
|
|
148
184
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
149
185
|
const { id, ...pollData } = extractPollData(event.poll);
|
|
186
|
+
if (pollData.is_closed) this.closeConfirmed = true;
|
|
150
187
|
// @ts-expect-error type mismatch
|
|
151
|
-
this.state.partialNext({
|
|
188
|
+
this.state.partialNext({
|
|
189
|
+
...pollData,
|
|
190
|
+
// Server-owned translations, which `extractPollData` (an update request) leaves out. Copied
|
|
191
|
+
// even when absent: the event carries the whole poll, and a change made under channel-only
|
|
192
|
+
// translation drops the stale ones.
|
|
193
|
+
description_i18n: event.poll.description_i18n,
|
|
194
|
+
lastActivityAt: new Date(event.created_at),
|
|
195
|
+
name_i18n: event.poll.name_i18n,
|
|
196
|
+
});
|
|
152
197
|
this.upsertOfflineDb();
|
|
153
198
|
};
|
|
154
199
|
|
|
155
200
|
public handlePollClosed = (event: Event) => {
|
|
156
201
|
if (event.poll?.id && event.poll.id !== this.id) return;
|
|
157
202
|
if (!isPollClosedEventEvent(event)) return;
|
|
203
|
+
this.closeConfirmed = true;
|
|
158
204
|
this.state.partialNext({
|
|
159
205
|
is_closed: true,
|
|
160
206
|
lastActivityAt: new Date(event.created_at),
|
|
@@ -169,8 +215,7 @@ export class Poll {
|
|
|
169
215
|
const isOwnVote = event.poll_vote.user_id === this.client.userID;
|
|
170
216
|
let latestAnswers = [...(currentState.latest_answers as PollAnswer[])];
|
|
171
217
|
let ownAnswer = currentState.ownAnswer;
|
|
172
|
-
const ownVotesByOptionId =
|
|
173
|
-
let maxVotedOptionIds = currentState.maxVotedOptionIds;
|
|
218
|
+
const ownVotesByOptionId = { ...this.optimisticVotes.serverOwnVotes };
|
|
174
219
|
|
|
175
220
|
if (isOwnVote) {
|
|
176
221
|
if (isVoteAnswer(event.poll_vote)) {
|
|
@@ -182,20 +227,12 @@ export class Poll {
|
|
|
182
227
|
|
|
183
228
|
if (isVoteAnswer(event.poll_vote)) {
|
|
184
229
|
latestAnswers = [event.poll_vote, ...latestAnswers];
|
|
185
|
-
} else {
|
|
186
|
-
maxVotedOptionIds = getMaxVotedOptionIds(event.poll.vote_counts_by_option);
|
|
187
230
|
}
|
|
188
231
|
|
|
189
|
-
|
|
190
|
-
this.state.partialNext({
|
|
191
|
-
...pollEnrichData,
|
|
232
|
+
this.updateFromVoteEvent(event, ownVotesByOptionId, {
|
|
192
233
|
latest_answers: latestAnswers,
|
|
193
|
-
lastActivityAt: new Date(event.created_at),
|
|
194
234
|
ownAnswer,
|
|
195
|
-
ownVotesByOptionId,
|
|
196
|
-
maxVotedOptionIds,
|
|
197
235
|
});
|
|
198
|
-
this.upsertOfflineDb();
|
|
199
236
|
};
|
|
200
237
|
|
|
201
238
|
public handleVoteChanged = (event: Event) => {
|
|
@@ -206,8 +243,7 @@ export class Poll {
|
|
|
206
243
|
const isOwnVote = event.poll_vote.user_id === this.client.userID;
|
|
207
244
|
let latestAnswers = [...(currentState.latest_answers as PollAnswer[])];
|
|
208
245
|
let ownAnswer = currentState.ownAnswer;
|
|
209
|
-
let ownVotesByOptionId =
|
|
210
|
-
let maxVotedOptionIds = currentState.maxVotedOptionIds;
|
|
246
|
+
let ownVotesByOptionId = this.optimisticVotes.serverOwnVotes;
|
|
211
247
|
|
|
212
248
|
if (isOwnVote) {
|
|
213
249
|
if (isVoteAnswer(event.poll_vote)) {
|
|
@@ -238,24 +274,15 @@ export class Poll {
|
|
|
238
274
|
if (ownAnswer?.id === event.poll_vote.id) {
|
|
239
275
|
ownAnswer = undefined;
|
|
240
276
|
}
|
|
241
|
-
maxVotedOptionIds = getMaxVotedOptionIds(event.poll.vote_counts_by_option);
|
|
242
277
|
}
|
|
243
278
|
} else if (isVoteAnswer(event.poll_vote)) {
|
|
244
279
|
latestAnswers = [event.poll_vote, ...latestAnswers];
|
|
245
|
-
} else {
|
|
246
|
-
maxVotedOptionIds = getMaxVotedOptionIds(event.poll.vote_counts_by_option);
|
|
247
280
|
}
|
|
248
281
|
|
|
249
|
-
|
|
250
|
-
this.state.partialNext({
|
|
251
|
-
...pollEnrichData,
|
|
282
|
+
this.updateFromVoteEvent(event, ownVotesByOptionId, {
|
|
252
283
|
latest_answers: latestAnswers,
|
|
253
|
-
lastActivityAt: new Date(event.created_at),
|
|
254
284
|
ownAnswer,
|
|
255
|
-
ownVotesByOptionId,
|
|
256
|
-
maxVotedOptionIds,
|
|
257
285
|
});
|
|
258
|
-
this.upsertOfflineDb();
|
|
259
286
|
};
|
|
260
287
|
|
|
261
288
|
public handleVoteRemoved = (event: Event) => {
|
|
@@ -265,31 +292,21 @@ export class Poll {
|
|
|
265
292
|
const isOwnVote = event.poll_vote.user_id === this.client.userID;
|
|
266
293
|
let latestAnswers = [...(currentState.latest_answers as PollAnswer[])];
|
|
267
294
|
let ownAnswer = currentState.ownAnswer;
|
|
268
|
-
const ownVotesByOptionId = { ...
|
|
269
|
-
let maxVotedOptionIds = currentState.maxVotedOptionIds;
|
|
295
|
+
const ownVotesByOptionId = { ...this.optimisticVotes.serverOwnVotes };
|
|
270
296
|
|
|
271
297
|
if (isVoteAnswer(event.poll_vote)) {
|
|
272
298
|
latestAnswers = latestAnswers.filter((answer) => answer.id !== event.poll_vote.id);
|
|
273
299
|
if (isOwnVote) {
|
|
274
300
|
ownAnswer = undefined;
|
|
275
301
|
}
|
|
276
|
-
} else {
|
|
277
|
-
|
|
278
|
-
if (isOwnVote && event.poll_vote.option_id) {
|
|
279
|
-
delete ownVotesByOptionId[event.poll_vote.option_id];
|
|
280
|
-
}
|
|
302
|
+
} else if (isOwnVote && event.poll_vote.option_id) {
|
|
303
|
+
delete ownVotesByOptionId[event.poll_vote.option_id];
|
|
281
304
|
}
|
|
282
305
|
|
|
283
|
-
|
|
284
|
-
this.state.partialNext({
|
|
285
|
-
...pollEnrichData,
|
|
306
|
+
this.updateFromVoteEvent(event, ownVotesByOptionId, {
|
|
286
307
|
latest_answers: latestAnswers,
|
|
287
|
-
lastActivityAt: new Date(event.created_at),
|
|
288
308
|
ownAnswer,
|
|
289
|
-
ownVotesByOptionId,
|
|
290
|
-
maxVotedOptionIds,
|
|
291
309
|
});
|
|
292
|
-
this.upsertOfflineDb();
|
|
293
310
|
};
|
|
294
311
|
|
|
295
312
|
query = async (id: string) => {
|
|
@@ -304,7 +321,26 @@ export class Poll {
|
|
|
304
321
|
partialUpdate = async (partialPollObject: PartialPollUpdate) =>
|
|
305
322
|
await this.client.partialUpdatePoll(this.id as string, partialPollObject);
|
|
306
323
|
|
|
307
|
-
|
|
324
|
+
/**
|
|
325
|
+
* Closes the poll. The poll is marked as closed optimistically and the change is
|
|
326
|
+
* reverted if the request fails, unless the server confirmed the close meanwhile.
|
|
327
|
+
* Does nothing if the poll is already closed.
|
|
328
|
+
*/
|
|
329
|
+
close = async () => {
|
|
330
|
+
if (this.data.is_closed) return;
|
|
331
|
+
|
|
332
|
+
this.closeConfirmed = false;
|
|
333
|
+
this.state.partialNext({ is_closed: true });
|
|
334
|
+
|
|
335
|
+
try {
|
|
336
|
+
return await this.client.closePoll(this.id as string);
|
|
337
|
+
} catch (error) {
|
|
338
|
+
if (!this.closeConfirmed) {
|
|
339
|
+
this.state.partialNext({ is_closed: false });
|
|
340
|
+
}
|
|
341
|
+
throw error;
|
|
342
|
+
}
|
|
343
|
+
};
|
|
308
344
|
|
|
309
345
|
delete = async () => await this.client.deletePoll(this.id as string);
|
|
310
346
|
|
|
@@ -317,6 +353,11 @@ export class Poll {
|
|
|
317
353
|
deleteOption = async (optionId: string) =>
|
|
318
354
|
await this.client.deletePollOption(this.id as string, optionId);
|
|
319
355
|
|
|
356
|
+
/**
|
|
357
|
+
* Casts a vote for an option. The vote is shown right away through a local placeholder vote,
|
|
358
|
+
* which the server's vote replaces once the WS events of all pending vote changes arrived.
|
|
359
|
+
* If the request fails, the change is reverted.
|
|
360
|
+
*/
|
|
320
361
|
castVote = async (optionId: string, messageId: string) => {
|
|
321
362
|
const { max_votes_allowed, ownVotesByOptionId } = this.data;
|
|
322
363
|
|
|
@@ -336,13 +377,17 @@ export class Poll {
|
|
|
336
377
|
});
|
|
337
378
|
return;
|
|
338
379
|
}
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
});
|
|
380
|
+
|
|
381
|
+
return await this.optimisticVotes.castVote(optionId, messageId);
|
|
342
382
|
};
|
|
343
383
|
|
|
384
|
+
/**
|
|
385
|
+
* Removes a vote. The vote is removed right away and restored if the request fails. Vote
|
|
386
|
+
* requests are sent in order, so removing a vote whose cast is not confirmed yet uses the vote
|
|
387
|
+
* id from the cast's response; if that cast failed, there is nothing to remove.
|
|
388
|
+
*/
|
|
344
389
|
removeVote = async (voteId: string, messageId: string) =>
|
|
345
|
-
await this.
|
|
390
|
+
await this.optimisticVotes.removeVote(voteId, messageId);
|
|
346
391
|
|
|
347
392
|
addAnswer = async (answerText: string, messageId: string) =>
|
|
348
393
|
await this.client.addPollAnswer(messageId, this.id as string, answerText);
|
|
@@ -367,20 +412,6 @@ export class Poll {
|
|
|
367
412
|
);
|
|
368
413
|
}
|
|
369
414
|
|
|
370
|
-
function getMaxVotedOptionIds(voteCountsByOption: PollResponse['vote_counts_by_option']) {
|
|
371
|
-
let maxVotes = 0;
|
|
372
|
-
let winningOptions: string[] = [];
|
|
373
|
-
for (const [id, count] of Object.entries(voteCountsByOption ?? {})) {
|
|
374
|
-
if (count > maxVotes) {
|
|
375
|
-
winningOptions = [id];
|
|
376
|
-
maxVotes = count;
|
|
377
|
-
} else if (count === maxVotes) {
|
|
378
|
-
winningOptions.push(id);
|
|
379
|
-
}
|
|
380
|
-
}
|
|
381
|
-
return winningOptions;
|
|
382
|
-
}
|
|
383
|
-
|
|
384
415
|
function getOwnVotesByOptionId(ownVotes: PollVote[]) {
|
|
385
416
|
return !ownVotes
|
|
386
417
|
? ({} as Record<OptionId, PollVote>)
|
|
@@ -406,7 +437,10 @@ export function extractPollData(pollResponse: PollResponse): PollData {
|
|
|
406
437
|
};
|
|
407
438
|
}
|
|
408
439
|
|
|
409
|
-
export function mapPollStateToResponse(
|
|
440
|
+
export function mapPollStateToResponse(
|
|
441
|
+
poll: Poll,
|
|
442
|
+
state: PollState = poll.data,
|
|
443
|
+
): PollResponse {
|
|
410
444
|
const {
|
|
411
445
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
412
446
|
lastActivityAt,
|
|
@@ -415,7 +449,7 @@ export function mapPollStateToResponse(poll: Poll): PollResponse {
|
|
|
415
449
|
ownVotesByOptionId,
|
|
416
450
|
ownAnswer,
|
|
417
451
|
...restState
|
|
418
|
-
} =
|
|
452
|
+
} = state;
|
|
419
453
|
const ownVotes = [
|
|
420
454
|
...Object.values(ownVotesByOptionId),
|
|
421
455
|
...(ownAnswer ? [ownAnswer] : []),
|
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
import type { StreamChat } from './client';
|
|
2
|
+
import type { Poll, PollState } from './poll';
|
|
3
|
+
import type { PollResponse, PollVote } from './types';
|
|
4
|
+
import { generateUUIDv4 } from './utils';
|
|
5
|
+
import { hasPending, withoutConcurrency } from './utils/concurrency';
|
|
6
|
+
|
|
7
|
+
type OptionId = string;
|
|
8
|
+
|
|
9
|
+
// The vote fields of the poll state that optimistic updates change
|
|
10
|
+
type VoteState = Pick<
|
|
11
|
+
PollState,
|
|
12
|
+
'latest_votes_by_option' | 'ownVotesByOptionId' | 'vote_count' | 'vote_counts_by_option'
|
|
13
|
+
>;
|
|
14
|
+
|
|
15
|
+
// An own vote change is the server vote of a cast, or the option of a removal
|
|
16
|
+
type OwnVoteChange = { optionId: OptionId; vote?: PollVote };
|
|
17
|
+
|
|
18
|
+
// How long to wait for missing WS events of own vote changes after the last request finished
|
|
19
|
+
const CATCH_UP_TIMEOUT_MS = 3000;
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Optimistic updates for the current user's votes on a poll. Vote changes are shown right away.
|
|
23
|
+
* While any of them is not confirmed by its WS event, vote events are only stored, as the server
|
|
24
|
+
* state they carry does not contain the pending changes yet. Once all are confirmed (a failed
|
|
25
|
+
* request counts as confirmed), the server's vote state is shown, which also reverts failed changes.
|
|
26
|
+
* Vote requests are sent one after another, so the server applies them in the order they were made.
|
|
27
|
+
* A lost WS event is recovered from after CATCH_UP_TIMEOUT_MS (see applySucceededChanges).
|
|
28
|
+
*/
|
|
29
|
+
export class OptimisticPollVotes {
|
|
30
|
+
// The server's vote state. WS events only carry the vote that changed, so own votes are kept here.
|
|
31
|
+
private serverVoteState: VoteState;
|
|
32
|
+
// Own vote changes not confirmed by a WS event yet
|
|
33
|
+
private pendingCount = 0;
|
|
34
|
+
// Own vote changes whose requests succeeded since the server's vote state was last shown
|
|
35
|
+
private succeededChanges: OwnVoteChange[] = [];
|
|
36
|
+
// Vote requests with this tag are sent one after another. A symbol, so it is unique per instance.
|
|
37
|
+
private readonly requestTag = Symbol('poll-votes');
|
|
38
|
+
private catchUpTimeout?: ReturnType<typeof setTimeout>;
|
|
39
|
+
|
|
40
|
+
private readonly client: StreamChat;
|
|
41
|
+
private readonly poll: Poll;
|
|
42
|
+
|
|
43
|
+
constructor({ client, poll }: { client: StreamChat; poll: Poll }) {
|
|
44
|
+
this.client = client;
|
|
45
|
+
this.poll = poll;
|
|
46
|
+
this.serverVoteState = pickVoteState(poll.data);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
get serverOwnVotes() {
|
|
50
|
+
return this.serverVoteState.ownVotesByOptionId;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
withServerVotes = (pollState: PollState): PollState => ({
|
|
54
|
+
...pollState,
|
|
55
|
+
...this.serverVoteState,
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Casts a vote for an option, shown right away through a placeholder vote. In polls with unique
|
|
60
|
+
* votes, it replaces the existing own votes.
|
|
61
|
+
*/
|
|
62
|
+
castVote = (optionId: OptionId, messageId: string) => {
|
|
63
|
+
const sendRequest = () =>
|
|
64
|
+
this.client.castPollVote(messageId, this.poll.id, { option_id: optionId });
|
|
65
|
+
const state = this.poll.data;
|
|
66
|
+
// already voted for this option, there is nothing to show
|
|
67
|
+
if (state.ownVotesByOptionId[optionId]) return this.send(sendRequest);
|
|
68
|
+
|
|
69
|
+
const replacedVotes = state.enforce_unique_vote
|
|
70
|
+
? Object.values(state.ownVotesByOptionId)
|
|
71
|
+
: [];
|
|
72
|
+
this.poll.state.partialNext(
|
|
73
|
+
applyOwnVoteDelta(state, {
|
|
74
|
+
add: [this.createPlaceholderVote(optionId)],
|
|
75
|
+
remove: replacedVotes,
|
|
76
|
+
}),
|
|
77
|
+
);
|
|
78
|
+
return this.track(sendRequest, (response) => ({
|
|
79
|
+
optionId,
|
|
80
|
+
vote: response.vote as PollVote,
|
|
81
|
+
}));
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
// Removes a vote, right away.
|
|
85
|
+
removeVote = (voteId: string, messageId: string) => {
|
|
86
|
+
const sendRequest = (id: string) =>
|
|
87
|
+
this.client.removePollVote(messageId, this.poll.id, id);
|
|
88
|
+
const state = this.poll.data;
|
|
89
|
+
const vote = Object.values(state.ownVotesByOptionId).find(({ id }) => id === voteId);
|
|
90
|
+
// not a shown own vote, there is nothing to show
|
|
91
|
+
if (!vote?.option_id) return this.send(() => sendRequest(voteId));
|
|
92
|
+
|
|
93
|
+
const optionId = vote.option_id;
|
|
94
|
+
this.poll.state.partialNext(applyOwnVoteDelta(state, { remove: [vote] }));
|
|
95
|
+
return this.track(
|
|
96
|
+
// runs when the removal's turn comes, so a preceding cast of the vote has finished
|
|
97
|
+
() => {
|
|
98
|
+
const serverVoteId = this.getServerVoteId(vote);
|
|
99
|
+
// the vote's cast failed, so there is nothing to remove
|
|
100
|
+
return serverVoteId ? sendRequest(serverVoteId) : Promise.resolve(undefined);
|
|
101
|
+
},
|
|
102
|
+
() => ({ optionId }),
|
|
103
|
+
);
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
// Sends a vote request once the previous one has finished, whether it succeeded or not.
|
|
107
|
+
private send = async <T>(sendRequest: () => Promise<T>): Promise<T> => {
|
|
108
|
+
try {
|
|
109
|
+
return (await withoutConcurrency(this.requestTag, sendRequest)) as T;
|
|
110
|
+
} finally {
|
|
111
|
+
// once nothing is left to send, wait for the WS events of the pending changes
|
|
112
|
+
if (!hasPending(this.requestTag)) this.scheduleCatchUp();
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
// Stores the vote state of a WS vote event and returns the vote fields to show, if any.
|
|
117
|
+
handleVoteEvent = (
|
|
118
|
+
poll: PollResponse,
|
|
119
|
+
{
|
|
120
|
+
confirmsOwnVote,
|
|
121
|
+
ownVotesByOptionId,
|
|
122
|
+
}: { confirmsOwnVote: boolean; ownVotesByOptionId: Record<OptionId, PollVote> },
|
|
123
|
+
): Partial<PollState> => {
|
|
124
|
+
this.serverVoteState = {
|
|
125
|
+
latest_votes_by_option: poll.latest_votes_by_option,
|
|
126
|
+
ownVotesByOptionId,
|
|
127
|
+
vote_count: poll.vote_count,
|
|
128
|
+
vote_counts_by_option: poll.vote_counts_by_option,
|
|
129
|
+
};
|
|
130
|
+
if (confirmsOwnVote) this.pendingCount = Math.max(this.pendingCount - 1, 0);
|
|
131
|
+
return this.pendingCount > 0 ? {} : this.takeServerVoteState();
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
// Fresh server state (e.g. a refetch) replaces everything, pending changes are dropped.
|
|
135
|
+
reset = (pollState: PollState) => {
|
|
136
|
+
this.serverVoteState = pickVoteState(pollState);
|
|
137
|
+
this.pendingCount = 0;
|
|
138
|
+
this.succeededChanges = [];
|
|
139
|
+
clearTimeout(this.catchUpTimeout);
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
// Tracks an own vote change until its request settles. `sendRequest` resolves to undefined
|
|
143
|
+
// when no request was needed.
|
|
144
|
+
private track = async <T>(
|
|
145
|
+
sendRequest: () => Promise<T | undefined>,
|
|
146
|
+
toChange: (response: T) => OwnVoteChange,
|
|
147
|
+
) => {
|
|
148
|
+
this.pendingCount += 1;
|
|
149
|
+
clearTimeout(this.catchUpTimeout);
|
|
150
|
+
|
|
151
|
+
let response: T | undefined;
|
|
152
|
+
try {
|
|
153
|
+
response = await this.send(async () => {
|
|
154
|
+
const result = await sendRequest();
|
|
155
|
+
// recorded before the next request is sent, as a removal looks up the vote id in here
|
|
156
|
+
if (result !== undefined) this.succeededChanges.push(toChange(result));
|
|
157
|
+
return result;
|
|
158
|
+
});
|
|
159
|
+
} catch (error) {
|
|
160
|
+
this.settleWithoutEvent();
|
|
161
|
+
throw error;
|
|
162
|
+
}
|
|
163
|
+
if (response === undefined) this.settleWithoutEvent();
|
|
164
|
+
return response;
|
|
165
|
+
};
|
|
166
|
+
|
|
167
|
+
// A failed or skipped request gets no WS event, so it counts as confirmed right away.
|
|
168
|
+
private settleWithoutEvent = () => {
|
|
169
|
+
this.pendingCount = Math.max(this.pendingCount - 1, 0);
|
|
170
|
+
if (this.pendingCount === 0) this.poll.state.partialNext(this.takeServerVoteState());
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
// The vote shown for a cast until the server's vote arrives
|
|
174
|
+
private createPlaceholderVote = (optionId: OptionId): PollVote => {
|
|
175
|
+
const now = new Date().toISOString();
|
|
176
|
+
return {
|
|
177
|
+
created_at: now,
|
|
178
|
+
id: `local-${generateUUIDv4()}`,
|
|
179
|
+
option_id: optionId,
|
|
180
|
+
poll_id: this.poll.id,
|
|
181
|
+
updated_at: now,
|
|
182
|
+
user: this.client.user,
|
|
183
|
+
user_id: this.client.userID,
|
|
184
|
+
};
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* The server id of a vote to remove, once everything sent before the removal has finished. Casts
|
|
189
|
+
* and removals of an option alternate, so the option's last succeeded change tells: a cast is the
|
|
190
|
+
* vote being removed (e.g. a placeholder), a removal means the cast in between failed. Without
|
|
191
|
+
* one, the server's own vote of the option is the vote being removed.
|
|
192
|
+
*/
|
|
193
|
+
private getServerVoteId = (vote: PollVote) => {
|
|
194
|
+
for (let i = this.succeededChanges.length - 1; i >= 0; i--) {
|
|
195
|
+
const change = this.succeededChanges[i];
|
|
196
|
+
if (change.optionId === vote.option_id) return change.vote?.id;
|
|
197
|
+
}
|
|
198
|
+
return this.serverVoteState.ownVotesByOptionId[vote.option_id as OptionId]?.id;
|
|
199
|
+
};
|
|
200
|
+
|
|
201
|
+
private takeServerVoteState = () => {
|
|
202
|
+
clearTimeout(this.catchUpTimeout);
|
|
203
|
+
this.succeededChanges = [];
|
|
204
|
+
return {
|
|
205
|
+
...this.serverVoteState,
|
|
206
|
+
maxVotedOptionIds: getMaxVotedOptionIds(this.serverVoteState.vote_counts_by_option),
|
|
207
|
+
};
|
|
208
|
+
};
|
|
209
|
+
|
|
210
|
+
private scheduleCatchUp = () => {
|
|
211
|
+
clearTimeout(this.catchUpTimeout);
|
|
212
|
+
if (this.pendingCount === 0) return;
|
|
213
|
+
this.catchUpTimeout = setTimeout(this.applySucceededChanges, CATCH_UP_TIMEOUT_MS);
|
|
214
|
+
};
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* A WS event of an own vote change got lost, so the server's own votes are stale. All requests
|
|
218
|
+
* have finished (the timeout starts once nothing is left to send and a new request cancels it),
|
|
219
|
+
* so applying the succeeded changes in order gives the server's own votes (changes whose events
|
|
220
|
+
* did arrive end up the same). They are shown with the vote counts of the last WS event, which
|
|
221
|
+
* contain the other users' votes too.
|
|
222
|
+
*/
|
|
223
|
+
private applySucceededChanges = () => {
|
|
224
|
+
const { enforce_unique_vote } = this.poll.data;
|
|
225
|
+
let ownVotesByOptionId = { ...this.serverVoteState.ownVotesByOptionId };
|
|
226
|
+
for (const { optionId, vote } of this.succeededChanges) {
|
|
227
|
+
if (!vote) {
|
|
228
|
+
delete ownVotesByOptionId[optionId];
|
|
229
|
+
} else if (enforce_unique_vote) {
|
|
230
|
+
ownVotesByOptionId = { [optionId]: vote };
|
|
231
|
+
} else {
|
|
232
|
+
ownVotesByOptionId[optionId] = vote;
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
this.serverVoteState = { ...this.serverVoteState, ownVotesByOptionId };
|
|
237
|
+
this.pendingCount = 0;
|
|
238
|
+
// also drops a failed vote that was still shown
|
|
239
|
+
this.poll.state.partialNext(this.takeServerVoteState());
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function pickVoteState(state: PollState): VoteState {
|
|
244
|
+
return {
|
|
245
|
+
latest_votes_by_option: state.latest_votes_by_option,
|
|
246
|
+
ownVotesByOptionId: state.ownVotesByOptionId,
|
|
247
|
+
vote_count: state.vote_count,
|
|
248
|
+
vote_counts_by_option: state.vote_counts_by_option,
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Adds and removes the current user's votes: own votes, vote counts, latest votes and the
|
|
254
|
+
* max-voted options. Returns new objects so that state selectors pick up the change.
|
|
255
|
+
*/
|
|
256
|
+
function applyOwnVoteDelta(
|
|
257
|
+
state: PollState,
|
|
258
|
+
{ add = [], remove = [] }: { add?: PollVote[]; remove?: PollVote[] },
|
|
259
|
+
): VoteState & Pick<PollState, 'maxVotedOptionIds'> {
|
|
260
|
+
const ownVotesByOptionId = { ...state.ownVotesByOptionId };
|
|
261
|
+
const voteCountsByOption = { ...state.vote_counts_by_option };
|
|
262
|
+
// null for anonymous polls, in which case there is nothing to update
|
|
263
|
+
const latestVotesByOption = state.latest_votes_by_option
|
|
264
|
+
? { ...state.latest_votes_by_option }
|
|
265
|
+
: state.latest_votes_by_option;
|
|
266
|
+
let voteCount = state.vote_count ?? 0;
|
|
267
|
+
|
|
268
|
+
for (const vote of remove) {
|
|
269
|
+
const optionId = vote.option_id;
|
|
270
|
+
if (!optionId) continue;
|
|
271
|
+
delete ownVotesByOptionId[optionId];
|
|
272
|
+
// the server omits options without votes, so a count that drops to 0 is removed
|
|
273
|
+
const optionVoteCount = (voteCountsByOption[optionId] ?? 0) - 1;
|
|
274
|
+
if (optionVoteCount > 0) {
|
|
275
|
+
voteCountsByOption[optionId] = optionVoteCount;
|
|
276
|
+
} else {
|
|
277
|
+
delete voteCountsByOption[optionId];
|
|
278
|
+
}
|
|
279
|
+
voteCount = Math.max(voteCount - 1, 0);
|
|
280
|
+
if (latestVotesByOption?.[optionId]) {
|
|
281
|
+
latestVotesByOption[optionId] = latestVotesByOption[optionId].filter(
|
|
282
|
+
(latestVote) => latestVote.id !== vote.id,
|
|
283
|
+
);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
for (const vote of add) {
|
|
288
|
+
const optionId = vote.option_id;
|
|
289
|
+
if (!optionId) continue;
|
|
290
|
+
ownVotesByOptionId[optionId] = vote;
|
|
291
|
+
voteCountsByOption[optionId] = (voteCountsByOption[optionId] ?? 0) + 1;
|
|
292
|
+
voteCount += 1;
|
|
293
|
+
if (latestVotesByOption && state.voting_visibility !== 'anonymous') {
|
|
294
|
+
latestVotesByOption[optionId] = [vote, ...(latestVotesByOption[optionId] ?? [])];
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
return {
|
|
299
|
+
latest_votes_by_option: latestVotesByOption,
|
|
300
|
+
maxVotedOptionIds: getMaxVotedOptionIds(voteCountsByOption),
|
|
301
|
+
ownVotesByOptionId,
|
|
302
|
+
vote_count: voteCount,
|
|
303
|
+
vote_counts_by_option: voteCountsByOption,
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
export function getMaxVotedOptionIds(
|
|
308
|
+
voteCountsByOption: PollResponse['vote_counts_by_option'],
|
|
309
|
+
) {
|
|
310
|
+
let maxVotes = 0;
|
|
311
|
+
let winningOptions: string[] = [];
|
|
312
|
+
for (const [id, count] of Object.entries(voteCountsByOption ?? {})) {
|
|
313
|
+
if (count > maxVotes) {
|
|
314
|
+
winningOptions = [id];
|
|
315
|
+
maxVotes = count;
|
|
316
|
+
} else if (count === maxVotes) {
|
|
317
|
+
winningOptions.push(id);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
return winningOptions;
|
|
321
|
+
}
|
package/src/thread.ts
CHANGED
|
@@ -7,6 +7,8 @@ import {
|
|
|
7
7
|
} from './utils';
|
|
8
8
|
import type {
|
|
9
9
|
AscDesc,
|
|
10
|
+
ChannelData,
|
|
11
|
+
ChannelResponse,
|
|
10
12
|
EventTypes,
|
|
11
13
|
LocalMessage,
|
|
12
14
|
MessagePaginationOptions,
|
|
@@ -127,10 +129,15 @@ export class Thread extends WithSubscriptions {
|
|
|
127
129
|
}) {
|
|
128
130
|
super();
|
|
129
131
|
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
}
|
|
132
|
+
// `name` is custom channel data: widening the types compiles
|
|
133
|
+
// whether or not the app augments `CustomChannelData` with it.
|
|
134
|
+
const channelResponse: ChannelResponse & { name?: string } = threadData.channel;
|
|
135
|
+
const channelData: ChannelData & { name?: string } = { name: channelResponse.name };
|
|
136
|
+
const channel = client.channel(
|
|
137
|
+
threadData.channel.type,
|
|
138
|
+
threadData.channel.id,
|
|
139
|
+
channelData,
|
|
140
|
+
);
|
|
134
141
|
channel._hydrateMembers({
|
|
135
142
|
members: threadData.channel.members ?? [],
|
|
136
143
|
overrideCurrentState: false,
|