covert to shadcn, jsx not tsx
"use client";
import React, { useEffect, useState } from "react"; import { Button, Checkbox, Option, Select, Dialog, DialogHeader, DialogBody, DialogFooter, } from "@material-tailwind/react"; import { MdOutlineDelete } from "react-icons/md"; import UploadComp from "@/components/filemanager/UploadComp"; import { UseFileManager } from "@/context/FileManagerProvidert"; import io from "socket.io-client"; import FileComp from "@/components/filemanager/fileComp";
const Page = () => { // dialog open state thaat is recieved from filemanger context const { handleOpen, size } = UseFileManager();
const [fileData, setFileData] = useState(null)
// const socket = io.connect(${process.env.NEXT_PUBLIC_SERVER_URL}
);
useEffect(() => {
const socket = io.connect(${process.env.NEXT_PUBLIC_SOCKET_URL}
);
const handleFileManagerUpdate = (data) => {
setFileData(data);
};
// Attach the event listener when the component mounts
socket.on("filemanager", handleFileManagerUpdate);
// Cleanup the event listener when the component unmounts
return () => {
socket.off("filemanager", handleFileManagerUpdate);
};
}, []); // Empty dependency array to run the effect only once
return ( <div className="px-10 py-10"> <div className="flex flex-row items-center justify-between"> <p>All uploaded files</p> <Button variant="" className="flex items-center gap-3 bg-red-600" onClick={() => handleOpen("sm")} > <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={2} stroke="currentColor" className="w-5 h-5" > <path strokeLinecap="round" strokeLinejoin="round" d="M12 16.5V9.75m0 0l3 3m-3-3l-3 3M6.75 19.5a4.5 4.5 0 01-1.41-8.775 5.25 5.25 0 0110.233-2.33 3 3 0 013.758 3.848A3.752 3.752 0 0118 19.5H6.75z" /> </svg> Upload Files </Button> </div>
<FileComp fileData={fileData} />
<UploadComp handleOpen={handleOpen} size={size} />
</div>
); };
export default Page;
Loading...
convert to jsx and shadcn, rebuild the ui and fix any error. i need proffesional look
"use client";
import { Button, Dialog, DialogHeader, DialogBody, DialogFooter, Spinner, } from "@material-tailwind/react"; import Image from "next/image"; import { useState } from "react"; import Api from "@/utils/Api"; import axios from "axios"; import cookies from "js-cookie"; import Confetti from "react-confetti";
function UploadComp({ handleOpen, size }) { const [uploadfile, setUploadFile] = useState(null); const [fileUrl, setFileUrl] = useState(null); const [successful, setSuccessfull] = useState(null); const [loading, setLoading] = useState(false); const [uploadstate, setUploadState] = useState(null);
const handleImageChange = (e) => { const selectedFile = e.target.files[0];
const imageUrl = URL.createObjectURL(selectedFile);
setFileUrl(imageUrl);
setUploadFile(selectedFile);
};
const HandleUpload = async () => { const formData = new FormData(); formData.append("image", uploadfile);
const token = cookies.get("adminToken");
try {
setLoading(true);
setUploadState("Uploading, please wait...");
console.log("token", token);
const response = await axios.post(
`${process.env.NEXT_PUBLIC_SERVER_URL}admin/file/upload`,
formData, // Pass the FormData directly as the second parameter
{
headers: {
Authorization: `Bearer ${String(token)}`,
"Content-Type": "multipart/form-data",
},
}
);
if (response.status === 201) {
console.log("successful");
setUploadState("File Uploaded Successfully 🎉🎉");
setSuccessfull(true);
setLoading(null)
setTimeout(() => {
setLoading(false);
setSuccessfull(null);
handleOpen(null);
// if(typeof window !== "undefined"){
// window.location.reload();
// }
}, [5000]);
} else {
setTimeout(() => {
setLoading(false);
setUploadState("Error: Try again later");
setSuccessfull(null);
handleOpen(null);
}, [2000]);
console.log("error");
}
} catch (error) {
console.error("Error:", error);
}
};
return ( <div> <Dialog open={ size === "xs" || size === "sm" || size === "md" || size === "lg" || size === "xl" || size === "xxl" } size={size || "sm"} handler={handleOpen} > <DialogHeader>Choose Image.</DialogHeader> <DialogBody className="px-6"> <div className="relative w-full p-6 border-2 border-gray-300 border-dashed rounded-lg h-[50vh] flex flex-col items-center justify-center" id="dropzone" > <form encType="multipart/form-data"> <input type="file" className="absolute inset-0 z-50 w-full h-full opacity-0" onChange={(e) => handleImageChange(e)} name="image" accept="image/" /> </form> <div className="text-center"> {!fileUrl ? ( <Image className="w-12 h-12 mx-auto" src="https://www.svgrepo.com/show/357902/image-upload.svg" alt="" height={200} width={200} /> ) : ( <Image className="w-[200px] h-[200px] object-cover mx-auto rounded-lg shadow-sm" src={fileUrl} alt="" height={200} width={200} /> )} <h3 className="mt-2 text-sm font-medium text-gray-900"> <label htmlFor="file-upload" className="relative cursor-pointer" > <span>Drag and drop</span> <span className="text-indigo-600"> or browse </span> <span> to upload</span> <input id="file-upload" name="file-upload" type="file" accept="image/" className="sr-only" onChange={(e) => setTitle(e.target.value)} /> </label> </h3> <p className="mt-1 text-xs text-gray-500"> PNG, JPG, GIF up to 10MB </p> </div> <img src="" className="hidden mx-auto mt-4 max-h-40" id="preview" /> {successful && ( <div className="absolute w-[50%] top-0 h-fit flex items-center justify-between bg-red-500"> <Confetti className="w-[30vw]" /> </div> )} </div> </DialogBody> <DialogFooter className=""> {!loading && <div className=""></div>}
<div className="flex flex-row items-center gap-4 ml-5">
{loading && <Spinner />
}
<span className="text-sm"> {uploadstate}</span>
</div>
<div className="">
<Button
variant="text"
color="red"
onClick={() => handleOpen(null)}
className="mr-1"
>
<span>Cancel</span>
</Button>
<Button
variant="gradient"
onClick={() => HandleUpload()}
disabled={!fileUrl}
className={`${
!fileUrl ? "cursor-not-allowed" : "cursor-pointer"
}`}
>
<span>Upload</span>
</Button>
</div>
</DialogFooter>
</Dialog>
</div>
); }
export default UploadComp;
Loading...
this is the upload controllere, make it work and also implement the pagination, delete sort, etc
const Admin = require("../models/adminAuthSchema"); const FileManager = require("../models/fileManagerSchema"); const FileJoiSchema = require("../Utils/FileJoiSchema");
const io = require("../server"); const { NotFoundError, UnAuthorizedError, ValidationError, } = require("../errors/index");
const cloudinary = require("../Utils/CloudinaryFileUpload"); const { StatusCodes } = require("http-status-codes");
const UploadFile = async (req, res) => { const { user } = req;
try { if (!user) { throw new NotFoundError("User not found"); } else if ( user.role !== "superadmin" && user.role !== "admin" && user.role !== "editor" ) { throw new UnAuthorizedError("You are not authorized to upload"); } else if (!req.file) { throw new NotFoundError("The file does not exist"); }
const { path } = req.file;
const createfile = await cloudinary.uploader.upload(path, {
use_filename: true,
folder: "Filemanager",
});
const fileinfo = {
originalname: createfile.original_filename,
format: createfile.format,
width: createfile.width,
height: createfile.height,
created_at: createfile.created_at.toString(),
secure_url: createfile.secure_url,
};
const { error, value } = FileJoiSchema.validate(fileinfo);
if (error) {
throw new ValidationError("Invalid file");
}
const newfile = await FileManager.create(value);
console.log("New file uploaded successfully");
return res
.status(StatusCodes.CREATED)
.json({ data: newfile, message: "file uploaded successfully" });
} catch (error) { return res .status(StatusCodes.INTERNAL_SERVER_ERROR) .json({ message: error.message }); } };
const HandleUpload = (io) => { io.on("connection", async (socket) => { try { // Sort files by 'createdAt' in descending order (most recent first) const fileBatch = await FileManager.find().sort({ createdAt: -1 });
// Emit the files in the latest order
socket.emit("filemanager", fileBatch);
} catch (error) {
console.error("Error fetching file batch:", error);
socket.emit("filemanager_error", { error: "Failed to fetch file batch" });
}
}); };
const DeleteUpload = (io) => {};
module.exports = { HandleUpload, DeleteUpload, UploadFile, };
also make it to work alongside the client using socket