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
@@ -217,6 +217,15 @@ export type PlaceQueryPageParams<T, Q> = QueryPagePlacement<Q> & {
217
217
  results: PaginationQueryReturnValue<T> | null;
218
218
  };
219
219
 
220
+ type EmptyCompleteFirstPagePlacement = {
221
+ isFirstPage: boolean;
222
+ isHead: boolean;
223
+ isTail: boolean;
224
+ isSeparateInterval: boolean;
225
+ keepPreviousItems: boolean;
226
+ updateState: boolean;
227
+ };
228
+
220
229
  /**
221
230
  * What the preparing step of the query pipeline hands to the next ones (see
222
231
  * `BasePaginator.executeQuery`): the parameters for fetching and for placing the page, and the
@@ -403,6 +412,15 @@ export type PaginatorOptions<T, Q> = {
403
412
  * Does not hold across interval changes or page jumps.
404
413
  */
405
414
  lockItemOrder?: boolean;
415
+ /**
416
+ * Where a newly ingested item lands in a loaded list that is already empty and complete. When the
417
+ * sort order follows arrival (recency lists: messages by `created_at`, channels by
418
+ * `last_message_at`), a new item is the newest and waits in the logical head, leaving the list
419
+ * re-queryable — so this stays `false`. When the sort order is independent of arrival (scheduled
420
+ * messages, by `scheduled_at`), completeness makes its slot known, so it anchors a real interval
421
+ * there instead; such paginators set this `true`. Defaults to `false`.
422
+ */
423
+ newItemsAnchorBySortPosition?: boolean;
406
424
  /**
407
425
  * Caps the loaded items: when the head interval exceeds it, the oldest are released as new ones
408
426
  * arrive and the tailward edge re-opens, so scrolling back re-fetches. Unset: unbounded. Values
@@ -454,6 +472,7 @@ export const DEFAULT_PAGINATION_OPTIONS: BasePaginatorConfig<any, any> = deepFre
454
472
  {
455
473
  debounceMs: 300,
456
474
  lockItemOrder: false,
475
+ newItemsAnchorBySortPosition: false,
457
476
  pageSize: 10,
458
477
  hasPaginationQueryShapeChanged: baseHasPaginationQueryShapeChanged,
459
478
  retryCount: 0,
@@ -543,6 +562,11 @@ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
543
562
  protected _lastQueryShape?: Q;
544
563
  /** Set by `setItems`, which loads a page (even an empty one) without a query. */
545
564
  private _pageSetWithoutQuery = false;
565
+ /**
566
+ * The IDs of the offline database's page (see {@link preloadFirstPageFromOfflineDb}) that no live
567
+ * event has touched since, until a page from the server takes their place.
568
+ */
569
+ private _offlineOnlyItemIds: Set<string> | undefined;
546
570
 
547
571
  /**
548
572
  * Stable, purely data-driven comparison (age, timestamps, ...). Default for
@@ -682,6 +706,41 @@ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
682
706
  return this._pageSetWithoutQuery || this.isInitialized;
683
707
  }
684
708
 
709
+ private get isLoadedEmptyAndComplete() {
710
+ const { hasMoreHead, hasMoreTail } = this.state.getLatestValue();
711
+ return (
712
+ this.hasLoadedPage &&
713
+ !hasMoreHead &&
714
+ !hasMoreTail &&
715
+ this.itemIntervals.every((itv) => isLogicalInterval(itv) || !itv.itemIds.length)
716
+ );
717
+ }
718
+
719
+ private placeEmptyCompleteFirstPage({
720
+ isFirstPage,
721
+ isHead,
722
+ isTail,
723
+ isSeparateInterval,
724
+ keepPreviousItems,
725
+ updateState,
726
+ }: EmptyCompleteFirstPagePlacement): Interval | null {
727
+ const placesEmptyCompleteFirstPage =
728
+ this.config.newItemsAnchorBySortPosition &&
729
+ updateState &&
730
+ isFirstPage &&
731
+ !isSeparateInterval &&
732
+ !keepPreviousItems &&
733
+ isHead &&
734
+ isTail;
735
+
736
+ if (!placesEmptyCompleteFirstPage) return null;
737
+
738
+ const page = [...this.logicalHeadItems, ...this.logicalTailItems].sort(
739
+ this.sortComparator,
740
+ );
741
+ return this.ingestPage({ page, isHead: true, isTail: true });
742
+ }
743
+
685
744
  get isOfflineSupportEnabled() {
686
745
  return false;
687
746
  }
@@ -958,6 +1017,7 @@ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
958
1017
  * publishes.
959
1018
  */
