stream-chat 10.1.0 → 10.2.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.
@@ -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> = {
@@ -276,6 +280,12 @@ export type PaginatorState<T> = {
276
280
  hasMoreHead: boolean;
277
281
  hasMoreTail: boolean;
278
282
  isLoading: boolean;
283
+ /**
284
+ * The direction of the running query while it loads a page at an edge of the loaded items
285
+ * (`toHead()`, `toTail()`). `undefined` while no query runs, and for a query that loads no such
286
+ * page: a first page, a refresh, or a page at a query shape the caller gives (a jump).
287
+ */
288
+ loadingDirection?: PaginationDirection;
279
289
  items: T[] | undefined;
280
290
  lastQueryError?: Error;
281
291
  cursor?: PaginatorCursor;
@@ -527,6 +537,8 @@ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
527
537
  protected _itemIndex: ItemIndexApi<T>;
528
538
 
529
539
  protected _executeQueryDebounced!: DebouncedExecQueryFunction<Q>;
540
+ /** How many times `resetState()` ran, which tells the work started before a reset apart. */
541
+ private _stateResetCount = 0;
530
542
  /** Last effective query shape produced by the subclass for the most recent request. */
531
543
  protected _lastQueryShape?: Q;
532
544
  /** Set by `setItems`, which loads a page (even an empty one) without a query. */
@@ -600,6 +612,12 @@ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
600
612
  cursor: this.config.initialCursor,
601
613
  offset: this.config.initialOffset ?? 0,
602
614
  });
615
+ // A query has a loading direction only while it loads: every path that ends a query clears it.
616
+ this.state.addPreprocessor((next) => {
617
+ if (!next.isLoading && next.loadingDirection !== undefined) {
618
+ next.loadingDirection = undefined;
619
+ }
620
+ });
603
621
  // Called directly: `onChanged` fires on changes, not on the initial build.
604
622
  this.rebuildStatePublishThrottles(this.config.stateThrottleMs);
605
623
  this.intervalViews = new StateStore<PaginatorIntervalViews<T>>({
@@ -639,6 +657,11 @@ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
639
657
  return this.state.getLatestValue().isLoading;
640
658
  }
641
659
 
660
+ /** See {@link PaginatorState.loadingDirection}. */
661
+ get loadingDirection() {
662
+ return this.state.getLatestValue().loadingDirection;
663
+ }
664
+
642
665
  /**
643
666
  * True once a query has run or a non-empty interval was loaded without one (`setItems`, or a
644
667
  * subclass calling `recordLoadedIntervalQueryShape`). Cleared by `resetState`.
@@ -672,6 +695,7 @@ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
672
695
  hasMoreHead: true,
673
696
  hasMoreTail: true,
674
697
  isLoading: false,
698
+ loadingDirection: undefined,
675
699
  items: undefined,
676
700
  lastQueryError: undefined,
677
701
  cursor: this.config.initialCursor,
@@ -976,7 +1000,8 @@ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
976
1000
  /**
977
1001
  * The last step of the query pipeline (see {@link executeQuery}): applies what a response holds
978
1002
  * 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.
1003
+ * arrived, also when placing its page failed or a reset made it ignored (see
1004
+ * {@link executeQuery}). Does nothing by default.
980
1005
  */
981
1006
  protected applyQueryResponseRest(
982
1007
  _response: R,
@@ -2887,38 +2912,50 @@ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
2887
2912
 
2888
2913
  /**
2889
2914
  * {@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.
2915
+ * error is reported (see {@link reportFailedFetch}). After a `resetState()`
2916
+ * (`checkWasStateResetDuringQuery`), it stops retrying and returns `null` without reporting.
2893
2917
  */
2894
2918
  protected async fetchQueryResponseWithRetries(
2895
2919
  params: PaginationQueryParams<Q> = {},
2920
+ {
2921
+ checkWasStateResetDuringQuery = () => false,
2922
+ }: { checkWasStateResetDuringQuery?: () => boolean } = {},
2896
2923
  ): 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
- });
2924
+ let remainingRetries = params.retryCount ?? 0;
2925
+ while (true) {
2926
+ try {
2927
+ return await this.fetchQueryResponse({ ...params, retryCount: remainingRetries });
2928
+ } catch (e) {
2929
+ // the attempt belongs to the state the reset cleared, and so would a retry
2930
+ if (checkWasStateResetDuringQuery()) return null;
2931
+ if (remainingRetries > 0) {
2932
+ remainingRetries -= 1;
2933
+ await sleep(DEFAULT_QUERY_CHANNELS_MS_BETWEEN_RETRIES);
2934
+ if (checkWasStateResetDuringQuery()) return null;
2935
+ continue;
2936
+ }
2937
+ return this.reportFailedFetch(e as Error);
2907
2938
  }
2939
+ }
2940
+ }
2908
2941
 
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
- }
2942
+ /**
2943
+ * Handles a query whose attempts all failed: sets `lastQueryError` (unless offline support is on
2944
+ * and items are loaded). With `throwErrors`, ends loading and throws; otherwise returns `null`
2945
+ * and the caller ends the query.
2946
+ */
2947
+ private reportFailedFetch(e: Error): null {
2948
+ const isOfflineSupportEnabledWithItems =
2949
+ this.isOfflineSupportEnabled && (this.items ?? []).length > 0;
2950
+ if (!isOfflineSupportEnabledWithItems) {
2951
+ this.state.partialNext({ lastQueryError: e });
2952
+ }
2915
2953
 
2916
- if (this.config.throwErrors) {
2917
- this.state.partialNext({ isLoading: false });
2918
- throw e;
2919
- }
2920
- return null;
2954
+ if (this.config.throwErrors) {
2955
+ this.state.partialNext({ isLoading: false });
2956
+ throw e;
2921
2957
  }
2958
+ return null;
2922
2959
  }
