stream-chat 10.2.0 → 10.3.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.
Files changed (108) hide show
  1. package/dist/cjs/index.browser.js +4712 -2818
  2. package/dist/cjs/index.browser.js.map +4 -4
  3. package/dist/cjs/index.node.js +4733 -2818
  4. package/dist/cjs/index.node.js.map +4 -4
  5. package/dist/esm/index.mjs +4712 -2818
  6. package/dist/esm/index.mjs.map +4 -4
  7. package/dist/types/channel.d.ts +62 -3
  8. package/dist/types/client.d.ts +9 -1
  9. package/dist/types/configuration/types.d.ts +2 -0
  10. package/dist/types/connection/ConnectionRecoveryManager.d.ts +1 -0
  11. package/dist/types/gen/chat/ChatApi.d.ts +12 -1
  12. package/dist/types/gen/models/index.d.ts +659 -11
  13. package/dist/types/gen/moderation/ModerationApi.d.ts +3 -1
  14. package/dist/types/index.d.ts +2 -0
  15. package/dist/types/messageComposer/attachmentManager.d.ts +2 -0
  16. package/dist/types/messageComposer/index.d.ts +1 -0
  17. package/dist/types/messageComposer/linkPreviewsManager.d.ts +1 -0
  18. package/dist/types/messageComposer/messageComposer.d.ts +33 -7
  19. package/dist/types/messageComposer/middleware/messageComposer/compositionValidation.d.ts +1 -2
  20. package/dist/types/messageComposer/middleware/messageComposer/index.d.ts +1 -0
  21. package/dist/types/messageComposer/middleware/messageComposer/scheduledMessage.d.ts +4 -0
  22. package/dist/types/messageComposer/middleware/textComposer/commandUtils.d.ts +1 -0
  23. package/dist/types/messageComposer/scheduledMessageComposition.d.ts +32 -0
  24. package/dist/types/messageMarks/MessageMarkManager.d.ts +44 -0
  25. package/dist/types/messageMarks/index.d.ts +1 -0
  26. package/dist/types/messageOperations/MessageOperations.d.ts +12 -1
  27. package/dist/types/messageOperations/index.d.ts +1 -0
  28. package/dist/types/messageOperations/reflectMessageMarkEvent.d.ts +9 -0
  29. package/dist/types/messageOperations/sendOrdering.d.ts +4 -3
  30. package/dist/types/messageOperations/types.d.ts +6 -2
  31. package/dist/types/notifications/types.d.ts +4 -0
  32. package/dist/types/offline-support/offline_support_api.d.ts +19 -1
  33. package/dist/types/offline-support/types.d.ts +19 -1
  34. package/dist/types/pagination/PaginatorView.d.ts +55 -0
  35. package/dist/types/pagination/index.d.ts +1 -0
  36. package/dist/types/pagination/paginators/BasePaginator.d.ts +41 -0
  37. package/dist/types/pagination/paginators/ChannelPaginator.d.ts +0 -9
  38. package/dist/types/pagination/paginators/MessageMarkPaginator.d.ts +61 -0
  39. package/dist/types/pagination/paginators/ScheduledMessagePaginator.d.ts +83 -0
  40. package/dist/types/pagination/paginators/index.d.ts +2 -0
  41. package/dist/types/scheduledMessages/ScheduledMessagePaginatorsManager.d.ts +47 -0
  42. package/dist/types/scheduledMessages/ScheduledMessageStatePolicy.d.ts +12 -0
  43. package/dist/types/scheduledMessages/ScheduledMessagesView.d.ts +38 -0
  44. package/dist/types/scheduledMessages/composition.d.ts +5 -0
  45. package/dist/types/scheduledMessages/constants.d.ts +56 -0
  46. package/dist/types/scheduledMessages/editResolvers.d.ts +4 -0
  47. package/dist/types/scheduledMessages/errors.d.ts +3 -0
  48. package/dist/types/scheduledMessages/eventHandlers.d.ts +8 -0
  49. package/dist/types/scheduledMessages/index.d.ts +7 -0
  50. package/dist/types/scheduledMessages/limits.d.ts +6 -0
  51. package/dist/types/scheduledMessages/types.d.ts +65 -0
  52. package/dist/types/thread.d.ts +12 -1
  53. package/dist/types/utils.d.ts +7 -0
  54. package/package.json +1 -1
  55. package/src/channel.ts +231 -7
  56. package/src/client.ts +46 -2
  57. package/src/configuration/keys.ts +2 -0
  58. package/src/configuration/shape.ts +15 -0
  59. package/src/configuration/types.ts +3 -1
  60. package/src/connection/ConnectionRecoveryManager.ts +7 -0
  61. package/src/errors.ts +11 -0
  62. package/src/gen/chat/ChatApi.ts +60 -3
  63. package/src/gen/models/index.ts +794 -23
  64. package/src/gen/moderation/ModerationApi.ts +24 -3
  65. package/src/index.ts +2 -0
  66. package/src/messageComposer/attachmentManager.ts +43 -24
  67. package/src/messageComposer/index.ts +1 -0
  68. package/src/messageComposer/messageComposer.ts +140 -32
  69. package/src/messageComposer/middleware/messageComposer/MessageComposerMiddlewareExecutor.ts +2 -0
  70. package/src/messageComposer/middleware/messageComposer/compositionValidation.ts +40 -47
  71. package/src/messageComposer/middleware/messageComposer/index.ts +1 -0
  72. package/src/messageComposer/middleware/messageComposer/scheduledMessage.ts +38 -0
  73. package/src/messageComposer/middleware/textComposer/commandUtils.ts +8 -0
  74. package/src/messageComposer/scheduledMessageComposition.ts +324 -0
  75. package/src/messageMarks/MessageMarkManager.ts +145 -0
  76. package/src/messageMarks/index.ts +1 -0
  77. package/src/messageOperations/MessageOperationStatePolicy.ts +7 -0
  78. package/src/messageOperations/MessageOperations.ts +154 -1
  79. package/src/messageOperations/index.ts +1 -0
  80. package/src/messageOperations/reflectMessageMarkEvent.ts +47 -0
  81. package/src/messageOperations/reflectReactionEvent.ts +3 -0
  82. package/src/messageOperations/sendOrdering.ts +11 -4
  83. package/src/messageOperations/types.ts +6 -2
  84. package/src/notifications/types.ts +4 -0
  85. package/src/offline-support/offline_support_api.ts +61 -1
  86. package/src/offline-support/queueableOperations.ts +6 -0
  87. package/src/offline-support/types.ts +28 -0
  88. package/src/pagination/PaginatorView.ts +103 -0
  89. package/src/pagination/index.ts +1 -0
  90. package/src/pagination/paginators/BasePaginator.ts +179 -27
  91. package/src/pagination/paginators/ChannelPaginator.ts +8 -28
  92. package/src/pagination/paginators/MessageIntervalPaginator.ts +4 -1
  93. package/src/pagination/paginators/MessageMarkPaginator.ts +222 -0
  94. package/src/pagination/paginators/ScheduledMessagePaginator.ts +352 -0
  95. package/src/pagination/paginators/index.ts +2 -0
  96. package/src/scheduledMessages/ScheduledMessagePaginatorsManager.ts +268 -0
  97. package/src/scheduledMessages/ScheduledMessageStatePolicy.ts +42 -0
  98. package/src/scheduledMessages/ScheduledMessagesView.ts +57 -0
  99. package/src/scheduledMessages/composition.ts +129 -0
  100. package/src/scheduledMessages/constants.ts +79 -0
  101. package/src/scheduledMessages/editResolvers.ts +51 -0
  102. package/src/scheduledMessages/errors.ts +45 -0
  103. package/src/scheduledMessages/eventHandlers.ts +58 -0
  104. package/src/scheduledMessages/index.ts +7 -0
  105. package/src/scheduledMessages/limits.ts +32 -0
  106. package/src/scheduledMessages/types.ts +124 -0
  107. package/src/thread.ts +41 -17
  108. package/src/utils.ts +18 -0
