All files / packages/components/src utils.ts

100% Statements 13/13
100% Branches 12/12
100% Functions 6/6
100% Lines 11/11

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              171211x                             332x 14154x     14154x     332x             20444x     20444x       97x   20444x 5946x   20444x              
import { clsx } from "clsx";
import type { ClassValue } from "clsx";
import { isNonNullish } from "remeda";
import { twMerge } from "tailwind-merge";
 
import type { TRPCMutationResult, TRPCMutationState } from "~app/trpc";
 
export const cn = (...inputs: ClassValue[]) => twMerge(clsx(inputs));
 
type PropertyKey = string | number | symbol;
type Issue = {
	readonly message: string;
	readonly path?: readonly (PropertyKey | { key: PropertyKey })[] | undefined;
};
 
export type FieldError = (Issue | undefined) | (Issue | undefined)[];
 
// oxlint-disable-next-line typescript/no-explicit-any
type MutationOrState = TRPCMutationResult<any> | TRPCMutationState<any>;
type ValueOrArray<T> = T | T[];
export type MutationsProp = ValueOrArray<MutationOrState | undefined>;
 
export const getMutationLoading = (mutation?: MutationsProp) => {
	const mutations = (
		Array.isArray(mutation) ? mutation : mutation ? [mutation] : []
	).filter(isNonNullish);
	return mutations.some(({ status }) => status === "pending");
};
 
export const getErrorState = ({
	mutation,
	fieldError,
}: {
	mutation?: MutationsProp;
	fieldError?: FieldError;
}) => {
	const mutations = (
		Array.isArray(mutation) ? mutation : mutation ? [mutation] : []
	).filter(isNonNullish);
	const fieldErrorMessages = (
		Array.isArray(fieldError) ? fieldError : [fieldError].filter(Boolean)
	)
		.filter(isNonNullish)
		.map(({ message }) => message)
		.filter(isNonNullish);
	const mutationMessages = mutations
		.map(({ error }) => error?.message)
		.filter(isNonNullish);
	return {
		isWarning: fieldErrorMessages.length !== 0,
		isError: mutationMessages.length !== 0,
		errors:
			fieldErrorMessages.length === 0 ? mutationMessages : fieldErrorMessages,
	};
};