2923
2960
 
2924
2961
  /**
@@ -2937,9 +2974,13 @@ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
2937
2974
  * as `lastQueryError` (a failed fetch not while offline support is on and items are loaded), and
2938
2975
  * rejects the call only with `throwErrors` set.
2939
2976
  *
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`.
2977
+ * If `resetState()` runs while the query runs, the query is ignored: it places no page, records
2978
+ * no error and throws nothing, also with `throwErrors`. The queries started after the reset own
2979
+ * the state. Its response's other data is still applied ({@link applyQueryResponseRest}).
2980
+ *
2981
+ * Resolves to `undefined` when the query cannot run now (see {@link canExecuteQuery}) or its
2982
+ * results were ignored, and to what the placing step returned otherwise, whose `targetInterval`
2983
+ * is `null` when no page was placed, with `isSuperseded`.
2943
2984
  *
2944
2985
  * @param params - Query parameters.
2945
2986
  * @param params.claimsActiveInterval - Whether the query claims the active interval.
@@ -2971,10 +3012,18 @@ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
2971
3012
  fetchParams,
2972
3013
  offlinePreloadPromise,
2973
3014
  placeParams,
3015
+ checkWasStateResetDuringQuery,
2974
3016
  }: PreparedQuery<Q>): Promise<ExecuteQueryReturnValue<T> | undefined> {
2975
3017
  if (offlinePreloadPromise) await offlinePreloadPromise;
3018
+ if (checkWasStateResetDuringQuery()) return undefined;
2976
3019
 
2977
- const response = await this.fetchQueryResponseWithRetries(fetchParams);
3020
+ const response = await this.fetchQueryResponseWithRetries(fetchParams, {
3021
+ checkWasStateResetDuringQuery,
3022
+ });
3023
+ if (checkWasStateResetDuringQuery()) {
3024
+ if (response !== null) this.applyResponseRestOfIgnoredQuery(response, placeParams);
3025
+ return undefined;
3026
+ }
2978
3027
  if (response === null) return this.placeQueryPage({ ...placeParams, results: null });
2979
3028
 
2980
3029
  // Every step after the fetch runs, whichever fails: the rest of a response that arrived is
@@ -2997,6 +3046,21 @@ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
2997
3046
  return errors.length > 0 ? this.reportQueryError(errors[0], placed) : placed;
2998
3047
  }
2999
3048
 
3049
+ /**
3050
+ * {@link applyQueryResponseRest} for a query a reset made ignored (see {@link executeQuery}).
3051
+ * An ignored query reports nothing, so an error here is swallowed.
3052
+ */
3053
+ private applyResponseRestOfIgnoredQuery(
3054
+ response: R,
3055
+ placeParams: QueryPagePlacement<Q>,
3056
+ ) {
3057
+ try {
3058
+ this.applyQueryResponseRest(response, placeParams);
3059
+ } catch {
3060
+ // reported neither in the state nor to the caller
3061
+ }
3062
+ }
3063
+
3000
3064
  /**
3001
3065
  * Ends a query whose step after the fetch failed: records the error as `lastQueryError` and
3002
3066
  * throws it with `throwErrors` set (see {@link executeQuery}). Otherwise returns what the query
@@ -3015,6 +3079,15 @@ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
3015
3079
  };
3016
3080
  }
3017
3081
 
3082
+ /**
3083
+ * Returns a function telling whether `resetState()` ran since this call. Work started before a
3084
+ * reset uses it to ignore its results instead of writing them into the reset state.
3085
+ */
3086
+ protected makeStateResetWatcher(): () => boolean {
3087
+ const resetCount = this._stateResetCount;
3088
+ return () => resetCount !== this._stateResetCount;
3089
+ }
3090
+
3018
3091
  /**
3019
3092
  * Whether a query claims the active interval by default (see
3020
3093
  * `PaginationQueryParams.claimsActiveInterval`, which overrides it):
@@ -3050,6 +3123,7 @@ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
3050
3123
  updateState = true,
3051
3124
  }: PaginationQueryParams<Q>): PreparedQuery<Q> | undefined {
3052
3125
  if (!this.canExecuteQuery({ direction, reset })) return undefined;
3126
+ const checkWasStateResetDuringQuery = this.makeStateResetWatcher();
3053
3127
  const claims =
3054
3128
  claimsActiveInterval ??
3055
3129
  this.decidesActiveInterval({ queryShape: forcedQueryShape, reset, updateState });
@@ -3106,19 +3180,31 @@ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
3106
3180
  publishStateBeforeFirstQuery(undefined);
3107
3181
  } else {
3108
3182
  offlinePreloadPromise = (async () => {
3109
- const items = await this.preloadFirstPageFromOfflineDb({
3110
- direction,
3111
- queryShape,
3112
- reset,
3113
- retryCount,
3114
- });
3183
+ let items: T[] | undefined;
3184
+ try {
3185
+ items = await this.preloadFirstPageFromOfflineDb({
3186
+ direction,
3187
+ queryShape,
3188
+ reset,
3189
+ retryCount,
3190
+ });
3191
+ } catch (error) {
3192
+ if (checkWasStateResetDuringQuery()) return;
3193
+ throw error;
3194
+ }
3195
+ if (checkWasStateResetDuringQuery()) return;
3115
3196
  publishStateBeforeFirstQuery(items ?? stateBeforeFirstQuery.items);
3116
3197
  })();
3117
3198
  }
3118
3199
  } else if (!silent) {
3119
3200
  // A next page, or a refresh keeping the items: loading shows without blanking the list, and
3120
- // the page merges into the loaded intervals in `placeQueryPage`.
3121
- this.state.partialNext({ isLoading: true });
3201
+ // the page merges into the loaded intervals in `placeQueryPage`. Only a next page loads at an
3202
+ // edge of the loaded items; a page at the caller's shape has no known place.
3203
+ const loadsAtEdge = !isFirstPage && !forcedQueryShape;
3204
+ this.state.partialNext({
3205
+ isLoading: true,
3206
+ loadingDirection: loadsAtEdge ? direction : undefined,
3207
+ });
3122
3208
  }
3123
3209
 
3124
3210
  // a page at the caller's shape has no known place relative to the active interval
@@ -3140,6 +3226,7 @@ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
3140
3226
  requestedPageSize: this.getRequestedPageSize(queryShape),
3141
3227
  updateState,
3142
3228
  },
3229
+ checkWasStateResetDuringQuery,
3143
3230
  };
3144
3231
  }
3145
3232
 
@@ -3189,6 +3276,55 @@ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
3189
3276
  );
3190
3277
  }
3191
3278
 
3279
+ /**
3280
+ * Whether an empty page (from the server or after `filterQueryResults`) keeps the loaded items
3281
+ * instead of blanking them: on a `keepPreviousItems` refresh or a next page, when `items` is
3282
+ * defined (`hasResults`). With `items` undefined there is nothing to keep, so the page sets `[]`.
3283
+ */
3284
+ private emptyPageKeepsLoadedItems({
3285
+ isFirstPage,
3286
+ keepPreviousItems,
3287
+ }: Pick<QueryPagePlacement<Q>, 'isFirstPage' | 'keepPreviousItems'>): boolean {
3288
+ return this.hasResults && (!!keepPreviousItems || !isFirstPage);
3289
+ }
3290
+
3291
+ /**
3292
+ * Whether placing a page publishes its whole state: with `updateState`, or when the paginator's
3293
+ * own `updateState: false` query settles a list without items
3294
+ * ({@link emptyPageSettlesListWithoutItems}). Otherwise {@link publishStoredPage} publishes only
3295
+ * what the stored page changed.
3296
+ */
3297
+ private commitsPlacedState(
3298
+ placement: QueryPagePlacement<Q>,
3299
+ page: T[],
3300
+ { endsQuery }: { endsQuery: boolean },
3301
+ ): boolean {
3302
+ return (
3303
+ placement.updateState !== false ||
3304
+ (endsQuery && this.emptyPageSettlesListWithoutItems(placement, page))
3305
+ );
3306
+ }
3307
+
3308
+ /**
3309
+ * Whether an empty, only-stored first page sets a list without items (`items` undefined) to
3310
+ * `[]`. Storing an empty page leaves nothing a later publish could show, so it is published now.
3311
+ * Not for a page at the caller's shape (`startsSeparateInterval`): it says nothing about the
3312
+ * list's own first page. Not for a superseded claim ({@link claimIsSuperseded}): the later claim
3313
+ * owns the list.
3314
+ */
3315
+ private emptyPageSettlesListWithoutItems(
3316
+ placement: QueryPagePlacement<Q>,
3317
+ page: T[],
3318
+ ): boolean {
3319
+ return (
3320
+ placement.isFirstPage &&
3321
+ page.length === 0 &&
3322
+ !this.hasResults &&
3323
+ !placement.startsSeparateInterval &&
3324
+ !this.claimIsSuperseded(placement)
3325
+ );
3326
+ }
3327
+
3192
3328
  /** Whether a claim on the active interval followed the query's own (`activeIntervalClaim`). */
