1import { message as errMessage } from "@clo/lib/error.ts";
2import type { Timer } from "@clo/lib/ts.ts";
3import {
4 type FC,
5 type MouseEvent,
6 type MouseEventHandler,
7 type ReactNode,
8 useCallback,
9 useEffect,
10 useMemo,
11 useRef,
12 useState,
13 useSyncExternalStore,
14} from "react";
15import { jsx } from "react/jsx-runtime";
16import type { MutationClient } from "./client.ts";
17import { formatFriendlyError, Mutation } from "./mutation.ts";
18import type { RunOptions } from "./types.ts";
19
20/**
21 * Subscribe to a mutation's status, as well as accessing a local `run` method.
22 * The resulting mutation can be used directly or passed to a {@link createMutationButton|mutation button}.
23 */
24export function useMutate<
25 Args extends unknown[],
26 Result,
27>(
28 mutation: Mutation<Args, Result> | null,
29): UseMutateResult<Args, Result> {
30 const [_, setRerender] = useState(0);
31 const [observer] = useState(() => new Observer<Args, Result>(setRerender));
32 if (mutation !== observer.mutation) {
33 observer.mutation = mutation;
34 observer.reset();
35 }
36 // The allowed subscription lives in useSyncExternalStore: the server never
37 // subscribes, and StrictMode's simulated remount resubscribes.
38 const subscribeAllowed = useMemo(() => (onChange: () => void) => {
39 if (!mutation) return () => {};
40 const unsubscribeMutation = mutation.subscribeAllowed(onChange);
41 const unsubscribeClient = mutation.client.userContext?.sub(onChange) ?? (() => {});
42 return () => {
43 unsubscribeMutation();
44 unsubscribeClient();
45 };
46 }, [mutation]);
47 // Everything the subscription can change about a render, as one comparable value.
48 const allowedSnapshot = () =>
49 mutation === null ? -1 : (mutation.isAllowed() ? 1 : 0) | (mutation.isUnauthenticated() ? 2 : 0);
50 useSyncExternalStore(subscribeAllowed, allowedSnapshot, allowedSnapshot);
51 useEffect(() => () => void observer.reset(), []);
52 return observer.binding;
53}
54
55export interface AsyncCallbackOptions {
56 /** Phrased for the template `Could not ${describe}`. Omitted yields a generic error message. */
57 describe?: string;
58 /** Success message shown through the client's global handler. Omitted shows nothing. */
59 describeResult?: string | null;
60}
61
62/**
63 * Binds {@link useAsyncCallback} to a client so ad-hoc async callbacks route
64 * their status and errors through it. A codebase re-exports the result once:
65 * `export const useAsyncCallback = bindAsyncCallback(mutations)`.
66 */
67export function bindAsyncCallback(
68 client: MutationClient<object, object, object, string>,
69): <Args extends unknown[], Result>(
70 callback: (...args: Args) => Promise<Result>,
71 options?: AsyncCallbackOptions,
72) => UseMutateResult<Args, Result> {
73 return function useAsyncCallback<Args extends unknown[], Result>(
74 callback: (...args: Args) => Promise<Result>,
75 options?: AsyncCallbackOptions,
76 ): UseMutateResult<Args, Result> {
77 const live = useRef({ callback, options });
78 live.current = { callback, options };
79 // A stable, unregistered mutation with no optimistic state; every field
80 // reads the ref so it tracks the latest callback and options. Empty
81 // describe/describeResult fall through to the generic error message and no
82 // success toast, respectively.
83 const [mutation] = useState(() =>
84 new Mutation<Args, Result>(client, {
85 id: "",
86 mutate: (...args) => live.current.callback(...args),
87 optimistic: () => {},
88 describe: () => live.current.options?.describe ?? "",
89 describeResult: () => live.current.options?.describeResult ?? "",
90 refetchOnSuccess: false,
91 })
92 );
93 return useMutate(mutation);
94 };
95}
96
97export type UseMutateResult<Args extends unknown[], Result> =
98 & UseMutateResultBase<Args, Result>
99 & (
100 | UseMutateSuccess<Result>
101 | UseMutateError
102 | UseMutateIdle
103 );
104
105export interface UseMutateResultBase<Args extends unknown[], Result> {
106 run: (...args: Args) => void;
107 runWithOptions: (
108 ..._: [...args: Args, options: RunOptions<Result>]
109 ) => void;
110
111 /** Unset error and success states */
112 clear: () => void;
113 /** Set `error`, useful for input validators or whatever */
114 setError: (error: unknown) => void;
115 /** The arguments of the latest mutation call */
116 args: Args | undefined;
117 /** `true` when controls should be disabled */
118 isDisabled: boolean;
119 /** `true` when a mutation exists and its authentication requirement is satisfied. */
120 isAllowed: boolean;
121}
122
123export interface UseMutateSuccess<Result> {
124 status: "success";
125 result: Result;
126 error: undefined;
127 errorMessage: undefined;
128 /** `true` when a `mutate` function is currently running. */
129 isMutating: false;
130 /** `true` when a loading indicator should be shown. */
131 isPending: false;
132 /** `true` when a mutation has completed and has a result. */
133 isSuccess: true;
134 /** `true` when a mutation has failed. */
135 isError: false;
136 /** `true` when there is optimistic state applied. */
137 isOptimisticData: boolean;
138}
139export interface UseMutateError {
140 status: "error";
141 result: undefined;
142 error: unknown;
143 /** User-friendly in this format: `Could not {action}: {details}` */
144 errorMessage: string;
145 /** `true` when a `mutate` function is currently running. */
146 isMutating: false;
147 /** `true` when a loading indicator should be shown. */
148 isPending: false;
149 /** `true` when a mutation has completed and has a result. */
150 isSuccess: false;
151 /** `true` when a mutation has failed. */
152 isError: true;
153 /** `true` when there is optimistic state applied. */
154 isOptimisticData: boolean;
155}
156export interface UseMutateIdle {
157 status: "idle" | "mutating";
158 result: undefined;
159 error: undefined;
160 errorMessage: undefined;
161 /** `true` when a `mutate` function is currently running. */
162 isMutating: boolean;
163 /** `true` when a loading indicator should be shown. */
164 isPending: boolean;
165 /** `true` when a mutation has completed and has a result. */
166 isSuccess: false;
167 /** `true` when a mutation has failed. */
168 isError: false;
169 /** `true` when there is optimistic state applied. */
170 isOptimisticData: boolean;
171}
172
173type AnyMutationStateWithoutRun<Args extends unknown[], Result> =
174 & Omit<
175 UseMutateIdle,
176 "status" | "result" | "error" | "isSuccess" | "isError" | "errorMessage"
177 >
178 & {
179 status: "idle" | "mutating" | "error" | "success";
180 result: undefined | Result;
181 error: undefined | unknown;
182 errorMessage: undefined | string;
183 isSuccess: boolean;
184 isError: boolean;
185 args: Args | undefined;
186 };
187
188export type AnyMutationState<Args extends unknown[], Result> =
189 & AnyMutationStateWithoutRun<Args, Result>
190 & UseMutateResultBase<Args, Result>;
191
192function initialState() {
193 return {
194 status: "idle",
195 result: undefined,
196 error: undefined,
197 errorMessage: undefined,
198 isMutating: false,
199 isPending: false,
200 isSuccess: false,
201 isError: false,
202 isOptimisticData: false,
203 args: undefined,
204 } as const;
205}
206
207class Observer<Args extends unknown[], Result> {
208 setRerender: (fn: number) => void;
209 mutation: Mutation<Args, Result> | null = null;
210 unsubscribe: (() => void) | null = null;
211 currentKey: string | null = null;
212 pendingTimer: Timer | null = null;
213 debounced: boolean = false;
214
215 constructor(setRerender: (fn: number) => void) {
216 this.setRerender = setRerender;
217 }
218
219 watched: Set<string> = new Set();
220 state: AnyMutationStateWithoutRun<Args, Result> = initialState();
221 setState(newState: Partial<AnyMutationStateWithoutRun<Args, Result>>) {
222 let updateUi = false;
223 const current: Record<string, unknown> = this.state;
224 for (const [key, value] of Object.entries(newState)) {
225 if (value !== current[key]) {
226 current[key] = value;
227 updateUi ||= this.watched.has(key);
228 }
229 }
230 if (updateUi) {
231 this.setRerender(Math.random());
232 }
233 }
234
235 reset() {
236 this.unsubscribe?.();
237 this.unsubscribe = null;
238 this.currentKey = null;
239 this.state = initialState();
240 this.resetPending();
241 this.debounced = false;
242 }
243
244 resetPending() {
245 this.setState({ isPending: false });
246 if (this.pendingTimer) clearTimeout(this.pendingTimer);
247 this.pendingTimer = null;
248 }
249
250 computeErrorMessage(error: unknown): string | undefined {
251 if (!error) return undefined;
252 const mutation = this.mutation;
253 return formatFriendlyError(
254 this.state.args ? mutation?.describe(...this.state.args) ?? null : null,
255 error,
256 );
257 }
258
259 run(...args: Args) {
260 const mutation = this.mutation;
261 if (!mutation) return;
262 this.setState({ args });
263 const key = mutation.key(args);
264 if (key !== this.currentKey) {
265 this.currentKey = key;
266 this.unsubscribe?.();
267 this.unsubscribe = mutation.subscribe(
268 mutation.key(args),
269 ({ status, error, result, debounced }) => {
270 this.debounced = debounced;
271
272 if (status === "idle") {
273 this.setState({
274 isMutating: false,
275 isOptimisticData: false,
276 });
277 this.resetPending();
278 return;
279 }
280 const hasError = error != null;
281 const hasResult = result != null;
282
283 this.setState({
284 status: hasError
285 ? "error"
286 : hasResult
287 ? "success"
288 : status === "mutating"
289 ? "mutating"
290 : "idle",
291 error: error ?? undefined,
292 errorMessage: this.state.error === error && this.state.errorMessage
293 ? this.state.errorMessage
294 : this.computeErrorMessage(error ?? undefined),
295 result: result ?? undefined,
296 isMutating: status === "mutating",
297 isSuccess: hasResult && !hasError,
298 isError: hasError,
299 isOptimisticData: status === "waiting" || status === "mutating"
300 || status === "refetching",
301 args: hasError || hasResult ? undefined : this.state.args,
302 });
303
304 if (!this.state.isPending && this.state.isMutating && !debounced) {
305 this.pendingTimer ??= setTimeout(() => {
306 this.pendingTimer = null;
307 this.setState({ isPending: true });
308 }, 200);
309 } else {
310 this.resetPending();
311 }
312 },
313 );
314 }
315 // Use global error/success handling if this usage of the hook doesn't check for
316 // errors or success. This makes it act pretty awesome in terms of defaults.
317 // You don't have to worry about result UI, they'll surface exactly once.
318 const watchesError = this.watched.has("isError")
319 || this.watched.has("error") || this.watched.has("errorMessage");
320 const watchesSuccess = this.watched.has("isSuccess")
321 || this.watched.has("result");
322 const promise = mutation.runWithOptions(
323 ...args,
324 {
325 onSuccessUi: watchesSuccess ? () => {} : undefined,
326 onError: watchesError ? () => {} : undefined,
327 // For debounced mutations, suppress global handlers in runWithOptions
328 // The debounce logic (#enqueueDebouncedCall) will call them once if needed
329 // But only if the component isn't watching success/error
330 } satisfies RunOptions<Result>,
331 );
332 return promise;
333 }
334
335 runWithOptions(...array: [...args: Args, options: RunOptions<Result>]): void {
336 const mutation = this.mutation;
337 if (!mutation) return;
338
339 const args = array.slice() as Args;
340 const options = args.pop() as RunOptions<Result>;
341
342 this.setState({ args });
343 const key = mutation.key(args);
344
345 // Set up subscription if key changed
346 if (key !== this.currentKey) {
347 this.currentKey = key;
348 this.unsubscribe?.();
349 this.resetPending();
350 this.unsubscribe = mutation.subscribe(
351 mutation.key(args),
352 ({ status, error, result, debounced }) => {
353 this.debounced = debounced;
354
355 if (status === "idle") {
356 this.setState({
357 isMutating: false,
358 isPending: false,
359 isOptimisticData: false,
360 });
361 return;
362 }
363 const hasError = error != null;
364 const hasResult = result != null;
365
366 this.setState({
367 status: hasError
368 ? "error"
369 : hasResult
370 ? "success"
371 : status === "mutating"
372 ? "mutating"
373 : "idle",
374 error: error ?? undefined,
375 errorMessage: this.state.error === error && this.state.errorMessage
376 ? this.state.errorMessage
377 : this.computeErrorMessage(error ?? undefined),
378 result: result ?? undefined,
379 isMutating: status === "mutating",
380 isPending: !debounced && (status === "mutating" || status === "refetching"),
381 isSuccess: hasResult && !hasError,
382 isError: hasError,
383 isOptimisticData: status === "waiting" || status === "mutating"
384 || status === "refetching",
385 args: hasError || hasResult ? undefined : this.state.args,
386 });
387 },
388 );
389 }
390
391 // Delegate to the mutation's runWithOptions and return the promise
392 return mutation.runWithOptions(...args, options);
393 }
394
395 binding: UseMutateResult<Args, Result> = ((self: this) => ({
396 run: self.run.bind(self),
397 runWithOptions: self.runWithOptions.bind(self),
398 clear() {
399 self.setState({
400 status: ["error", "success"].includes(self.state.status)
401 ? "idle"
402 : self.state.status,
403 isError: false,
404 isSuccess: false,
405 error: undefined,
406 errorMessage: undefined,
407 result: undefined,
408 });
409 },
410 setError(error: unknown) {
411 self.setState({
412 status: "error",
413 error,
414 errorMessage: errMessage(error),
415 isError: true,
416 isSuccess: false,
417 result: undefined,
418 });
419 },
420 get status() {
421 self.watched.add("status");
422 return self.state.status;
423 },
424 get result() {
425 self.watched.add("result");
426 return self.state.result;
427 },
428 get error() {
429 self.watched.add("error");
430 return self.state.error;
431 },
432 get errorMessage() {
433 self.watched.add("errorMessage");
434 return self.state.errorMessage;
435 },
436 get isMutating() {
437 self.watched.add("isMutating");
438 return self.state.isMutating;
439 },
440 get isAllowed() {
441 return self.mutation?.isAllowed() ?? false;
442 },
443 get isDisabled() {
444 self.watched.add("isMutating");
445 const mutation = self.mutation;
446 if (!mutation || (self.state.isMutating && !self.debounced)) return true;
447 if (mutation.isAllowed()) return false;
448 // Unauthenticated clicks stay enabled when they can route to a sign-in flow.
449 return !(mutation.isUnauthenticated() && mutation.client.handleUnauthenticated);
450 },
451 get isPending() {
452 self.watched.add("isPending");
453 return self.state.isPending;
454 },
455 get isSuccess() {
456 self.watched.add("isSuccess");
457 return self.state.isSuccess;
458 },
459 get isError() {
460 self.watched.add("isError");
461 return self.state.isError;
462 },
463 get isOptimisticData() {
464 self.watched.add("isOptimisticData");
465 return self.state.isOptimisticData;
466 },
467 get args() {
468 self.watched.add("args");
469 return self.state.args;
470 },
471 } as UseMutateResult<Args, Result>))(this);
472}
473
474interface BaseButtonProps {
475 onClick: MouseEventHandler<HTMLElement> | undefined;
476 isPending: boolean;
477}
478
479export interface MutationButtonComponent<Props> {
480 <Args extends unknown[], Result>(
481 props:
482 & MutationButtonProps<Args, Result>
483 & Props,
484 ): ReactNode;
485 displayName?: string;
486}
487
488export interface MutationButtonProps<Args extends unknown[], Result> {
489 mutation:
490 | Mutation<Args, Result>
491 | UseMutateResult<Args, Result>;
492 /** Preventing default will interrupt the mutation */
493 args: NoInfer<Args> | null | ((e: MouseEvent) => NoInfer<Args> | null);
494 /** Preventing default will interrupt the mutation */
495 onClick?: (e: MouseEvent) => void;
496 disabled?: boolean;
497
498 /** Omitting this will use the global error handler */
499 onError?: (result: unknown) => void;
500 /** Omitting this will use the global success handler */
501 onSuccessUi?: (result: Result) => void;
502 /** Does not prevent the global handler */
503 onSuccessData?: (result: Result) => void;
504 /** Called instead of running an authenticated mutation when no user is available. */
505 onUnauthenticated?: RunOptions<Result>["onUnauthenticated"];
506
507 /** Global event handlers will still be called! */
508 onSettled?: (
509 event: {
510 status: "success";
511 result: Result;
512 } | {
513 status: "error";
514 error: unknown;
515 },
516 ) => void;
517
518 /** Setting this to true will opt out of the behavior that non-allowed buttons are hidden. */
519 showNotAllowed?: boolean;
520}
521
522/**
523 * Wraps a custom button component with logic to execute a mutation. The wrapped
524 * component must accept `onClick` and an `isPending` property. When the inner
525 * component emits `onClick`, that will begin the mutation. This is a trival
526 * abstraction on top of `useMutate`, but with type gymnastics to allow safe
527 * types.
528 */
529export function createMutationButton<Props>(
530 // Prevent calling this function if missing `onClick`
531 base: Required<Props> extends BaseButtonProps ? FC<Props>
532 : "Base component is missing required props",
533): MutationButtonComponent<Flatten<Omit<Props, keyof BaseButtonProps>>> {
534 const Component = base as ResolveMutationButtonFc<Props, unknown[], unknown>;
535 // apply the generics at a type level to allow `.bind` to work
536 type BareProps = Omit<Props, keyof BaseButtonProps>;
537 const bound = (GenericMutationButton<Props, unknown[], unknown>)
538 // the `as` clause here converts the second and third generic parameter
539 // back into unspecified generics.
540 .bind(null, Component) as MutationButtonComponent<BareProps>;
541 // react devtools loves display names
542 bound.displayName = `MutationButton[${Component.displayName ?? Component.name}]`;
543
544 return bound;
545}
546
547type Identity<T> = T;
548type Flatten<T> = Identity<{ [K in keyof T]: T[K] }>;
549type ResolveMutationButtonFc<Props, Args extends unknown[], Result> = FC<
550 & Omit<Props, keyof MutationButtonProps<Args, Result>>
551 & BaseButtonProps
552 & { disabled?: boolean }
553>;
554
555function GenericMutationButton<
556 Props,
557 Args extends unknown[],
558 Result,
559>(
560 Component: ResolveMutationButtonFc<Props, Args, Result>,
561 props: MutationButtonProps<Args, Result> & Props,
562) {
563 const {
564 mutation,
565 args,
566 onClick,
567 disabled: disabledAttr,
568 onError,
569 onSuccessUi,
570 onSuccessData,
571 onUnauthenticated,
572 onSettled,
573 showNotAllowed,
574 ...forwarded
575 } = props;
576 forwarded satisfies Omit<Props, keyof MutationButtonProps<Args, Result>>;
577
578 const localHook = useMutate("subscribe" in mutation ? mutation : null);
579 const state = "subscribe" in mutation ? localHook : mutation;
580 const disabled = disabledAttr || args == null || state.isDisabled;
581 const handleClick = useCallback((e: MouseEvent) => {
582 onClick?.(e);
583 if (e.defaultPrevented) return;
584 const computedArgs = typeof args === "function" ? args(e) : args;
585 if (!computedArgs || e.defaultPrevented) return;
586 state.runWithOptions(
587 ...computedArgs,
588 { onSuccessUi, onSuccessData, onError, onUnauthenticated, onSettled },
589 );
590 }, [args, onClick, onError, onSettled, onSuccessUi, onSuccessData, onUnauthenticated, state]);
591
592 // Buttons the user can never click are hidden; a signed-out `auth: true`
593 // button stays visible when it can route the click to the sign-in flow.
594 if (!showNotAllowed && !state.isAllowed && state.isDisabled) return null;
595
596 // NOTE: the JSR has trouble with JSX syntax for some reason.
597 return jsx(
598 Component,
599 {
600 ...forwarded,
601 disabled,
602 onClick: disabled ? undefined : handleClick,
603 isPending: state.isPending,
604 } satisfies Parameters<typeof Component>[0],
605 );
606}