Files
client_panel/app/components/FilesEditor/index.tsx

125 lines
3.3 KiB
TypeScript

"use client";
import { formatDistanceToNow } from "date-fns";
import React, { useEffect, useState, useRef } from "react";
import DocumentIcon from "@/components/Icons/Document";
import FolderIcon from "@/components/Icons/Folder";
import MenuIcon from "@/components/Icons/Menu";
import ContextMenuContainer from "./ContextMenu/container";
const initialContextMenu = {
show: false,
x: 0,
y: 0,
file: null,
};
interface FileProps {
attributes: {
name: string;
modified_at: string;
size: number;
is_file: boolean;
};
}
const Index = () => {
const [apiKey, setApiKey] = useState("");
const [fileList, setFileList] = useState([]);
const [contextMenu, setContextMenu] = useState(initialContextMenu);
const handleClickContextMenu = (
e: React.MouseEvent<HTMLDivElement, MouseEvent>,
file: any
) => {
e.preventDefault();
console.log("Right Clicked", file, e);
const { pageX, pageY } = e;
setContextMenu({ show: true, x: pageX, y: pageY, file });
};
const handleContextMenuClose = () => {
setContextMenu(initialContextMenu);
};
const setCredentials = async () => {
setApiKey("ptlc_aDGU4VHNQuN5t6dyxNzVon3UZLR5ehuySmdR7xsUbMm");
};
const formateDate = (isoDate: string) => {
const date = new Date(isoDate);
return formatDistanceToNow(date, { addSuffix: true });
};
const fetchFiles = async (apiKey: string) => {
try {
const response = await fetch(
"https://ptero.przeqpiciel.com/api/client/servers/0bf192ab/files/list",
{
method: "GET",
headers: {
Authorization: `Bearer ${apiKey.toString()}`,
"Content-Type": "application/json",
},
}
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
setFileList(data.data);
} catch (error) {
console.error("Error fetching data:", error);
}
};
useEffect(() => {
const fetchData = async () => {
await setCredentials();
while (apiKey === "") {
await new Promise((r) => setTimeout(r, 200));
}
await fetchFiles(apiKey);
};
fetchData();
}, [apiKey]);
return (
<>
{contextMenu.show && (
<ContextMenuContainer
x={contextMenu.x}
y={contextMenu.y}
closeContextMenu={handleContextMenuClose}
file={contextMenu.file}
/>
)}
{fileList.map((file: FileProps) => (
<div
isfile={file.attributes.is_file.toString()}
className="flex justify-between gap-4 bg-slate-400 mb-1 hover:bg-slate-500 pl-4 pr-4 pt-1 pb-1 rounded-md"
key={file.attributes.name}
>
<div className="w-10">
{file.attributes.is_file ? <DocumentIcon /> : <FolderIcon />}
</div>
<div className="w-48 text-left">{file.attributes.name}</div>
<div className="w-48 text-right">
{file.attributes.is_file ? file.attributes.size + " bytes" : ""}
</div>
<div title={file.attributes.modified_at} className="w-60 text-right">
{formateDate(file.attributes.modified_at)}
</div>
<div onClick={(e) => handleClickContextMenu(e, file)}>
<MenuIcon />
</div>
</div>
))}
</>
);
};
export default Index;