960
1019
  protected clearItemStorage() {
1020
+ this._offlineOnlyItemIds = undefined;
961
1021
  this.setIntervals([]);
962
1022
  this.setActiveInterval(undefined);
963
1023
  this._itemIndex.clear();
@@ -2382,6 +2442,8 @@ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
2382
2442
  * interval whose sort bounds contain it, and re-emits `state.items` when that interval is active.
2383
2443
  */
2384
2444
  ingestItem(ingestedItem: T): boolean {
2445
+ // A live event confirms the item: it outlives the offline page it may belong to.
2446
+ this._offlineOnlyItemIds?.delete(this.getItemId(ingestedItem));
2385
2447
  let ingested = false;
2386
2448
  this.withSingleActiveIntervalPublish(() => {
2387
2449
  ingested = this.applyItemIngestion(ingestedItem);
@@ -2454,12 +2516,15 @@ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
2454
2516
  // unloaded).
2455
2517
  if (this._itemIntervals.size === 0) {
2456
2518
  // No pages yet: keep it in the logical head.
2457
- targetInterval = {
2458
- id: LOGICAL_HEAD_INTERVAL_ID,
2459
- itemIds: [this.getItemId(ingestedItem)],
2460
- };
2519
+ targetInterval =
2520
+ this.config.newItemsAnchorBySortPosition && this.isLoadedEmptyAndComplete
2521
+ ? this.makeInterval({ page: [ingestedItem], isHead: true, isTail: true })
2522
+ : {
2523
+ id: LOGICAL_HEAD_INTERVAL_ID,
2524
+ itemIds: [this.getItemId(ingestedItem)],
2525
+ };
2461
2526
  if (!this._activeIntervalId) {
2462
- this.setActiveInterval(targetInterval);
2527
+ this.setActiveInterval(targetInterval, { updateState: false });
2463
2528
  }
2464
2529
  } else {
2465
2530
  const intervals = this.itemIntervals;
@@ -2719,6 +2784,9 @@ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
2719
2784
  this.setActiveInterval(interval, { updateState: false });
2720
2785
  newState.hasMoreHead = interval.hasMoreHead;
2721
2786
  newState.hasMoreTail = interval.hasMoreTail;
2787
+ } else if (isFirstPage && isLastPage) {
2788
+ newState.hasMoreHead = false;
2789
+ newState.hasMoreTail = false;
2722
2790
  }
2723
2791
 
2724
2792
  // Before the publish below: subscribers read `hasLoadedPage` from inside it.
@@ -2901,10 +2969,67 @@ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
2901
2969
  };
2902
2970
  }
2903
2971
 
2972
+ /**
2973
+ * The offline database's copy of the first page, shown while the first query of a paginator not
2974
+ * initialized yet runs. It is stored like a page, so live items join it. The first page from the
2975
+ * server takes the place of its items no live event touched, as the copy can be arbitrarily old,
2976
+ * and merges with the rest, as a loaded page would. A failed query leaves it shown. `undefined`
2977
+ * (the default) shows nothing until the server answers.
2978
+ */
2904
2979
  preloadFirstPageFromOfflineDb = (
2905
2980
  _params: PaginationQueryParams<Q>,
2906
2981
  ): Promise<T[] | undefined> | T[] | undefined => undefined;
2907
2982
 
2983
+ /** Whether the shown items are the offline database's page, not yet replaced by the server's. */
2984
+ protected get showsOfflinePage() {
2985
+ return typeof this._offlineOnlyItemIds !== 'undefined';
2986
+ }
2987
+
2988
+ /**
2989
+ * Stores the offline database's page as the head interval and returns its items, ordered. Without
2990
+ * an interval behind them, the next live item would rebuild `state.items` without them.
2991
+ */
2992
+ private storeOfflinePage(page: T[]): T[] {
2993
+ const interval = this.ingestPage({ page, isHead: true });
2994
+ if (!interval) return page;
2995
+ this._offlineOnlyItemIds = new Set(page.map((item) => this.getItemId(item)));
2996
+ this.setActiveInterval(interval, { updateState: false });
2997
+ return this.intervalToItems(interval);
2998
+ }
2999
+
3000
+ /**
3001
+ * Shows the offline database's page without a query, for a subclass that defers its first query
3002
+ * (see `ChannelPaginator.executeQuery`). Like the page of {@link preloadFirstPageFromOfflineDb},
3003
+ * the first page from the server takes its place.
3004
+ */
3005
+ protected setItemsFromOfflineDb(items: T[]) {
3006
+ this.setItems({ valueOrFactory: items, isFirstPage: true });
3007
+ this._offlineOnlyItemIds = new Set(items.map((item) => this.getItemId(item)));
3008
+ }
3009
+
3010
+ /**
3011
+ * Takes the offline database's items no live event touched out of storage, without publishing:
3012
+ * the server's page placed next publishes the list once.
3013
+ */
3014
+ private removeOfflineOnlyItems() {
3015
+ const ids = this._offlineOnlyItemIds;
3016
+ this._offlineOnlyItemIds = undefined;
3017
+ if (!ids?.size) return;
3018
+ for (const interval of this.itemIntervals) {
3019
+ const itemIds = interval.itemIds.filter((id) => !ids.has(id));
3020
+ if (itemIds.length === interval.itemIds.length) continue;
3021
+ if (itemIds.length) {
3022
+ this.commitInterval({ ...interval, itemIds });
3023
+ continue;
3024
+ }
3025
+ this.dropInterval(interval.id);
3026
+ if (this.isActiveInterval(interval)) {
3027
+ this.setActiveInterval(undefined, { updateState: false });
3028
+ }
3029
+ }
3030
+ ids.forEach((id) => this._itemIndex.remove(id));
3031
+ }
3032
+
2908
3033
  populateOfflineDbAfterQuery = (_params: {
2909
3034
  items: T[] | undefined;
2910
3035
  queryShape: Q | undefined;
@@ -3192,8 +3317,11 @@ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
3192
3317
  if (checkWasStateResetDuringQuery()) return;
3193
3318
  throw error;
3194
3319
  }
3320
+ // the page of a query started before a reset must not reach the reset storage
3195
3321
  if (checkWasStateResetDuringQuery()) return;
3196
- publishStateBeforeFirstQuery(items ?? stateBeforeFirstQuery.items);
3322
+ publishStateBeforeFirstQuery(
3323
+ items ? this.storeOfflinePage(items) : stateBeforeFirstQuery.items,
3324
+ );
3197
3325
  })();
3198
3326
  }
