Track HiveGrid Cloud planning reference
This commit is contained in:
1 parent
b3d5ea6764
commit
e341c5938a
5784 files changed
+1104929
-3
No files matched your search
@@ -0,0 +1,139 @@
|
||||
// P4 Files (AK-P4a) §11 — Upload view with drag&drop + multi-file queue and
|
||||
// per-file progress (chunked init -> chunk -> complete). Loader gates on
|
||||
// files.write (404 if module off / missing). Baseline functional UI; Subframe
|
||||
// polish follows Davids D-P4 delta.
|
||||
|
||||
import { useCallback, useRef, useState } from "react";
|
||||
import { type LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { buildFileUploadVM, type FileUploadVM } from "@toolctrl/view-models";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { loadFilesContext, notFoundResponse, requireFilesPermission } from "~/utils/integrations/fileAccess.server";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
|
||||
type LoaderData = { title: string; vm: FileUploadVM; tenantSlug: string };
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
const ctx = await loadFilesContext({ request, params, requireModule: true });
|
||||
try {
|
||||
requireFilesPermission(ctx, "files.write");
|
||||
} catch {
|
||||
throw notFoundResponse();
|
||||
}
|
||||
const vm = buildFileUploadVM({ canWrite: true });
|
||||
return Response.json({ title: `${t("files.upload.title")} | ${process.env.APP_NAME}`, vm, tenantSlug: params.tenant ?? "" } satisfies LoaderData);
|
||||
};
|
||||
|
||||
type QueueItem = { clientId: string; filename: string; sizeBytes: number; status: "queued" | "uploading" | "processing" | "done" | "error"; progressPercent: number; errorKey: string | null };
|
||||
|
||||
export default function FilesUploadRoute() {
|
||||
const { t } = useTranslation();
|
||||
const { vm, tenantSlug } = useLoaderData<LoaderData>();
|
||||
const [items, setItems] = useState<QueueItem[]>([]);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const chunkSize = vm.status === "ready" && vm.data ? vm.data.chunkSizeBytes : 5 * 1024 * 1024;
|
||||
|
||||
const update = useCallback((clientId: string, patch: Partial<QueueItem>) => {
|
||||
setItems((current) => current.map((item) => (item.clientId === clientId ? { ...item, ...patch } : item)));
|
||||
}, []);
|
||||
|
||||
const uploadOne = useCallback(
|
||||
async (file: File, clientId: string) => {
|
||||
try {
|
||||
update(clientId, { status: "uploading", progressPercent: 0 });
|
||||
const initRes = await fetch(`/${tenantSlug}/files/upload/init`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ originalFilename: file.name, mimeType: file.type || "application/octet-stream", totalSizeBytes: file.size }),
|
||||
});
|
||||
if (!initRes.ok) {
|
||||
const body = (await initRes.json().catch(() => ({}))) as { error?: string };
|
||||
update(clientId, { status: "error", errorKey: body.error ?? "files.error.invalidUploadRequest" });
|
||||
return;
|
||||
}
|
||||
const { uploadId, totalChunks } = (await initRes.json()) as { uploadId: string; chunkSize: number; totalChunks: number };
|
||||
for (let index = 0; index < totalChunks; index += 1) {
|
||||
const slice = file.slice(index * chunkSize, (index + 1) * chunkSize);
|
||||
const chunkRes = await fetch(`/${tenantSlug}/files/upload/${uploadId}/chunk/${index}`, { method: "POST", body: slice });
|
||||
if (!chunkRes.ok) {
|
||||
const body = (await chunkRes.json().catch(() => ({}))) as { error?: string };
|
||||
update(clientId, { status: "error", errorKey: body.error ?? "files.error.uploadIncomplete" });
|
||||
return;
|
||||
}
|
||||
update(clientId, { progressPercent: Math.round(((index + 1) / totalChunks) * 100) });
|
||||
}
|
||||
update(clientId, { status: "processing" });
|
||||
const completeRes = await fetch(`/${tenantSlug}/files/upload/${uploadId}/complete`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({}),
|
||||
});
|
||||
if (!completeRes.ok) {
|
||||
const body = (await completeRes.json().catch(() => ({}))) as { error?: string };
|
||||
update(clientId, { status: "error", errorKey: body.error ?? "files.error.uploadIncomplete" });
|
||||
return;
|
||||
}
|
||||
update(clientId, { status: "done", progressPercent: 100 });
|
||||
} catch {
|
||||
update(clientId, { status: "error", errorKey: "files.error.uploadIncomplete" });
|
||||
}
|
||||
},
|
||||
[chunkSize, tenantSlug, update],
|
||||
);
|
||||
|
||||
const onFiles = useCallback(
|
||||
(fileList: FileList | null) => {
|
||||
if (!fileList) return;
|
||||
const next: QueueItem[] = [];
|
||||
for (const file of Array.from(fileList)) {
|
||||
const clientId = `${file.name}-${file.size}-${file.lastModified}`;
|
||||
next.push({ clientId, filename: file.name, sizeBytes: file.size, status: "queued", progressPercent: 0, errorKey: null });
|
||||
void uploadOne(file, clientId);
|
||||
}
|
||||
setItems((current) => [...current, ...next]);
|
||||
},
|
||||
[uploadOne],
|
||||
);
|
||||
|
||||
if (vm.status !== "ready" || !vm.data) {
|
||||
return <main className="mx-auto max-w-3xl px-4 py-10" data-ui-id="ui.files.upload" />;
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="mx-auto max-w-3xl px-4 py-10" data-ui-id="ui.files.upload">
|
||||
<h1 className="text-foreground text-xl font-semibold">{t("files.upload.title")}</h1>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => inputRef.current?.click()}
|
||||
onDragOver={(event) => event.preventDefault()}
|
||||
onDrop={(event) => {
|
||||
event.preventDefault();
|
||||
onFiles(event.dataTransfer.files);
|
||||
}}
|
||||
className="border-muted-foreground/40 mt-6 flex w-full flex-col items-center rounded-lg border-2 border-dashed px-6 py-12"
|
||||
data-ui-id="ui.files.upload.dropzone"
|
||||
>
|
||||
<span className="text-foreground font-medium">{t(vm.data.dropzoneHeadlineKey)}</span>
|
||||
<span className="text-muted-foreground mt-1 text-sm">{t(vm.data.dropzoneBodyKey)}</span>
|
||||
<span className="text-muted-foreground mt-3 text-xs">{t(vm.data.heicNoticeKey)}</span>
|
||||
</button>
|
||||
<input ref={inputRef} type="file" multiple className="hidden" onChange={(event) => onFiles(event.target.files)} data-ui-id="ui.files.upload.input" />
|
||||
|
||||
<ul className="mt-6 space-y-2" data-ui-id="ui.files.upload.queue">
|
||||
{items.map((item) => (
|
||||
<li key={item.clientId} className="border-b py-2 text-sm" data-row-id={item.clientId} data-status={item.status}>
|
||||
<div className="flex items-center justify-between">
|
||||
<span>{item.filename}</span>
|
||||
<span className="text-muted-foreground">{item.status === "error" && item.errorKey ? t(item.errorKey) : `${item.progressPercent}%`}</span>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
Reference in new issue
Block a user