Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: image dropzone field #85

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions apps/nextjs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@
"framer-motion": "^10.16.4",
"next": "^13.5.4",
"react": "18.2.0",
"react-avatar-editor": "14.0.0-beta.5",
"react-dom": "18.2.0",
"react-dropzone": "^14.2.3",
"react-hook-form": "^7.47.0",
"react-icons": "^4.11.0",
"react-markdown": "^9.0.0",
Expand All @@ -48,6 +50,7 @@
"@tailwindcss/typography": "^0.5.10",
"@types/node": "^18.17.19",
"@types/react": "^18.2.25",
"@types/react-avatar-editor": "^13.0.2",
"@types/react-dom": "^18.2.10",
"dotenv-cli": "^7.3.0",
"eslint": "^8.50.0",
Expand Down
71 changes: 71 additions & 0 deletions apps/nextjs/src/app/_components/Dropzone.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import React, { useCallback, useState } from "react";
import classNames from "classnames";
import type { FileRejection } from "react-dropzone";
import { ErrorCode, useDropzone } from "react-dropzone";

import { ACCEPTED_MIME_TYPES, MAX_FILE_SIZE } from "../_lib/constants";
import {
INVALID_IMAGE_MIME_TYPES,
INVALID_IMAGE_SIZE,
} from "../_lib/validations";

/* Props - <Dropzone />
============================================================================= */
interface Props {
className?: string;
children: React.ReactNode;
}

/* <Dropzone />
============================================================================= */
const Dropzone: React.FC<Props> = ({ className, children }) => {
const [selectedFile, setSelectedFile] = useState<File | null>(null);
const [errors, setErrors] = useState<string[] | null>(null);

// const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop });
const onDropRejected = useCallback((fileRejections: FileRejection[]) => {
// Customize errors message
const err = fileRejections[0]?.errors.map((error) => {
return (
{
[ErrorCode.FileInvalidType]: INVALID_IMAGE_MIME_TYPES,
[ErrorCode.FileTooLarge]: INVALID_IMAGE_SIZE,
}[error.code] || error.message
);
});

setErrors(err);
}, []);

const onDropAccepted = useCallback((acceptedFiles: File[]) => {
setErrors(null);
setSelectedFile(acceptedFiles[0] ?? null);
}, []);

// FIXME: types seems to be broken
// eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-assignment
const { getRootProps, getInputProps, isDragActive } = useDropzone({
// accept awaits object in format `{'image/*': []}`
accept: ACCEPTED_MIME_TYPES.reduce(
(mimes, type) => ({ ...mimes, [type]: [] }),
{},
),
onDropRejected,
onDropAccepted,
multiple: false,
maxSize: MAX_FILE_SIZE,
});

return (
<div {...getRootProps()}>
<input {...getInputProps()} />
{isDragActive ? (
<p>Drop the files here ...</p>
) : (
<p>Drag 'n' drop some files here, or click to select files</p>
)}
</div>
);
};

export default Dropzone;
56 changes: 56 additions & 0 deletions apps/nextjs/src/app/_components/form/ImageField.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { useEffect, useId, useRef, useState } from "react";
import type { InputHTMLAttributes } from "react";
import classNames from "classnames";
import type AvatarEditor from "react-avatar-editor";
import { ErrorCode, useDropzone } from "react-dropzone";
import { useFormContext } from "react-hook-form";
import { toast } from "react-toastify";

import Button from "../button";
import ErrorMessage from "./ErrorMessage";
import Label from "./Label";

/* Props - <ImageField />
============================================================================= */
type Props = {
label: string;
name: string;
className?: string;
} & InputHTMLAttributes<HTMLInputElement>;

/* <ImageField />
============================================================================= */
const ImageField: React.FC<Props> = ({ label, className, ...props }) => {
const avatarEditorRef = useRef<AvatarEditor>(null);
const [scale, setScale] = useState<number>(1.2);
const id = useId();
const {
register,
formState: { errors },
} = useFormContext();

return (
<figure className={classNames(className)}>
<Label htmlFor={`image-field-${id}`} className="block">
{label}
</Label>

<div
className={classNames(
"border-olive-green m-auto flex h-64 w-64 flex-col items-center justify-center rounded-full border-2 border-dashed text-center",
)}
>
<input
className="visibility-hidden"
type="file"
accept="image/*"
{...getInputProps()}
/>
</div>

<ErrorMessage error={errors[props.name]} />
</figure>
);
};

export default ImageField;
21 changes: 21 additions & 0 deletions apps/nextjs/src/app/_lib/validations.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { MB_BYTES } from "./constants";

// Zod validation constants
export const INVALID_EMAIL = "Неправильний E-mail";
export const INVALID_PASSWORD = "Неправильний пароль";
export const INVALID_PHONE = "Перевірте правельність номеру телефону";
export const INVALID_PHONE_STARTS_FROM_ZERO =
"Телефон не може починатися з нуля, перевірте правильність вводу";
export const INVALID_CONFIRM_PASSWORD = "Паролі не співпадають";
export const INVALID_IMAGE_MIME_TYPES =
"Підтримуються тільки наступні формати зображення .jpg, .jpeg, .png та .webp.";
export const INVALID_IMAGE_SIZE = `Файл завеликий. Завантажте зображення до ${MB_BYTES}Mb`;

export const REQUIRED_NAME = "Введіть ваше ім'я";
export const REQUIRED_EMAIL = "Введіть ваш E-mail";
export const REQUIRED_PHONE = "Введіть ваш номер телефону";
export const REQUIRED_PASSWORD = "Пароль має бути довжиною мінімум 8 символів";
export const REQUIRED_FILE = "Завантажте файл";

export const PHONE_REGEX = /^(\+380) \(\d{2}\) \d{3}\-\d{4}$/;
export const PHONE_REGEX_STARTS_FROM_ZERO = /^(\+380) \([^0].*$/;
49 changes: 49 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading