stream-chat 10.0.2 → 10.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -174,8 +174,10 @@ export type PaginationQueryParams<Q> = {
174
174
  silent?: boolean;
175
175
  /**
176
176
  * Whether the page's interval becomes the active one and the state is published. Default: true.
177
- * Otherwise the page is only stored; one landing in the active interval is still published. Even
178
- * with it, the paginator's own page can be only stored (see `BasePaginator.isPageOnlyStored`).
177
+ * With `false` the page is only stored. It is still published when it lands in the active
178
+ * interval, or when it is an empty first page of a list without items (not at a caller's
179
+ * `queryShape`, not superseded by a later claim). With `true` the paginator's own page can still
180
+ * be only stored (see `BasePaginator.isPageOnlyStored`).
179
181
  */
180
182
  updateState?: boolean;
181
183
  };
@@ -224,6 +226,8 @@ type PreparedQuery<Q> = {
224
226
  fetchParams: PaginationQueryParams<Q>;
225
227
  offlinePreloadPromise?: Promise<void>;
226
228
  placeParams: QueryPagePlacement<Q>;
229
+ /** Whether `resetState()` ran while the query ran (see `BasePaginator.makeStateResetWatcher`). */
230
+ checkWasStateResetDuringQuery: () => boolean;
227
231
  };
228
232
 
