All files / packages/app/features/user user-avatar-input.tsx

94% Statements 47/50
95.45% Branches 21/22
90% Functions 18/20
95.91% Lines 47/49

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 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296                                                  23x   23x   492x     492x 492x 489x   492x         23x   96x     96x 96x                               23x                           525x 571x 571x       571x   571x     1x       571x               571x               1x 1x 1x         571x       1x 1x           571x 571x       571x 571x       571x 1x   571x 571x 571x       244x     244x         571x                               2139x   496x     739x             246x                                                                                   492x                               2139x   496x                                                                                       280x 2x                  
import React from "react";
 
import { useMutation, useSuspenseQuery } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { doNothing } from "remeda";
import { z } from "zod";
 
import { ConfirmModal } from "~app/components/confirm-modal";
import { suspendedFallback } from "~app/components/suspense-wrapper";
import { useBooleanState } from "~app/hooks/use-boolean-state";
import { useTrpcMutationOptions } from "~app/hooks/use-trpc-mutation-options";
import { useAppForm } from "~app/utils/forms";
import { useTRPC } from "~app/utils/trpc";
import { Avatar } from "~components/avatar";
import { Button } from "~components/button";
import { Card } from "~components/card";
import { FileInput } from "~components/file-input";
import { Icon } from "~components/icons";
import { ImageCropper, getFormData } from "~components/image-cropper";
import { SkeletonAvatar } from "~components/skeleton-avatar";
import { Slider } from "~components/slider";
import { Text } from "~components/text";
import { View } from "~components/view";
import { options as userChangeAvatarOptions } from "~mutations/user/change-avatar";
 
const MAX_ZOOM = 5;
 
const OnlyAvatarButton = suspendedFallback<React.ComponentProps<typeof Button>>(
	(props) => {
		const trpc = useTRPC();
		const {
			data: { user },
		} = useSuspenseQuery(trpc.user.get.queryOptions());
		if (!user.avatarUrl) {
			return null;
		}
		return <Button {...props} />;
	},
	null,
);
 
const PeerAvatar = suspendedFallback<{ onClick: () => void }>(
	({ onClick }) => {
		const trpc = useTRPC();
		const {
			data: { user },
		} = useSuspenseQuery(trpc.user.get.queryOptions());
		return (
			<Avatar
				hashId={user.id}
				image={
					user.avatarUrl ? { url: user.avatarUrl, alt: user.email } : undefined
				}
				onPress={onClick}
				size="lg"
				className="cursor-pointer"
				testID="avatar-button"
			/>
		);
	},
	<SkeletonAvatar size="lg" />,
);
 
const formSchema = z.strictObject({
	avatar: z.string(),
	croppedArea: z.strictObject({
		x: z.int().nonnegative(),
		y: z.int().nonnegative(),
		width: z.int().positive(),
		height: z.int().positive(),
	}),
});
 
type Form = z.infer<typeof formSchema>;
 
type Props = React.PropsWithChildren;
 
export const UserAvatarInput: React.FC<Props> = ({ children }) => {
	const { t } = useTranslation("user");
	const trpc = useTRPC();
	const [
		isAvatarEditorOpen,
		{ setTrue: enableAvatarEdit, setFalse: disableAvatarEdit },
	] = useBooleanState();
 
	const updateAvatarMutation = useMutation(
		trpc.user.changeAvatar.mutationOptions(
			useTrpcMutationOptions(userChangeAvatarOptions, {
				onSuccess: () => disableAvatarEdit(),
			}),
		),
	);
	const defaultValues: Partial<Form> = {
		croppedArea: {
			x: 0,
			y: 0,
			width: 0,
			height: 0,
		},
	};
	const form = useAppForm({
		defaultValues: defaultValues as Form,
		validators: {
			onMount: formSchema,
			onChange: formSchema,
			onSubmit: formSchema,
		},
		onSubmit: async ({ value, formApi }) => {
			const formData = await getFormData(value.avatar, value.croppedArea);
			updateAvatarMutation.mutate(formData, {
				onSuccess: () => formApi.reset(),
			});
		},
	});
 
	const removeAvatarMutation = useMutation(
		trpc.user.changeAvatar.mutationOptions(
			useTrpcMutationOptions(userChangeAvatarOptions, {
				onSuccess: () => {
					disableAvatarEdit();
					form.reset();
				},
			}),
		),
	);
 
	const [zoom, setZoom] = React.useState(1);
	const [crop, setCrop] = React.useState<
		React.ComponentProps<typeof ImageCropper>["crop"]
	>({ x: 0, y: 0 });
	// oxlint-disable-next-line typescript/strict-void-return
	const inputClickRef = React.useRef<() => void>(doNothing);
	const onInputButtonClick = React.useCallback(() => {
		inputClickRef.current();
	}, []);
 
	const resetAvatar = React.useCallback(() => {
		removeAvatarMutation.mutate(new FormData());
	}, [removeAvatarMutation]);
	const resetEditor = React.useCallback(() => form.reset(), [form]);
	const avatar = <PeerAvatar onClick={enableAvatarEdit} />;
	const onCropChange = React.useCallback<
		React.ComponentProps<typeof ImageCropper>["onCropChange"]
	>(
		(nextCrop) => {
			Iif (updateAvatarMutation.isPending || removeAvatarMutation.isPending) {
				return;
			}
			setCrop(nextCrop);
		},
		[removeAvatarMutation.isPending, updateAvatarMutation.isPending],
	);
 
	return (
		<form.AppForm>
			<form.Form className="flex flex-row gap-4" testID="avatar-form">
				{isAvatarEditorOpen ? (
					<View className="h-80 flex-1 flex-row justify-between gap-4">
						<Slider
							className="z-10 h-full"
							label={t("avatar.slider.label")}
							minValue={1}
							maxValue={MAX_ZOOM}
							step={0.01}
							orientation="vertical"
							value={zoom}
							onChange={setZoom}
						/>
 
						<form.Subscribe selector={(state) => state.values.avatar}>
							{(selectedAvatar) =>
								selectedAvatar ? (
									<form.AppField name="croppedArea">
										{(field) => (
											<ImageCropper
												image={selectedAvatar}
												crop={crop}
												zoom={zoom}
												maxZoom={MAX_ZOOM}
												onCropChange={onCropChange}
												onCropComplete={(_area, areaPixels) =>
													field.setValue(areaPixels)
												}
												onZoomChange={setZoom}
											/>
										)}
									</form.AppField>
								) : (
									<Card
										className="w-full"
										bodyClassName="cursor-pointer items-center justify-center"
										onPress={onInputButtonClick}
									>
										<View className="absolute top-0 left-0 m-4 opacity-30">
											{avatar}
										</View>
										<Text>{t("avatar.uploadImage.text")}</Text>
									</Card>
								)
							}
						</form.Subscribe>
						<View className="gap-4">
							<Button
								color="warning"
								variant="bordered"
								isDisabled={
									updateAvatarMutation.isPending ||
									removeAvatarMutation.isPending
								}
								onPress={disableAvatarEdit}
								isIconOnly
								aria-label={t("avatar.closeEditor")}
							>
								<Icon name="close" className="size-6" />
							</Button>
							<ConfirmModal
								onConfirm={resetAvatar}
								isLoading={removeAvatarMutation.isPending}
								title={t("avatar.remove.title")}
								subtitle={t("avatar.remove.subtitle")}
								confirmText={t("avatar.remove.confirm")}
							>
								{({ openModal }) => (
									<OnlyAvatarButton
										color="danger"
										variant="bordered"
										isLoading={removeAvatarMutation.isPending}
										isDisabled={
											updateAvatarMutation.isPending ||
											removeAvatarMutation.isPending
										}
										onPress={openModal}
										isIconOnly
										aria-label={t("avatar.remove.title")}
									>
										<Icon name="trash" className="size-6" />
									</OnlyAvatarButton>
								)}
							</ConfirmModal>
							<form.Subscribe selector={(state) => state.values.avatar}>
								{(selectedAvatar) => (
									<>
										<Button
											color="warning"
											variant="bordered"
											isDisabled={
												updateAvatarMutation.isPending ||
												removeAvatarMutation.isPending ||
												!selectedAvatar
											}
											onPress={resetEditor}
											isIconOnly
											aria-label={t("avatar.resetAvatar")}
										>
											<Icon name="sync" className="size-6" />
										</Button>
										<Button
											color="success"
											variant="bordered"
											isLoading={updateAvatarMutation.isPending}
											isDisabled={
												updateAvatarMutation.isPending ||
												removeAvatarMutation.isPending ||
												!selectedAvatar
											}
											type="submit"
											isIconOnly
											aria-label={t("avatar.saveAvatar")}
										>
											<Icon name="check" className="size-6" />
										</Button>
									</>
								)}
							</form.Subscribe>
						</View>
					</View>
				) : (
					<>
						{avatar}
						{children}
					</>
				)}
 
				<form.AppField name="avatar">
					{(field) => (
						<FileInput
							onFileUpdate={(dataUrl) => field.setValue(dataUrl)}
							onClickRef={inputClickRef}
						/>
					)}
				</form.AppField>
			</form.Form>
		</form.AppForm>
	);
};