@@ -4,6 +4,7 @@ import type {
4
4
  MessageResponse,
5
5
  ReactionRequest,
6
6
  SendReactionRequest,
7
+ StreamResponse,
7
8
  UpdateMessageOptions,
8
9
  } from '../types';
9
10
  import { applyReactionLocally } from './applyReactionLocally';
@@ -11,10 +12,21 @@ import { FailedSendCache } from './FailedSendCache';
11
12
  import { deepFreezeConfig } from '../configuration/utils/deepFreezeConfig';
12
13
  import type { StateStore } from '@stream-io/state-store';
13
14
  import { ConfigController } from '../configuration/ConfigController';
14
- import { formatMessage, localMessageToNewMessagePayload } from '../utils';
15
+ import {
16
+ formatMessage,
17
+ localMessageToNewMessagePayload,
18
+ sanitizeOutgoingAttachments,
19
+ } from '../utils';
15
20
  import { dateToNs } from '../utils/time';
16
21
  import { MessageOperationStatePolicy } from './MessageOperationStatePolicy';
22
+ import { ScheduledMessageStatePolicy } from '../scheduledMessages/ScheduledMessageStatePolicy';
23
+ import type { ScheduledMessageOperationKind } from '../scheduledMessages/ScheduledMessageStatePolicy';
17
24
  import type { QueueableType } from '../offline-support';