3193
3329
  private claimIsSuperseded({ activeIntervalClaim }: QueryPagePlacement<Q>): boolean {
3194
3330
  return (
@@ -3213,7 +3349,10 @@ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
3213
3349
  * of the paginator's own queries may still be running.
3214
3350
  */
3215
3351
  protected placePage(
3216
- {
3352
+ placement: QueryPagePlacement<Q> & { results: PaginationQueryReturnValue<T> },
3353
+ { endsQuery }: { endsQuery: boolean },
3354
+ ): ExecuteQueryReturnValue<T> {
3355
+ const {
3217
3356
  startsSeparateInterval,
3218
3357
  direction,
3219
3358
  isFirstPage,
@@ -3222,9 +3361,7 @@ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
3222
3361
  requestedPageSize,
3223
3362
  results,
3224
3363
  updateState = true,
3225
- }: QueryPagePlacement<Q> & { results: PaginationQueryReturnValue<T> },
3226
- { endsQuery }: { endsQuery: boolean },
3227
- ): ExecuteQueryReturnValue<T> {
3364
+ } = placement;
3228
3365
  const stateUpdate: Partial<PaginatorState<T>> = endsQuery
3229
3366
  ? { isLoading: false, lastQueryError: undefined }
3230
3367
  : {};
@@ -3280,11 +3417,9 @@ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
3280
3417
  } else if (
3281
3418
  updateState &&
3282
3419
  !filteredItems.length &&
3283
- (keepPreviousItems || !isFirstPage)
3420
+ this.emptyPageKeepsLoadedItems({ isFirstPage, keepPreviousItems })
3284
3421
  ) {
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.
3422
+ // `ingestPage` returns no interval for an empty page, so the loaded items are carried over.
3288
3423
  stateUpdate.items = this.items;
3289
3424
  }
3290
3425
 
@@ -3423,10 +3558,11 @@ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
3423
3558
  const state = endsQuery
3424
3559
  ? this.getStateAfterQuery(stateUpdate, isFirstPage)
3425
3560
  : { ...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 });
3561
+ // Committing the results is `commitsPlacedState`'s call; ending the query is not: an
3562
+ // uncommitted page still clears the `isLoading` that `executeQuery` published.
3563
+ if (this.commitsPlacedState(placement, filteredItems, { endsQuery })) {
3564
+ this.state.next(state);
3565
+ } else this.publishStoredPage({ endsQuery, interval, state });
3430
3566
  // Only the first page of the paginator's own query is cached; a later page cannot change it.
3431
3567
  if (endsQuery && isFirstPage) {
3432
3568
  this.populateOfflineDbAfterQuery({ items: state.items, queryShape });
@@ -3465,7 +3601,12 @@ export abstract class BasePaginator<T, Q, R = PaginationQueryReturnValue<T>> {
3465
3601
  this._executeQueryDebounced.cancel();
3466
3602
  }
3467
3603
 
3604
+ /**
3605
+ * Returns the paginator to "never queried" (`items: undefined`). A query running meanwhile is
3606
+ * ignored (see {@link executeQuery}); a debounced query stays scheduled.
3607
+ */
3468
3608
  resetState() {
3609
+ this._stateResetCount++;
3469
3610
  // Nothing is loaded, so the next query is a first page again. A stale shape would make a
3470
3611
  // re-query with an unchanged shape a continuation, ingested without `isHead`. Cleared before
3471
3612
  // 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 {