Certainly! Below is an optimized version of your custom ContentsInput component and the associated ImageInput component. This refactored implementation leverages React Hook Form for efficient form state management and Zod for schema validation. Additionally, it ensures optimal code readability, maintainability, and adherence to industry best practices.
Key Enhancements:
-
Form State Management with React Hook Form:
- Utilizes
useForm and useFieldArray for handling dynamic fields efficiently.
- Simplifies state management, reducing the need for multiple
useState hooks.
-
Schema Validation with Zod:
- Ensures type-safe form data with predefined schemas.
- Provides clear error messages and validation rules.
-
Asynchronous Operations:
- Implements debounced auto-saving using
useEffect and setTimeout.
- Handles file uploads and deletions via API routes, ensuring separation of concerns.
-
Optimized Component Structure:
- Separates concerns by handling image uploads in the
ImageInput component.
- Ensures components are reusable and maintainable.
-
Error Handling and User Feedback:
- Provides clear feedback to users during save operations.
- Allows retrying failed save attempts.
-
Type Safety and ESLint Compliance:
- Ensures all TypeScript types are correctly defined and used.
- Adheres to ESLint rules to maintain code quality.
1. Define Zod Schemas
First, define the Zod schemas for IContent to enforce validation rules.
// validation/content.schema.ts
import { z } from "zod";
export const contentSchema = z.object({
type: z.enum(["text", "image"]),
content: z.string().min(1, "Content cannot be empty"),
});
export const contentsSchema = z.array(contentSchema);
export type IContent = z.infer<typeof contentSchema>;
export type FormData = z.infer<typeof z.object({ contents: contentsSchema })>;
2. API Routes for File Operations
Ensure you have API routes to handle file uploads and deletions. This separation aligns with best practices, keeping server actions distinct from client components.
// app/api/uploadFile/route.ts
import { NextResponse } from "next/server";
import { uploadFile } from "@/app/actions/server/default.action"; // Adjust the import path accordingly
export async function POST(request: Request) {
try {
const formData = await request.formData();
const fileId = await uploadFile(formData);
return NextResponse.json({ fileId }, { status: 200 });
} catch (error) {
console.error("Upload Error:", error);
return NextResponse.json({ error: "File upload failed" }, { status: 500 });
}
}
// app/api/deleteFile/route.ts
import { NextResponse } from "next/server";
import { deleteFile } from "@/app/actions/server/default.action"; // Adjust the import path accordingly
export async function DELETE(request: Request) {
try {
const { fileId } = await request.json();
await deleteFile(fileId);
return NextResponse.json({ message: "File deleted successfully" }, { status: 200 });
} catch (error) {
console.error("Delete Error:", error);
return NextResponse.json({ error: "File deletion failed" }, { status: 500 });
}
}
3. Optimized ContentsInput Component
Here's the refactored ContentsInput component using React Hook Form and Zod:
// components/c-ui/contents/input/index.tsx
"use client";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { cn } from "@/lib/utils";
import { VariantProps, cva } from "class-variance-authority";
import {
CheckIcon,
ImagePlusIcon,
ListPlusIcon,
SaveIcon,
TrashIcon,
} from "lucide-react";
import { useState, useRef, useEffect } from "react";
import ImageInput from "./image";
import { IContent, contentsSchema } from "@/validation/content.schema";
import { useForm, useFieldArray, Controller } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
interface IContentsInputProps
extends VariantProps<typeof contentsInputVariant> {
keyPrefix: string;
label?: string;
defaultValue?: IContent[];
onChange?: (value: IContent[]) => void;
onSave?: (value: IContent[]) => Promise<void>;
disabled?: boolean;
placeholder?: string;
}
const contentsInputVariant = cva("flex flex-col gap-3");
const fieldInputVariant = cva("flex gap-2 items-start");
const textInputVariant = cva("resize-none w-full");
const ContentsInput: React.FC<IContentsInputProps> = ({
keyPrefix,
label = "Contents",
defaultValue = [],
onChange,
onSave,
disabled = false,
placeholder,
className,
...props
}) => {
const {
control,
handleSubmit,
watch,
reset,
formState: { errors },
} = useForm<{
contents: IContent[];
}>({
resolver: zodResolver(
z.object({
contents: contentsSchema,
})
),
defaultValues: { contents: defaultValue },
});
const { fields, append, remove } = useFieldArray({
control,
name: "contents",
});
const [status, setStatus] = useState<"idle" | "saving" | "saved" | "failed">(
"idle"
);
const saveTimeoutRef = useRef<NodeJS.Timeout | null>(null);
const watchedContents = watch("contents");
// Handle onChange prop
useEffect(() => {
if (onChange) {
onChange(watchedContents);
}
}, [watchedContents, onChange]);
// Handle auto-save with debouncing
useEffect(() => {
if (!onSave) return;
setStatus("saving");
setStatus("saving");
if (saveTimeoutRef.current) {
clearTimeout(saveTimeoutRef.current);
}
saveTimeoutRef.current = setTimeout(async () => {
try {
await onSave(watchedContents);
setStatus("saved");
} catch (error) {
setStatus("failed");
console.error("Save Error:", error);
} finally {
// Reset status after some time
setTimeout(() => setStatus("idle"), 3000);
}
}, 2000);
return () => {
if (saveTimeoutRef.current) {
clearTimeout(saveTimeoutRef.current);
}
};
}, [watchedContents, onSave]);
// Handle adding new content
const handleAdd = (type: "text" | "image") => {
append({ type, content: "" });
};
// Handle deleting content
const handleDelete = async (index: number) => {
const content = watchedContents[index];
if (content.type === "image") {
const fileId = extractFileId(content.content);
if (fileId && onSave) {
try {
await fetch("/api/deleteFile", {
method: "DELETE",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ fileId }),
});
} catch (error) {
console.error("Delete File Error:", error);
}
}
}
remove(index);
};
// Extract fileId from the URL
const extractFileId = (url: string): string | null => {
const regex = /fileId=([^&]+)/;
const match = url.match(regex);
return match ? match[1] : null;
};
return (
<div className={cn(contentsInputVariant(), className)} {...props}>
<div className="flex items-center justify-between">
<Label>{label}</Label>
<div className="flex items-center gap-2">
{status === "saving" && (
<div className="flex items-center px-2 text-primary">
<div className="h-4 w-4 animate-spin rounded-full border-2 border-t-2 border-primary mr-1"></div>
<span className="text-sm">Saving...</span>
</div>
)}
{status === "saved" && (
<div className="flex items-center px-2 text-success">
<CheckIcon className="h-4 w-4 mr-1" />
<span className="text-sm">Saved</span>
</div>
)}
{status === "failed" && (
<Button
size="sm"
variant="ghost"
color="destructive"
onClick={() => handleSubmit(onSave)()}
disabled={disabled}
>
<SaveIcon className="h-4 w-4 mr-1" />
Try Again
</Button>
)}
<Button
size="sm"
onClick={() => handleAdd("text")}
disabled={disabled}
>
<ListPlusIcon className="h-4 w-4 mr-1" />
Add Text
</Button>
<Button
size="sm"
onClick={() => handleAdd("image")}
disabled={disabled}
>
<ImagePlusIcon className="h-4 w-4 mr-1" />
Upload Image
</Button>
</div>
</div>
{watchedContents.length === 0 && placeholder && (
<div className="flex items-center justify-center py-5 px-10">
<p className="text-center text-neutral-foreground text-lg font-medium">
{placeholder}
</p>
</div>
)}
{fields.map((field, index) => (
<div key={field.id} className={cn(fieldInputVariant())}>
<Controller
control={control}
name={`contents.${index}.content`}
render={({ field: controllerField, fieldState }) => {
if (watchedContents[index].type === "text") {
return (
<Textarea
{...controllerField}
className={cn(textInputVariant(), {
"border-red-500":
fieldState.error?.message !== undefined,
})}
placeholder={placeholder}
disabled={disabled}
/>
);
} else if (watchedContents[index].type === "image") {
return (
<ImageInput
name={`contents.${index}.content`}
control={control}
disabled={disabled}
size="md" // You can make size dynamic if needed
/>
);
}
return null;
}}
/>
<Button
variant="ghost"
color="destructive"
size="icon"
onClick={() => handleDelete(index)}
disabled={disabled}
>
<TrashIcon className="h-4 w-4" />
</Button>
</div>
))}
</div>
);
};
export default ContentsInput;
4. Optimized ImageInput Component
Refactor the ImageInput to integrate seamlessly with React Hook Form and handle asynchronous uploads.
// components/c-ui/contents/input/image.tsx
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import Image from "next/image";
import React, { useState } from "react";
import { ImagePlusIcon } from "lucide-react";
import { useController, Control } from "react-hook-form";
interface IProps {
name: string;
control: Control<any>;
disabled: boolean;
size: "md" | "lg";
}
const ImageInput: React.FC<IProps> = ({
name,
control,
disabled,
size,
}) => {
const {
field: { value, onChange },
fieldState: { error },
} = useController({
name,
control,
});
const [uploading, setUploading] = useState(false);
const [uploadError, setUploadError] = useState<string | null>(null);
const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
setUploading(true);
setUploadError(null);
const formData = new FormData();
formData.append("file", file);
try {
const response = await fetch("/api/uploadFile", {
method: "POST",
body: formData,
});
if (!response.ok) {
throw new Error("File upload failed");
}
const data = await response.json();
const fileUrl = `https://app.ehllie.com/api/file/image?fileId=${data.fileId}`;
onChange(fileUrl);
} catch (err) {
console.error(err);
setUploadError("Failed to upload image. Please try again.");
} finally {
setUploading(false);
}
};
const displayUrl = value.startsWith("https://app.ehllie.com/")
? value.replace("https://app.ehllie.com/", "/")
: value;
return (
<Label htmlFor={name} className="cursor-pointer w-full">
{value ? (
<Image
src={displayUrl}
alt="Uploaded Image"
width={800}
height={800}
className={`${
size === "md" ? "w-full sm:w-96" : "w-full sm:w-full"
} rounded-md object-contain`}
/>
) : (
<UploadPlaceholder />
)}
{uploading && (
<div className="absolute inset-0 flex items-center justify-center bg-gray-200 bg-opacity-50 rounded-md">
<div className="loader"></div>
</div>
)}
{uploadError && (
<p className="text-red-500 text-sm mt-2">{uploadError}</p>
)}
<Input
id={name}
type="file"
accept="image/*"
className="hidden"
onChange={handleUpload}
disabled={disabled || uploading}
/>
</Label>
);
};
export default ImageInput;
const UploadPlaceholder: React.FC = () => (
<div className="h-72 w-full sm:w-96 flex flex-col items-center justify-center space-y-4 border-2 border-dashed border-neutral-foreground rounded-md">
<ImagePlusIcon className="h-10 w-10 text-neutral-foreground" />
<p className="text-center text-lg font-medium text-neutral-foreground">
Upload an image of your diagram or handwritten answer
</p>
</div>
);
5. Styling and Utilities
Ensure that your utility functions and styles are correctly defined to support the components.
// lib/utils.ts
export const cn = (...classes: (string | undefined | false)[]) => {
return classes.filter(Boolean).join(" ");
};
6. Server Actions Adjustment
To align with the API routes, adjust your server actions accordingly.
// app/actions/server/default.action.ts
import File from "@/database/models/file.model";
import Submission from "@/database/models/submission.model";
import { generateCode } from "@/lib/utils";
import { getSession } from "@auth0/nextjs-auth0";
export const createSubmission = async (questionId: string): Promise<string> => {
const session = await getSession();
if (!session) throw new Error("Unauthorized");
let invite = generateCode(6);
let isUnique = false;
while (!isUnique) {
const submission = await Submission.exists({ invite });
if (!submission) isUnique = true;
else invite = generateCode(6);
}
const newSubmission = new Submission({
teacherId: session.user.email,
questionId,
invite,
});
await newSubmission.save();
return newSubmission._id;
};
export const uploadFile = async (formData: FormData): Promise<string> => {
const file = formData.get("file");
if (!(file instanceof File)) throw new Error("Invalid file");
const buffer = Buffer.from(await file.arrayBuffer());
const contentType = file.type;
const newFile = new File({
contentType,
data: buffer,
});
await newFile.save();
return newFile._id;
};
export const deleteFileAction = async (fileId: string): Promise<void> => {
await File.findByIdAndDelete(fileId);
};
Note: Ensure that your API routes correctly invoke these server actions.
7. ESLint and TypeScript Compliance
Ensure that your tsconfig.json and .eslintrc.js are correctly set up to prevent type and linting errors. Here's a basic setup:
// tsconfig.json
{
"compilerOptions": {
"target": "ES6",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": false,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "ESNext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"types": ["node"]
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
// .eslintrc.js
module.exports = {
parser: "@typescript-eslint/parser",
parserOptions: {
ecmaVersion: 2020,
sourceType: "module",
ecmaFeatures: {
jsx: true,
},
},
plugins: ["@typescript-eslint", "react"],
extends: [
"eslint:recommended",
"plugin:react/recommended",
"plugin:@typescript-eslint/recommended",
"next/core-web-vitals",
],
rules: {
// Add or override rules as needed
"react/react-in-jsx-scope": "off", // Next.js handles React import
},
settings: {
react: {
version: "detect",
},
},
};
8. Final Remarks
This optimized implementation ensures:
-
Efficiency: By leveraging React Hook Form and Zod, form state and validations are handled efficiently without unnecessary re-renders.
-
Readability: Clear component structures and separation of concerns make the codebase easier to understand and maintain.
-
Scalability: The use of dynamic field arrays (useFieldArray) allows for easy scalability when dealing with varying numbers of content blocks.
-
User Experience: Debounced auto-saving provides a seamless experience, with clear feedback during save operations.
Ensure that all paths and imports are correctly adjusted based on your project's structure. Additionally, test all functionalities thoroughly to confirm seamless integration between the client and server components.