Skip to content

Commit

Permalink
fix(image): pr comments
Browse files Browse the repository at this point in the history
  • Loading branch information
NicoSerranoP committed Dec 17, 2024
1 parent ccfc38e commit b97e8a1
Showing 1 changed file with 24 additions and 19 deletions.
43 changes: 24 additions & 19 deletions packages/interface/src/components/ImageUpload.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
/* eslint-disable react/require-default-props */

import { useMutation } from "@tanstack/react-query";
import clsx from "clsx";
import { ImageIcon } from "lucide-react";
import { type ComponentProps, ElementType, forwardRef, useRef, useCallback } from "react";
import { type ComponentProps, forwardRef, useRef, useCallback, ChangeEvent } from "react";
import { Controller, useFormContext } from "react-hook-form";
import { toast } from "sonner";

import { IconButton } from "~/components/ui/Button";

import { PolymorphicRef } from "./ui";

export interface IImageUploadProps extends ComponentProps<"img"> {
name?: string;
maxSize?: number;
Expand All @@ -22,7 +22,7 @@ export const ImageUpload = forwardRef(
className,
}: IImageUploadProps,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
ref: PolymorphicRef<ElementType>,
_,
): JSX.Element => {
const internalRef = useRef<HTMLInputElement>(null);
const { control } = useFormContext();
Expand All @@ -44,18 +44,31 @@ export const ImageUpload = forwardRef(
e.preventDefault();
}, []);

const onClickContainer = useCallback(() => {
internalRef.current?.click();
}, [internalRef]);

const onChangeInputImage = useCallback(
(event: ChangeEvent<HTMLInputElement>, onChange: (event: string) => void) => {
const [file] = event.target.files ?? [];
if (file) {
select.mutate(file, {
onSuccess: (objectUrl) => {
onChange(objectUrl);
},
});
}
},
[select],
);

return (
<Controller
control={control}
name={name}
render={({ field: { value, onChange, ...field } }) => (
// eslint-disable-next-line jsx-a11y/no-static-element-interactions, jsx-a11y/click-events-have-key-events
<div
className={clsx("relative cursor-pointer overflow-hidden", className)}
onClick={() => {
internalRef.current?.click();
}}
>
<div className={clsx("relative cursor-pointer overflow-hidden", className)} onClick={onClickContainer}>
<IconButton className="absolute bottom-1 right-1" icon={ImageIcon} onClick={onClickIconButton} />

<div
Expand All @@ -71,16 +84,8 @@ export const ImageUpload = forwardRef(
accept="image/png, image/jpeg"
className="hidden"
type="file"
// value={value?.[name]}
onChange={(event) => {
const [file] = event.target.files ?? [];
if (file) {
select.mutate(file, {
onSuccess: (objectUrl) => {
onChange(objectUrl);
},
});
}
onChangeInputImage(event, onChange);
}}
/>
</div>
Expand Down

0 comments on commit b97e8a1

Please sign in to comment.