stream-chat 9.52.1 → 9.54.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/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
- this.state.partialNext(this.getInitialStateFromPollResponse(poll));
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,6 +183,7 @@ 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
188
  this.state.partialNext({ ...pollData, lastActivityAt: new Date(event.created_at) });
152
189
  this.upsertOfflineDb();
@@ -155,6 +192,7 @@ export class Poll {
155
192
  public handlePollClosed = (event: Event) => {
156
193
  if (event.poll?.id && event.poll.id !== this.id) return;
157
194
  if (!isPollClosedEventEvent(event)) return;
195
+ this.closeConfirmed = true;
158
196
  this.state.partialNext({
159
197
  is_closed: true,
160
198
  lastActivityAt: new Date(event.created_at),
@@ -169,8 +207,7 @@ export class Poll {
169
207
  const isOwnVote = event.poll_vote.user_id === this.client.userID;
170
208
  let latestAnswers = [...(currentState.latest_answers as PollAnswer[])];
171
209
  let ownAnswer = currentState.ownAnswer;
172
- const ownVotesByOptionId = currentState.ownVotesByOptionId;
173
- let maxVotedOptionIds = currentState.maxVotedOptionIds;
210
+ const ownVotesByOptionId = { ...this.optimisticVotes.serverOwnVotes };
174
211
 
175
212
  if (isOwnVote) {
176
213
  if (isVoteAnswer(event.poll_vote)) {
@@ -182,20 +219,12 @@ export class Poll {
182
219
 
183
220
  if (isVoteAnswer(event.poll_vote)) {
184
221
  latestAnswers = [event.poll_vote, ...latestAnswers];
185
- } else {
186
- maxVotedOptionIds = getMaxVotedOptionIds(event.poll.vote_counts_by_option);
187
222
  }
188
223
 
189
- const pollEnrichData = extractPollEnrichedData(event.poll);
190
- this.state.partialNext({
191
- ...pollEnrichData,
224
+ this.updateFromVoteEvent(event, ownVotesByOptionId, {
192
225
  latest_answers: latestAnswers,
193
- lastActivityAt: new Date(event.created_at),
194
226
  ownAnswer,
195
- ownVotesByOptionId,
196
- maxVotedOptionIds,
197
227
  });
198
- this.upsertOfflineDb();
199
228
  };
200
229
 
201
230
  public handleVoteChanged = (event: Event) => {
@@ -206,8 +235,7 @@ export class Poll {
206
235
  const isOwnVote = event.poll_vote.user_id === this.client.userID;
207
236
  let latestAnswers = [...(currentState.latest_answers as PollAnswer[])];
208
237
  let ownAnswer = currentState.ownAnswer;
209
- let ownVotesByOptionId = currentState.ownVotesByOptionId;
210
- let maxVotedOptionIds = currentState.maxVotedOptionIds;
238
+ let ownVotesByOptionId = this.optimisticVotes.serverOwnVotes;
211
239
 
212
240
  if (isOwnVote) {
213
241
  if (isVoteAnswer(event.poll_vote)) {
@@ -238,24 +266,15 @@ export class Poll {
238
266
  if (ownAnswer?.id === event.poll_vote.id) {
239
267
  ownAnswer = undefined;
240
268
  }
241
- maxVotedOptionIds = getMaxVotedOptionIds(event.poll.vote_counts_by_option);
242
269
  }
243
270
  } else if (isVoteAnswer(event.poll_vote)) {
244
271
  latestAnswers = [event.poll_vote, ...latestAnswers];
245
- } else {
246
- maxVotedOptionIds = getMaxVotedOptionIds(event.poll.vote_counts_by_option);
247
272
  }
248
273
 
249
- const pollEnrichData = extractPollEnrichedData(event.poll);
250
- this.state.partialNext({
251
- ...pollEnrichData,
274
+ this.updateFromVoteEvent(event, ownVotesByOptionId, {
252
275
  latest_answers: latestAnswers,
253
- lastActivityAt: new Date(event.created_at),
254
276
  ownAnswer,
255
- ownVotesByOptionId,
256
- maxVotedOptionIds,
257
277
  });
258
- this.upsertOfflineDb();
259
278
  };
260
279
 
261
280
  public handleVoteRemoved = (event: Event) => {
@@ -265,31 +284,21 @@ export class Poll {
265
284
  const isOwnVote = event.poll_vote.user_id === this.client.userID;
266
285
  let latestAnswers = [...(currentState.latest_answers as PollAnswer[])];
267
286
  let ownAnswer = currentState.ownAnswer;
268
- const ownVotesByOptionId = { ...currentState.ownVotesByOptionId };
269
- let maxVotedOptionIds = currentState.maxVotedOptionIds;
287
+ const ownVotesByOptionId = { ...this.optimisticVotes.serverOwnVotes };
270
288
 
271
289
  if (isVoteAnswer(event.poll_vote)) {
272
290
  latestAnswers = latestAnswers.filter((answer) => answer.id !== event.poll_vote.id);
273
291
  if (isOwnVote) {
274
292
  ownAnswer = undefined;
275
293
  }
276
- } else {
277
- maxVotedOptionIds = getMaxVotedOptionIds(event.poll.vote_counts_by_option);
278
- if (isOwnVote && event.poll_vote.option_id) {
279
- delete ownVotesByOptionId[event.poll_vote.option_id];
280
- }
294
+ } else if (isOwnVote && event.poll_vote.option_id) {
295
+ delete ownVotesByOptionId[event.poll_vote.option_id];
281
296
  }
282
297
 
283
- const pollEnrichData = extractPollEnrichedData(event.poll);
284
- this.state.partialNext({
285
- ...pollEnrichData,
298
+ this.updateFromVoteEvent(event, ownVotesByOptionId, {
286
299
  latest_answers: latestAnswers,
287
- lastActivityAt: new Date(event.created_at),
288
300
  ownAnswer,
289
- ownVotesByOptionId,
290
- maxVotedOptionIds,
291
301
  });
292
- this.upsertOfflineDb();
293
302
  };
294
303
 
295
304
  query = async (id: string) => {
@@ -304,7 +313,26 @@ export class Poll {
304
313
  partialUpdate = async (partialPollObject: PartialPollUpdate) =>
305
314
  await this.client.partialUpdatePoll(this.id as string, partialPollObject);
306
315
 
307
- close = async () => await this.client.closePoll(this.id as string);
316
+ /**
317
+ * Closes the poll. The poll is marked as closed optimistically and the change is
318
+ * reverted if the request fails, unless the server confirmed the close meanwhile.
319
+ * Does nothing if the poll is already closed.
320
+ */
321
+ close = async () => {
322
+ if (this.data.is_closed) return;
323
+
324
+ this.closeConfirmed = false;
325
+ this.state.partialNext({ is_closed: true });
326
+
327
+ try {
328
+ return await this.client.closePoll(this.id as string);
329
+ } catch (error) {
330
+ if (!this.closeConfirmed) {
331
+ this.state.partialNext({ is_closed: false });
332
+ }
333
+ throw error;
334
+ }
335
+ };
308
336
 
309
337
  delete = async () => await this.client.deletePoll(this.id as string);
310
338
 
@@ -317,6 +345,11 @@ export class Poll {
317
345
  deleteOption = async (optionId: string) =>
318
346
  await this.client.deletePollOption(this.id as string, optionId);
319
347
 
348
+ /**
349
+ * Casts a vote for an option. The vote is shown right away through a local placeholder vote,
350
+ * which the server's vote replaces once the WS events of all pending vote changes arrived.
351
+ * If the request fails, the change is reverted.
352
+ */
320
353
  castVote = async (optionId: string, messageId: string) => {
321
354
  const { max_votes_allowed, ownVotesByOptionId } = this.data;
322
355
 
@@ -336,13 +369,17 @@ export class Poll {
336
369
  });
337
370
  return;
338
371
  }
339
- return await this.client.castPollVote(messageId, this.id as string, {
340
- option_id: optionId,
341
- });
372
+
373
+ return await this.optimisticVotes.castVote(optionId, messageId);
342
374
  };
343
375
 
376
+ /**
377
+ * Removes a vote. The vote is removed right away and restored if the request fails. Vote
378
+ * requests are sent in order, so removing a vote whose cast is not confirmed yet uses the vote
379
+ * id from the cast's response; if that cast failed, there is nothing to remove.
380
+ */
344
381
  removeVote = async (voteId: string, messageId: string) =>
345
- await this.client.removePollVote(messageId, this.id as string, voteId);
382
+ await this.optimisticVotes.removeVote(voteId, messageId);
346
383
 
347
384
  addAnswer = async (answerText: string, messageId: string) =>
348
385
  await this.client.addPollAnswer(messageId, this.id as string, answerText);
@@ -367,20 +404,6 @@ export class Poll {
367
404
  );
368
405
  }
369
406
 
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
407
  function getOwnVotesByOptionId(ownVotes: PollVote[]) {
385
408
  return !ownVotes
386
409
  ? ({} as Record<OptionId, PollVote>)
@@ -406,7 +429,10 @@ export function extractPollData(pollResponse: PollResponse): PollData {
406
429
  };
407
430
  }
408
431
 
409
- export function mapPollStateToResponse(poll: Poll): PollResponse {
432
+ export function mapPollStateToResponse(
433
+ poll: Poll,
434
+ state: PollState = poll.data,
435
+ ): PollResponse {
410
436
  const {
411
437
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
412
438
  lastActivityAt,
@@ -415,7 +441,7 @@ export function mapPollStateToResponse(poll: Poll): PollResponse {
415
441
  ownVotesByOptionId,
416
442
  ownAnswer,
417
443
  ...restState
418
- } = poll.data;
444
+ } = state;
419
445
  const ownVotes = [
420
446
  ...Object.values(ownVotesByOptionId),
421
447
  ...(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
+ }