25
+ import type {
26
+ ScheduledMessageResponse,
27
+ SendMessageRequest,
28
+ SendMessageResponse,
29
+ } from '../gen/models';
18
30
  import type {
19
31
  DefaultOperationRequest,
20
32
  MessageOperationsContext,
@@ -22,6 +34,13 @@ import type {
22
34
  OperationParams,
23
35
  OperationRequestFn,
24
36
  } from './types';
37
+ import type {
38
+ DefaultScheduledMessageRequest,
39
+ ScheduledMessageRequestFn,
40
+ ScheduledMessageRequestHandlers,
41
+ ScheduleMessageParams,
42
+ UpdateScheduledMessageParams,
43
+ } from '../scheduledMessages/types';
25
44
 
26
45
  export type MessageOperationsConfig = {
27
46
  /** Most failed sends kept for retry; the oldest is evicted past this (defaults to 100). */
@@ -65,6 +84,7 @@ const isFailedEdit = (localMessage: LocalMessage) =>
65
84
  export class MessageOperations {
66
85
  private ctx: MessageOperationsContext;
67
86
  private policy: MessageOperationStatePolicy;
87
+ private scheduledPolicy: ScheduledMessageStatePolicy;
68
88
  private readonly failedSendCache = new FailedSendCache(() => this.config);
69
89
  private readonly normalizeOutgoingMessage: NonNullable<
70
90
  MessageOperationsContext['normalizeOutgoingMessage']
@@ -85,6 +105,10 @@ export class MessageOperations {
85
105
  purge: ctx.purge,
86
106
  remove: ctx.remove,
87
107
  });
108
+ this.scheduledPolicy = new ScheduledMessageStatePolicy({
109
+ ingest: (scheduledMessage) => this.ingestScheduledMessage(scheduledMessage),
110
+ get: (id) => ctx.channel.getClient().scheduledMessageStore.get(id),
111
+ });
88
112
  this.normalizeOutgoingMessage = ctx.normalizeOutgoingMessage ?? ((m) => m);
89
113
  this.sequenceRequests = ctx.sequenceRequests ?? ((_kind, request) => request());
90
114
  this.configController = new ConfigController<MessageOperationsConfig>({
@@ -330,6 +354,135 @@ export class MessageOperations {
330
354
  );
331
355
  }
332
356
 
357
+ ingestScheduledMessage(scheduledMessage: ScheduledMessageResponse) {
358
+ const { channel } = this.ctx;
359
+ channel.scheduledMessagesPaginator.ingestItem(scheduledMessage);
360
+ channel.getClient().scheduledMessagePaginators.ingest(scheduledMessage);
361
+ }
362
+
363
+ private get scheduledRequestHandlers(): ScheduledMessageRequestHandlers {
364
+ return this.ctx.channel.configState.getLatestValue().requestHandlers ?? {};
365
+ }
366
+
367
+ private resolveScheduledRequest<TParams, TResponse>(
368
+ handler: ScheduledMessageRequestFn<TParams, TResponse> | undefined,
369
+ defaultRequest: DefaultScheduledMessageRequest<TParams, TResponse>,
370
+ params: TParams,
371
+ ) {
372
+ return handler ? handler(params, defaultRequest) : defaultRequest(params);
373
+ }
374
+
375
+ private async runScheduled<R extends { scheduled_message?: ScheduledMessageResponse }>(
376
+ kind: ScheduledMessageOperationKind,
377
+ id: string | undefined,
378
+ doRequest: () => Promise<R>,
379
+ ): Promise<R> {
380
+ try {
381
+ const response = await doRequest();
382
+ this.scheduledPolicy.success(kind, response.scheduled_message);
383
+ return response;
384
+ } catch (error) {
385
+ this.scheduledPolicy.failure(kind, id, error);
386
+ throw error;
387
+ }
388
+ }
389
+
390
+ async scheduleMessage({
391
+ localMessage,
392
+ message,
393
+ options,
394
+ }: ScheduleMessageParams): Promise<StreamResponse<SendMessageResponse>> {
395
+ return await this.runScheduled('schedule', undefined, () =>
396
+ this.sequenceRequests('schedule', async () => {
397
+ let outgoingMessage = message;
398
+
399
+ if (localMessage) {
400
+ const settled = await this.withSettledUploads<'schedule'>({
401
+ localMessage,
402
+ message,
403
+ });
404
+ if (settled.failureReason) throw settled.failureReason;
405
+ outgoingMessage = settled.params.message ?? message;
406
+ }
407
+
408
+ const request: SendMessageRequest = {
409
+ ...options,
410
+ message: sanitizeOutgoingAttachments(outgoingMessage),
411
+ };
412
+
413
+ return await this.resolveScheduledRequest(
414
+ this.scheduledRequestHandlers.scheduleMessageRequest,
415
+ (params) => this.ctx.channel.sendMessage(params),
416
+ request,
417
+ );
418
+ }),
419
+ );
420
+ }
421
+
422
+ async updateScheduledMessage(
423
+ id: string,
424
+ { localMessage, request }: UpdateScheduledMessageParams,
425
+ ): Promise<ScheduledMessageResponse> {
426
+ let outgoingMessage = request.message;
427
+
428
+ if (localMessage && outgoingMessage) {
429
+ const settled = await this.withSettledUploads<'schedule'>({
430
+ localMessage,
431
+ message: outgoingMessage,
432
+ });
433
+ if (settled.failureReason) throw settled.failureReason;
434
+ outgoingMessage = settled.params.message ?? outgoingMessage;
435
+ }
436
+
437
+ const sanitizedRequest = outgoingMessage
438
+ ? { ...request, message: sanitizeOutgoingAttachments(outgoingMessage) }
439
+ : request;
440
+
441
+ const { scheduled_message: scheduledMessage } = await this.runScheduled(
442
+ 'update',
443
+ id,
444
+ () =>
445
+ this.resolveScheduledRequest(
446
+ this.scheduledRequestHandlers.updateScheduledMessageRequest,
447
+ ({ id, request }) =>
448
+ this.ctx.channel.getClient().updateScheduledMessage({ id }, request),
449
+ { id, request: sanitizedRequest },
450
+ ),
451
+ );
452
+
453
+ return scheduledMessage;
454
+ }
455
+
456
+ async deleteScheduledMessage(id: string): Promise<ScheduledMessageResponse> {
457
+ const { scheduled_message: scheduledMessage } = await this.runScheduled(
458
+ 'cancel',
459
+ id,
460
+ () =>
461
+ this.resolveScheduledRequest(
462
+ this.scheduledRequestHandlers.deleteScheduledMessageRequest,
463
+ ({ id }) => this.ctx.channel.getClient().deleteScheduledMessage({ id }),
464
+ { id },
465
+ ),
466
+ );
467
+
468
+ return scheduledMessage;
469
+ }
470
+
471
+ async sendScheduledMessageNow(id: string): Promise<ScheduledMessageResponse> {
472
+ const { scheduled_message: scheduledMessage } = await this.runScheduled(
473
+ 'sendNow',
474
+ id,
475
+ () =>
476
+ this.resolveScheduledRequest(
477
+ this.scheduledRequestHandlers.sendScheduledMessageNowRequest,
478
+ ({ id }) => this.ctx.channel.getClient().sendScheduledMessageNow({ id }),
479
+ { id },
480
+ ),
481
+ );
482
+
483
+ return scheduledMessage;
484
+ }
485
+
333
486
  /**
334
487
  * Adds a reaction optimistically: it is applied to the cached message at once, then sent through the
335
488
  * offline queue. The response's counts reconcile; a definitive failure rolls it back, a request queued
@@ -3,6 +3,7 @@ export { createMessageOperations } from './createMessageOperations';
3
3
  export { MessageOperationStatePolicy } from './MessageOperationStatePolicy';
4
4
  export { applyReactionLocally } from './applyReactionLocally';
5
5
  export { reflectReactionEvent } from './reflectReactionEvent';
6
+ export { reflectMessageMarkEvent } from './reflectMessageMarkEvent';
6
7
  export type { OptimisticOutcome } from './MessageOperationStatePolicy';
7
8
  export type {
8
9
  DefaultOperationRequest,
@@ -0,0 +1,47 @@
1
+ import type { StreamChat } from '../client';
2
+ import type { MessageMarkResponse } from '../types';
3
+
4
+ /**
5
+ * Applies a `message.mark_added` event to the canonical copy of the message, by ID, as an
6
+ * idempotent set-add keyed (message_id, user_id, type). The mark joins `mark_groups` on the
7
+ * current user's own message, or `own_marks` when the current user marked another user's message.
8
+ * No-op when nothing holds the message or the client has no user.
9
+ */
10
+ export const reflectMessageMarkEvent = (
11
+ client: StreamChat,
12
+ mark: MessageMarkResponse,
13
+ ): void => {
14
+ const userId = client.userId;
15
+ if (!userId) return;
16
+
17
+ const store = client.messageStore;
18
+ const storedMessage = store.get(mark.message_id);
19
+ if (!storedMessage) return;
20
+ if (storedMessage.user?.id === userId) {
21
+ const group = storedMessage.mark_groups?.[mark.type] ?? { count: 0, latest_by: [] };
22
+ if (group.latest_by.some((marker) => marker.user_id === mark.user_id)) return;
23
+ store.upsert({
24
+ ...storedMessage,
25
+ mark_groups: {
26
+ ...storedMessage.mark_groups,
27
+ [mark.type]: {
28
+ count: group.count + 1,
29
+ latest_by: [
30
+ { created_at: mark.created_at, user_id: mark.user_id },
31
+ ...group.latest_by,
32
+ ],
33
+ },
34
+ },
35
+ });
36
+ return;
37
+ }
38
+
39
+ if (mark.user_id === userId) {
40
+ const ownMarks = storedMessage.own_marks ?? [];
41
+ if (ownMarks.some((own) => own.type === mark.type)) return;
42
+ store.upsert({
43
+ ...storedMessage,
44
+ own_marks: [...ownMarks, { created_at: mark.created_at, type: mark.type }],
45
+ });
46
+ }
47
+ };
@@ -39,5 +39,8 @@ export const reflectReactionEvent = (
39
39
  removed,
40
40
  userId: client.userId,
41
41
  }),
42
+ // Events don't carry marks; keep the local ones.
43
+ mark_groups: formatted.mark_groups ?? existing?.mark_groups,
44
+ own_marks: formatted.own_marks ?? existing?.own_marks,
42
45
  });
