@cloudwick/astral-ui-cli 2.1.0 → 2.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.
@@ -4,6 +4,7 @@ export const keyboardKeys = {
4
4
  arrowLeft: "ArrowLeft",
5
5
  arrowRight: "ArrowRight",
6
6
  enter: "Enter",
7
+ space: " ",
7
8
  escape: "Escape",
8
9
  end: "End",
9
10
  home: "Home",
@@ -1,5 +1,20 @@
1
1
  export { useWindowSize } from "./useWindowSize";
2
- export { useInfiniteScroll } from "./useInfiniteScroll";
2
+ export { useInfiniteScroll, type TSentinelRef } from "./useInfiniteScroll";
3
3
  export { useDebouncedCallback } from "./useDebouncedCallback";
4
+ export { useFilterQuery } from "./useFilterQuery";
5
+ export {
6
+ useAsyncOptions,
7
+ type TAsyncRequest,
8
+ type TPrefetch,
9
+ type TLoadOptions,
10
+ type ILoadOptionsMeta,
11
+ type IOptionPage,
12
+ type IUseAsyncOptionsArgs,
13
+ type IUseAsyncOptionsResult
14
+ } from "./useAsyncOptions";
15
+ export { useAvailableProjection } from "./useAvailableProjection";
16
+ export { usePrefetchBaseline } from "./usePrefetchBaseline";
17
+ export { useIgnoredPropWarning } from "./useIgnoredPropWarning";
18
+ export { useOnValueChange } from "./useOnValueChange";
4
19
  export { useIsTruncated } from "./useIsTruncated";
5
- export { useListboxKeyboardNav } from "./useListboxKeyboardNav";
20
+ export { useListboxKeyboardNav } from "./useListboxKeyboardNav";
@@ -0,0 +1,346 @@
1
+ import { useCallback, useEffect, useReducer, useRef, type Reducer } from "react";
2
+
3
+ import {
4
+ asyncOptionsReducer,
5
+ createInitialState,
6
+ normalisePage,
7
+ type IAsyncOptionsState,
8
+ type TAsyncOptionsAction,
9
+ type TRequestSlot
10
+ } from "./useAsyncOptionsReducer";
11
+
12
+ /** Why the hook is calling `loadOptions`. A `T`-union, not an `E`-enum: it never crosses a public prop surface. */
13
+ export type TAsyncRequest = "defaults" | "search" | "more" | "reload";
14
+
15
+ /**
16
+ * When a server-sourced list fetches its unfiltered baseline. The component decides which trigger the
17
+ * value maps to and passes `prefetchDefaults: prefetch !== "never"` here; a surface with no open/close
18
+ * narrows the union rather than redefining it.
19
+ */
20
+ export type TPrefetch = "mount" | "open" | "never";
21
+
22
+ export interface ILoadOptionsMeta {
23
+ /** Aborts superseded requests. Honouring it is optional — the ticket guard is independent. */
24
+ signal: AbortSignal;
25
+ /** undefined for the first page of a bucket; else the cursor the previous page returned. */
26
+ cursor: unknown;
27
+ /** Zero-based page index within the current bucket. Convenience for offset/limit APIs. */
28
+ page: number;
29
+ /** Why the hook is calling. */
30
+ reason: TAsyncRequest;
31
+ }
32
+
33
+ export interface IOptionPage<TOptionType> {
34
+ options: readonly TOptionType[];
35
+ /** Opaque, handed back on the next call for this bucket. Absent/null ⇒ no further pages. */
36
+ cursor?: unknown;
37
+ /** Explicit override; defaults to `cursor` being present. */
38
+ hasMore?: boolean;
39
+ /** Total matching rows on the server, if known. Rendered as "(loaded of total)". */
40
+ total?: number;
41
+ }
42
+
43
+ export type TLoadOptions<TOptionType> = (
44
+ query: string,
45
+ meta: ILoadOptionsMeta
46
+ ) => Promise<readonly TOptionType[] | IOptionPage<TOptionType>>;
47
+
48
+ export interface IUseAsyncOptionsArgs<TOptionType> {
49
+ /** Option source. Without it every returned callback is inert and no state is ever written. */
50
+ loadOptions?: TLoadOptions<TOptionType>;
51
+ /**
52
+ * Shown before the first fetch and whenever no bucket is loaded. Never blocks the baseline fetch,
53
+ * and is not hidden by it either — but a search replaces it, since it is not a result for a query.
54
+ */
55
+ initialOptions?: readonly TOptionType[];
56
+ /** Fetch the empty-query baseline when `ensureDefaults()` is first called. @default true */
57
+ prefetchDefaults?: boolean;
58
+ /** Clearing the query revalidates the cached baseline instead of only restoring it. @default false */
59
+ refetchOnClear?: boolean;
60
+ /** Identity of the option set. A change drops both buckets and rejects in-flight landings. */
61
+ optionsKey?: string | number;
62
+ /** Identity for append dedupe. Without it a paged append is blind. */
63
+ getOptionKey?: ( option: TOptionType ) => string | number;
64
+ /** Notified with the raw cause of every genuine (non-aborted, non-superseded) failure. */
65
+ onLoadError?: ( error: unknown ) => void;
66
+ }
67
+
68
+ export interface IUseAsyncOptionsResult<TOptionType> {
69
+ /** Active bucket, pages concatenated. Exactly the objects `loadOptions` returned — never re-materialised. */
70
+ options: readonly TOptionType[];
71
+ /** Any request in flight. Feeds aria-busy. */
72
+ isBusy: boolean;
73
+ /** Loader INSTEAD of rows. Gates nav keys and aria-activedescendant. */
74
+ isReplacing: boolean;
75
+ /** Loader BELOW rows. Feeds useInfiniteScroll's in-flight gate. */
76
+ isLoadingMore: boolean;
77
+ /** Only the reload button spins. Overlaps isReplacing; neither implies the other. */
78
+ isReloading: boolean;
79
+ hasError: boolean;
80
+ /** Which request failed; a failed "more" must not blank the list. */
81
+ errorKind: TAsyncRequest | null;
82
+ /** False while a failed page is blocking, so a sentinel still in view cannot retry-loop. */
83
+ hasMore: boolean;
84
+ /** Server total for the active bucket, when the loader reported one. */
85
+ total: number | undefined;
86
+ /** Wire to useFilterQuery — already debounced upstream. Stable identity. */
87
+ onFilterChange: ( query: string ) => void;
88
+ /** Idempotent; joins an in-flight base request. Call on open (or mount). Stable identity. */
89
+ ensureDefaults: () => void;
90
+ /** Re-run the query the list currently reflects, from page one. Stable identity. */
91
+ reload: () => void;
92
+ /** Next page of the active bucket. Safe to call from an IntersectionObserver. Stable identity. */
93
+ loadMore: () => void;
94
+ /** Clears the failed-page block and retries that page. Only ever called from a user gesture. */
95
+ retryMore: () => void;
96
+ }
97
+
98
+ // Module-level so it is assignable to any instantiation with no cast and no per-render identity churn.
99
+ const EMPTY_OPTIONS: readonly never[] = [];
100
+
101
+ /**
102
+ * Owns an async option source: request ordering, the empty-query baseline, paging with dedupe, and
103
+ * the loading/error kinds the surfaces render. The monotonic ticket per slot — not the upstream
104
+ * debounce — is what makes out-of-order responses impossible.
105
+ *
106
+ * Every returned callback has a permanently stable identity (config and callbacks are read through
107
+ * refs), so an inline arrow `loadOptions` at the call site costs nothing and needs no `useMemo`.
108
+ */
109
+ export function useAsyncOptions<TOptionType>({
110
+ loadOptions,
111
+ initialOptions,
112
+ prefetchDefaults = true,
113
+ refetchOnClear = false,
114
+ optionsKey,
115
+ getOptionKey,
116
+ onLoadError
117
+ }: IUseAsyncOptionsArgs<TOptionType> ): IUseAsyncOptionsResult<TOptionType> {
118
+ const [ state, dispatch ] = useReducer(
119
+ asyncOptionsReducer as Reducer<IAsyncOptionsState<TOptionType>, TAsyncOptionsAction<TOptionType>>,
120
+ optionsKey,
121
+ ( key: string | number | undefined ) => createInitialState<TOptionType>( key )
122
+ );
123
+
124
+ const loadOptionsRef = useRef( loadOptions );
125
+ loadOptionsRef.current = loadOptions;
126
+ const getOptionKeyRef = useRef( getOptionKey );
127
+ getOptionKeyRef.current = getOptionKey;
128
+ const onLoadErrorRef = useRef( onLoadError );
129
+ onLoadErrorRef.current = onLoadError;
130
+ const configRef = useRef({ prefetchDefaults, refetchOnClear });
131
+ configRef.current = { prefetchDefaults, refetchOnClear };
132
+ const stateRef = useRef( state );
133
+ stateRef.current = state;
134
+
135
+ // Monotonic per slot. A landed response is accepted only if its ticket still matches AND the
136
+ // optionsKey it was issued under still matches.
137
+ const ticketRef = useRef({ base: 0, view: 0 });
138
+ const abortRef = useRef<{ base: AbortController | null; view: AbortController | null }>({ base: null, view: null });
139
+ // Synchronous one-page-at-a-time gate. Not redundant with `pending`: an IntersectionObserver
140
+ // callback can fire twice before React commits the `start` dispatch.
141
+ const moreLatchRef = useRef( false );
142
+ // Same reasoning for the base slot: an `optionsKey` change runs the prefetch effect AND the clear
143
+ // path in one commit, and both reach `ensureDefaults` before the first `start` has committed.
144
+ const baseLatchRef = useRef( false );
145
+ const mountedRef = useRef( true );
146
+
147
+ // Dispatched from the render body, not an effect: an effect-based reset paints one frame of the
148
+ // previous parent's options. State, so a discarded render discards the reset with it — and
149
+ // `state.key` is what the reducer rejects superseded responses against. The aborts are a side
150
+ // effect, so they live in the effect below.
151
+ if ( state.key !== optionsKey ) {
152
+ dispatch({ type: "invalidate", key: optionsKey });
153
+ }
154
+
155
+ const run = useCallback((
156
+ slot: TRequestSlot,
157
+ kind: TAsyncRequest,
158
+ query: string,
159
+ position: { cursor: unknown; page: number }
160
+ ) => {
161
+ const load = loadOptionsRef.current;
162
+ if ( !load ) {
163
+ return;
164
+ }
165
+ const ticket = ticketRef.current[slot] + 1;
166
+ ticketRef.current[slot] = ticket;
167
+ abortRef.current[slot]?.abort();
168
+ const controller = new AbortController();
169
+ abortRef.current[slot] = controller;
170
+ if ( slot === "base" ) {
171
+ baseLatchRef.current = true;
172
+ }
173
+ // Stamped on every action for this request, so a response that outlives its key cannot land.
174
+ const { key } = stateRef.current;
175
+ dispatch({ type: "start", slot, kind, key });
176
+
177
+ // The latches never outlive their request, whether it landed, failed or was superseded.
178
+ const settle = (): void => {
179
+ if ( kind === "more" ) {
180
+ moreLatchRef.current = false;
181
+ }
182
+ if ( slot === "base" ) {
183
+ baseLatchRef.current = false;
184
+ }
185
+ };
186
+ const isAccepted = (): boolean =>
187
+ mountedRef.current && ticketRef.current[slot] === ticket && stateRef.current.key === key;
188
+
189
+ load( query, { signal: controller.signal, cursor: position.cursor, page: position.page, reason: kind })
190
+ .then(( result ) => {
191
+ settle();
192
+ if ( !isAccepted()) {
193
+ return;
194
+ }
195
+ dispatch({
196
+ type: "land",
197
+ slot,
198
+ kind,
199
+ query,
200
+ key,
201
+ page: normalisePage( result ),
202
+ getOptionKey: getOptionKeyRef.current
203
+ });
204
+ })
205
+ .catch(( cause: unknown ) => {
206
+ settle();
207
+ if ( !isAccepted() || controller.signal.aborted ) {
208
+ return;
209
+ }
210
+ onLoadErrorRef.current?.( cause );
211
+ dispatch({ type: "fail", slot, kind, key });
212
+ });
213
+ }, []);
214
+
215
+ const ensureDefaults = useCallback(() => {
216
+ if ( !loadOptionsRef.current ) {
217
+ return;
218
+ }
219
+ const { current } = stateRef;
220
+ // Join an in-flight base request rather than duplicating it. The latch, not just `pending`, is
221
+ // what makes this reliable: callers reach here from effects, and two of them in one commit (the
222
+ // open/`optionsKey` prefetch, then the clear path) both see a `pending.base` that React has not
223
+ // committed yet. The `aborted` clause is the StrictMode safety net: double-invoke runs
224
+ // effect → cleanup (aborts) → effect, and the refs survive.
225
+ if (( baseLatchRef.current || current.pending.base !== null ) &&
226
+ abortRef.current.base?.signal.aborted !== true ) {
227
+ return;
228
+ }
229
+ if ( current.base !== null && !configRef.current.refetchOnClear ) {
230
+ return;
231
+ }
232
+ if ( !configRef.current.prefetchDefaults && current.base === null ) {
233
+ return;
234
+ }
235
+ run( "base", "defaults", "", { cursor: undefined, page: 0 });
236
+ }, [run]);
237
+
238
+ const onFilterChangeInternal = useCallback(( query: string ) => {
239
+ if ( !loadOptionsRef.current ) {
240
+ return;
241
+ }
242
+ dispatch({ type: "set-query", query });
243
+ if ( query !== "" ) {
244
+ run( "view", "search", query, { cursor: undefined, page: 0 });
245
+ return;
246
+ }
247
+ // Every menu close takes this path. Clear ALWAYS restores the baseline; `refetchOnClear` only
248
+ // decides whether ensureDefaults also revalidates it — stale rows stay on screen either way.
249
+ ticketRef.current.view += 1;
250
+ abortRef.current.view?.abort();
251
+ abortRef.current.view = null;
252
+ moreLatchRef.current = false;
253
+ dispatch({ type: "restore-base" });
254
+ ensureDefaults();
255
+ }, [ run, ensureDefaults ]);
256
+
257
+ const startMore = useCallback(() => {
258
+ const { current } = stateRef;
259
+ if ( current.pending.base !== null || current.pending.view !== null ) {
260
+ return;
261
+ }
262
+ const searchBucket = current.search;
263
+ const bucket = searchBucket ?? current.base;
264
+ if ( !bucket || !bucket.hasMore ) {
265
+ return;
266
+ }
267
+ moreLatchRef.current = true;
268
+ run(
269
+ searchBucket ? "view" : "base",
270
+ "more",
271
+ searchBucket ? searchBucket.query : "",
272
+ { cursor: bucket.cursor, page: bucket.page }
273
+ );
274
+ }, [run]);
275
+
276
+ const loadMore = useCallback(() => {
277
+ if ( moreLatchRef.current || stateRef.current.moreBlocked ) {
278
+ return;
279
+ }
280
+ startMore();
281
+ }, [startMore]);
282
+
283
+ const retryMore = useCallback(() => {
284
+ moreLatchRef.current = false;
285
+ dispatch({ type: "unblock-more" });
286
+ // stateRef still reports the block (the dispatch above has not committed), so this bypasses
287
+ // loadMore's gate rather than reading it.
288
+ startMore();
289
+ }, [startMore]);
290
+
291
+ const reload = useCallback(() => {
292
+ const { query } = stateRef.current;
293
+ run( query === "" ? "base" : "view", "reload", query, { cursor: undefined, page: 0 });
294
+ }, [run]);
295
+
296
+ // Cancels the previous key's network work. A cleanup, so it runs before every effect body in the
297
+ // commit — including the consumers' `ensureDefaults` prefetch, which also depends on `optionsKey`.
298
+ // The aborted controllers are left in place, not nulled: `ensureDefaults` reads `aborted` as its
299
+ // StrictMode net, and a null there reads as "in flight" and swallows the re-fetch.
300
+ useEffect(() => () => {
301
+ abortRef.current.base?.abort();
302
+ abortRef.current.view?.abort();
303
+ moreLatchRef.current = false;
304
+ baseLatchRef.current = false;
305
+ }, [optionsKey]);
306
+
307
+ useEffect(() => {
308
+ mountedRef.current = true;
309
+ return () => {
310
+ mountedRef.current = false;
311
+ };
312
+ }, []);
313
+
314
+ const activeBucket = state.search ?? state.base;
315
+ const { pending } = state;
316
+ // Seed rows are what `options` returns while no bucket is loaded, which is exactly the window a
317
+ // baseline fetch runs in — so treating that fetch as "replacing" would mean the seed the consumer
318
+ // asked to show instantly is never once painted.
319
+ const hasSeedRows = activeBucket === null && ( initialOptions?.length ?? 0 ) > 0;
320
+
321
+ return {
322
+ // `initialOptions` sits UNDER the buckets rather than inside `base`, so seeding the list does not
323
+ // count as a loaded baseline — a surface can show rows instantly and still prefetch the real ones.
324
+ options: activeBucket?.options ?? initialOptions ?? EMPTY_OPTIONS,
325
+ isBusy: pending.base !== null || pending.view !== null,
326
+ // False during a stale-revalidating baseline fetch over an existing bucket — or over seed rows,
327
+ // which serve the same purpose; true when there is nothing to show. A search or a view reload
328
+ // still replaces: seed rows are not results for a query, and showing them as such would be a lie.
329
+ // Derived here, once, so two surfaces cannot derive it differently.
330
+ isReplacing:
331
+ pending.view === "search" ||
332
+ pending.view === "reload" ||
333
+ (( pending.base === "defaults" || pending.base === "reload" ) && state.base === null && !hasSeedRows ),
334
+ isLoadingMore: pending.base === "more" || pending.view === "more",
335
+ isReloading: pending.base === "reload" || pending.view === "reload",
336
+ hasError: state.error !== null,
337
+ errorKind: state.error?.kind ?? null,
338
+ hasMore: activeBucket?.hasMore === true && !state.moreBlocked,
339
+ total: activeBucket?.total,
340
+ onFilterChange: onFilterChangeInternal,
341
+ ensureDefaults,
342
+ reload,
343
+ loadMore,
344
+ retryMore
345
+ };
346
+ }
@@ -0,0 +1,182 @@
1
+ // The pure half of useAsyncOptions: the two-bucket state model and its reducer. No React, no
2
+ // requests — `run` validates the ticket and the optionsKey before dispatching, so nothing here needs
3
+ // to know that a network exists. The sibling import is type-only, so there is no runtime cycle.
4
+ import { mergeUnique } from "@utils";
5
+ import type { IOptionPage, TAsyncRequest } from "./useAsyncOptions";
6
+
7
+ /**
8
+ * One request slot. `base` (the empty-query baseline) and `view` (the current query) write disjoint
9
+ * state, so making them cancel each other would be pure loss — and is exactly what would let a menu
10
+ * close destroy the baseline it is meant to restore.
11
+ */
12
+ export type TRequestSlot = "base" | "view";
13
+
14
+ export interface IOptionBucket<TOptionType> {
15
+ options: readonly TOptionType[];
16
+ cursor: unknown;
17
+ /** Pages landed so far; the next request for this bucket gets `meta.page = page`. */
18
+ page: number;
19
+ hasMore: boolean;
20
+ total: number | undefined;
21
+ }
22
+
23
+ export interface IPendingKinds {
24
+ base: TAsyncRequest | null;
25
+ view: TAsyncRequest | null;
26
+ }
27
+
28
+ /**
29
+ * Two buckets, never sharing storage: the empty-query result and the current-query result are
30
+ * different things, so clearing the query can *restore* rather than destroy. `pending` holds the
31
+ * request *kind* per slot rather than a boolean, because "which loader do I render" is a question
32
+ * about the kind — and parallel booleans are how loading state and error state drift out of step.
33
+ */
34
+ export interface IAsyncOptionsState<TOptionType> {
35
+ base: IOptionBucket<TOptionType> | null;
36
+ search: ( IOptionBucket<TOptionType> & { query: string }) | null;
37
+ pending: IPendingKinds;
38
+ /** Only the kind: the raw cause goes straight to `onLoadError`, and nothing renders it. */
39
+ error: { kind: TAsyncRequest } | null;
40
+ /** Set by a failed page append; disarms `hasMore` until `retryMore()`. */
41
+ moreBlocked: boolean;
42
+ query: string;
43
+ key: string | number | undefined;
44
+ }
45
+
46
+ /** The `optionsKey` a request was issued under. See the guard at the top of the reducer. */
47
+ type TKeyed = { key: string | number | undefined };
48
+
49
+ export type TAsyncOptionsAction<TOptionType> =
50
+ | { type: "set-query"; query: string }
51
+ | { type: "invalidate"; key: string | number | undefined }
52
+ | ({ type: "start"; slot: TRequestSlot; kind: TAsyncRequest } & TKeyed )
53
+ | ({
54
+ type: "land";
55
+ slot: TRequestSlot;
56
+ kind: TAsyncRequest;
57
+ query: string;
58
+ page: IOptionPage<TOptionType>;
59
+ getOptionKey?: ( option: TOptionType ) => string | number;
60
+ } & TKeyed )
61
+ | ({ type: "fail"; slot: TRequestSlot; kind: TAsyncRequest } & TKeyed )
62
+ | { type: "restore-base" }
63
+ | { type: "unblock-more" };
64
+
65
+ const isKeyed = <TOptionType>(
66
+ action: TAsyncOptionsAction<TOptionType>
67
+ ): action is TAsyncOptionsAction<TOptionType> & TKeyed =>
68
+ action.type === "start" || action.type === "land" || action.type === "fail";
69
+
70
+ const withPending = ( pending: IPendingKinds, slot: TRequestSlot, kind: TAsyncRequest | null ): IPendingKinds =>
71
+ ( slot === "base" ? { base: kind, view: pending.view } : { base: pending.base, view: kind });
72
+
73
+ /** A bare array return normalises to a single, final page, so the simple case stays a one-liner. */
74
+ export const normalisePage = <TOptionType>(
75
+ result: readonly TOptionType[] | IOptionPage<TOptionType>
76
+ ): IOptionPage<TOptionType> => ( Array.isArray( result ) ? { options: result } : result as IOptionPage<TOptionType> );
77
+
78
+ /**
79
+ * Appends, dropping any option whose key is already present (first occurrence wins). Server paging
80
+ * over an unstable sort returns duplicates, both consuming surfaces key their rows by `value`, and
81
+ * this is the only layer that sees both pages. Returns `existing` by identity when the page added
82
+ * nothing, so a re-landing page cannot invalidate the surfaces' memos over the pool.
83
+ */
84
+ function appendUnique<TOptionType>(
85
+ existing: readonly TOptionType[],
86
+ incoming: readonly TOptionType[],
87
+ getOptionKey?: ( option: TOptionType ) => string | number
88
+ ): readonly TOptionType[] {
89
+ if ( !getOptionKey ) {
90
+ return incoming.length === 0 ? existing : [ ...existing, ...incoming ];
91
+ }
92
+ const merged = mergeUnique([ existing, incoming ], getOptionKey );
93
+ return merged.length === existing.length ? existing : merged;
94
+ }
95
+
96
+ function mergeBucket<TOptionType>(
97
+ previous: IOptionBucket<TOptionType> | null,
98
+ page: IOptionPage<TOptionType>,
99
+ getOptionKey?: ( option: TOptionType ) => string | number
100
+ ): IOptionBucket<TOptionType> {
101
+ const { cursor } = page;
102
+ return {
103
+ // A replacing page keeps the loader's own array reference; only an append allocates.
104
+ options: previous ? appendUnique( previous.options, page.options, getOptionKey ) : page.options,
105
+ cursor,
106
+ page: ( previous?.page ?? 0 ) + 1,
107
+ hasMore: page.hasMore ?? ( cursor !== undefined && cursor !== null ),
108
+ total: page.total ?? previous?.total
109
+ };
110
+ }
111
+
112
+ export function createInitialState<TOptionType>( key: string | number | undefined ): IAsyncOptionsState<TOptionType> {
113
+ return {
114
+ base: null,
115
+ search: null,
116
+ pending: { base: null, view: null },
117
+ error: null,
118
+ moreBlocked: false,
119
+ query: "",
120
+ key
121
+ };
122
+ }
123
+
124
+ export function asyncOptionsReducer<TOptionType>(
125
+ state: IAsyncOptionsState<TOptionType>,
126
+ action: TAsyncOptionsAction<TOptionType>
127
+ ): IAsyncOptionsState<TOptionType> {
128
+ // A response issued under a superseded `optionsKey` is dropped here, against the very state whose
129
+ // identity it is checked against — rather than by bumping a ticket ref from the render body, where a
130
+ // discarded render would consume the change and abort a live request nothing re-issues.
131
+ if ( isKeyed( action ) && action.key !== state.key ) {
132
+ return state;
133
+ }
134
+ switch ( action.type ) {
135
+ case "set-query":
136
+ return state.query === action.query ? state : { ...state, query: action.query };
137
+ // Drops both buckets, both cursors, the error and the block. Leaves the query alone (owned by
138
+ // useFilterQuery) and the committed selection alone (owned by the consumer).
139
+ case "invalidate":
140
+ return { ...createInitialState<TOptionType>( action.key ), query: state.query };
141
+ // Clearing the error in the same dispatch that starts the fetch makes "does a retry clear the
142
+ // error?" true by construction rather than a question.
143
+ case "start":
144
+ return {
145
+ ...state,
146
+ pending: withPending( state.pending, action.slot, action.kind ),
147
+ error: null,
148
+ moreBlocked: action.kind === "more" ? state.moreBlocked : false
149
+ };
150
+ case "land": {
151
+ const pending = withPending( state.pending, action.slot, null );
152
+ const previous = action.kind === "more"
153
+ ? ( action.slot === "base" ? state.base : state.search )
154
+ : null;
155
+ const bucket = mergeBucket( previous, action.page, action.getOptionKey );
156
+ return action.slot === "base"
157
+ ? { ...state, base: bucket, pending, error: null }
158
+ : { ...state, search: { ...bucket, query: action.query }, pending, error: null };
159
+ }
160
+ // A failure leaves the previous bucket intact, so the surfaces can choose between "error instead
161
+ // of rows" (no bucket yet) and "error banner over stale rows".
162
+ case "fail":
163
+ return {
164
+ ...state,
165
+ pending: withPending( state.pending, action.slot, null ),
166
+ error: { kind: action.kind },
167
+ moreBlocked: action.kind === "more" ? true : state.moreBlocked
168
+ };
169
+ case "restore-base":
170
+ return {
171
+ ...state,
172
+ search: null,
173
+ pending: withPending( state.pending, "view", null ),
174
+ error: null,
175
+ moreBlocked: false
176
+ };
177
+ case "unblock-more":
178
+ return state.moreBlocked ? { ...state, moreBlocked: false } : state;
179
+ default:
180
+ return state;
181
+ }
182
+ }
@@ -0,0 +1,77 @@
1
+ import { useMemo, type ReactNode } from "react";
2
+
3
+ import { matchesQuery } from "@utils";
4
+
5
+ /** The shape both transfer surfaces project: anything `matchesQuery` can search and `value` can key. */
6
+ interface IProjectableItem {
7
+ value: string | number;
8
+ label: ReactNode;
9
+ searchValue?: string;
10
+ }
11
+
12
+ // One shared identity for the disabled case, so a consumer that never turns the projection on does
13
+ // not invalidate the memos downstream of it on every render.
14
+ const EMPTY: never[] = [];
15
+ const NO_KEYS: ReadonlySet<never> = new Set();
16
+ const DISABLED: { items: never[]; keys: ReadonlySet<never> } = { items: EMPTY, keys: NO_KEYS };
17
+
18
+ /**
19
+ * The Available panel of a server-sourced transfer surface: the loaded pool, plus items the pool may
20
+ * not contain, minus whatever is already selected.
21
+ *
22
+ * The pool is the server's answer for the active query, so it needs no local matching — but
23
+ * `remembered` (items the surface is carrying itself: a deselected row, a committed-but-never-fetched
24
+ * option) is not, and would otherwise render as a result for a query it does not match. Splitting the
25
+ * two halves is also what keeps a keystroke cheap: only the second memo depends on `query`, and it
26
+ * hands back the first one **by identity** when nothing was remembered — the common case, and the one
27
+ * that would otherwise re-run every pass the panel memoises over this array.
28
+ */
29
+ export function useAvailableProjection<TItem extends IProjectableItem>(
30
+ enabled: boolean,
31
+ pool: readonly TItem[],
32
+ remembered: readonly TItem[],
33
+ selected: readonly TItem[],
34
+ query: string
35
+ ): TItem[] {
36
+ // Gated too: a sync consumer would otherwise rebuild this on every selection change for two memos
37
+ // that immediately discard it.
38
+ const chosen = useMemo<ReadonlySet<TItem["value"]>>(
39
+ () => ( enabled ? new Set( selected.map(( item ) => item.value )) : NO_KEYS ),
40
+ [ enabled, selected ]
41
+ );
42
+
43
+ // The keys travel with the rows so the second memo can test membership without a second pass over
44
+ // the pool — which, on a paged source, is the whole loaded set on every landed page.
45
+ const fromPool = useMemo<{ items: TItem[]; keys: ReadonlySet<TItem["value"]> }>(() => {
46
+ if ( !enabled ) {
47
+ return DISABLED;
48
+ }
49
+ const items: TItem[] = [];
50
+ const keys = new Set<TItem["value"]>();
51
+ for ( const item of pool ) {
52
+ if ( chosen.has( item.value ) || keys.has( item.value )) {
53
+ continue;
54
+ }
55
+ keys.add( item.value );
56
+ items.push( item );
57
+ }
58
+ return { items, keys };
59
+ }, [ enabled, pool, chosen ]);
60
+
61
+ return useMemo(() => {
62
+ if ( !enabled ) {
63
+ return EMPTY;
64
+ }
65
+ const extras: TItem[] = [];
66
+ const extraKeys = new Set<TItem["value"]>();
67
+ for ( const item of remembered ) {
68
+ const key = item.value;
69
+ if ( chosen.has( key ) || fromPool.keys.has( key ) || extraKeys.has( key ) || !matchesQuery( item, query )) {
70
+ continue;
71
+ }
72
+ extraKeys.add( key );
73
+ extras.push( item );
74
+ }
75
+ return extras.length === 0 ? fromPool.items : fromPool.items.concat( extras );
76
+ }, [ enabled, fromPool, remembered, chosen, query ]);
77
+ }