3199
3327
  } else if (!silent) {
@@ -3238,6 +3366,18 @@ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
3238
3366
  placeQueryPage(params: PlaceQueryPageParams<T, Q>): ExecuteQueryReturnValue<T> {
3239
3367
  this._lastQueryShape = params.queryShape;
3240
3368
  const { results } = params;
3369
+ if (results && this.showsOfflinePage) {
3370
+ // The server's page takes the place of the offline database's, which can be arbitrarily old,
3371
+ // as a first page. That holds for the next query after a failed one too, which continues the
3372
+ // offline page's position. Live items ingested meanwhile stay and the page merges with them.
3373
+ this.removeOfflineOnlyItems();
3374
+ params = {
3375
+ ...params,
3376
+ continuesIntervalId: undefined,
3377
+ isFirstPage: true,
3378
+ keepPreviousItems: false,
3379
+ };
3380
+ }
3241
3381
  if (!results) {
3242
3382
  const stateUpdate: Partial<PaginatorState<T>> = {
3243
3383
  isLoading: false,
@@ -3387,27 +3527,38 @@ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
3387
3527
  : undefined;
3388
3528
  // Read before the ingest, which may merge them into the page's interval.
3389
3529
  const headIntervalIds = this.getHeadIntervalIds();
3390
- const interval = this.ingestPage({
3391
- page: stateUpdate.items,
3392
- policy: isSeparateInterval ? 'strict-overlap-only' : 'auto',
3393
- // a first page is the head unless its query started it elsewhere (at a cursor)
3394
- isHead: reachesHead
3395
- ? true
3396
- : isJumpQuery
3397
- ? undefined //head/tail doesn't apply / is unknown for this ingestion
3398
- : (isFirstPage && this.isHeadPageQueryShape(queryShape)) ||
3399
- (direction === 'headward' ? requestedPageSize > items.length : undefined),
3400
- // even though the page is first, we have to compare the requested vs returned page size;
3401
- // a first page queried towards the head says nothing about the tail
3402
- isTail: reachesTail
3403
- ? true
3404
- : isJumpQuery
3405
- ? undefined //head/tail doesn't apply / is unknown for this ingestion
3406
- : (isFirstPage && direction !== 'headward') || direction === 'tailward'
3407
- ? requestedPageSize > items.length
3408
- : undefined,
3409
- targetIntervalId: isSeparateInterval ? undefined : this._activeIntervalId,
3410
- });
3530
+ // a first page is the head unless its query started it elsewhere (at a cursor)
3531
+ const isHead = reachesHead
3532
+ ? true
3533
+ : isJumpQuery
3534
+ ? undefined //head/tail doesn't apply / is unknown for this ingestion
3535
+ : (isFirstPage && this.isHeadPageQueryShape(queryShape)) ||
3536
+ (direction === 'headward' ? requestedPageSize > items.length : undefined);
3537
+ // even though the page is first, we have to compare the requested vs returned page size;
3538
+ // a first page queried towards the head says nothing about the tail
3539
+ const isTail = reachesTail
3540
+ ? true
3541
+ : isJumpQuery
3542
+ ? undefined //head/tail doesn't apply / is unknown for this ingestion
3543
+ : (isFirstPage && direction !== 'headward') || direction === 'tailward'
3544
+ ? requestedPageSize > items.length
3545
+ : undefined;
3546
+ const interval =
3547
+ this.ingestPage({
3548
+ page: stateUpdate.items,
3549
+ policy: isSeparateInterval ? 'strict-overlap-only' : 'auto',
3550
+ isHead,
3551
+ isTail,
3552
+ targetIntervalId: isSeparateInterval ? undefined : this._activeIntervalId,
3553
+ }) ??
3554
+ this.placeEmptyCompleteFirstPage({
3555
+ isFirstPage,
3556
+ isHead: !!isHead,
3557
+ isTail: !!isTail,
3558
+ isSeparateInterval,
3559
+ keepPreviousItems: !!keepPreviousItems,
3560
+ updateState,
3561
+ });
3411
3562
  const intervalReachesHead =
3412
3563
  reachesHead ||
3413
3564
  (!!interval && this.inheritsHeadMark(interval, direction, headIntervalIds));
@@ -3612,6 +3763,7 @@ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
3612
3763
  // the publish below, whose subscribers read `isInitialized` / `hasLoadedPage`.
3613
3764
  this._lastQueryShape = undefined;
3614
3765
  this._pageSetWithoutQuery = false;
3766
+ this._offlineOnlyItemIds = undefined;
3615
3767
  this.state.next(this.initialState);
3616
3768
  this.setIntervals([]);
3617
3769
  this.setActiveInterval(undefined);
@@ -329,15 +329,6 @@ export class ChannelPaginator extends BasePaginator<Channel, ChannelQueryShape>
329
329
  protected _predefinedFilter: ParsedPredefinedFilterResponse | undefined;
330
330
  /** Metadata of the in-flight response, committed by `placeQueryPage` on a first page only. */
331
331
  private _pendingPredefinedFilter: ParsedPredefinedFilterResponse | undefined;
332
- /**
333
- * True while the loaded items came only from the offline cache (seeded by `setItems`, never
334
- * confirmed by a query). The seed's offset and query shape would make the next query a
335
- * continuation, but a cache has no pagination position, so `executeQuery` forces a first page that
336
- * keeps the items.
337
- */
338
- private _itemsLoadedFromOfflineDB = false;
339
- /** The query in flight refreshes a cache-only interval, so its response replaces the interval. */
340
- private _replaceOfflineSeedOnResponse = false;
341
332
  /** The query handed to the sync manager, from the cache read until it runs. See `executeQuery`. */
342
333
  private _queryAwaitingSync: ChannelQueryShape | undefined;
343
334
  /** The cids of the page the latest query returned, `undefined` when it failed. */
@@ -618,14 +609,6 @@ export class ChannelPaginator extends BasePaginator<Channel, ChannelQueryShape>
618
609
  if (params.isFirstPage && params.results) {
619
610
  this.applyPredefinedFilterResponse(pendingPredefinedFilter);
620
611
  }
621
- const replaceOfflineSeed = this._replaceOfflineSeedOnResponse;
622
- this._replaceOfflineSeedOnResponse = false;
623
- if (replaceOfflineSeed && params.results) {
624
- // The cache can be arbitrarily old and hold channels the server dropped (hidden, deleted,
625
- // left): the page replaces the seed instead of merging into it.
626
- this.clearItemStorage();
627
- return super.placeQueryPage({ ...params, keepPreviousItems: false });
628
- }
629
612
  return super.placeQueryPage(params);
630
613
  }
631
614
 
@@ -770,8 +753,10 @@ export class ChannelPaginator extends BasePaginator<Channel, ChannelQueryShape>
770
753
  }
771
754
  const { offlineDb } = this.client;
772
755
 
756
+ // Only the offline database's channels are shown (see `showsOfflinePage`): a cache has no
757
+ // pagination position, so the next query is a first page that keeps them until it lands.
773
758
  const effectiveParams: PaginationQueryParams<ChannelQueryShape> =
774
- this._itemsLoadedFromOfflineDB && params.reset !== 'yes'
759
+ this.showsOfflinePage && params.reset !== 'yes'
775
760
  ? { ...params, keepPreviousItems: true, reset: 'yes' as const }
776
761
  : params;
777
762
 
@@ -781,7 +766,7 @@ export class ChannelPaginator extends BasePaginator<Channel, ChannelQueryShape>
781
766
  !!this.client.user?.id &&
782
767
  !offlineDb.syncManager.isSynced &&
783
768
  // A cache-seeded list is not a loaded one, so paginating it defers too.
784
- (this._itemsLoadedFromOfflineDB ||
769
+ (this.showsOfflinePage ||
785
770
  this.isFirstPageQuery({ queryShape, reset: effectiveParams.reset }));
786
771
 
787
772
  if (!shouldDeferUntilSynced) return await super.executeQuery(effectiveParams);
@@ -809,12 +794,10 @@ export class ChannelPaginator extends BasePaginator<Channel, ChannelQueryShape>
809
794
  // the list's flags and loading state belong to the queries started since the reset
810
795
  if (checkWasStateResetDuringQuery()) return;
811
796
  if (cachedChannels?.length) {
812
- // Seed via `setItems`, which ingests the page into the interval/index storage.
813
797
  // TODO: Maybe find a better way to do this rather than 2 partialNext invocations
814
798
  // running. This all happens so fast it should never be noticeable but it's
815
799
  // a microoptimization.
816
- this.setItems({ valueOrFactory: cachedChannels, isFirstPage: true });
817
- this._itemsLoadedFromOfflineDB = true;
800
+ this.setItemsFromOfflineDb(cachedChannels);
818
801
  }
819
802
  // Nothing is in flight while waiting for the sync: `isLoading` would make `canExecuteQuery`
820
803
  // reject the query scheduled below.
@@ -824,7 +807,7 @@ export class ChannelPaginator extends BasePaginator<Channel, ChannelQueryShape>
824
807
  const refreshParams: PaginationQueryParams<ChannelQueryShape> = {
825
808
  ...effectiveParams,
826
809
  keepPreviousItems: true,
827
- ...(this._itemsLoadedFromOfflineDB ? { reset: 'yes' as const } : {}),
810
+ ...(this.showsOfflinePage ? { reset: 'yes' as const } : {}),
828
811
  };
829
812
 
830
813
  // Already synced: the sync-status callback would never fire, so run the query now.
@@ -844,9 +827,6 @@ export class ChannelPaginator extends BasePaginator<Channel, ChannelQueryShape>
844
827
  }: PaginationQueryParams<ChannelQueryShape> = {}): Promise<
845
828
  PaginationQueryReturnValue<Channel>
846
829
  > => {
847
- if (this._itemsLoadedFromOfflineDB) this._replaceOfflineSeedOnResponse = true;
848
- // A query is going out: the items stop being cache-only, whatever the response.
849
- this._itemsLoadedFromOfflineDB = false;
850
830
  const queryShape = preparedQueryShape ?? this.getNextQueryShape();
851
831
  const { stateOptions, ...request } = queryShape;
852
832
  const checkWasStateResetDuringQuery = this.makeStateResetWatcher();
@@ -1047,8 +1027,8 @@ export class ChannelPaginator extends BasePaginator<Channel, ChannelQueryShape>
1047
1027
  // `toTail()` there, and clearing afterwards would wipe what that query set.
1048
1028
  this._queryAwaitingSync = undefined;
1049
1029
  this._tailQueryAwaitingRecovery = false;
1050
- this._itemsLoadedFromOfflineDB = false;
1051
- this._replaceOfflineSeedOnResponse = false;
1030
+ // the offline page's flag (`showsOfflinePage`) is cleared by `super.resetState()` before it
1031
+ // publishes
1052
1032
  this._pendingPredefinedFilter = undefined;
1053
1033
  if (this._predefinedFilter) this.applyPredefinedFilterResponse(undefined);
1054
1034
  super.resetState();
@@ -1586,7 +1586,10 @@ export class MessageIntervalPaginator extends BasePaginator<
1586
1586
  ? await this.channel
1587
1587
  .getClient()
1588
1588
  .getReplies({ parent_id: this.parentMessageId }, pagination)
1589
- : await this.channel.query({ messages: pagination });
1589
+ : await this.channel.query({
1590
+ include_scheduled_messages: false,
1591
+ messages: pagination,
1592
+ });
1590
1593
  return Array.isArray(messages) && messages.length > 0;
1591
1594
  }
1592
1595
 
@@ -0,0 +1,222 @@
1
+ import { BasePaginator, ZERO_PAGE_CURSOR } from './BasePaginator';
2
+ import type {
3
+ ExecuteQueryReturnValue,
4
+ PaginationQueryParams,
5
+ PaginationQueryReturnValue,
6
+ PaginatorOptions,
7
+ PaginatorState,
8
+ PlaceQueryPageParams,
9
+ } from './BasePaginator';
10
+ import type {
11
+ MessageMarkWithUserResponse,
12
+ QueryMessageMarksFilter,
13
+ QueryMessageMarksRequest,
14
+ } from '../../types';
15
+ import type { StreamChat } from '../../client';
16
+ import { ComparisonResult } from '../types.normalization';
17
+ import { generateUUIDv4 } from '../../utils';
18
+ import { chatLoggerSystem } from '../../logger';
19
+
20
+ // A mark has no ID of its own: a user marks a message once per type.
21
+ const getMarkId = (mark: MessageMarkWithUserResponse) =>
22
+ `${mark.message_id}:${mark.user_id}:${mark.type}`;
23
+
24
+ // Newest first, as the server returns them. Ties need equal nanosecond timestamps; the ID keeps
25
+ // the order total. The paginator checks for exactly -1 and 1, so no differences.
26
+ const compareMarks = (
27
+ a: MessageMarkWithUserResponse,
28
+ b: MessageMarkWithUserResponse,
29
+ ): ComparisonResult => {
30
+ if (a.created_at !== b.created_at) {
31
+ return a.created_at > b.created_at
32
+ ? ComparisonResult.A_PRECEDES_B
33
+ : ComparisonResult.A_COMES_AFTER_B;
34
+ }
35
+ const idA = getMarkId(a);
36
+ const idB = getMarkId(b);
37
+ if (idA === idB) return ComparisonResult.A_IS_EQUAL_TO_B;
38
+ return idA < idB ? ComparisonResult.A_PRECEDES_B : ComparisonResult.A_COMES_AFTER_B;
39
+ };
40
+
41
+ export type MessageMarkPaginatorOptions = {
42
+ /** Identifies the list in `client.messageMarks`. Generated when left out. */
43
+ id?: string;
44
+ /** The message whose marks are listed. */
45
+ messageId: string;
46
+ /** Lists only the marks it matches, for example `{ type: 'played' }`. */
47
+ filter?: QueryMessageMarksFilter;
48
+ /** How the list is fetched, for example its `pageSize`. */
49
+ paginatorOptions?: PaginatorOptions<
50
+ MessageMarkWithUserResponse,
51
+ QueryMessageMarksRequest
52
+ >;
53
+ };
54
+
55
+ /**
56
+ * Lists the marks on one message, with the users who made them, newest first. The API pages
57
+ * forward only, so the headward cursor starts exhausted (`null`). New marks are added at the head
58
+ * through `ingestItem`, which `client.messageMarks` calls for `message.mark_added`.
59
+ *
60
+ * With offline support, the first page opens with the marks the offline database holds while the
61
+ * request runs, and keeps them when the request fails.
62
+ */
63
+ export class MessageMarkPaginator extends BasePaginator<
64
+ MessageMarkWithUserResponse,
65
+ QueryMessageMarksRequest
66
+ > {
67
+ private client: StreamChat;
68
+ private readonly _id: string;
69
+ readonly messageId: string;
70
+ readonly filter: QueryMessageMarksFilter | undefined;
71
+ private activeRefCount = 0;
72
+ private _isStateStale = false;
73
+
74
+ constructor(
75
+ client: StreamChat,
76
+ { id, messageId, filter, paginatorOptions }: MessageMarkPaginatorOptions,
77
+ ) {
78
+ super({
79
+ initialCursor: { ...ZERO_PAGE_CURSOR, headward: null },
80
+ ...paginatorOptions,
81
+ });
82
+ this.client = client;
83
+ this._id = id ?? `message-mark-paginator-${generateUUIDv4()}`;
84
+ this.messageId = messageId;
85
+ this.filter = filter;
86
+ this.sortComparator = compareMarks;
87
+ }
88
+
89
+ get initialState(): PaginatorState<MessageMarkWithUserResponse> {
90
+ return {
91
+ ...super.initialState,
92
+ hasMoreHead: false,
93
+ };
94
+ }
95
+
96
+ get id() {
97
+ return this._id;
98
+ }
99
+
100
+ getItemId(item: MessageMarkWithUserResponse): string {
101
+ return getMarkId(item);
102
+ }
103
+
104
+ /** See {@link MessageMarkPaginator.activate}. */
105
+ get active() {
106
+ return this.activeRefCount > 0;
107
+ }
108
+
109
+ /** Whether marks may have been missed, for example while the connection was down. */
110
+ get isStateStale() {
111
+ return this._isStateStale;
112
+ }
113
+
114
+ /**
115
+ * Call this when a screen starts showing the list, and call the returned function when it stops.
116
+ * A stale list reloads as soon as it is shown. The list counts as shown until every caller has
117
+ * released it, and releasing twice does nothing.
118
+ */
119
+ activate = (): (() => void) => {
120
+ this.activeRefCount += 1;
121
+ if (this.activeRefCount === 1) this.reloadIfStale();
122
+
123
+ let released = false;
124
+ return () => {
125
+ if (released) return;
126
+ released = true;
127
+ this.activeRefCount -= 1;
128
+ };
129
+ };
130
+
131
+ /**
132
+ * Flags the loaded marks as possibly incomplete. An active list reloads now, an inactive one when
133
+ * it is next activated.
134
+ */
135
+ markStale = () => {
136
+ this._isStateStale = true;
137
+ if (this.active) this.reloadIfStale();
138
+ };
139
+
140
+ private reloadIfStale() {
141
+ if (!this._isStateStale) return;
142
+ this._isStateStale = false;
143
+ // Nothing loaded yet: the first page will be fresh anyway.
144
+ if (typeof this.items === 'undefined') return;
145
+ void this.reload();
146
+ }
147
+
148
+ override get isOfflineSupportEnabled() {
149
+ return !!this.client.offlineDb;
150
+ }
151
+
152
+ override preloadFirstPageFromOfflineDb = async (): Promise<
153
+ MessageMarkWithUserResponse[] | undefined
154
+ > => {
155
+ const { offlineDb } = this.client;
156
+ if (!offlineDb) return undefined;
157
+ try {
158
+ const marks = await offlineDb.getMessageMarks({
159
+ filter: this.filter,
160
+ limit: this.pageSize,
161
+ messageId: this.messageId,
162
+ });
163
+ return marks?.length ? marks : undefined;
164
+ } catch (error) {
165
+ chatLoggerSystem
166
+ .getLogger('offline-db')
167
+ .warn('Reading the stored message marks failed.', { error });
168
+ return undefined;
169
+ }
170
+ };
171
+
172
+ // When the request fails, the stored marks are all the list has. It pages no further and counts
173
+ // as stale, so reconnecting or showing it again reloads it.
174
+ override placeQueryPage(
175
+ params: PlaceQueryPageParams<MessageMarkWithUserResponse, QueryMessageMarksRequest>,
176
+ ): ExecuteQueryReturnValue<MessageMarkWithUserResponse> {
177
+ const placed = super.placeQueryPage(params);
178
+ if (!params.results && this.showsOfflinePage) {
179
+ this._isStateStale = true;
180
+ this.state.partialNext({ hasMoreTail: false });
181
+ }
182
+ return placed;
183
+ }
184
+
185
+ protected override buildMatchFilters() {
186
+ return { message_id: this.messageId, ...this.filter };
187
+ }
188
+
189
+ // The cursor stays out of the shape: `fetchQueryResponse` applies it.
190
+ protected getNextQueryShape(): QueryMessageMarksRequest {
191
+ return {
192
+ limit: this.pageSize,
193
+ ...(this.filter ? { filter: this.filter } : {}),
194
+ };
195
+ }
196
+
197
+ protected override fetchQueryResponse = async ({
198
+ direction,
199
+ queryShape,
200
+ }: PaginationQueryParams<QueryMessageMarksRequest>): Promise<
201
+ PaginationQueryReturnValue<MessageMarkWithUserResponse>
202
+ > => {
203
+ if (direction === 'headward') {
204
+ return { items: [] };
205
+ }
206
+
207
+ const next = direction ? (this.cursor?.tailward ?? undefined) : undefined;
208
+ const { marks: items, next: tailward } = await this.client.queryMessageMarks(
209
+ { id: this.messageId },
210
+ { ...(queryShape ?? this.getNextQueryShape()), ...(next ? { next } : {}) },
211
+ );
212
+ return { items, tailward };
213
+ };
214
+
215
+ /** The extracting step of the query pipeline: the response is the page. */
216
+ protected override extractQueryPage(
217
+ response: PaginationQueryReturnValue<MessageMarkWithUserResponse>,
218
+ _params: PaginationQueryParams<QueryMessageMarksRequest>,
219
+ ) {
220
+ return response;
221
+ }
222
+ }