@koolbase/core 12.26.0 → 12.28.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.
@@ -1,5 +1,5 @@
1
1
  import type { KoolbaseDatabase } from './database.js';
2
- import type { KoolbaseRecord } from './types.js';
2
+ import type { FieldSearch, KoolbaseRecord } from './types.js';
3
3
  export type CollectionStatus = 'loading' | 'loaded' | 'error';
4
4
  /** What to read. Equality only: each `where` entry is field = literal value. */
5
5
  export interface CollectionQuery {
@@ -16,6 +16,14 @@ export interface CollectionQuery {
16
16
  * in, and goes live then.
17
17
  */
18
18
  live?: boolean;
19
+ /**
20
+ * A search over the fields it names, on the server (#160): the first load
21
+ * is of its matches. Not part of the query's identity -- change it with
22
+ * setSearch(), which keeps the controller and what it shows.
23
+ */
24
+ search?: FieldSearch | null;
25
+ /** How long setSearch() waits for the typing to pause. 250 ms. */
26
+ searchDelayMs?: number;
19
27
  }
20
28
  export interface CollectionState {
21
29
  readonly status: CollectionStatus;
@@ -30,6 +38,23 @@ export interface CollectionState {
30
38
  readonly loadingMore: boolean;
31
39
  /** Whether the server has rows past the last page loaded. True before the first load. */
32
40
  readonly hasMore: boolean;
41
+ /**
42
+ * True from setSearch() until the server answers it (#160). The records
43
+ * shown meanwhile are from before the search: what an app filters from
44
+ * them is a preview, not the answer.
45
+ */
46
+ readonly searching: boolean;
47
+ /** Why the server could not answer the latest search, or null. The records are not its answer. */
48
+ readonly searchError: unknown;
49
+ /**
50
+ * True while the search is not run on the server, so the records are the
51
+ * list unsearched and an app filters them itself: the server refused this
52
+ * list's search (a field_search it will not take -- the collection's
53
+ * fields changed since the app was built; it is not asked again while
54
+ * this controller lives), or the search is wider than the server takes
55
+ * (a Choice matching more than 100 values, text over 100 characters).
56
+ */
57
+ readonly searchLoadedOnly: boolean;
33
58
  }
34
59
  export declare const initialCollectionState: CollectionState;
35
60
  /** One string per distinct query, whatever the order of its `where` keys. */
@@ -49,7 +74,30 @@ export declare class KoolbaseCollectionController {
49
74
  private unregister;
50
75
  private unlive;
51
76
  private liveTimer;
77
+ private search;
78
+ private searchTimer;
79
+ private searchRefused;
80
+ private answered;
81
+ private refreshToken;
52
82
  constructor(db: QueryReader, collection: string, query?: CollectionQuery);
83
+ /** The search the server runs: none when it is refused or too wide. */
84
+ private serverSearch;
85
+ private loadedOnly;
86
+ /**
87
+ * Search on the server (#160), once the typing pauses (searchDelayMs): page
88
+ * one of the matches replaces what is shown, never merged with it, and
89
+ * paging continues inside the search. A newer search, or a refresh, drops
90
+ * an older one's answer. Null or empty text: the list unsearched again.
91
+ * Until the server answers, `searching` is true; if it cannot,
92
+ * `searchError` says why and the records shown are not its answer.
93
+ */
94
+ setSearch(search?: FieldSearch | null): void;
95
+ private runSearch;
96
+ /**
97
+ * After the server refused the search: it is not sent again while this
98
+ * controller lives, and the list is read unsearched for the app to filter.
99
+ */
100
+ private refuse;
53
101
  getState(): CollectionState;
54
102
  /** Called on every change. Returns the unsubscribe. */
55
103
  subscribe(listener: () => void): () => void;
@@ -27,6 +27,7 @@ exports.KoolbaseCollectionController = exports.initialCollectionState = void 0;
27
27
  exports.collectionQueryKey = collectionQueryKey;
28
28
  const live_source_js_1 = require("./live-source.js");
29
29
  const query_refresh_js_1 = require("./query-refresh.js");
30
+ const errors_js_1 = require("./errors.js");
30
31
  exports.initialCollectionState = Object.freeze({
31
32
  status: 'loading',
32
33
  records: Object.freeze([]),
@@ -35,7 +36,31 @@ exports.initialCollectionState = Object.freeze({
35
36
  refreshing: false,
36
37
  loadingMore: false,
37
38
  hasMore: true,
39
+ searching: false,
40
+ searchError: null,
41
+ searchLoadedOnly: false,
38
42
  });
43
+ /** A search with text to search, or null: none. */
44
+ function normalizedSearch(search) {
45
+ if (!search || search.text.trim() === '')
46
+ return null;
47
+ return {
48
+ text: search.text.trim(),
49
+ fields: [...(search.fields ?? [])],
50
+ choices: (search.choices ?? []).map((c) => ({ field: c.field, values: [...c.values], listed: [...c.listed] })),
51
+ };
52
+ }
53
+ /** The server's limits on a search (#160): past them it refuses it. */
54
+ const SEARCH_MAX_TEXT = 100;
55
+ const SEARCH_MAX_VALUES = 100;
56
+ /** A search the server takes, by its size: text and each Choice's matching values. */
57
+ function withinServerLimits(search) {
58
+ return Array.from(search.text).length <= SEARCH_MAX_TEXT && (search.choices ?? []).every((c) => c.values.length <= SEARCH_MAX_VALUES);
59
+ }
60
+ /** The server refusing a field_search (400): this search, as sent, will never be answered. */
61
+ function isSearchRefusal(error) {
62
+ return error instanceof errors_js_1.KoolbaseError && error.message.startsWith('field_search:');
63
+ }
39
64
  function sortedWhere(where) {
40
65
  const out = {};
41
66
  for (const key of Object.keys(where ?? {}).sort())
@@ -82,9 +107,98 @@ class KoolbaseCollectionController {
82
107
  // A live list's realtime subscription, and its pending debounced re-read.
83
108
  this.unlive = null;
84
109
  this.liveTimer = null;
110
+ this.searchTimer = null;
111
+ // The server refused this list's search: it is not asked again.
112
+ this.searchRefused = false;
113
+ // The latest refresh(): only it ends `refreshing`.
114
+ this.refreshToken = 0;
85
115
  this.db = db;
86
116
  this.collection = collection;
87
117
  this.spec = query;
118
+ this.search = normalizedSearch(query.search);
119
+ this.state = Object.freeze({ ...this.state, searchLoadedOnly: this.loadedOnly() });
120
+ }
121
+ /** The search the server runs: none when it is refused or too wide. */
122
+ serverSearch() {
123
+ return this.search && !this.searchRefused && withinServerLimits(this.search) ? this.search : null;
124
+ }
125
+ loadedOnly() {
126
+ return this.search !== null && this.serverSearch() === null;
127
+ }
128
+ /**
129
+ * Search on the server (#160), once the typing pauses (searchDelayMs): page
130
+ * one of the matches replaces what is shown, never merged with it, and
131
+ * paging continues inside the search. A newer search, or a refresh, drops
132
+ * an older one's answer. Null or empty text: the list unsearched again.
133
+ * Until the server answers, `searching` is true; if it cannot,
134
+ * `searchError` says why and the records shown are not its answer.
135
+ */
136
+ setSearch(search) {
137
+ if (this.disposed)
138
+ return;
139
+ const next = normalizedSearch(search);
140
+ if (JSON.stringify(next) === JSON.stringify(this.search))
141
+ return;
142
+ this.search = next;
143
+ // What is shown already answers the server's search (both not sent, say):
144
+ // nothing to read again, and nothing still waiting is wanted.
145
+ if (this.answered !== undefined && JSON.stringify(this.serverSearch()) === this.answered && this.state.status === 'loaded') {
146
+ if (this.searchTimer) {
147
+ clearTimeout(this.searchTimer);
148
+ this.searchTimer = null;
149
+ }
150
+ this.generation++;
151
+ this.set({ searching: false, searchError: null, loadingMore: false, searchLoadedOnly: this.loadedOnly() });
152
+ return;
153
+ }
154
+ // Whatever is in flight was for the old search.
155
+ this.generation++;
156
+ if (this.searchTimer)
157
+ clearTimeout(this.searchTimer);
158
+ this.set({ searching: true, searchError: null, loadingMore: false, searchLoadedOnly: this.loadedOnly() });
159
+ this.searchTimer = setTimeout(() => {
160
+ this.searchTimer = null;
161
+ void this.runSearch();
162
+ }, this.spec.searchDelayMs ?? 250);
163
+ this.searchTimer.unref?.();
164
+ }
165
+ async runSearch() {
166
+ if (this.disposed)
167
+ return;
168
+ const gen = ++this.generation;
169
+ if (this.state.loadingMore)
170
+ this.set({ loadingMore: false });
171
+ const asking = JSON.stringify(this.serverSearch());
172
+ try {
173
+ const result = await this.db.query(this.collection, this.options(0, 'network-only'));
174
+ if (this.isStale(gen))
175
+ return;
176
+ this.answered = asking;
177
+ this.showPageOne(result, false, false);
178
+ this.set({ searching: false, searchError: null });
179
+ }
180
+ catch (error) {
181
+ if (this.isStale(gen))
182
+ return;
183
+ if (this.refuse(error))
184
+ return;
185
+ // Nothing loaded yet to show under it: the list's own error.
186
+ this.set(this.state.status === 'loaded'
187
+ ? { searching: false, searchError: error }
188
+ : { searching: false, searchError: error, status: 'error', error });
189
+ }
190
+ }
191
+ /**
192
+ * After the server refused the search: it is not sent again while this
193
+ * controller lives, and the list is read unsearched for the app to filter.
194
+ */
195
+ refuse(error) {
196
+ if (!isSearchRefusal(error) || this.serverSearch() === null)
197
+ return false;
198
+ this.searchRefused = true;
199
+ this.set({ searching: true, searchError: null, searchLoadedOnly: true });
200
+ void this.runSearch();
201
+ return true;
88
202
  }
89
203
  getState() {
90
204
  return this.state;
@@ -112,9 +226,11 @@ class KoolbaseCollectionController {
112
226
  async refresh() {
113
227
  if (this.disposed)
114
228
  return;
229
+ const token = ++this.refreshToken;
115
230
  this.set({ refreshing: true });
116
- const gen = await this.firstPage('network-only');
117
- if (!this.isStale(gen))
231
+ await this.firstPage('network-only');
232
+ // Ended by the latest refresh, whatever superseded its read.
233
+ if (token === this.refreshToken)
118
234
  this.set({ refreshing: false });
119
235
  }
120
236
  /**
@@ -148,13 +264,15 @@ class KoolbaseCollectionController {
148
264
  */
149
265
  async loadMore() {
150
266
  const s = this.state;
151
- if (this.disposed || s.loadingMore || !s.hasMore || s.status !== 'loaded')
267
+ // Not while a search waits for its answer (#160): the next page of the
268
+ // records shown is not the next page of the search.
269
+ if (this.disposed || s.loadingMore || s.searching || !s.hasMore || s.status !== 'loaded')
152
270
  return;
153
271
  const gen = this.generation;
154
272
  const offset = this.nextOffset;
155
273
  this.set({ loadingMore: true });
156
274
  try {
157
- const result = await this.db.query(this.collection, this.options(offset, 'default'));
275
+ const result = await this.db.query(this.collection, this.options(offset, this.serverSearch() ? 'network-only' : 'default'));
158
276
  if (this.isStale(gen))
159
277
  return;
160
278
  this.laterPages = [...this.laterPages, ...result.records];
@@ -163,8 +281,11 @@ class KoolbaseCollectionController {
163
281
  const total = result.records.length === 0 ? this.nextOffset : result.total;
164
282
  this.publish({}, total);
165
283
  }
166
- catch {
167
- // Keep what is shown; the caller can try again.
284
+ catch (error) {
285
+ // Refused (the schema changed since): the list unsearched. Otherwise
286
+ // keep what is shown; the caller can try again.
287
+ if (!this.isStale(gen))
288
+ this.refuse(error);
168
289
  }
169
290
  finally {
170
291
  if (!this.isStale(gen))
@@ -182,6 +303,10 @@ class KoolbaseCollectionController {
182
303
  clearTimeout(this.liveTimer);
183
304
  this.liveTimer = null;
184
305
  }
306
+ if (this.searchTimer) {
307
+ clearTimeout(this.searchTimer);
308
+ this.searchTimer = null;
309
+ }
185
310
  this.listeners.clear();
186
311
  }
187
312
  async firstPage(cache) {
@@ -190,15 +315,37 @@ class KoolbaseCollectionController {
190
315
  // will not clear its own flag.
191
316
  if (this.state.loadingMore)
192
317
  this.set({ loadingMore: false });
318
+ const asking = JSON.stringify(this.serverSearch());
193
319
  try {
194
- const result = await this.db.query(this.collection, this.options(0, cache, (fresh) => {
195
- if (!this.isStale(gen))
320
+ const result = await this.db.query(this.collection,
321
+ // A search's answer is the server's, never a cached one (#160).
322
+ this.options(0, this.serverSearch() ? 'network-only' : cache, (fresh) => {
323
+ if (!this.isStale(gen)) {
324
+ this.answered = asking;
196
325
  this.showPageOne(fresh, false, true);
326
+ }
197
327
  }));
198
- if (!this.isStale(gen))
328
+ if (!this.isStale(gen)) {
329
+ this.answered = asking;
199
330
  this.showPageOne(result, result.isFromCache === true, false);
331
+ // A search this fetch superseded is answered by it -- unless a newer
332
+ // one is still waiting for the typing to pause.
333
+ if (!this.searchTimer && (this.state.searching || this.state.searchError !== null)) {
334
+ this.set({ searching: false, searchError: null });
335
+ }
336
+ }
200
337
  }
201
338
  catch (error) {
339
+ // The server refused the search: read unsearched, at once -- the
340
+ // generation this returns is that read's, so refresh() ends with it.
341
+ if (!this.isStale(gen) && isSearchRefusal(error) && this.serverSearch() !== null) {
342
+ this.searchRefused = true;
343
+ this.set({ searchError: null, searchLoadedOnly: true });
344
+ return this.firstPage(cache);
345
+ }
346
+ if (!this.isStale(gen) && this.state.searching && !this.searchTimer) {
347
+ this.set({ searching: false, searchError: error });
348
+ }
202
349
  if (!this.isStale(gen) && this.state.records.length === 0) {
203
350
  this.set({ status: 'error', error });
204
351
  }
@@ -231,6 +378,7 @@ class KoolbaseCollectionController {
231
378
  offset,
232
379
  orderBy: this.spec.orderBy,
233
380
  orderDesc: this.spec.orderDesc,
381
+ ...(this.serverSearch() ? { fieldSearch: this.serverSearch() } : {}),
234
382
  cache,
235
383
  onRefresh,
236
384
  };
@@ -170,6 +170,16 @@ class KoolbaseDatabase {
170
170
  order_by: options.orderBy,
171
171
  order_desc: options.orderDesc ?? false,
172
172
  populate: options.populate ?? [],
173
+ // #160: only with text to search; the server checks the rest.
174
+ ...(options.fieldSearch && options.fieldSearch.text.trim() !== ''
175
+ ? {
176
+ field_search: {
177
+ text: options.fieldSearch.text,
178
+ fields: options.fieldSearch.fields ?? [],
179
+ choices: options.fieldSearch.choices ?? [],
180
+ },
181
+ }
182
+ : {}),
173
183
  });
174
184
  const records = raw.records.map(record_js_1.recordFromWire);
175
185
  // Individually, as well as under the query key. The query cache answers
@@ -211,6 +221,12 @@ class KoolbaseDatabase {
211
221
  // who to tell, not what to read, so it stays out the same way.
212
222
  const { cache: cachePolicy, onRefresh, ...queryOptions } = options;
213
223
  const queryHash = (0, cache_store_js_3.hashQuery)(collection, queryOptions);
224
+ // A search's answer is the server's (#160): never served from the cache,
225
+ // and not kept there -- one entry per search typed would pile up.
226
+ if (queryOptions.fieldSearch && queryOptions.fieldSearch.text.trim() !== '') {
227
+ const result = await this.runQuery(collection, queryOptions);
228
+ return { ...result, isFromCache: false };
229
+ }
214
230
  const cached = cachePolicy === 'network-only' ? null : await (0, cache_store_js_3.getCached)(userId, collection, queryHash);
215
231
  if (cached) {
216
232
  this.runQuery(collection, queryOptions)
@@ -32,6 +32,13 @@ function createUseCollection(getDb) {
32
32
  const subscribe = (0, react_1.useCallback)((onChange) => (controller ? controller.subscribe(onChange) : noop), [controller]);
33
33
  const getSnapshot = (0, react_1.useCallback)(() => (controller ? controller.getState() : index_js_1.initialCollectionState), [controller]);
34
34
  const state = (0, react_1.useSyncExternalStore)(subscribe, getSnapshot, getSnapshot);
35
+ // The search (#160) is not the query's identity: changing it keeps the
36
+ // controller, and what it shows, and searches after a pause.
37
+ const searchKey = JSON.stringify(query.search ?? null);
38
+ (0, react_1.useEffect)(() => {
39
+ controller?.setSearch(query.search ?? null);
40
+ // Depends on the search as a value, not the object.
41
+ }, [controller, searchKey]);
35
42
  const refresh = (0, react_1.useCallback)(() => (controller ? controller.refresh() : done()), [controller]);
36
43
  const loadMore = (0, react_1.useCallback)(() => (controller ? controller.loadMore() : done()), [controller]);
37
44
  return { ...state, refresh, loadMore };
@@ -262,6 +262,30 @@ export interface KoolbaseRecord {
262
262
  */
263
263
  revision?: number;
264
264
  }
265
+ /**
266
+ * A search over the fields it names, on the server (#160): records whose
267
+ * text fields contain `text`, ignoring case, inside the read rule and the
268
+ * filters and before the page -- so `total` and every page are of the
269
+ * matches. A Choice field is searched by its labels: `values` are the stored
270
+ * values whose label contains the text, `listed` every value the field
271
+ * declares (the server checks both against the declaration); a stored value
272
+ * not declared matches as itself. Empty `text` is no search.
273
+ */
274
+ export interface FieldSearch {
275
+ text: string;
276
+ /** Declared Text or Long text fields (any field, on a collection that declares none). */
277
+ fields?: string[];
278
+ /** Declared Choice fields, by their labels. */
279
+ choices?: ChoiceSearch[];
280
+ }
281
+ /** One Choice field in a [FieldSearch]. */
282
+ export interface ChoiceSearch {
283
+ field: string;
284
+ /** The stored values whose label contains the search text. */
285
+ values: string[];
286
+ /** Every value the field declares. */
287
+ listed: string[];
288
+ }
265
289
  export interface QueryOptions {
266
290
  filters?: Record<string, unknown>;
267
291
  limit?: number;
@@ -269,6 +293,8 @@ export interface QueryOptions {
269
293
  orderBy?: string;
270
294
  orderDesc?: boolean;
271
295
  populate?: string[];
296
+ /** A search over the fields it names, on the server (#160). Empty text: none. */
297
+ fieldSearch?: FieldSearch;
272
298
  /**
273
299
  * How to read: 'default' is cache-first, refreshed in the background;
274
300
  * 'network-only' skips the cache and waits for the server (the result still
@@ -1,5 +1,5 @@
1
1
  import type { KoolbaseDatabase } from './database.js';
2
- import type { KoolbaseRecord } from './types.js';
2
+ import type { FieldSearch, KoolbaseRecord } from './types.js';
3
3
  export type CollectionStatus = 'loading' | 'loaded' | 'error';
4
4
  /** What to read. Equality only: each `where` entry is field = literal value. */
5
5
  export interface CollectionQuery {
@@ -16,6 +16,14 @@ export interface CollectionQuery {
16
16
  * in, and goes live then.
17
17
  */
18
18
  live?: boolean;
19
+ /**
20
+ * A search over the fields it names, on the server (#160): the first load
21
+ * is of its matches. Not part of the query's identity -- change it with
22
+ * setSearch(), which keeps the controller and what it shows.
23
+ */
24
+ search?: FieldSearch | null;
25
+ /** How long setSearch() waits for the typing to pause. 250 ms. */
26
+ searchDelayMs?: number;
19
27
  }
20
28
  export interface CollectionState {
21
29
  readonly status: CollectionStatus;
@@ -30,6 +38,23 @@ export interface CollectionState {
30
38
  readonly loadingMore: boolean;
31
39
  /** Whether the server has rows past the last page loaded. True before the first load. */
32
40
  readonly hasMore: boolean;
41
+ /**
42
+ * True from setSearch() until the server answers it (#160). The records
43
+ * shown meanwhile are from before the search: what an app filters from
44
+ * them is a preview, not the answer.
45
+ */
46
+ readonly searching: boolean;
47
+ /** Why the server could not answer the latest search, or null. The records are not its answer. */
48
+ readonly searchError: unknown;
49
+ /**
50
+ * True while the search is not run on the server, so the records are the
51
+ * list unsearched and an app filters them itself: the server refused this
52
+ * list's search (a field_search it will not take -- the collection's
53
+ * fields changed since the app was built; it is not asked again while
54
+ * this controller lives), or the search is wider than the server takes
55
+ * (a Choice matching more than 100 values, text over 100 characters).
56
+ */
57
+ readonly searchLoadedOnly: boolean;
33
58
  }
34
59
  export declare const initialCollectionState: CollectionState;
35
60
  /** One string per distinct query, whatever the order of its `where` keys. */
@@ -49,7 +74,30 @@ export declare class KoolbaseCollectionController {
49
74
  private unregister;
50
75
  private unlive;
51
76
  private liveTimer;
77
+ private search;
78
+ private searchTimer;
79
+ private searchRefused;
80
+ private answered;
81
+ private refreshToken;
52
82
  constructor(db: QueryReader, collection: string, query?: CollectionQuery);
83
+ /** The search the server runs: none when it is refused or too wide. */
84
+ private serverSearch;
85
+ private loadedOnly;
86
+ /**
87
+ * Search on the server (#160), once the typing pauses (searchDelayMs): page
88
+ * one of the matches replaces what is shown, never merged with it, and
89
+ * paging continues inside the search. A newer search, or a refresh, drops
90
+ * an older one's answer. Null or empty text: the list unsearched again.
91
+ * Until the server answers, `searching` is true; if it cannot,
92
+ * `searchError` says why and the records shown are not its answer.
93
+ */
94
+ setSearch(search?: FieldSearch | null): void;
95
+ private runSearch;
96
+ /**
97
+ * After the server refused the search: it is not sent again while this
98
+ * controller lives, and the list is read unsearched for the app to filter.
99
+ */
100
+ private refuse;
53
101
  getState(): CollectionState;
54
102
  /** Called on every change. Returns the unsubscribe. */
55
103
  subscribe(listener: () => void): () => void;
@@ -23,6 +23,7 @@
23
23
  // from page one. Duplicates are removed; a skipped row cannot be detected.
24
24
  import { liveSource } from './live-source.js';
25
25
  import { registerQueryRefresher } from './query-refresh.js';
26
+ import { KoolbaseError } from './errors.js';
26
27
  export const initialCollectionState = Object.freeze({
27
28
  status: 'loading',
28
29
  records: Object.freeze([]),
@@ -31,7 +32,31 @@ export const initialCollectionState = Object.freeze({
31
32
  refreshing: false,
32
33
  loadingMore: false,
33
34
  hasMore: true,
35
+ searching: false,
36
+ searchError: null,
37
+ searchLoadedOnly: false,
34
38
  });
39
+ /** A search with text to search, or null: none. */
40
+ function normalizedSearch(search) {
41
+ if (!search || search.text.trim() === '')
42
+ return null;
43
+ return {
44
+ text: search.text.trim(),
45
+ fields: [...(search.fields ?? [])],
46
+ choices: (search.choices ?? []).map((c) => ({ field: c.field, values: [...c.values], listed: [...c.listed] })),
47
+ };
48
+ }
49
+ /** The server's limits on a search (#160): past them it refuses it. */
50
+ const SEARCH_MAX_TEXT = 100;
51
+ const SEARCH_MAX_VALUES = 100;
52
+ /** A search the server takes, by its size: text and each Choice's matching values. */
53
+ function withinServerLimits(search) {
54
+ return Array.from(search.text).length <= SEARCH_MAX_TEXT && (search.choices ?? []).every((c) => c.values.length <= SEARCH_MAX_VALUES);
55
+ }
56
+ /** The server refusing a field_search (400): this search, as sent, will never be answered. */
57
+ function isSearchRefusal(error) {
58
+ return error instanceof KoolbaseError && error.message.startsWith('field_search:');
59
+ }
35
60
  function sortedWhere(where) {
36
61
  const out = {};
37
62
  for (const key of Object.keys(where ?? {}).sort())
@@ -78,9 +103,98 @@ export class KoolbaseCollectionController {
78
103
  // A live list's realtime subscription, and its pending debounced re-read.
79
104
  this.unlive = null;
80
105
  this.liveTimer = null;
106
+ this.searchTimer = null;
107
+ // The server refused this list's search: it is not asked again.
108
+ this.searchRefused = false;
109
+ // The latest refresh(): only it ends `refreshing`.
110
+ this.refreshToken = 0;
81
111
  this.db = db;
82
112
  this.collection = collection;
83
113
  this.spec = query;
114
+ this.search = normalizedSearch(query.search);
115
+ this.state = Object.freeze({ ...this.state, searchLoadedOnly: this.loadedOnly() });
116
+ }
117
+ /** The search the server runs: none when it is refused or too wide. */
118
+ serverSearch() {
119
+ return this.search && !this.searchRefused && withinServerLimits(this.search) ? this.search : null;
120
+ }
121
+ loadedOnly() {
122
+ return this.search !== null && this.serverSearch() === null;
123
+ }
124
+ /**
125
+ * Search on the server (#160), once the typing pauses (searchDelayMs): page
126
+ * one of the matches replaces what is shown, never merged with it, and
127
+ * paging continues inside the search. A newer search, or a refresh, drops
128
+ * an older one's answer. Null or empty text: the list unsearched again.
129
+ * Until the server answers, `searching` is true; if it cannot,
130
+ * `searchError` says why and the records shown are not its answer.
131
+ */
132
+ setSearch(search) {
133
+ if (this.disposed)
134
+ return;
135
+ const next = normalizedSearch(search);
136
+ if (JSON.stringify(next) === JSON.stringify(this.search))
137
+ return;
138
+ this.search = next;
139
+ // What is shown already answers the server's search (both not sent, say):
140
+ // nothing to read again, and nothing still waiting is wanted.
141
+ if (this.answered !== undefined && JSON.stringify(this.serverSearch()) === this.answered && this.state.status === 'loaded') {
142
+ if (this.searchTimer) {
143
+ clearTimeout(this.searchTimer);
144
+ this.searchTimer = null;
145
+ }
146
+ this.generation++;
147
+ this.set({ searching: false, searchError: null, loadingMore: false, searchLoadedOnly: this.loadedOnly() });
148
+ return;
149
+ }
150
+ // Whatever is in flight was for the old search.
151
+ this.generation++;
152
+ if (this.searchTimer)
153
+ clearTimeout(this.searchTimer);
154
+ this.set({ searching: true, searchError: null, loadingMore: false, searchLoadedOnly: this.loadedOnly() });
155
+ this.searchTimer = setTimeout(() => {
156
+ this.searchTimer = null;
157
+ void this.runSearch();
158
+ }, this.spec.searchDelayMs ?? 250);
159
+ this.searchTimer.unref?.();
160
+ }
161
+ async runSearch() {
162
+ if (this.disposed)
163
+ return;
164
+ const gen = ++this.generation;
165
+ if (this.state.loadingMore)
166
+ this.set({ loadingMore: false });
167
+ const asking = JSON.stringify(this.serverSearch());
168
+ try {
169
+ const result = await this.db.query(this.collection, this.options(0, 'network-only'));
170
+ if (this.isStale(gen))
171
+ return;
172
+ this.answered = asking;
173
+ this.showPageOne(result, false, false);
174
+ this.set({ searching: false, searchError: null });
175
+ }
176
+ catch (error) {
177
+ if (this.isStale(gen))
178
+ return;
179
+ if (this.refuse(error))
180
+ return;
181
+ // Nothing loaded yet to show under it: the list's own error.
182
+ this.set(this.state.status === 'loaded'
183
+ ? { searching: false, searchError: error }
184
+ : { searching: false, searchError: error, status: 'error', error });
185
+ }
186
+ }
187
+ /**
188
+ * After the server refused the search: it is not sent again while this
189
+ * controller lives, and the list is read unsearched for the app to filter.
190
+ */
191
+ refuse(error) {
192
+ if (!isSearchRefusal(error) || this.serverSearch() === null)
193
+ return false;
194
+ this.searchRefused = true;
195
+ this.set({ searching: true, searchError: null, searchLoadedOnly: true });
196
+ void this.runSearch();
197
+ return true;
84
198
  }
85
199
  getState() {
86
200
  return this.state;
@@ -108,9 +222,11 @@ export class KoolbaseCollectionController {
108
222
  async refresh() {
109
223
  if (this.disposed)
110
224
  return;
225
+ const token = ++this.refreshToken;
111
226
  this.set({ refreshing: true });
112
- const gen = await this.firstPage('network-only');
113
- if (!this.isStale(gen))
227
+ await this.firstPage('network-only');
228
+ // Ended by the latest refresh, whatever superseded its read.
229
+ if (token === this.refreshToken)
114
230
  this.set({ refreshing: false });
115
231
  }
116
232
  /**
@@ -144,13 +260,15 @@ export class KoolbaseCollectionController {
144
260
  */
145
261
  async loadMore() {
146
262
  const s = this.state;
147
- if (this.disposed || s.loadingMore || !s.hasMore || s.status !== 'loaded')
263
+ // Not while a search waits for its answer (#160): the next page of the
264
+ // records shown is not the next page of the search.
265
+ if (this.disposed || s.loadingMore || s.searching || !s.hasMore || s.status !== 'loaded')
148
266
  return;
149
267
  const gen = this.generation;
150
268
  const offset = this.nextOffset;
151
269
  this.set({ loadingMore: true });
152
270
  try {
153
- const result = await this.db.query(this.collection, this.options(offset, 'default'));
271
+ const result = await this.db.query(this.collection, this.options(offset, this.serverSearch() ? 'network-only' : 'default'));
154
272
  if (this.isStale(gen))
155
273
  return;
156
274
  this.laterPages = [...this.laterPages, ...result.records];
@@ -159,8 +277,11 @@ export class KoolbaseCollectionController {
159
277
  const total = result.records.length === 0 ? this.nextOffset : result.total;
160
278
  this.publish({}, total);
161
279
  }
162
- catch {
163
- // Keep what is shown; the caller can try again.
280
+ catch (error) {
281
+ // Refused (the schema changed since): the list unsearched. Otherwise
282
+ // keep what is shown; the caller can try again.
283
+ if (!this.isStale(gen))
284
+ this.refuse(error);
164
285
  }
165
286
  finally {
166
287
  if (!this.isStale(gen))
@@ -178,6 +299,10 @@ export class KoolbaseCollectionController {
178
299
  clearTimeout(this.liveTimer);
179
300
  this.liveTimer = null;
180
301
  }
302
+ if (this.searchTimer) {
303
+ clearTimeout(this.searchTimer);
304
+ this.searchTimer = null;
305
+ }
181
306
  this.listeners.clear();
182
307
  }
183
308
  async firstPage(cache) {
@@ -186,15 +311,37 @@ export class KoolbaseCollectionController {
186
311
  // will not clear its own flag.
187
312
  if (this.state.loadingMore)
188
313
  this.set({ loadingMore: false });
314
+ const asking = JSON.stringify(this.serverSearch());
189
315
  try {
190
- const result = await this.db.query(this.collection, this.options(0, cache, (fresh) => {
191
- if (!this.isStale(gen))
316
+ const result = await this.db.query(this.collection,
317
+ // A search's answer is the server's, never a cached one (#160).
318
+ this.options(0, this.serverSearch() ? 'network-only' : cache, (fresh) => {
319
+ if (!this.isStale(gen)) {
320
+ this.answered = asking;
192
321
  this.showPageOne(fresh, false, true);
322
+ }
193
323
  }));
194
- if (!this.isStale(gen))
324
+ if (!this.isStale(gen)) {
325
+ this.answered = asking;
195
326
  this.showPageOne(result, result.isFromCache === true, false);
327
+ // A search this fetch superseded is answered by it -- unless a newer
328
+ // one is still waiting for the typing to pause.
329
+ if (!this.searchTimer && (this.state.searching || this.state.searchError !== null)) {
330
+ this.set({ searching: false, searchError: null });
331
+ }
332
+ }
196
333
  }
197
334
  catch (error) {
335
+ // The server refused the search: read unsearched, at once -- the
336
+ // generation this returns is that read's, so refresh() ends with it.
337
+ if (!this.isStale(gen) && isSearchRefusal(error) && this.serverSearch() !== null) {
338
+ this.searchRefused = true;
339
+ this.set({ searchError: null, searchLoadedOnly: true });
340
+ return this.firstPage(cache);
341
+ }
342
+ if (!this.isStale(gen) && this.state.searching && !this.searchTimer) {
343
+ this.set({ searching: false, searchError: error });
344
+ }
198
345
  if (!this.isStale(gen) && this.state.records.length === 0) {
199
346
  this.set({ status: 'error', error });
200
347
  }
@@ -227,6 +374,7 @@ export class KoolbaseCollectionController {
227
374
  offset,
228
375
  orderBy: this.spec.orderBy,
229
376
  orderDesc: this.spec.orderDesc,
377
+ ...(this.serverSearch() ? { fieldSearch: this.serverSearch() } : {}),
230
378
  cache,
231
379
  onRefresh,
232
380
  };
@@ -167,6 +167,16 @@ export class KoolbaseDatabase {
167
167
  order_by: options.orderBy,
168
168
  order_desc: options.orderDesc ?? false,
169
169
  populate: options.populate ?? [],
170
+ // #160: only with text to search; the server checks the rest.
171
+ ...(options.fieldSearch && options.fieldSearch.text.trim() !== ''
172
+ ? {
173
+ field_search: {
174
+ text: options.fieldSearch.text,
175
+ fields: options.fieldSearch.fields ?? [],
176
+ choices: options.fieldSearch.choices ?? [],
177
+ },
178
+ }
179
+ : {}),
170
180
  });
171
181
  const records = raw.records.map(recordFromWire);
172
182
  // Individually, as well as under the query key. The query cache answers
@@ -208,6 +218,12 @@ export class KoolbaseDatabase {
208
218
  // who to tell, not what to read, so it stays out the same way.
209
219
  const { cache: cachePolicy, onRefresh, ...queryOptions } = options;
210
220
  const queryHash = hashQuery(collection, queryOptions);
221
+ // A search's answer is the server's (#160): never served from the cache,
222
+ // and not kept there -- one entry per search typed would pile up.
223
+ if (queryOptions.fieldSearch && queryOptions.fieldSearch.text.trim() !== '') {
224
+ const result = await this.runQuery(collection, queryOptions);
225
+ return { ...result, isFromCache: false };
226
+ }
211
227
  const cached = cachePolicy === 'network-only' ? null : await getCached(userId, collection, queryHash);
212
228
  if (cached) {
213
229
  this.runQuery(collection, queryOptions)
@@ -29,6 +29,13 @@ export function createUseCollection(getDb) {
29
29
  const subscribe = useCallback((onChange) => (controller ? controller.subscribe(onChange) : noop), [controller]);
30
30
  const getSnapshot = useCallback(() => (controller ? controller.getState() : initialCollectionState), [controller]);
31
31
  const state = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
32
+ // The search (#160) is not the query's identity: changing it keeps the
33
+ // controller, and what it shows, and searches after a pause.
34
+ const searchKey = JSON.stringify(query.search ?? null);
35
+ useEffect(() => {
36
+ controller?.setSearch(query.search ?? null);
37
+ // Depends on the search as a value, not the object.
38
+ }, [controller, searchKey]);
32
39
  const refresh = useCallback(() => (controller ? controller.refresh() : done()), [controller]);
33
40
  const loadMore = useCallback(() => (controller ? controller.loadMore() : done()), [controller]);
34
41
  return { ...state, refresh, loadMore };
@@ -262,6 +262,30 @@ export interface KoolbaseRecord {
262
262
  */
263
263
  revision?: number;
264
264
  }
265
+ /**
266
+ * A search over the fields it names, on the server (#160): records whose
267
+ * text fields contain `text`, ignoring case, inside the read rule and the
268
+ * filters and before the page -- so `total` and every page are of the
269
+ * matches. A Choice field is searched by its labels: `values` are the stored
270
+ * values whose label contains the text, `listed` every value the field
271
+ * declares (the server checks both against the declaration); a stored value
272
+ * not declared matches as itself. Empty `text` is no search.
273
+ */
274
+ export interface FieldSearch {
275
+ text: string;
276
+ /** Declared Text or Long text fields (any field, on a collection that declares none). */
277
+ fields?: string[];
278
+ /** Declared Choice fields, by their labels. */
279
+ choices?: ChoiceSearch[];
280
+ }
281
+ /** One Choice field in a [FieldSearch]. */
282
+ export interface ChoiceSearch {
283
+ field: string;
284
+ /** The stored values whose label contains the search text. */
285
+ values: string[];
286
+ /** Every value the field declares. */
287
+ listed: string[];
288
+ }
265
289
  export interface QueryOptions {
266
290
  filters?: Record<string, unknown>;
267
291
  limit?: number;
@@ -269,6 +293,8 @@ export interface QueryOptions {
269
293
  orderBy?: string;
270
294
  orderDesc?: boolean;
271
295
  populate?: string[];
296
+ /** A search over the fields it names, on the server (#160). Empty text: none. */
297
+ fieldSearch?: FieldSearch;
272
298
  /**
273
299
  * How to read: 'default' is cache-first, refreshed in the background;
274
300
  * 'network-only' skips the cache and waits for the server (the result still
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@koolbase/core",
3
- "version": "12.26.0",
3
+ "version": "12.28.0",
4
4
  "description": "Koolbase SDK core \u2014 shared behaviour behind @koolbase/react-native and @koolbase/js. Install one of those, not this.",
5
5
  "main": "./dist/cjs/index.js",
6
6
  "types": "./dist/esm/index.d.ts",