All files / packages/app/utils toasts.ts

93.1% Statements 54/58
66.66% Branches 12/18
100% Functions 29/29
92.72% Lines 51/55

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266                            322x                                                                                                   322x   322x       422x     422x 694x       322x                               5472x   211x 211x 211x   211x     211x 71x   141x 178x       253x                 322x                                                   10089x                       128x         128x     59x         279x 279x   59x             59x                       53x         53x 112x 230x   53x             53x 53x     22x 22x 22x                         30x         30x 69x 147x   29x             30x 30x     24x 24x 23x         10089x 10089x   151x   59x   84x      
import Dataloader from "dataloader";
 
import type { TRPCMutationKey } from "~app/trpc";
import { addToast, closeToastById } from "~components/toast";
import type {
	LifecycleContextWithUpdateFns,
	TRPCMutationOptions,
	ToastContext,
	ToastObject,
	ToastOptions,
	UseContextedMutationOptions,
} from "~mutations/context";
import type { ArrayOf, MaybeAddElementToArray } from "~utils/types";
 
const DELAYS = {
	// Mutation are fired nearly simultaneously
	mutate: 10,
	// Success and errors might wait out a bit
	success: 300,
	error: 300,
};
 
type OnLifecycle<
	K extends "onMutate" | "onSuccess" | "onError",
	Path extends TRPCMutationKey,
	LifecycleContext = unknown,
> = Parameters<NonNullable<TRPCMutationOptions<Path, LifecycleContext>[K]>>;
type OptionsLocal<
	Path extends TRPCMutationKey,
	OuterContext = undefined,
	LifecycleContext = unknown,
> = {
	toastArgs: MaybeAddElementToArray<[], OuterContext>;
	mutateArgs: OnLifecycle<
		"onMutate",
		Path,
		LifecycleContextWithUpdateFns<LifecycleContext>
	>;
	successArgs: OnLifecycle<"onSuccess", Path, LifecycleContext>;
	errorArgs: OnLifecycle<"onError", Path, LifecycleContext>;
	toastObject?: ToastObject;
};
type MutateOptionsKey = "toastArgs" | "mutateArgs";
type ErrorOptionsKey = "toastArgs" | "errorArgs" | "toastObject";
type SuccessOptionsKey = "toastArgs" | "successArgs" | "toastObject";
 
type Dataloaders<
	Path extends TRPCMutationKey,
	OuterContext = undefined,
	LifecycleContext = unknown,
	Options extends OptionsLocal<Path, OuterContext, LifecycleContext> =
		OptionsLocal<Path, OuterContext, LifecycleContext>,
> = {
	mutateDataloader: Dataloader<
		Pick<Options, MutateOptionsKey>,
		ToastObject | undefined,
		string
	>;
	errorDataloader: Dataloader<Pick<Options, ErrorOptionsKey>, void, string>;
	successDataloader: Dataloader<Pick<Options, SuccessOptionsKey>, void, string>;
};
 
const dataloaderStorage: Partial<{
	[Path in TRPCMutationKey]: Dataloaders<Path>;
}> = {};
 
const createArrayOf = <T extends object, R extends unknown[]>(
	inputs: readonly T[],
	extract: (input: T) => R,
): ArrayOf<R> => {
	Iif (!inputs[0]) {
		throw new Error(`Creating ArrayOf requires at least 1 element`);
	}
	return extract(inputs[0]).map((_, index) =>
		inputs.map((input) => extract(input)[index]),
	) as ArrayOf<R>;
};
 
const createDataloader = <
	Input extends object,
	Output,
	OuterContextArgs extends unknown[],
	ActionArgs extends unknown[],
>(
	key: string,
	delay: number,
	getOptions: (
		...args1: ArrayOf<OuterContextArgs>
	) => (...args2: ArrayOf<ActionArgs>) => ToastOptions | undefined,
	getOuterContext: (input: Input) => OuterContextArgs,
	getActionArgs: (input: Input) => ActionArgs,
	runResult: (result: ToastOptions, inputs: readonly Input[]) => Output,
	runPre?: (inputs: readonly Input[]) => void,
) =>
	new Dataloader<Input, Output | undefined, string>(
		(inputs) => {
			runPre?.(inputs);
			const outerContext = createArrayOf(inputs, getOuterContext);
			const actionArgs = createArrayOf(inputs, getActionArgs);
			const toastOptions =
				typeof getOptions === "function"
					? getOptions(...outerContext)(...actionArgs)
					: getOptions;
			if (!toastOptions) {
				return Promise.resolve(inputs.map(() => undefined));
			}
			const result = runResult(toastOptions, inputs);
			return Promise.resolve(inputs.map(() => result));
		},
		{
			batchScheduleFn: (callback) => {
				setTimeout(callback, delay);
			},
			cacheKeyFn: JSON.stringify,
			name: key,
			// We don't want to memoize the response of dataloader as dataloader is just a batcher here
			cache: false,
		},
	);
 
