mirror of
https://github.com/Buriburizaem0n/admin-frontend-domain.git
synced 2026-02-05 05:00:06 +00:00
implement remaining features of the server page (#9)
* implement remaining features of the server page * fix fm init * ?
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useState, useRef } from "react"
|
||||
import { useEffect, useState, useRef, HTMLAttributes } from "react"
|
||||
import {
|
||||
Sheet,
|
||||
SheetTrigger,
|
||||
@@ -9,18 +9,160 @@ import {
|
||||
} from "./xui/overlayless-sheet"
|
||||
import { IconButton } from "./xui/icon-button"
|
||||
import { createFM } from "@/api/fm"
|
||||
import { ModelCreateFMResponse } from "@/types"
|
||||
import { ModelCreateFMResponse, FMEntry, FMOpcode, FMIdentifier, FMWorkerData, FMWorkerOpcode } from "@/types"
|
||||
import useWebSocket from "react-use-websocket"
|
||||
import { toast } from "sonner"
|
||||
import { ColumnDef } from "@tanstack/react-table"
|
||||
import { Folder, File } from "lucide-react"
|
||||
import { fm, formatPath, fmWorker as worker } from "@/lib/utils"
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
AlertDialogFooter,
|
||||
AlertDialogCancel,
|
||||
AlertDialogAction,
|
||||
} from "@/components/ui/alert-dialog"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { Row, flexRender } from "@tanstack/react-table"
|
||||
import { TableRow, TableCell } from "./ui/table"
|
||||
import { DataTable } from "./xui/virtulized-data-table"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Filepath } from "./xui/filepath"
|
||||
|
||||
interface FMProps {
|
||||
wsUrl: string;
|
||||
}
|
||||
|
||||
const arraysEqual = (a: Uint8Array, b: Uint8Array) => {
|
||||
if (a.length !== b.length) return false;
|
||||
for (let i = 0; i < a.length; i++) {
|
||||
if (a[i] !== b[i]) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
const FMComponent: React.FC<FMProps & JSX.IntrinsicElements["div"]> = ({ wsUrl, ...props }) => {
|
||||
const fmRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const { sendMessage } = useWebSocket(wsUrl, {
|
||||
const [dOpen, setdOpen] = useState(false);
|
||||
const [uOpen, setuOpen] = useState(false);
|
||||
|
||||
const columns: ColumnDef<FMEntry>[] = [
|
||||
{
|
||||
id: "type",
|
||||
header: () => <span>Type</span>,
|
||||
accessorFn: row => row.type,
|
||||
cell: ({ row }) => (
|
||||
row.original.type == 0 ? <File size={24} /> : <Folder size={24} />
|
||||
),
|
||||
},
|
||||
{
|
||||
header: () => <span>Name</span>,
|
||||
id: "name",
|
||||
accessorFn: row => row.name,
|
||||
cell: ({ row }) => (
|
||||
<div className="max-w-48 text-sm whitespace-normal break-words">
|
||||
{row.original.name}
|
||||
</div>
|
||||
),
|
||||
size: 5000,
|
||||
},
|
||||
{
|
||||
header: () => <span>Action</span>,
|
||||
id: "download",
|
||||
cell: ({ row }) => {
|
||||
return (
|
||||
<IconButton variant="ghost" icon="download" onClick={
|
||||
() => {
|
||||
if (!dOpen) setdOpen(true);
|
||||
downloadFile(row.original.name);
|
||||
}
|
||||
} />
|
||||
)
|
||||
},
|
||||
}
|
||||
]
|
||||
|
||||
const tableRowComponent = (rows: Row<FMEntry>[]) =>
|
||||
function getTableRow(props: HTMLAttributes<HTMLTableRowElement>) {
|
||||
// @ts-expect-error data-index is a valid attribute
|
||||
const index = props["data-index"];
|
||||
const row = rows[index];
|
||||
|
||||
if (!row) return null;
|
||||
|
||||
return (
|
||||
<TableRow
|
||||
key={row.id}
|
||||
data-state={row.getIsSelected() && "selected"}
|
||||
onClick={() => {
|
||||
if (row.original.type === 1) {
|
||||
setPath(`${currentPath}/${row.original.name}`);
|
||||
}
|
||||
}}
|
||||
className={row.original.type === 1 ? "cursor-pointer" : "cursor-default"}
|
||||
{...props}
|
||||
>
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<TableCell key={cell.id}>
|
||||
{flexRender(cell.column.columnDef.cell, cell.getContext())}
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
);
|
||||
};
|
||||
|
||||
const [fmEntires, setFMEntries] = useState<FMEntry[]>([]);
|
||||
|
||||
const firstChunk = useRef(true);
|
||||
const handleReady = useRef(false);
|
||||
const currentBasename = useRef('temp');
|
||||
|
||||
const waitForHandleReady = async () => {
|
||||
while (!handleReady.current) {
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
}
|
||||
};
|
||||
|
||||
worker.onmessage = async (event: MessageEvent<FMWorkerData>) => {
|
||||
switch (event.data.type) {
|
||||
case FMWorkerOpcode.Error: {
|
||||
console.error('Error from worker', event.data.error);
|
||||
break;
|
||||
}
|
||||
case FMWorkerOpcode.Progress: {
|
||||
handleReady.current = true;
|
||||
break;
|
||||
}
|
||||
case FMWorkerOpcode.Result: {
|
||||
handleReady.current = false;
|
||||
|
||||
if (event.data.blob && event.data.fileName) {
|
||||
const url = URL.createObjectURL(event.data.blob);
|
||||
const anchor = document.createElement('a');
|
||||
anchor.href = url;
|
||||
anchor.download = event.data.fileName;
|
||||
anchor.click();
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
firstChunk.current = true;
|
||||
if (dOpen) setdOpen(false);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const { sendMessage, getWebSocket } = useWebSocket(wsUrl, {
|
||||
share: false,
|
||||
onOpen: () => {
|
||||
listFile();
|
||||
@@ -29,48 +171,195 @@ const FMComponent: React.FC<FMProps & JSX.IntrinsicElements["div"]> = ({ wsUrl,
|
||||
console.log('WebSocket connection closed:', e);
|
||||
},
|
||||
onError: (e) => {
|
||||
console.log(e);
|
||||
console.error(e);
|
||||
toast("Websocket error", {
|
||||
description: "View console for details.",
|
||||
})
|
||||
},
|
||||
onMessage: async (e) => {
|
||||
try {
|
||||
const buf: ArrayBufferLike = e.data;
|
||||
|
||||
if (firstChunk.current) {
|
||||
const identifier = new Uint8Array(buf, 0, 4);
|
||||
if (arraysEqual(identifier, FMIdentifier.file)) {
|
||||
worker.postMessage({ operation: 1, arrayBuffer: buf, fileName: currentBasename.current });
|
||||
firstChunk.current = false;
|
||||
} else if (arraysEqual(identifier, FMIdentifier.fileName)) {
|
||||
const { path, fmList } = await fm.parseFMList(buf);
|
||||
setPath(path);
|
||||
setFMEntries(fmList);
|
||||
} else if (arraysEqual(identifier, FMIdentifier.error)) {
|
||||
const errBytes = buf.slice(4);
|
||||
const errMsg = new TextDecoder('utf-8').decode(errBytes);
|
||||
throw new Error(errMsg);
|
||||
} else if (arraysEqual(identifier, FMIdentifier.complete)) {
|
||||
// Upload completed
|
||||
if (uOpen) setuOpen(false);
|
||||
listFile();
|
||||
} else {
|
||||
throw new Error("Unknown identifier");
|
||||
}
|
||||
} else {
|
||||
await waitForHandleReady();
|
||||
worker.postMessage({ operation: 2, arrayBuffer: buf, fileName: currentBasename.current });
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error processing received data:', error);
|
||||
toast("FM error", {
|
||||
description: "View console for details.",
|
||||
})
|
||||
if (dOpen) setdOpen(false);
|
||||
if (uOpen) setuOpen(false);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const currentPath = useRef('').current;
|
||||
const socket = getWebSocket();
|
||||
useEffect(() => {
|
||||
if (socket && 'binaryType' in socket)
|
||||
socket.binaryType = 'arraybuffer';
|
||||
}, [socket])
|
||||
|
||||
const [currentPath, setPath] = useState('');
|
||||
useEffect(() => {
|
||||
listFile();
|
||||
}, [currentPath])
|
||||
|
||||
const listFile = () => {
|
||||
const prefix = new Int8Array([0]);
|
||||
const resizeMessage = new TextEncoder().encode(currentPath);
|
||||
const prefix = new Int8Array([FMOpcode.List]);
|
||||
const pathMsg = new TextEncoder().encode(currentPath);
|
||||
|
||||
const msg = new Int8Array(prefix.length + resizeMessage.length);
|
||||
const msg = new Int8Array(prefix.length + pathMsg.length);
|
||||
msg.set(prefix);
|
||||
msg.set(resizeMessage, prefix.length);
|
||||
msg.set(pathMsg, prefix.length);
|
||||
|
||||
sendMessage(msg);
|
||||
}
|
||||
|
||||
return <div ref={fmRef} {...props} />;
|
||||
const downloadFile = (basename: string) => {
|
||||
currentBasename.current = basename;
|
||||
const prefix = new Int8Array([FMOpcode.Download]);
|
||||
const filePathMessage = new TextEncoder().encode(`${currentPath}/${basename}`);
|
||||
|
||||
const msg = new Int8Array(prefix.length + filePathMessage.length);
|
||||
msg.set(prefix);
|
||||
msg.set(filePathMessage, prefix.length);
|
||||
|
||||
sendMessage(msg);
|
||||
}
|
||||
|
||||
const uploadFile = async (file: File) => {
|
||||
const chunkSize = 1048576; // 1MB chunk
|
||||
let offset = 0;
|
||||
|
||||
// Send header
|
||||
const header = fm.buildUploadHeader({ path: currentPath, file: file });
|
||||
sendMessage(header);
|
||||
|
||||
// Send data chunks
|
||||
while (offset < file.size) {
|
||||
const chunk = file.slice(offset, offset + chunkSize);
|
||||
const arrayBuffer = await fm.readFileAsArrayBuffer(chunk);
|
||||
if (arrayBuffer) sendMessage(arrayBuffer);
|
||||
offset += chunkSize;
|
||||
}
|
||||
}
|
||||
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const [gotoPath, setGotoPath] = useState('');
|
||||
return (
|
||||
<div ref={fmRef} {...props}>
|
||||
<div className="flex justify-center items-center gap-4">
|
||||
<AlertDialog>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<IconButton variant="ghost" icon="menu" />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent>
|
||||
<DropdownMenuItem onClick={listFile}>Refresh</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={
|
||||
async () => {
|
||||
await navigator.clipboard.writeText(formatPath(currentPath));
|
||||
}
|
||||
}>Copy path</DropdownMenuItem>
|
||||
<AlertDialogTrigger asChild>
|
||||
<DropdownMenuItem>Goto</DropdownMenuItem>
|
||||
</AlertDialogTrigger>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Goto</AlertDialogTitle>
|
||||
<AlertDialogDescription />
|
||||
</AlertDialogHeader>
|
||||
<Input className="mb-1" placeholder="Path" value={gotoPath} onChange={(e) => { setGotoPath(e.target.value) }} />
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={() => { setPath(gotoPath) }}>Confirm</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
<h1 className="text-base">Pseudo File Manager</h1>
|
||||
<div className="ml-auto">
|
||||
<input ref={fileInputRef} type="file" className="hidden" onChange={
|
||||
async (e) => {
|
||||
const files = e.target.files;
|
||||
if (files && files.length > 0) {
|
||||
if (!uOpen) setuOpen(true);
|
||||
await uploadFile(files[0]);
|
||||
}
|
||||
}
|
||||
} />
|
||||
<IconButton icon="upload" variant="ghost" onClick={
|
||||
() => {
|
||||
if (fileInputRef.current) fileInputRef.current.click();
|
||||
}
|
||||
} />
|
||||
</div>
|
||||
</div>
|
||||
<Filepath path={currentPath} setPath={setPath} />
|
||||
<AlertDialog open={dOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Downloading...</AlertDialogTitle>
|
||||
<AlertDialogDescription />
|
||||
</AlertDialogHeader>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
<AlertDialog open={uOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Uploading...</AlertDialogTitle>
|
||||
<AlertDialogDescription />
|
||||
</AlertDialogHeader>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
<DataTable columns={columns} data={fmEntires} rowComponent={tableRowComponent} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export const FMCard = ({ id }: { id?: string }) => {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [fm, setFM] = useState<ModelCreateFMResponse | null>(null);
|
||||
const [init, setInit] = useState(false);
|
||||
|
||||
const fetchFM = async () => {
|
||||
if (id && !fm) {
|
||||
if (id) {
|
||||
try {
|
||||
setInit(false);
|
||||
const createdFM = await createFM(id);
|
||||
setFM(createdFM);
|
||||
} catch (e) {
|
||||
toast("FM API Error", {
|
||||
description: "View console for details.",
|
||||
})
|
||||
console.log("fetch error", e);
|
||||
console.error("fetch error", e);
|
||||
return;
|
||||
}
|
||||
setInit(true);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,13 +368,18 @@ export const FMCard = ({ id }: { id?: string }) => {
|
||||
<SheetTrigger asChild>
|
||||
<IconButton icon="folder-closed" onClick={fetchFM} />
|
||||
</SheetTrigger>
|
||||
<SheetContent setOpen={setOpen}>
|
||||
<SheetHeader>
|
||||
<SheetTitle>Pseudo File Manager</SheetTitle>
|
||||
<SheetDescription />
|
||||
</SheetHeader>
|
||||
<div>
|
||||
|
||||
<SheetContent setOpen={setOpen} className="sm:min-w-[35%]">
|
||||
<div className="overflow-auto">
|
||||
<SheetTitle />
|
||||
<SheetHeader className="pb-2">
|
||||
<SheetDescription />
|
||||
</SheetHeader>
|
||||
{fm?.session_id && init
|
||||
?
|
||||
<FMComponent className="p-1 space-y-5" wsUrl={`/api/v1/ws/file/${fm.session_id}`} />
|
||||
:
|
||||
<p>The server does not exist, or have not been connected yet.</p>
|
||||
}
|
||||
</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
|
||||
@@ -40,7 +40,7 @@ const XtermComponent: React.FC<XtermProps & JSX.IntrinsicElements["div"]> = ({ w
|
||||
setClose(true);
|
||||
},
|
||||
onError: (e) => {
|
||||
console.log(e);
|
||||
console.error(e);
|
||||
toast("Websocket error", {
|
||||
description: "View console for details.",
|
||||
})
|
||||
@@ -88,7 +88,7 @@ const XtermComponent: React.FC<XtermProps & JSX.IntrinsicElements["div"]> = ({ w
|
||||
await sleep(1500);
|
||||
doResize();
|
||||
} catch (error) {
|
||||
console.log('resize error', error);
|
||||
console.error('resize error', error);
|
||||
} finally {
|
||||
sendResize.current = false;
|
||||
}
|
||||
@@ -134,7 +134,7 @@ export const TerminalPage = () => {
|
||||
toast("Terminal API Error", {
|
||||
description: "View console for details.",
|
||||
})
|
||||
console.log("fetch error", e);
|
||||
console.error("fetch error", e);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
115
src/components/ui/breadcrumb.tsx
Normal file
115
src/components/ui/breadcrumb.tsx
Normal file
@@ -0,0 +1,115 @@
|
||||
import * as React from "react"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { ChevronRight, MoreHorizontal } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const Breadcrumb = React.forwardRef<
|
||||
HTMLElement,
|
||||
React.ComponentPropsWithoutRef<"nav"> & {
|
||||
separator?: React.ReactNode
|
||||
}
|
||||
>(({ ...props }, ref) => <nav ref={ref} aria-label="breadcrumb" {...props} />)
|
||||
Breadcrumb.displayName = "Breadcrumb"
|
||||
|
||||
const BreadcrumbList = React.forwardRef<
|
||||
HTMLOListElement,
|
||||
React.ComponentPropsWithoutRef<"ol">
|
||||
>(({ className, ...props }, ref) => (
|
||||
<ol
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
BreadcrumbList.displayName = "BreadcrumbList"
|
||||
|
||||
const BreadcrumbItem = React.forwardRef<
|
||||
HTMLLIElement,
|
||||
React.ComponentPropsWithoutRef<"li">
|
||||
>(({ className, ...props }, ref) => (
|
||||
<li
|
||||
ref={ref}
|
||||
className={cn("inline-flex items-center gap-1.5", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
BreadcrumbItem.displayName = "BreadcrumbItem"
|
||||
|
||||
const BreadcrumbLink = React.forwardRef<
|
||||
HTMLAnchorElement,
|
||||
React.ComponentPropsWithoutRef<"a"> & {
|
||||
asChild?: boolean
|
||||
}
|
||||
>(({ asChild, className, ...props }, ref) => {
|
||||
const Comp = asChild ? Slot : "a"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
ref={ref}
|
||||
className={cn("transition-colors hover:text-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
BreadcrumbLink.displayName = "BreadcrumbLink"
|
||||
|
||||
const BreadcrumbPage = React.forwardRef<
|
||||
HTMLSpanElement,
|
||||
React.ComponentPropsWithoutRef<"span">
|
||||
>(({ className, ...props }, ref) => (
|
||||
<span
|
||||
ref={ref}
|
||||
role="link"
|
||||
aria-disabled="true"
|
||||
aria-current="page"
|
||||
className={cn("font-normal text-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
BreadcrumbPage.displayName = "BreadcrumbPage"
|
||||
|
||||
const BreadcrumbSeparator = ({
|
||||
children,
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"li">) => (
|
||||
<li
|
||||
role="presentation"
|
||||
aria-hidden="true"
|
||||
className={cn("[&>svg]:w-3.5 [&>svg]:h-3.5", className)}
|
||||
{...props}
|
||||
>
|
||||
{children ?? <ChevronRight />}
|
||||
</li>
|
||||
)
|
||||
BreadcrumbSeparator.displayName = "BreadcrumbSeparator"
|
||||
|
||||
const BreadcrumbEllipsis = ({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) => (
|
||||
<span
|
||||
role="presentation"
|
||||
aria-hidden="true"
|
||||
className={cn("flex h-9 w-9 items-center justify-center", className)}
|
||||
{...props}
|
||||
>
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
<span className="sr-only">More</span>
|
||||
</span>
|
||||
)
|
||||
BreadcrumbEllipsis.displayName = "BreadcrumbElipssis"
|
||||
|
||||
export {
|
||||
Breadcrumb,
|
||||
BreadcrumbList,
|
||||
BreadcrumbItem,
|
||||
BreadcrumbLink,
|
||||
BreadcrumbPage,
|
||||
BreadcrumbSeparator,
|
||||
BreadcrumbEllipsis,
|
||||
}
|
||||
102
src/components/xui/filepath.tsx
Normal file
102
src/components/xui/filepath.tsx
Normal file
@@ -0,0 +1,102 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import {
|
||||
Breadcrumb,
|
||||
BreadcrumbEllipsis,
|
||||
BreadcrumbItem,
|
||||
BreadcrumbList,
|
||||
BreadcrumbPage,
|
||||
BreadcrumbSeparator,
|
||||
} from "@/components/ui/breadcrumb"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { formatPath } from "@/lib/utils"
|
||||
|
||||
const ITEMS_TO_DISPLAY = 3
|
||||
|
||||
interface FilepathProps {
|
||||
path: string;
|
||||
setPath: React.Dispatch<React.SetStateAction<string>>;
|
||||
}
|
||||
|
||||
function pathToItems(path: string) {
|
||||
const segments = path.split('/').filter(Boolean);
|
||||
|
||||
const result: { href: string; label: string; }[] = [];
|
||||
|
||||
let currentPath = '';
|
||||
segments.forEach(segment => {
|
||||
currentPath += `/${segment}`;
|
||||
result.push({ href: currentPath, label: segment });
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export const Filepath: React.FC<FilepathProps> = ({ path, setPath }) => {
|
||||
const [open, setOpen] = React.useState(false)
|
||||
const items = pathToItems(formatPath(path));
|
||||
|
||||
return (
|
||||
<Breadcrumb>
|
||||
<BreadcrumbList>
|
||||
<BreadcrumbItem>
|
||||
<p className="cursor-pointer hover:text-white transition" onClick={() => { setPath('/') }}>{'/'}</p>
|
||||
</BreadcrumbItem>
|
||||
<BreadcrumbSeparator />
|
||||
{items.length > ITEMS_TO_DISPLAY ? (
|
||||
<>
|
||||
<BreadcrumbItem>
|
||||
{
|
||||
<DropdownMenu open={open} onOpenChange={setOpen}>
|
||||
<DropdownMenuTrigger
|
||||
className="flex items-center gap-1"
|
||||
aria-label="Toggle menu"
|
||||
>
|
||||
<BreadcrumbEllipsis className="h-4 w-4" />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="start">
|
||||
{items.slice(0, -ITEMS_TO_DISPLAY).map((item, index) => (
|
||||
<DropdownMenuItem key={index}>
|
||||
<p onClick={() => { setPath(item.href) }}>
|
||||
{item.label}
|
||||
</p>
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
}
|
||||
</BreadcrumbItem>
|
||||
<BreadcrumbSeparator />
|
||||
</>
|
||||
) : null}
|
||||
{items.slice(-ITEMS_TO_DISPLAY).map((item, index, slicedItems) => (
|
||||
<React.Fragment key={index}>
|
||||
<BreadcrumbItem className="overflow-auto">
|
||||
{item.href ? (
|
||||
<>
|
||||
<p
|
||||
className="max-w-20 truncate md:max-w-none cursor-pointer hover:text-white transition"
|
||||
onClick={() => { setPath(item.href) }}
|
||||
>
|
||||
{item.label}
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<BreadcrumbPage className="max-w-20 truncate md:max-w-none">
|
||||
{item.label}
|
||||
</BreadcrumbPage>
|
||||
)}
|
||||
</BreadcrumbItem>
|
||||
{index !== slicedItems.length - 1 ? <BreadcrumbSeparator /> : null}
|
||||
</React.Fragment>
|
||||
))}
|
||||
</BreadcrumbList>
|
||||
</Breadcrumb>
|
||||
)
|
||||
}
|
||||
@@ -1,9 +1,34 @@
|
||||
import { Plus, Edit2, Trash2, Terminal, CircleArrowUp, Clipboard, Check, FolderClosed, Play } from "lucide-react"
|
||||
import {
|
||||
Plus,
|
||||
Edit2,
|
||||
Trash2,
|
||||
Terminal,
|
||||
CircleArrowUp,
|
||||
Clipboard,
|
||||
Check,
|
||||
FolderClosed,
|
||||
Play,
|
||||
Download,
|
||||
Upload,
|
||||
Menu,
|
||||
} from "lucide-react"
|
||||
import { Button, ButtonProps } from "@/components/ui/button"
|
||||
import { forwardRef } from "react";
|
||||
|
||||
export interface IconButtonProps extends ButtonProps {
|
||||
icon: "clipboard" | "check" | "edit" | "trash" | "plus" | "terminal" | "update" | "folder-closed" | "play";
|
||||
icon:
|
||||
"clipboard" |
|
||||
"check" |
|
||||
"edit" |
|
||||
"trash" |
|
||||
"plus" |
|
||||
"terminal" |
|
||||
"update" |
|
||||
"folder-closed" |
|
||||
"play" |
|
||||
"download" |
|
||||
"upload" |
|
||||
"menu";
|
||||
}
|
||||
|
||||
export const IconButton = forwardRef<HTMLButtonElement, IconButtonProps>((props, ref) => {
|
||||
@@ -38,6 +63,15 @@ export const IconButton = forwardRef<HTMLButtonElement, IconButtonProps>((props,
|
||||
case "play": {
|
||||
return <Play />;
|
||||
}
|
||||
case "download": {
|
||||
return <Download />;
|
||||
}
|
||||
case "upload": {
|
||||
return <Upload />;
|
||||
}
|
||||
case "menu": {
|
||||
return <Menu />;
|
||||
}
|
||||
}
|
||||
})()}
|
||||
</Button>
|
||||
|
||||
180
src/components/xui/virtulized-data-table.tsx
Normal file
180
src/components/xui/virtulized-data-table.tsx
Normal file
@@ -0,0 +1,180 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
ColumnDef,
|
||||
Row,
|
||||
SortDirection,
|
||||
SortingState,
|
||||
flexRender,
|
||||
getCoreRowModel,
|
||||
getSortedRowModel,
|
||||
useReactTable,
|
||||
} from "@tanstack/react-table";
|
||||
|
||||
import { TableCell, TableHead, TableRow } from "@/components/ui/table";
|
||||
import { HTMLAttributes, forwardRef, useState, useRef, useEffect } from "react";
|
||||
import { TableVirtuoso } from "react-virtuoso";
|
||||
import { cn } from "@/lib/utils"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
|
||||
// Original Table is wrapped with a <div> (see https://ui.shadcn.com/docs/components/table#radix-:r24:-content-manual),
|
||||
// but here we don't want it, so let's use a new component with only <table> tag
|
||||
const TableComponent = forwardRef<
|
||||
HTMLTableElement,
|
||||
React.HTMLAttributes<HTMLTableElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<table
|
||||
ref={ref}
|
||||
className={cn("w-full caption-bottom text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
TableComponent.displayName = "TableComponent";
|
||||
|
||||
const TableRowComponent = <TData,>(rows: Row<TData>[]) =>
|
||||
function getTableRow(props: HTMLAttributes<HTMLTableRowElement>) {
|
||||
// @ts-expect-error data-index is a valid attribute
|
||||
const index = props["data-index"];
|
||||
const row = rows[index];
|
||||
|
||||
if (!row) return null;
|
||||
|
||||
return (
|
||||
<TableRow
|
||||
key={row.id}
|
||||
data-state={row.getIsSelected() && "selected"}
|
||||
className="translate-y-[50%]"
|
||||
{...props}
|
||||
>
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<TableCell key={cell.id}>
|
||||
{flexRender(cell.column.columnDef.cell, cell.getContext())}
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
);
|
||||
};
|
||||
|
||||
function SortingIndicator({ isSorted }: { isSorted: SortDirection | false }) {
|
||||
if (!isSorted) return null;
|
||||
return (
|
||||
<div>
|
||||
{
|
||||
{
|
||||
asc: "↑",
|
||||
desc: "↓",
|
||||
}[isSorted]
|
||||
}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface DataTableProps<TData, TValue> {
|
||||
columns: ColumnDef<TData, TValue>[];
|
||||
data: TData[];
|
||||
rowComponent?: (rows: Row<TData>[]) => (props: HTMLAttributes<HTMLTableRowElement>) => JSX.Element | null,
|
||||
}
|
||||
|
||||
export function DataTable<TData, TValue>({
|
||||
columns,
|
||||
data,
|
||||
rowComponent,
|
||||
}: DataTableProps<TData, TValue>) {
|
||||
const [sorting, setSorting] = useState<SortingState>([{
|
||||
id: 'type',
|
||||
desc: true,
|
||||
}]);
|
||||
const table = useReactTable({
|
||||
data,
|
||||
columns,
|
||||
state: {
|
||||
sorting,
|
||||
},
|
||||
onSortingChange: setSorting,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
});
|
||||
|
||||
const { rows } = table.getRowModel();
|
||||
|
||||
const [heightState, setHeight] = useState(0)
|
||||
const ref = useRef(null);
|
||||
useEffect(() => {
|
||||
const calculateHeight = () => {
|
||||
if (ref.current) {
|
||||
const virtuosoElement = ref.current;
|
||||
let topOffset = 0;
|
||||
let currentElement = virtuosoElement as any;
|
||||
|
||||
// Calculate the total offset from the top of the document
|
||||
while (currentElement) {
|
||||
topOffset += currentElement.offsetTop || 0;
|
||||
currentElement = currentElement.offsetParent as HTMLElement;
|
||||
}
|
||||
|
||||
const totalHeight = window.innerHeight;
|
||||
const calculatedHeight = totalHeight - topOffset;
|
||||
|
||||
setHeight(calculatedHeight);
|
||||
}
|
||||
};
|
||||
window.addEventListener('resize', calculateHeight);
|
||||
calculateHeight(); // Initial calculation
|
||||
|
||||
return () => window.removeEventListener('resize', calculateHeight);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="rounded-md border" ref={ref} style={{ height: heightState }}>
|
||||
<TableVirtuoso
|
||||
totalCount={rows.length}
|
||||
components={{
|
||||
Table: TableComponent,
|
||||
TableRow: rowComponent ? rowComponent(rows) : TableRowComponent(rows),
|
||||
Scroller: ScrollArea,
|
||||
}}
|
||||
fixedHeaderContent={() =>
|
||||
table.getHeaderGroups().map((headerGroup) => (
|
||||
// Change header background color to non-transparent
|
||||
<TableRow className="bg-card hover:bg-muted" key={headerGroup.id}>
|
||||
{headerGroup.headers.map((header) => {
|
||||
return (
|
||||
<TableHead
|
||||
key={header.id}
|
||||
colSpan={header.colSpan}
|
||||
style={{
|
||||
width: header.getSize(),
|
||||
}}
|
||||
>
|
||||
{header.isPlaceholder ? null : (
|
||||
<div
|
||||
className="flex items-center"
|
||||
{...{
|
||||
style: header.column.getCanSort()
|
||||
? {
|
||||
cursor: "pointer",
|
||||
userSelect: "none",
|
||||
}
|
||||
: {},
|
||||
onClick: header.column.getToggleSortingHandler(),
|
||||
}}
|
||||
>
|
||||
{flexRender(
|
||||
header.column.columnDef.header,
|
||||
header.getContext(),
|
||||
)}
|
||||
<SortingIndicator
|
||||
isSorted={header.column.getIsSorted()}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</TableHead>
|
||||
);
|
||||
})}
|
||||
</TableRow>
|
||||
))
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user