229
233
  export type ExecuteQueryReturnValue<T> = {
@@ -527,6 +531,8 @@ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
527
531
  protected _itemIndex: ItemIndexApi<T>;
528
532
 
529
533
  protected _executeQueryDebounced!: DebouncedExecQueryFunction<Q>;
534
+ /** How many times `resetState()` ran, which tells the work started before a reset apart. */
535
+ private _stateResetCount = 0;
530
536
  /** Last effective query shape produced by the subclass for the most recent request. */
531
537
  protected _lastQueryShape?: Q;
532
538
  /** Set by `setItems`, which loads a page (even an empty one) without a query. */
@@ -976,7 +982,8 @@ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
976
982
  /**
977
983
  * The last step of the query pipeline (see {@link executeQuery}): applies what a response holds
978
984
  * besides its page, once the page is placed with `placeParams`. Runs once for every response that
979
- * arrived, also when extracting or placing its page failed. Does nothing by default.
985
+ * arrived, also when placing its page failed or a reset made it ignored (see
986
+ * {@link executeQuery}). Does nothing by default.
980
987
  */
981
988
  protected applyQueryResponseRest(
982
989
  _response: R,
@@ -2887,38 +2894,50 @@ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
2887
2894
 
2888
2895
  /**
2889
2896
  * {@link fetchQueryResponse} with the paginator's retries. Once every attempt failed, the last
2890
- * error is recorded as `lastQueryError` (unless offline support is on and items are loaded), and
2891
- * thrown with `throwErrors` set, after ending the query; otherwise it returns `null`, for the
2892
- * caller to end the query.
2897
+ * error is reported (see {@link reportFailedFetch}). After a `resetState()`
2898
+ * (`checkWasStateResetDuringQuery`), it stops retrying and returns `null` without reporting.
2893
2899
  */
2894
2900
  protected async fetchQueryResponseWithRetries(
2895
2901
  params: PaginationQueryParams<Q> = {},
2902
+ {
2903
+ checkWasStateResetDuringQuery = () => false,
2904
+ }: { checkWasStateResetDuringQuery?: () => boolean } = {},
2896
2905
  ): Promise<R | null> {
2897
- const remainingRetries = params.retryCount ?? 0;
2898
- try {
2899
- return await this.fetchQueryResponse(params);
2900
- } catch (e) {
2901
- if (remainingRetries > 0) {
2902
- await sleep(DEFAULT_QUERY_CHANNELS_MS_BETWEEN_RETRIES);
2903
- return await this.fetchQueryResponseWithRetries({
2904
- ...params,
2905
- retryCount: remainingRetries - 1,
2906
- });
2906
+ let remainingRetries = params.retryCount ?? 0;
2907
+ while (true) {
2908
+ try {
2909
+ return await this.fetchQueryResponse({ ...params, retryCount: remainingRetries });
2910
+ } catch (e) {
2911
+ // the attempt belongs to the state the reset cleared, and so would a retry
2912
+ if (checkWasStateResetDuringQuery()) return null;
2913
+ if (remainingRetries > 0) {
2914
+ remainingRetries -= 1;
2915
+ await sleep(DEFAULT_QUERY_CHANNELS_MS_BETWEEN_RETRIES);
2916
+ if (checkWasStateResetDuringQuery()) return null;
2917
+ continue;
2918
+ }
2919
+ return this.reportFailedFetch(e as Error);
2907
2920
  }
2921
+ }
2922
+ }
2908
2923
 
2909
- // run only once all retries are exhausted
2910
- const isOfflineSupportEnabledWithItems =
2911
- this.isOfflineSupportEnabled && (this.items ?? []).length > 0;
2912
- if (!isOfflineSupportEnabledWithItems) {
2913
- this.state.partialNext({ lastQueryError: e as Error });
2914
- }
2924
+ /**
2925
+ * Handles a query whose attempts all failed: sets `lastQueryError` (unless offline support is on
2926
+ * and items are loaded). With `throwErrors`, ends loading and throws; otherwise returns `null`
2927
+ * and the caller ends the query.
2928
+ */
2929
+ private reportFailedFetch(e: Error): null {
2930
+ const isOfflineSupportEnabledWithItems =
2931
+ this.isOfflineSupportEnabled && (this.items ?? []).length > 0;
2932
+ if (!isOfflineSupportEnabledWithItems) {
2933
+ this.state.partialNext({ lastQueryError: e });
2934
+ }
2915
2935
 
2916
- if (this.config.throwErrors) {
2917
- this.state.partialNext({ isLoading: false });
2918
- throw e;
2919
- }
2920
- return null;
2936
+ if (this.config.throwErrors) {
2937
+ this.state.partialNext({ isLoading: false });
2938
+ throw e;
2921
2939
  }
2940
+ return null;
2922
2941
  }
2923
2942
 
2924
2943
  /**
@@ -2937,9 +2956,13 @@ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
2937
2956
  * as `lastQueryError` (a failed fetch not while offline support is on and items are loaded), and
2938
2957
  * rejects the call only with `throwErrors` set.
2939
2958
  *
2940
- * Resolves to `undefined` when the query cannot run now (see {@link canExecuteQuery}), and to
2941
- * what the placing step returned otherwise, whose `targetInterval` is `null` when no page was
2942
- * placed, with `isSuperseded`.
2959
+ * If `resetState()` runs while the query runs, the query is ignored: it places no page, records
2960
+ * no error and throws nothing, also with `throwErrors`. The queries started after the reset own
2961
+ * the state. Its response's other data is still applied ({@link applyQueryResponseRest}).
2962
+ *
2963
+ * Resolves to `undefined` when the query cannot run now (see {@link canExecuteQuery}) or its
2964
+ * results were ignored, and to what the placing step returned otherwise, whose `targetInterval`
2965
+ * is `null` when no page was placed, with `isSuperseded`.
2943
2966
  *
2944
2967
  * @param params - Query parameters.
2945
2968
  * @param params.claimsActiveInterval - Whether the query claims the active interval.
@@ -2971,10 +2994,18 @@ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
2971
2994
  fetchParams,
2972
2995
  offlinePreloadPromise,
2973
2996
  placeParams,
2997
+ checkWasStateResetDuringQuery,
2974
2998
  }: PreparedQuery<Q>): Promise<ExecuteQueryReturnValue<T> | undefined> {
2975
2999
  if (offlinePreloadPromise) await offlinePreloadPromise;
3000
+ if (checkWasStateResetDuringQuery()) return undefined;
2976
3001
 
2977
- const response = await this.fetchQueryResponseWithRetries(fetchParams);
3002
+ const response = await this.fetchQueryResponseWithRetries(fetchParams, {
3003
+ checkWasStateResetDuringQuery,
3004
+ });
3005
+ if (checkWasStateResetDuringQuery()) {
3006
+ if (response !== null) this.applyResponseRestOfIgnoredQuery(response, placeParams);
3007
+ return undefined;
3008
+ }
2978
3009
  if (response === null) return this.placeQueryPage({ ...placeParams, results: null });
2979
3010
 
2980
3011
  // Every step after the fetch runs, whichever fails: the rest of a response that arrived is
@@ -2997,6 +3028,21 @@ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
2997
3028
  return errors.length > 0 ? this.reportQueryError(errors[0], placed) : placed;
2998
3029
  }
2999
3030
 
3031
+ /**
3032
+ * {@link applyQueryResponseRest} for a query a reset made ignored (see {@link executeQuery}).
3033
+ * An ignored query reports nothing, so an error here is swallowed.
3034
+ */
3035
+ private applyResponseRestOfIgnoredQuery(
3036
+ response: R,
3037
+ placeParams: QueryPagePlacement<Q>,
3038
+ ) {
3039
+ try {
3040
+ this.applyQueryResponseRest(response, placeParams);
3041
+ } catch {
3042
+ // reported neither in the state nor to the caller
3043
+ }
3044
+ }
3045
+
3000
3046
  /**
3001
3047
  * Ends a query whose step after the fetch failed: records the error as `lastQueryError` and
3002
3048
  * throws it with `throwErrors` set (see {@link executeQuery}). Otherwise returns what the query
@@ -3015,6 +3061,15 @@ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
3015
3061
  };
3016
3062
  }
3017
3063
 
3064
+ /**
3065
+ * Returns a function telling whether `resetState()` ran since this call. Work started before a
3066
+ * reset uses it to ignore its results instead of writing them into the reset state.
3067
+ */
3068
+ protected makeStateResetWatcher(): () => boolean {
3069
+ const resetCount = this._stateResetCount;
3070
+ return () => resetCount !== this._stateResetCount;
3071
+ }
3072
+
3018
3073
  /**
3019
3074
  * Whether a query claims the active interval by default (see
3020
3075
  * `PaginationQueryParams.claimsActiveInterval`, which overrides it):
@@ -3050,6 +3105,7 @@ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
3050
3105
  updateState = true,
3051
3106
  }: PaginationQueryParams<Q>): PreparedQuery<Q> | undefined {
3052
3107
  if (!this.canExecuteQuery({ direction, reset })) return undefined;
3108
+ const checkWasStateResetDuringQuery = this.makeStateResetWatcher();
3053
3109
  const claims =
3054
3110
  claimsActiveInterval ??
3055
3111
  this.decidesActiveInterval({ queryShape: forcedQueryShape, reset, updateState });
@@ -3106,12 +3162,19 @@ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
3106
3162
  publishStateBeforeFirstQuery(undefined);
3107
3163
  } else {
3108
3164
  offlinePreloadPromise = (async () => {
3109
- const items = await this.preloadFirstPageFromOfflineDb({
3110
- direction,
3111
- queryShape,
3112
- reset,
3113
- retryCount,
3114
- });
3165
+ let items: T[] | undefined;
3166
+ try {
3167
+ items = await this.preloadFirstPageFromOfflineDb({
3168
+ direction,
3169
+ queryShape,
3170
+ reset,
3171
+ retryCount,
3172
+ });
3173
+ } catch (error) {
3174
+ if (checkWasStateResetDuringQuery()) return;
3175
+ throw error;
3176
+ }
3177
+ if (checkWasStateResetDuringQuery()) return;
3115
3178
  publishStateBeforeFirstQuery(items ?? stateBeforeFirstQuery.items);
3116
3179
  })();
3117
3180
  }
@@ -3140,6 +3203,7 @@ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
3140
3203
  requestedPageSize: this.getRequestedPageSize(queryShape),
3141
3204
  updateState,
3142
3205
  },
3206
+ checkWasStateResetDuringQuery,
3143
3207
  };
3144
3208
  }
3145
3209
 
@@ -3189,6 +3253,55 @@ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
3189
3253
  );
3190
3254
  }
3191
3255
 
3256
+ /**
3257
+ * Whether an empty page (from the server or after `filterQueryResults`) keeps the loaded items
3258
+ * instead of blanking them: on a `keepPreviousItems` refresh or a next page, when `items` is
3259
+ * defined (`hasResults`). With `items` undefined there is nothing to keep, so the page sets `[]`.
3260
+ */
3261
+ private emptyPageKeepsLoadedItems({
3262
+ isFirstPage,
3263
+ keepPreviousItems,
3264
+ }: Pick<QueryPagePlacement<Q>, 'isFirstPage' | 'keepPreviousItems'>): boolean {
3265
+ return this.hasResults && (!!keepPreviousItems || !isFirstPage);
3266
+ }
3267
+
3268
+ /**
3269
+ * Whether placing a page publishes its whole state: with `updateState`, or when the paginator's
3270
+ * own `updateState: false` query settles a list without items
3271
+ * ({@link emptyPageSettlesListWithoutItems}). Otherwise {@link publishStoredPage} publishes only
3272
+ * what the stored page changed.
3273
+ */
3274
+ private commitsPlacedState(
3275
+ placement: QueryPagePlacement<Q>,
3276
+ page: T[],
3277
+ { endsQuery }: { endsQuery: boolean },
3278
+ ): boolean {
3279
+ return (
3280
+ placement.updateState !== false ||
3281
+ (endsQuery && this.emptyPageSettlesListWithoutItems(placement, page))
3282
+ );
3283
+ }
3284
+
3285
+ /**
3286
+ * Whether an empty, only-stored first page sets a list without items (`items` undefined) to
3287
+ * `[]`. Storing an empty page leaves nothing a later publish could show, so it is published now.
3288
+ * Not for a page at the caller's shape (`startsSeparateInterval`): it says nothing about the
3289
+ * list's own first page. Not for a superseded claim ({@link claimIsSuperseded}): the later claim
3290
+ * owns the list.
3291
+ */
3292
+ private emptyPageSettlesListWithoutItems(
3293
+ placement: QueryPagePlacement<Q>,
3294
+ page: T[],
3295
+ ): boolean {
3296
+ return (
3297
+ placement.isFirstPage &&
3298
+ page.length === 0 &&
3299
+ !this.hasResults &&
3300
+ !placement.startsSeparateInterval &&
3301
+ !this.claimIsSuperseded(placement)
3302
+ );
3303
+ }
3304
+
3192
3305
  /** Whether a claim on the active interval followed the query's own (`activeIntervalClaim`). */
3193
3306
  private claimIsSuperseded({ activeIntervalClaim }: QueryPagePlacement<Q>): boolean {
3194
3307
  return (
@@ -3213,7 +3326,10 @@ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
3213
3326
  * of the paginator's own queries may still be running.
3214
3327
  */
3215
3328
  protected placePage(
3216
- {
3329
+ placement: QueryPagePlacement<Q> & { results: PaginationQueryReturnValue<T> },
3330
+ { endsQuery }: { endsQuery: boolean },
3331
+ ): ExecuteQueryReturnValue<T> {
3332
+ const {
3217
3333
  startsSeparateInterval,
3218
3334
  direction,
3219
3335
  isFirstPage,
@@ -3222,9 +3338,7 @@ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
3222
3338
  requestedPageSize,
3223
3339
  results,
3224
3340
  updateState = true,
3225
- }: QueryPagePlacement<Q> & { results: PaginationQueryReturnValue<T> },
3226
- { endsQuery }: { endsQuery: boolean },
3227
- ): ExecuteQueryReturnValue<T> {
3341
+ } = placement;
3228
3342
  const stateUpdate: Partial<PaginatorState<T>> = endsQuery
3229
3343
  ? { isLoading: false, lastQueryError: undefined }
3230
3344
  : {};
@@ -3280,11 +3394,9 @@ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
3280
3394
  } else if (
3281
3395
  updateState &&
3282
3396
  !filteredItems.length &&
3283
- (keepPreviousItems || !isFirstPage)
3397
+ this.emptyPageKeepsLoadedItems({ isFirstPage, keepPreviousItems })
3284
3398
  ) {
3285
- // A page left empty, by the server or by `filterQueryResults`, must not wipe the loaded items
3286
- // on a `keepPreviousItems` refresh or an incremental query (`ingestPage` returns null for it).
3287
- // A genuine reset still blanks.
3399
+ // `ingestPage` returns no interval for an empty page, so the loaded items are carried over.
3288
3400
  stateUpdate.items = this.items;
3289
3401
  }
3290
3402
 
@@ -3423,10 +3535,11 @@ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
3423
3535
  const state = endsQuery
3424
3536
  ? this.getStateAfterQuery(stateUpdate, isFirstPage)
3425
3537
  : { ...this.state.getLatestValue(), ...stateUpdate };
3426
- // `updateState` decides whether the results are committed, not whether the query is over: a
3427
- // caller that commits its own state must not be left with the `isLoading` executeQuery published.
3428
- if (updateState) this.state.next(state);
3429
- else this.publishStoredPage({ endsQuery, interval, state });
3538
+ // Committing the results is `commitsPlacedState`'s call; ending the query is not: an
3539
+ // uncommitted page still clears the `isLoading` that `executeQuery` published.
3540
+ if (this.commitsPlacedState(placement, filteredItems, { endsQuery })) {
3541
+ this.state.next(state);
3542
+ } else this.publishStoredPage({ endsQuery, interval, state });
3430
3543
  // Only the first page of the paginator's own query is cached; a later page cannot change it.
3431
3544
  if (endsQuery && isFirstPage) {
3432
3545
  this.populateOfflineDbAfterQuery({ items: state.items, queryShape });
@@ -3465,7 +3578,12 @@ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
3465
3578
  this._executeQueryDebounced.cancel();
3466
3579
  }
3467
3580
 
3581
+ /**
3582
+ * Returns the paginator to "never queried" (`items: undefined`). A query running meanwhile is
3583
+ * ignored (see {@link executeQuery}); a debounced query stays scheduled.
3584
+ */
3468
3585
  resetState() {
3586
+ this._stateResetCount++;
3469
3587
  // Nothing is loaded, so the next query is a first page again. A stale shape would make a
3470
3588
  // re-query with an unchanged shape a continuation, ingested without `isHead`. Cleared before
3471
3589
  // the publish below, whose subscribers read `isInitialized` / `hasLoadedPage`.
@@ -31,7 +31,7 @@ import type {
31
31
  } from '../../types';
32
32
  import type { FieldToDataResolver, PathResolver } from '../types.normalization';
33
33
  import { resolveDotPathValue } from '../utility.normalization';
34
- import { isEqual } from '../../utils/mergeWith/mergeWithCore';
34
+ import { isClassInstance, isEqual } from '../../utils/mergeWith/mergeWithCore';
35
35
 
36
36
  const hasSameItems = (current: Channel[] | undefined, next: Channel[] | undefined) => {
37
37
  if (current === next) return false;
@@ -105,7 +105,23 @@ export type ChannelPaginatorOptions = {
105
105
  store?: EntityStore<Channel>;
106
106
  };
107
107
 
108
- /** The query without its page: shapes with the same identity continue one pagination. */
108
+ /** A copy without `undefined` object values, which JSON drops from a request body. */
109
+ const withoutUndefinedValues = (value: unknown): unknown => {
110
+ if (Array.isArray(value)) return value.map(withoutUndefinedValues);
111
+ if (!value || typeof value !== 'object' || isClassInstance(value)) return value;
112
+ return Object.fromEntries(
113
+ Object.entries(value)
114
+ .filter(([, entry]) => entry !== undefined)
115
+ .map(([key, entry]) => [key, withoutUndefinedValues(entry)]),
116
+ );
117
+ };
118
+
119
+ /**
120
+ * The query without its page: shapes with the same identity send the same request and continue
121
+ * one pagination. `undefined` values inside a request field (filters, sort) are left out. A
122
+ * top-level `undefined` is kept: `client.queryChannels()` lets it override a default (`watch`,
123
+ * `state`).
124
+ */
109
125
  const getQueryIdentity = (queryShape: ChannelQueryShape | undefined) => {
110
126
  if (!queryShape) return queryShape;
111
127
  const {
@@ -116,7 +132,9 @@ const getQueryIdentity = (queryShape: ChannelQueryShape | undefined) => {
116
132
 
117
133
  ...identity
118
134
  } = queryShape;
119
- return identity;
135
+ return Object.fromEntries(
136
+ Object.entries(identity).map(([key, value]) => [key, withoutUndefinedValues(value)]),
137
+ );
120
138
  };
121
139
 
122
140
  const hasPaginationQueryShapeChanged: PaginationQueryShapeChangeIdentifier<
@@ -457,23 +475,61 @@ export class ChannelPaginator extends BasePaginator<Channel, ChannelQueryShape>
457
475
  return this._channelStateOptions;
458
476
  }
459
477
 
478
+ /** Sets the filters the list queries; a change resets the list (see `changeQuery`). */
460
479
  set staticFilters(filters: ChannelFilters | undefined) {
461
- this._staticFilters = filters;
480
+ this.changeQuery(() => {
481
+ this._staticFilters = filters;
482
+ });
462
483
  }
463
484
 
485
+ /** Sets the sort the list queries and orders by; a change resets the list (see `changeQuery`). */
464
486
  set sort(sort: SortParamRequest[] | undefined) {
465
- this._sort = sort;
466
- this.sortComparator = this.buildSortComparator(this.effectiveSort);
487
+ this.changeQuery(() => {
488
+ this._sort = sort;
489
+ this.sortComparator = this.buildSortComparator(this.effectiveSort);
490
+ });
467
491
  }
468
492
 
493
+ /** Sets the request options; one that changes the query resets the list (see `changeQuery`). */
469
494
  set options(options: ChannelPaginatorRequestOptions | undefined) {
470
- this._options = options;
495
+ this.changeQuery(() => {
496
+ this._options = options;
497
+ });
471
498
  }
472
499
 
473
500
  set channelStateOptions(options: ChannelStateOptions | undefined) {
474
501
  this._channelStateOptions = options;
475
502
  }
476
503
 
504
+ /**
505
+ * Applies a change to a query input (filters, sort, options) and resets the list with
506
+ * `resetState()` when the query identity changes (`queryChangeDiscardsPages`). It compares the
507
+ * whole query before and after, so setting an equal value or only a page-size option keeps the
508
+ * loaded pages.
509
+ *
510
+ * After a reset the list stays "never queried" until `toTail()` or `reload()` loads the new
511
+ * query's first page. A query still running for the old query is ignored; a debounced query
512
+ * stays scheduled and runs with the new query.
513
+ */
514
+ private changeQuery(applyChange: () => void) {
515
+ const queryBefore = this.getNextQueryShape();
516
+ applyChange();
517
+ if (this.queryChangeDiscardsPages(queryBefore)) this.resetState();
518
+ }
519
+
520
+ /**
521
+ * Whether the next query has another identity than `queryBefore`
522
+ * (`hasPaginationQueryShapeChanged`). The identity is the filters, the sort and the request
523
+ * options, such as `watch` or `predefined_filter`. It leaves out `limit` and `offset` (the page)
524
+ * and `member_limit` and `message_limit` (how much of each channel loads).
525
+ */
526
+ private queryChangeDiscardsPages(queryBefore: ChannelQueryShape): boolean {
527
+ return this.config.hasPaginationQueryShapeChanged(
528
+ queryBefore,
529
+ this.getNextQueryShape(),
530
+ );
531
+ }
532
+
477
533
  get sortComparatorFactory(): ChannelSortComparatorFactory | undefined {
478
534
  return this._sortComparatorFactory;
479
535
  }
@@ -507,7 +563,24 @@ export class ChannelPaginator extends BasePaginator<Channel, ChannelQueryShape>
507
563
  baseFilters: { ...this.effectiveFilters },
508
564
  });
509
565
 
566
+ /**
567
+ * Whether the list runs a `predefined_filter` query and holds neither a page nor the filter the
568
+ * server reported for it (`predefinedFilter`): its `staticFilters` do not say which channels it
569
+ * holds. A list holding items without that filter (loaded through `doRequest`, or from an offline
570
+ * cache stored without it) matches by `staticFilters`.
571
+ */
572
+ private get awaitsPredefinedFilter(): boolean {
573
+ return (
574
+ !!this._options?.predefined_filter && !this._predefinedFilter && !this.hasResults
575
+ );
576
+ }
577
+
578
+ /**
579
+ * Whether `channel` belongs to the list. Nothing does while a list with
580
+ * `options.predefined_filter` holds neither a page nor `predefinedFilter`.
581
+ */
510
582
  matchesFilter(channel: Channel): boolean {
583
+ if (this.awaitsPredefinedFilter) return false;
511
584
  const filters = this.buildMatchFilters();
512
585
 
513
586
  // Like `queryChannels`, exclude hidden channels unless the filter asks for them. Not a synthetic
@@ -638,6 +711,7 @@ export class ChannelPaginator extends BasePaginator<Channel, ChannelQueryShape>
638
711
  return undefined;
639
712
 
640
713
  const { stateOptions: _, ...request } = queryShape;
714
+ const checkWasStateResetDuringQuery = this.makeStateResetWatcher();
641
715
 
642
716
  try {
643
717
  const cachedQuery = await this.client.offlineDb.getChannelsForQuery({
@@ -645,7 +719,8 @@ export class ChannelPaginator extends BasePaginator<Channel, ChannelQueryShape>
645
719
  options: request,
646
720
  });
647
721
 
648
- if (cachedQuery) {
722
+ // the cache of a query started before a reset must not reach the list or the channel store
723
+ if (cachedQuery && !checkWasStateResetDuringQuery()) {
649
724
  if (cachedQuery.predefinedFilter) {
650
725
  this.applyPredefinedFilterResponse(cachedQuery.predefinedFilter);
651
726
  }
@@ -657,7 +732,8 @@ export class ChannelPaginator extends BasePaginator<Channel, ChannelQueryShape>
657
732
  }
658
733
  } catch (error) {
659
734
  chatLoggerSystem.getLogger('channel').error((error as Error).message);
660
- if (this.config.throwErrors) throw error;
735
+ // a query started before a reset reports nothing
736
+ if (this.config.throwErrors && !checkWasStateResetDuringQuery()) throw error;
661
737
  }
662
738
  return;
663
739
  };
@@ -717,6 +793,7 @@ export class ChannelPaginator extends BasePaginator<Channel, ChannelQueryShape>
717
793
  return;
718
794
  }
719
795
  this._queryAwaitingSync = queryShape;
796
+ const checkWasStateResetDuringQuery = this.makeStateResetWatcher();
720
797
 
721
798
  if (!this.isInitialized) {
722
799
  let cachedChannels: Channel[] | undefined;
@@ -729,6 +806,8 @@ export class ChannelPaginator extends BasePaginator<Channel, ChannelQueryShape>
729
806
  this._queryAwaitingSync = undefined;
730
807
  throw error;
731
808
  }
809
+ // the list's flags and loading state belong to the queries started since the reset
810
+ if (checkWasStateResetDuringQuery()) return;
732
811
  if (cachedChannels?.length) {
733
812
  // Seed via `setItems`, which ingests the page into the interval/index storage.
734
813
  // TODO: Maybe find a better way to do this rather than 2 partialNext invocations
@@ -770,6 +849,7 @@ export class ChannelPaginator extends BasePaginator<Channel, ChannelQueryShape>
770
849
  this._itemsLoadedFromOfflineDB = false;
771
850
  const queryShape = preparedQueryShape ?? this.getNextQueryShape();
772
851
  const { stateOptions, ...request } = queryShape;
852
+ const checkWasStateResetDuringQuery = this.makeStateResetWatcher();
773
853
  let items: Channel[];
774
854
  if (this.config.doRequest) {
775
855
  items = (await this.config.doRequest(queryShape)).items;
@@ -780,7 +860,10 @@ export class ChannelPaginator extends BasePaginator<Channel, ChannelQueryShape>
780
860
  withResponse: true,
781
861
  });
782
862
  items = response.channels;
783
- this._pendingPredefinedFilter = response.predefined_filter;
863
+ // the response of a query started before a reset describes no query the list runs
864
+ if (!checkWasStateResetDuringQuery()) {
865
+ this._pendingPredefinedFilter = response.predefined_filter;
866
+ }
784
867
  }
785
868
  return { items };
786
869
  };
@@ -954,11 +1037,22 @@ export class ChannelPaginator extends BasePaginator<Channel, ChannelQueryShape>
954
1037
  this.removeItem({ id, item: channel as Channel });
955
1038
  }
956
1039
 
1040
+ /**
1041
+ * Returns the list to "never queried": no channels, no loaded pages, no `predefinedFilter`, and
1042
+ * no record of queries in progress. A query running meanwhile is ignored; a debounced query
1043
+ * stays scheduled.
1044
+ */
957
1045
  resetState() {
958
- super.resetState();
959
- this._itemIndex.clear();
1046
+ // Cleared before `super.resetState()` notifies `paginator.state` subscribers: one may call
1047
+ // `toTail()` there, and clearing afterwards would wipe what that query set.
960
1048
  this._queryAwaitingSync = undefined;
961
1049
  this._tailQueryAwaitingRecovery = false;
1050
+ this._itemsLoadedFromOfflineDB = false;
1051
+ this._replaceOfflineSeedOnResponse = false;
1052
+ this._pendingPredefinedFilter = undefined;
1053
+ if (this._predefinedFilter) this.applyPredefinedFilterResponse(undefined);
1054
+ super.resetState();
1055
+ this._itemIndex.clear();
962
1056
  }
963
1057
 
964
1058
  removeItem(params: { id?: string; item?: Channel }): ItemCoordinates {
@@ -876,6 +876,7 @@ export class MessageIntervalPaginator extends BasePaginator<
876
876
  this.claimActiveInterval();
877
877
  this.showLoadedInterval(interval);
878
878
  } else {
879
+ const checkWasStateResetDuringQuery = this.makeStateResetWatcher();
879
880
  const result = await this.executeQuery({
880
881
  claimsActiveInterval: true,
881
882
  // Always send a limit: the replies endpoint ignores `id_around` without one.
@@ -885,6 +886,8 @@ export class MessageIntervalPaginator extends BasePaginator<
885
886
  });
886
887
  // a later claim decides the active interval, and the page stays stored
887
888
  if (result?.isSuperseded) return false;
889
+ // a reset ignored the query: not a failed jump
890
+ if (checkWasStateResetDuringQuery()) return false;
888
891
  localMessage = this.getItem(messageId);
889
892
  if (!localMessage || !result || !result.targetInterval) {
890
893
  this.channel.getClient().notifications.addError({
@@ -957,6 +960,7 @@ export class MessageIntervalPaginator extends BasePaginator<
957
960
  */
958
961
  jumpToTheLatestMessage = async (options?: JumpToMessageOptions): Promise<boolean> => {
959
962
  if (!this.latestHeadInterval) {
963
+ const checkWasStateResetDuringQuery = this.makeStateResetWatcher();
960
964
  const result = await this.executeQuery({
961
965
  claimsActiveInterval: true,
962
966
  queryShape: { limit: this.pageSize },
@@ -964,6 +968,8 @@ export class MessageIntervalPaginator extends BasePaginator<
964
968
  });
965
969
  // a later claim decides the active interval, and the page stays stored
966
970
  if (result?.isSuperseded) return false;
971
+ // a reset ignored the query: not a failed jump
972
+ if (checkWasStateResetDuringQuery()) return false;
967
973
  }
968
974
 
969
975
  const latestMessageId = this.latestHeadInterval?.itemIds.slice(-1)[0];
@@ -722,6 +722,7 @@ export class MessagePaginator extends MessageIntervalPaginator {
722
722
  });
723
723
 
724
724
  if (!inferredLastReadMessageId) {
725
+ const checkWasStateResetDuringQuery = this.makeStateResetWatcher();
725
726
  const result = await this.executeQuery({
726
727
  claimsActiveInterval: true,
727
728
  queryShape: {
@@ -733,6 +734,8 @@ export class MessagePaginator extends MessageIntervalPaginator {
733
734
  });
734
735
  // a later claim decides the active interval, and the page stays stored
735
736
  if (result?.isSuperseded) return false;
737
+ // a reset ignored the query: not a failed jump
738
+ if (checkWasStateResetDuringQuery()) return false;
736
739
  if (result) {
737
740
  ({
738
741
  firstUnreadMessageId: inferredFirstUnreadMessageId,
@@ -0,0 +1,30 @@
1
+ import type { ChannelResponse } from '../gen/models';
2
+
3
+ export const getCarriedActiveMemberCount = ({
4
+ next,
5
+ previous,
6
+ }: {
7
+ next: Partial<ChannelResponse>;
8
+ previous: Partial<ChannelResponse> | undefined;
9
+ }) => {
10
+ const { active_member_count: nextActiveMemberCount } = next;
11
+
12
+ const {
13
+ active_member_count: previousActiveMemberCount,
14
+ member_count: previousMemberCount,
15
+ } = previous ?? {};
16
+
17
+ const hasOwnActiveMemberCount = typeof nextActiveMemberCount === 'number';
18
+ const hasPreviousActiveMemberCount = typeof previousActiveMemberCount === 'number';
19
+ if (hasOwnActiveMemberCount || !hasPreviousActiveMemberCount) return undefined;
20
+
21
+ // Only Query Channels returns the count, so between queries shift the last known value
22
+ // by the change in member_count (an estimate, clamped to [0, member_count]).
23
+ const memberCount = next.member_count ?? previousMemberCount;
24
+ const delta =
25
+ typeof next.member_count === 'number' && typeof previousMemberCount === 'number'
26
+ ? next.member_count - previousMemberCount
27
+ : 0;
28
+ const shifted = Math.max(0, previousActiveMemberCount + delta);
29
+ return typeof memberCount === 'number' ? Math.min(shifted, memberCount) : shifted;
30
+ };