export const getMutationToaster = <
	Path extends TRPCMutationKey,
	OuterContext = undefined,
	LifecycleContext = unknown,
	Options extends OptionsLocal<Path, OuterContext, LifecycleContext> =
		OptionsLocal<Path, OuterContext, LifecycleContext>,
>(
	key: Path,
	toastContext: ToastContext,
	mutateToastOptions: UseContextedMutationOptions<
		Path,
		OuterContext,
		LifecycleContext
	>["mutateToastOptions"],
	errorToastOptions: UseContextedMutationOptions<
		Path,
		OuterContext,
		LifecycleContext
	>["errorToastOptions"],
	successToastOptions: UseContextedMutationOptions<
		Path,
		OuterContext,
		LifecycleContext
	>["successToastOptions"],
) => {
	const dataloaders: Dataloaders<Path, OuterContext, LifecycleContext> =
		(dataloaderStorage[key] as
			| Dataloaders<Path, OuterContext, LifecycleContext>
			| undefined) || {
			mutateDataloader: createDataloader<
				Pick<Options, MutateOptionsKey>,
				{ id: string; count: number },
				Options["toastArgs"],
				Options["mutateArgs"]
			>(
				key,
				DELAYS.mutate,
				(...toastArgs) =>
					(
						...mutateArgs: ArrayOf<
							OnLifecycle<"onMutate", Path, LifecycleContext>
						>
					) => {
						Iif (!mutateToastOptions) {
							return;
						}
						return mutateToastOptions(
							toastContext,
							...toastArgs,
						)(...mutateArgs);
					},
				(input) => input.toastArgs,
				(input) => input.mutateArgs,
				(result, inputs) => {
					const toastId = addToast({
						title: toastContext.t("toasts.header.mutate"),
						description: result.text,
						timeout: Infinity,
					});
					// We always have a toast queue
					// oxlint-disable-next-line typescript/no-non-null-assertion
					return { id: toastId!, count: inputs.length };
				},
			),
			errorDataloader: createDataloader<
				Pick<Options, ErrorOptionsKey>,
				void,
				Options["toastArgs"],
				Options["errorArgs"]
			>(
				key,
				DELAYS.error,
				(...toastArgs) =>
					(
						...errorArgs: ArrayOf<
							OnLifecycle<"onError", Path, LifecycleContext>
						>
					) =>
						errorToastOptions(toastContext, ...toastArgs)(...errorArgs),
				(input) => input.toastArgs,
				(input) => input.errorArgs,
				(result) => {
					addToast({
						title: toastContext.t("toasts.header.error"),
						description: result.text,
						color: "danger",
					});
				},
				(inputs) => {
					const toastObject = inputs[0]?.toastObject;
					Iif (!toastObject) {
						return;
					}
					toastObject.count -= inputs.length;
					Eif (toastObject.count === 0) {
						closeToastById(toastObject.id);
					}
				},
			),
			successDataloader: createDataloader<
				Pick<Options, SuccessOptionsKey>,
				void,
				Options["toastArgs"],
				Options["successArgs"]
			>(
				key,
				DELAYS.success,
				(...toastArgs) =>
					(
						...successArgs: ArrayOf<
							OnLifecycle<"onSuccess", Path, LifecycleContext>
						>
					) =>
						successToastOptions?.(toastContext, ...toastArgs)(...successArgs),
				(input) => input.toastArgs,
				(input) => input.successArgs,
				(result) => {
					addToast({
						title: toastContext.t("toasts.header.success"),
						description: result.text,
						color: "success",
					});
				},
				(inputs) => {
					const toastObject = inputs[0]?.toastObject;
					Iif (!toastObject) {
						return;
					}
					toastObject.count -= inputs.length;
					if (toastObject.count === 0) {
						closeToastById(toastObject.id);
					}
				},
			),
		};
	dataloaderStorage[key] = dataloaders as unknown as Dataloaders<Path>;
	return {
		mutateToast: (input: Pick<Options, MutateOptionsKey>) =>
			dataloaders.mutateDataloader.load(input),
		errorToast: (input: Pick<Options, ErrorOptionsKey>) =>
			dataloaders.errorDataloader.load(input),
		successToast: (input: Pick<Options, SuccessOptionsKey>) =>
			dataloaders.successDataloader.load(input),
	};
};