mirror of
https://github.com/Buriburizaem0n/admin-frontend-domain.git
synced 2026-02-04 04:30: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 { ModelServer, ModelServerForm } from "@/types"
|
||||
import { ModelServer, ModelServerForm, ModelForceUpdateResponse } from "@/types"
|
||||
import { fetcher, FetcherMethod } from "./api"
|
||||
|
||||
export const updateServer = async (id: number, data: ModelServerForm): Promise<void> => {
|
||||
@@ -9,6 +9,10 @@ export const deleteServer = async (id: number[]): Promise<void> => {
|
||||
return fetcher<void>(FetcherMethod.POST, '/api/v1/batch-delete/server', id);
|
||||
}
|
||||
|
||||
export const forceUpdateServer = async (id: number[]): Promise<ModelForceUpdateResponse> => {
|
||||
return fetcher<ModelForceUpdateResponse>(FetcherMethod.POST, '/api/v1/force-update/server', id);
|
||||
}
|
||||
|
||||
export const getServers = async (): Promise<ModelServer[]> => {
|
||||
return fetcher<ModelServer[]>(FetcherMethod.GET, '/api/v1/server', null);
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
71
src/lib/fm.ts
Normal file
71
src/lib/fm.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
let receivedLength = 0;
|
||||
let expectedLength = 0;
|
||||
let root: FileSystemDirectoryHandle;
|
||||
let draftHandle: FileSystemFileHandle;
|
||||
let accessHandle: FileSystemSyncAccessHandle;
|
||||
|
||||
enum Operation {
|
||||
WriteHeader = 1,
|
||||
WriteChunks,
|
||||
DeleteFiles,
|
||||
};
|
||||
|
||||
onmessage = async function (event) {
|
||||
try {
|
||||
const { operation, arrayBuffer, fileName } = event.data;
|
||||
|
||||
switch (operation) {
|
||||
case Operation.WriteHeader: {
|
||||
const dataView = new DataView(arrayBuffer);
|
||||
expectedLength = Number(dataView.getBigUint64(4, false));
|
||||
receivedLength = 0;
|
||||
|
||||
// Create a new temporary file
|
||||
root = await navigator.storage.getDirectory();
|
||||
draftHandle = await root.getFileHandle(fileName, { create: true });
|
||||
accessHandle = await draftHandle.createSyncAccessHandle();
|
||||
|
||||
// Inform that file handle is created
|
||||
const dataChunk = arrayBuffer.slice(12);
|
||||
receivedLength += dataChunk.byteLength;
|
||||
accessHandle.write(dataChunk, { at: 0 });
|
||||
const progress = 'got handle';
|
||||
postMessage({ type: 1, progress: progress });
|
||||
break;
|
||||
}
|
||||
case Operation.WriteChunks: {
|
||||
if (!accessHandle) {
|
||||
throw new Error('accessHandle is undefined');
|
||||
}
|
||||
|
||||
const dataChunk = arrayBuffer;
|
||||
accessHandle.write(dataChunk, { at: receivedLength });
|
||||
receivedLength += dataChunk.byteLength;
|
||||
|
||||
if (receivedLength === expectedLength) {
|
||||
accessHandle.flush();
|
||||
accessHandle.close();
|
||||
|
||||
const fileBlob = await draftHandle.getFile();
|
||||
const blob = new Blob([fileBlob], { type: 'application/octet-stream' });
|
||||
|
||||
postMessage({ type: 2, blob: blob, fileName: fileName });
|
||||
}
|
||||
break;
|
||||
}
|
||||
case Operation.DeleteFiles: {
|
||||
for await (const [name, handle] of root.entries()) {
|
||||
if (handle.kind === 'file') {
|
||||
await root.removeEntry(name);
|
||||
} else if (handle.kind === 'directory') {
|
||||
await root.removeEntry(name, { recursive: true });
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof Error)
|
||||
postMessage({ type: 0, error: error.message });
|
||||
}
|
||||
};
|
||||
@@ -1,6 +1,8 @@
|
||||
import { clsx, type ClassValue } from "clsx"
|
||||
import { twMerge } from "tailwind-merge"
|
||||
import { z } from "zod"
|
||||
import { FMEntry, FMOpcode } from "@/types"
|
||||
import FMWorker from "./fm?worker"
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
@@ -46,3 +48,68 @@ export const conv = {
|
||||
export const sleep = (ms: number) => {
|
||||
return new Promise(resolve => setTimeout(resolve, ms));
|
||||
};
|
||||
|
||||
export const fm = {
|
||||
parseFMList: async (buf: ArrayBufferLike) => {
|
||||
const dataView = new DataView(buf);
|
||||
let offset = 4; // Identifier: 4 bytes (NZFN), not needed here
|
||||
|
||||
const pathLength = dataView.getUint32(offset);
|
||||
offset += 4; // File Path Length: 4 bytes
|
||||
|
||||
const pathBuf = new Uint8Array(buf, offset, pathLength);
|
||||
const path = new TextDecoder('utf-8').decode(pathBuf);
|
||||
offset += pathLength; // Path: N bytes
|
||||
|
||||
const fmList: FMEntry[] = [];
|
||||
while (offset < dataView.byteLength) {
|
||||
const fileType = dataView.getUint8(offset);
|
||||
offset += 1; // File Type: 1 byte
|
||||
|
||||
const nameLength = dataView.getUint8(offset);
|
||||
offset += 1; // File Name Length: 1 byte
|
||||
|
||||
const nameBuf = new Uint8Array(buf, offset, nameLength);
|
||||
const name = new TextDecoder('utf-8').decode(nameBuf);
|
||||
offset += nameLength; // File Name: N bytes
|
||||
|
||||
fmList.push({
|
||||
type: fileType,
|
||||
name: name,
|
||||
})
|
||||
}
|
||||
|
||||
return { path, fmList };
|
||||
},
|
||||
|
||||
buildUploadHeader: ({ path, file }: { path: string, file: File }) => {
|
||||
const filePath = `${path}/${file.name}`;
|
||||
|
||||
// Build header (opcode + file size + path)
|
||||
const filePathBytes = new TextEncoder().encode(filePath);
|
||||
const header = new ArrayBuffer(1 + 8 + filePathBytes.length);
|
||||
const headerView = new DataView(header);
|
||||
|
||||
headerView.setUint8(0, FMOpcode.Upload);
|
||||
headerView.setBigUint64(1, BigInt(file.size), false);
|
||||
|
||||
new Uint8Array(header, 9).set(filePathBytes);
|
||||
return header;
|
||||
},
|
||||
|
||||
readFileAsArrayBuffer: async (blob: Blob): Promise<string | ArrayBuffer | null> => {
|
||||
const reader = new FileReader();
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
reader.onload = () => resolve(reader.result);
|
||||
reader.onerror = () => reject(reader.error);
|
||||
reader.readAsArrayBuffer(blob);
|
||||
});
|
||||
},
|
||||
}
|
||||
|
||||
export const fmWorker = new FMWorker();
|
||||
|
||||
export function formatPath(path: string) {
|
||||
return path.replace(/\/{2,}/g, '/');
|
||||
}
|
||||
|
||||
@@ -141,16 +141,17 @@ export default function CronPage() {
|
||||
try {
|
||||
await runCron(s.id);
|
||||
} catch (e) {
|
||||
console.log(e);
|
||||
console.error(e);
|
||||
toast("Error executing task", {
|
||||
description: "Please see the console for details.",
|
||||
})
|
||||
await mutate()
|
||||
await mutate();
|
||||
return;
|
||||
}
|
||||
toast("Success", {
|
||||
description: "The task triggered successfully.",
|
||||
})
|
||||
await mutate()
|
||||
await mutate();
|
||||
}} />
|
||||
<CronCard mutate={mutate} data={s} />
|
||||
</>
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { swrFetcher } from "@/api/api"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
|
||||
import { ModelServer as Server } from "@/types"
|
||||
import { ModelServer as Server, ModelForceUpdateResponse } from "@/types"
|
||||
import { ColumnDef, flexRender, getCoreRowModel, useReactTable } from "@tanstack/react-table"
|
||||
import useSWR from "swr"
|
||||
import { HeaderButtonGroup } from "@/components/header-button-group"
|
||||
import { deleteServer } from "@/api/server"
|
||||
import { deleteServer, forceUpdateServer } from "@/api/server"
|
||||
import { ServerCard } from "@/components/server"
|
||||
import { Skeleton } from "@/components/ui/skeleton"
|
||||
import { ActionButtonGroup } from "@/components/action-button-group"
|
||||
@@ -154,7 +154,34 @@ export default function ServerPage() {
|
||||
id: selectedRows.map(r => r.original.id),
|
||||
mutate: mutate,
|
||||
}}>
|
||||
<IconButton icon="update" />
|
||||
<IconButton icon="update" onClick={
|
||||
async () => {
|
||||
const id = selectedRows.map(r => r.original.id);
|
||||
if (id.length < 1) {
|
||||
toast("Error", {
|
||||
description: "No rows are selected."
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
let resp: ModelForceUpdateResponse = {};
|
||||
try {
|
||||
resp = await forceUpdateServer(id);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
toast("Error executing task", {
|
||||
description: "Please see the console for details.",
|
||||
})
|
||||
return;
|
||||
}
|
||||
toast("Task executed successfully", {
|
||||
description: `Result (Server ID):
|
||||
${resp.success?.length ? `Success: ${resp.success.join(",")}, ` : ''}
|
||||
${resp.failure?.length ? `Failure: ${resp.failure.join(",")}, ` : ''}
|
||||
${resp.offline?.length ? `Offline: ${resp.offline.join(",")}` : ''}
|
||||
`
|
||||
})
|
||||
}} />
|
||||
</HeaderButtonGroup>
|
||||
</div>
|
||||
{isLoading ? (
|
||||
|
||||
@@ -93,6 +93,12 @@ export interface GithubComNaibaNezhaModelCommonResponseModelConfig {
|
||||
success: boolean;
|
||||
}
|
||||
|
||||
export interface GithubComNaibaNezhaModelCommonResponseModelForceUpdateResponse {
|
||||
data: ModelForceUpdateResponse;
|
||||
error: string;
|
||||
success: boolean;
|
||||
}
|
||||
|
||||
export interface GithubComNaibaNezhaModelCommonResponseModelLoginResponse {
|
||||
data: ModelLoginResponse;
|
||||
error: string;
|
||||
@@ -279,6 +285,12 @@ export interface ModelDDNSProfile {
|
||||
webhook_url: string;
|
||||
}
|
||||
|
||||
export interface ModelForceUpdateResponse {
|
||||
failure?: number[];
|
||||
offline?: number[];
|
||||
success?: number[];
|
||||
}
|
||||
|
||||
export interface ModelHost {
|
||||
arch: string;
|
||||
boot_time: number;
|
||||
|
||||
37
src/types/fm.ts
Normal file
37
src/types/fm.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
export interface FMEntry {
|
||||
type: number,
|
||||
name: string,
|
||||
}
|
||||
|
||||
export enum FMOpcode {
|
||||
List,
|
||||
Download,
|
||||
Upload,
|
||||
}
|
||||
|
||||
export const FMIdentifier = {
|
||||
file: new Uint8Array([0x4E, 0x5A, 0x54, 0x44]), // NZTD
|
||||
fileName: new Uint8Array([0x4E, 0x5A, 0x46, 0x4E]), // NZFN
|
||||
error: new Uint8Array([0x4E, 0x45, 0x52, 0x52]), // NERR
|
||||
complete: new Uint8Array([0x4E, 0x5A, 0x55, 0x50]), // NZUP
|
||||
}
|
||||
|
||||
export interface FMWorkerPost {
|
||||
operation: number;
|
||||
arrayBuffer: ArrayBuffer;
|
||||
fileName: string;
|
||||
}
|
||||
|
||||
export enum FMWorkerOpcode {
|
||||
Error,
|
||||
Progress,
|
||||
Result,
|
||||
}
|
||||
|
||||
export interface FMWorkerData {
|
||||
type: FMWorkerOpcode,
|
||||
error: string,
|
||||
blob?: Blob,
|
||||
progress?: string,
|
||||
fileName?: string,
|
||||
}
|
||||
@@ -10,3 +10,4 @@ export * from './notification';
|
||||
export * from './alert-rule';
|
||||
export * from './notificationStore';
|
||||
export * from './notificationContext';
|
||||
export * from './fm';
|
||||
|
||||
Reference in New Issue
Block a user