43
46
  };
@@ -3,10 +3,17 @@ import { withoutConcurrency } from '../utils/concurrency';
3
3
  import type { MessageComposer } from '../messageComposer/messageComposer';
4
4
  import type { OperationKind } from './types';
5
5
 
6
+ const SEND_ORDERED_KINDS: ReadonlySet<OperationKind> = new Set([
7
+ 'retry',
8
+ 'schedule',
9
+ 'send',
10
+ ]);
11
+
6
12
  /**
7
- * The {@link MessageOperationsContext.sequenceRequests} policy of `Channel` and `Thread`. Sends and
8
- * retries wait for each other while the composer may hand over still-uploading files, so a short text
9
- * sent after a photo is not dated first. Edits and deletes never wait.
13
+ * The {@link MessageOperationsContext.sequenceRequests} policy of `Channel` and `Thread`. Sends,
14
+ * retries and schedules wait for each other while the composer may hand over still-uploading files, so
15
+ * a short text sent after a photo is not dated first. Edits, deletes and the other scheduled-message
16
+ * operations never wait.
10
17
  */
11
18
  export const keepSendOrderWhilePendingUploadsAllowed = <T>({
12
19
  channelCid,
@@ -20,6 +27,6 @@ export const keepSendOrderWhilePendingUploadsAllowed = <T>({
20
27
  kind: OperationKind;
21
28
  request: () => Promise<T>;
22
29
  }): Promise<T> =>
23
- (kind === 'send' || kind === 'retry') && composer.allowsPendingUploads
30
+ SEND_ORDERED_KINDS.has(kind) && composer.allowsPendingUploads
24
31
  ? withoutConcurrency(`stream-chat/send-message/${channelCid}`, request)
25
32
  : request();
@@ -12,7 +12,7 @@ import type { QueueableType } from '../offline-support/types';
12
12
  import type { Channel } from '../channel';
13
13
  import type { StreamChat } from '../client';
14
14
 
15
- export type OperationKind = 'send' | 'retry' | 'update' | 'delete';
15
+ export type OperationKind = 'send' | 'retry' | 'update' | 'delete' | 'schedule';
16
16
 
17
17
  export type MessageOperationSpec = {
18
18
  send: {
@@ -31,12 +31,16 @@ export type MessageOperationSpec = {
31
31
  options: DeleteMessageOptions;
32
32
  requestResult: { message: MessageResponse };
33
33
  };
34
+ schedule: {
35
+ options: SendMessageOptions;
36
+ requestResult: SendMessageAPIResponse;
37
+ };
34
38
  };
35
39
 
36
40
  export type OperationParams<K extends OperationKind> = {
37
41
  localMessage: LocalMessage;
38
42
  options?: MessageOperationSpec[K]['options'];
39
- } & (K extends 'send' | 'retry' ? { message?: MessageRequest } : {});
43
+ } & (K extends 'send' | 'retry' | 'schedule' ? { message?: MessageRequest } : {});
40
44
 
41
45
  export type OperationResponse = { message: MessageResponse };
42
46
 
@@ -38,6 +38,10 @@ export const CORE_NOTIFICATION_TYPE = {
38
38
  messageUpdateFailed: 'api:message:update:failed',
39
39
  pollCastVoteLimit: 'validation:poll:castVote:limit',
40
40
  pollCreateFailed: 'api:poll:create:failed',
41
+ scheduledMessageBlocked: 'validation:scheduled-message:blocked',
42
+ scheduledMessageCompositionEnded: 'validation:scheduled-message:composition:ended',
43
+ scheduledMessageCreateFailed: 'api:scheduled-message:create:failed',
44
+ scheduledMessageUpdateFailed: 'api:scheduled-message:update:failed',
41
45
  } as const;
42
46
 
43
47
  /** A notification type emitted by `stream-chat` itself. See {@link CORE_NOTIFICATION_TYPE}. */
@@ -75,6 +75,8 @@ export abstract class AbstractOfflineDB implements OfflineDBApi {
75
75
  /** Writes the reaction, the message carrying it and the associated users. */
76
76
  abstract insertReaction: OfflineDBApi['insertReaction'];
77
77
 
78
+ abstract insertMessageMark: OfflineDBApi['insertMessageMark'];
79
+
78
80
  /** Upserts the CIDs for a filter + sort query hash (cids table only). */
79
81
  abstract upsertCidsForQuery: OfflineDBApi['upsertCidsForQuery'];
80
82
 
@@ -149,6 +151,8 @@ export abstract class AbstractOfflineDB implements OfflineDBApi {
149
151
 
150
152
  abstract getReactions: OfflineDBApi['getReactions'];
151
153
 
154
+ abstract getMessageMarks: OfflineDBApi['getMessageMarks'];
155
+
152
156
  /** Runs the queries in one transaction. */
153
157
  abstract executeSqlBatch: OfflineDBApi['executeSqlBatch'];
154
158
 
@@ -744,6 +748,41 @@ export abstract class AbstractOfflineDB implements OfflineDBApi {
744
748
  return [];
745
749
  };
746
750
 
751
+ /**
752
+ * Stores the mark, and the message's mark summaries as the message store holds them: the event
753
+ * carries only the mark, which `Channel` has applied to that copy by the time a live event reaches
754
+ * the DB. A message the store does not hold, or a thread reply, is skipped and gets its marks
755
+ * stored with its next query.
756
+ *
757
+ * @param payload.event - The WS event we are trying to process.
758
+ * @param payload.execute - Whether to immediately execute the queries. Defaults to `true`.
759
+ * @returns The prepared queries.
760
+ */
761
+ public handleMessageMarkAddedEvent = async ({
762
+ event,
763
+ execute = true,
764
+ }: {
765
+ event: EventPayload<'message.mark_added'>;
766
+ execute?: boolean;
767
+ }) => {
768
+ const message = this.client.messageStore.get(event.mark.message_id);
769
+
770
+ if (message && !message.parent_id) {
771
+ return await this.queriesWithChannelGuard(
772
+ { event, execute },
773
+ async (executeOverride) =>
774
+ await this.insertMessageMark({
775
+ execute: executeOverride,
776
+ mark: event.mark,
777
+ message,
778
+ user: event.user,
779
+ }),
780
+ );
781
+ }
782
+
783
+ return [];
784
+ };
785
+
747
786
  /**
748
787
  * Sets `hidden` from the event type, as the event's channel does not carry it.
749
788
  *
@@ -952,6 +991,10 @@ export abstract class AbstractOfflineDB implements OfflineDBApi {
952
991
  return this.handleMessageUpdatedEvent({ event, execute });
953
992
  }
954
993
 
994
+ if (type === 'message.mark_added') {
995
+ return await this.handleMessageMarkAddedEvent({ event, execute });
996
+ }
997
+
955
998
  if (type === 'message.read' || type === 'notification.mark_read') {
956
999
  // The DB stores channel reads only, so thread read events are skipped.
957
1000
  if (event.thread) return [];
@@ -1094,10 +1137,23 @@ export abstract class AbstractOfflineDB implements OfflineDBApi {
1094
1137
  });
1095
1138
  };
1096
1139
 
1140
+ /** Whether a mark of the same type is already queued for the message. */
1141
+ private isMessageMarkQueued = async (
1142
+ task: Extract<PendingTask, { type: 'send-message-mark' }>,
1143
+ ) => {
1144
+ const [{ id }, { type }] = task.payload;
1145
+ const pendingTasks = await this.getPendingTasks({ messageId: id });
1146
+
1147
+ return pendingTasks.some(
1148
+ (pending) =>
1149
+ pending.type === 'send-message-mark' && pending.payload[1]?.type === type,
1150
+ );
1151
+ };
1152
+
1097
1153
  /**
1098
1154
  * Stores the task. An edit of a never-sent message is folded into its queued send instead. With no
1099
1155
  * queued send, an edit `isMessageUpdateReplayable` refuses (attachments still on local URLs) is
1100
- * dropped.
1156
+ * dropped. A mark already queued for the message is not queued again.
1101
1157
  *
1102
1158
  * @param payload.task - The pending task to store.
1103
1159
  */
@@ -1107,6 +1163,10 @@ export abstract class AbstractOfflineDB implements OfflineDBApi {
1107
1163
  return;
1108
1164
  }
1109
1165
 
1166
+ if (task.type === 'send-message-mark' && (await this.isMessageMarkQueued(task))) {
1167
+ return;
1168
+ }
1169
+
1110
1170
  await this.addPendingTask(task);
1111
1171
  };
1112
1172
 
@@ -131,6 +131,12 @@ export const QUEUEABLE_OPERATIONS: {
131
131
  run: ({ channel, client, task }) =>
132
132
  channelOf(client, task, channel).sendMessage(...task.payload),
133
133
  },
134
+ // Nothing to settle on replay; `message.mark_added` updates the message.
135
+ 'send-message-mark': {
136
+ needsChannel: false,
137
+ logFailureAs: { message: 'Marking the message failed.', method: 'createMessageMark' },
138
+ run: ({ client, task }) => client.createMessageMark(...task.payload),
139
+ },
134
140
  'send-reaction': {
135
141
  needsChannel: false,
136
142
  logFailureAs: { message: 'Sending the reaction failed.', method: 'sendReaction' },
@@ -7,15 +7,19 @@ import type {
7
7
  DraftResponse,
8
8
  GetApplicationResponse,
9
9
  LocalMessage,
10
+ MessageMarkResponse,
11
+ MessageMarkWithUserResponse,
10
12
  MessageResponse,
11
13
  ParsedPredefinedFilterResponse,
12
14
  PollResponseData,
13
15
  QueryChannelsRequest,
16
+ QueryMessageMarksFilter,
14
17
  ReactionFilters,
15
18
  ReactionResponse,
16
19
  ReadStateResponse,
17
20
  SortParamRequest,
18
21
  TimestampNS,
22
+ UserResponse,
19
23
  } from '../types';
20
24
  import type { Channel } from '../channel';
21
25
  import type { StreamChat } from '../client';
@@ -30,6 +34,15 @@ export type DBInsertReactionType = {
30
34
  execute?: boolean;
31
35
  };
32
36
 
37
+ export type DBInsertMessageMarkType = {
38
+ /** The message as it holds the mark: its `mark_groups` and `own_marks` are stored. */
39
+ message: MessageResponse | LocalMessage;
40
+ mark: MessageMarkResponse;
41
+ /** Who made the mark, stored so the mark lists with their name. */
42
+ user?: UserResponse;
43
+ execute?: boolean;
44
+ };
45
+
33
46
  export type DBUpsertCidsForQueryType = {
34
47
  cids: string[];
35
48
  filters?: ChannelFilters;
@@ -142,6 +155,12 @@ export type DBGetReactionsType = {
142
155
  limit?: number;
143
156
  };
144
157
 
158
+ export type DBGetMessageMarksType = {
159
+ messageId: string;
160
+ filter?: QueryMessageMarksFilter;
161
+ limit?: number;
162
+ };
163
+
145
164
  export type DBDeletePendingTaskType = {
146
165
  id: number;
147
166
  };
@@ -218,6 +237,9 @@ export type ExecuteBatchDBQueriesType = PrepareBatchDBQueries[];
218
237
  */
219
238
  export interface OfflineDBApi {
220
239
  insertReaction: (options: DBInsertReactionType) => Promise<ExecuteBatchDBQueriesType>;
240
+ insertMessageMark: (
241
+ options: DBInsertMessageMarkType,
242
+ ) => Promise<ExecuteBatchDBQueriesType>;
221
243
  upsertCidsForQuery: (
222
244
  options: DBUpsertCidsForQueryType,
223
245
  ) => Promise<ExecuteBatchDBQueriesType>;
@@ -251,6 +273,10 @@ export interface OfflineDBApi {
251
273
  options: DBGetAppSettingsType,
252
274
  ) => Promise<GetApplicationResponse | null>;
253
275
  getReactions: (options: DBGetReactionsType) => Promise<ReactionResponse[] | null>;
276
+ /** The stored marks on a message, newest first, with the users who made them. */
277
+ getMessageMarks: (
278
+ options: DBGetMessageMarksType,
279
+ ) => Promise<MessageMarkWithUserResponse[] | null>;
254
280
  executeSqlBatch: (queries: ExecuteBatchDBQueriesType) => Promise<unknown>;
255
281
  addPendingTask: (task: PendingTask) => Promise<() => Promise<void>>;
256
282
  getPendingTasks: (conditions?: DBGetPendingTasksType) => Promise<PendingTask[]>;
@@ -288,6 +314,7 @@ export type PendingTaskTypes = {
288
314
  deleteReaction: 'delete-reaction';
289
315
  sendReaction: 'send-reaction';
290
316
  sendMessage: 'send-message';
317
+ sendMessageMark: 'send-message-mark';
291
318
  createDraft: 'create-draft';
292
319
  deleteDraft: 'delete-draft';
293
320
  };
@@ -308,6 +335,7 @@ export type QueueableOperationSignatures = {
308
335
  'delete-message': StreamChat['deleteMessage'];
309
336
  'delete-reaction': StreamChat['deleteReaction'];
310
337
  'send-message': Channel['sendMessage'];
338
+ 'send-message-mark': StreamChat['createMessageMark'];
311
339
  'send-reaction': StreamChat['sendReaction'];
312
340
  'update-message': StreamChat['updateMessage'];
313
341
  };
@@ -0,0 +1,103 @@
1
+ import { StateStore } from '@stream-io/state-store';
2
+ import { WithSubscriptions } from '../utils/WithSubscriptions';
3
+ import type { BasePaginator } from './paginators/BasePaginator';
4
+
5
+ type Loader<T> = BasePaginator<T, any>['toTail'];
6
+ type DebouncedLoader<T> = BasePaginator<T, any>['toTailDebounced'];
7
+
8
+ export type PaginatorViewState<T> = {
9
+ /**
10
+ * The items of the paginator's active interval (`state.items`) the predicate accepts, in the
11
+ * paginator's order. `undefined` until the paginator has items.
12
+ */
13
+ items: T[] | undefined;
14
+ };
15
+
16
+ export type PaginatorViewPredicate<T> = (item: T) => boolean;
17
+
18
+ export type PaginatorViewOptions<T> = {
19
+ /** The list the items come from. The view only reads it. */
20
+ paginator: BasePaginator<T, any>;
21
+ /** Which items the view shows; all of them without it. */
22
+ predicate?: PaginatorViewPredicate<T>;
23
+ };
24
+
25
+ const sameItems = <T>(first: T[] | undefined, second: T[] | undefined) =>
26
+ first === second ||
27
+ (!!first &&
28
+ !!second &&
29
+ first.length === second.length &&
30
+ first.every((item, index) => item === second[index]));
31
+
32
+ /**
33
+ * A subset of a paginator's loaded items, kept in step with it: a list derived from another, not a
34
+ * list of its own. Nothing is copied or queried, so every view of a paginator agrees with it. Use
35
+ * one when the server cannot filter what a UI shows, e.g. a thread's scheduled replies among a
36
+ * channel's scheduled messages.
37
+ *
38
+ * It narrows the active interval only (`state.items`). Not to be confused with the paginator's
39
+ * `intervalViews`, which project whole intervals. It never writes the paginator's items; its
40
+ * `toHead` / `toTail` (and their debounced versions) are the paginator's own, so a UI holding only
41
+ * the view can load further pages, in whichever direction that paginator grows.
42
+ *
43
+ * `state` follows the paginator while subscriptions are registered. Registering is ref-counted:
44
+ * each holder (an owning object, a UI showing the view) registers while it holds the view. On
45
+ * registering, `state` catches up at once.
46
+ */
47
+ export class PaginatorView<T> extends WithSubscriptions {
48
+ public readonly paginator: BasePaginator<T, any>;
49
+ public readonly state: StateStore<PaginatorViewState<T>>;
50
+ private readonly predicate?: PaginatorViewPredicate<T>;
51
+
52
+ constructor({ paginator, predicate }: PaginatorViewOptions<T>) {
53
+ super();
54
+ this.paginator = paginator;
55
+ this.predicate = predicate;
56
+ this.state = new StateStore<PaginatorViewState<T>>({
57
+ items: this.selectItems(paginator.state.getLatestValue().items),
58
+ });
59
+ }
60
+
61
+ /** The paginator's `toHead`: loads the page headward of the loaded items. */
62
+ public toHead: Loader<T> = (params) => this.paginator.toHead(params);
63
+
64
+ /** The paginator's `toTail`: loads the page tailward of the loaded items. */
65
+ public toTail: Loader<T> = (params) => this.paginator.toTail(params);
66
+
67
+ /** The paginator's `toHeadDebounced`. */
68
+ public toHeadDebounced: DebouncedLoader<T> = (params) =>
69
+ this.paginator.toHeadDebounced(params);
70
+
71
+ /** The paginator's `toTailDebounced`. */
72
+ public toTailDebounced: DebouncedLoader<T> = (params) =>
73
+ this.paginator.toTailDebounced(params);
74
+
75
+ /** Whether the view takes an item, loaded or not. */
76
+ public accepts = (item: T) => this.predicate?.(item) ?? true;
77
+
78
+ public registerSubscriptions = () => {
79
+ this.incrementRefCount();
80
+ if (this.hasSubscriptions) return;
81
+
82
+ // fires at once, so `state` is current from here on
83
+ this.addUnsubscribeFunction(
84
+ this.paginator.state.subscribeWithSelector(
85
+ ({ items }) => ({ items }),
86
+ ({ items }) => this.syncItems(items),
87
+ ),
88
+ );
89
+ };
90
+
91
+ private selectItems(items: T[] | undefined) {
92
+ if (!items || !this.predicate) return items;
93
+ return items.filter(this.accepts);
94
+ }
95
+
96
+ /** Writes the view's own `state` from the paginator's items; never the paginator. */
97
+ private syncItems(paginatorItems: T[] | undefined) {
98
+ const items = this.selectItems(paginatorItems);
99
+ // the same items keep the same array, so subscribers are not notified for nothing
100
+ if (sameItems(this.state.getLatestValue().items, items)) return;
101
+ this.state.next({ items });
102
+ }
103
+ }
@@ -1,3 +1,4 @@
1
1
  export * from './paginators';
2
2
  export * from './FilterBuilder';
3
3
  export type { FieldToDataResolver } from './types.normalization';
4
+ export * from './PaginatorView';