// AK-P4a Interim-UI (AD-28) — Files browser preview screen composed from ~/ui. // Pure presentational component: renders the server-built FileBrowserVM passed as // a prop and reports filter/view changes through injected actions. No useLoaderData, // no server imports. The final Subframe optics land as a tracked design-nachzug once // David's D-P4 delta ships; this interim screen keeps the VM/loader boundary stable. import { type FormEvent, useState } from "react"; import { useTranslation } from "react-i18next"; import { fileTypeLabelKey } from "~/utils/files/fileTypeLabel"; import { FeatherDownload, FeatherFile, FeatherFileText, FeatherGrid, FeatherLink, FeatherList, FeatherTag, FeatherUpload, FeatherUser } from "@subframe/core"; import type { FileBrowserRow, FileBrowserVM, FilePreviewStatus, FileScanStatus, FileViewMode } from "@hivegrid/view-models"; import { PAGE_HEADER_ICON_CLASS, PageBody, PageHeader, PageShell } from "../shared/PageShell"; import { FacetFilterBar, type ClientFacet } from "../shared/FacetFilterBar"; import { FileUploadDialog } from "./FileUploadDialog"; import type { FileUploadDisplayItem } from "./FileUploadPage"; import { BadgeFeedback } from "~/ui/components/BadgeFeedback"; import { Button } from "~/ui/components/Button"; import { Card } from "~/ui/components/Card"; import { Checkbox } from "~/ui/components/Checkbox"; import { Table } from "~/ui/components/Table"; import { Tag_Label } from "~/ui/components/Tag_Label"; import { ToggleGroup } from "~/ui/components/ToggleGroup"; import { APP_TIME_ZONE } from "~/locale/format"; import { useLiveFilter } from "~/hooks/use-live-filter"; import { useSaveToast, type SaveActionResult } from "~/hooks/use-save-toast"; import { AppLink } from "~/components/app/AppLink"; export type FilesBrowserQuery = { mimeGroup: string | null; entityType: string | null; tag: string | null; assignedToUserId: string | null; includeArchived: boolean; /** Free-text search over the file name. */ q: string; viewMode: FileViewMode; }; export type FilesBrowserActions = { /** Navigate (GET) to the same route with the given filter/view state. */ onApply: (query: FilesBrowserQuery) => void; /** Navigate (GET) to another page of the current result set. */ onGoToPage: (query: FilesBrowserQuery, page: number) => void; /** Toggle a single row in the bulk selection. */ onToggleSelect: (id: string) => void; /** Select or clear all currently-listed rows. */ onToggleSelectAll: (ids: readonly string[], selectAll: boolean) => void; }; export type FilesBrowserUpload = { /** Queue of the open dialog session. */ items: readonly FileUploadDisplayItem[]; /** Hand picked/dropped files to the route's chunked upload pipeline. */ onFiles: (files: FileList | null) => void; /** True while at least one file is still on its way. */ uploading: boolean; /** Clear the queue when the dialog closes. */ onClose: () => void; }; export type FilesBrowserPageProps = { vm: FileBrowserVM; /** * Upload pipeline of the route. Absent for a reader — without it the header * shows no upload button, because there would be nothing behind it. */ upload?: FilesBrowserUpload; /** Absolute action URL the bulk-ZIP form POSTs to. */ bulkZipAction: string; /** Currently selected row ids (for the bulk-ZIP download). */ selectedIds: readonly string[]; actions: FilesBrowserActions; }; /** Mime groups the server knows how to filter on. */ const MIME_GROUPS = ["image", "pdf", "text"] as const; type StatusBadge = { farbe: "subtle-positive" | "subtle-warning" | "subtle-negative" | "subtle-neutral"; key: string }; function previewBadge(status: FilePreviewStatus): StatusBadge { switch (status) { case "ready": return { farbe: "subtle-positive", key: "files.browser.status.preview.ready" }; case "generating": return { farbe: "subtle-warning", key: "files.browser.status.preview.generating" }; case "failed": return { farbe: "subtle-negative", key: "files.browser.status.preview.failed" }; case "not_supported": return { farbe: "subtle-neutral", key: "files.browser.status.preview.notSupported" }; case "pending": default: return { farbe: "subtle-warning", key: "files.browser.status.preview.pending" }; } } function scanBadge(status: FileScanStatus): StatusBadge | null { if (status === "infected") return { farbe: "subtle-negative", key: "files.browser.status.scan.infected" }; if (status === "pending") return { farbe: "subtle-warning", key: "files.browser.status.scan.pending" }; return null; } function formatBytes(bytes: number): string { if (bytes < 1024) return `${bytes} B`; const units = ["KB", "MB", "GB"]; let value = bytes / 1024; let unitIndex = 0; while (value >= 1024 && unitIndex < units.length - 1) { value /= 1024; unitIndex += 1; } return `${value.toFixed(1)} ${units[unitIndex]}`; } export function FilesBrowserPage({ vm, upload, bulkZipAction, selectedIds, actions }: FilesBrowserPageProps) { const { t, i18n } = useTranslation(); const [uploadOpen, setUploadOpen] = useState(false); const [downloadingZip, setDownloadingZip] = useState(false); const [downloadError, setDownloadError] = useState(); useSaveToast(downloadError); // Local search buffer, live-committed to the route (GET) debounced — the same // behaviour the board filter bar has. const data = vm.status === "ready" ? vm.data : null; const searchFromVm = data?.filter.q ?? ""; const [search, setSearch] = useState(searchFromVm); /** Current query with one part replaced — the shape every control reports. */ function currentQuery(patch: Partial = {}): FilesBrowserQuery { return { mimeGroup: data?.filter.mimeGroup ?? null, entityType: data?.filter.entityType ?? null, tag: data?.filter.tags[0] ?? null, assignedToUserId: data?.filter.assignedToUserId ?? null, includeArchived: data?.filter.includeArchived ?? false, q: searchFromVm, viewMode: data?.viewMode ?? "table", ...patch, }; } function applyPatch(patch: Partial) { actions.onApply(currentQuery(patch)); } useLiveFilter(search.trim(), searchFromVm.trim(), () => applyPatch({ q: search.trim() })); // Loading / not-ready: keep the marker so the shell + e2e see a stable surface. if (!data) { return ( } title={t("files.browser.title")} subtitle={t("files.browser.subtitle")} /> {null} ); } const { rows, viewMode, filter, filterOptions, canWrite, pagination } = data; const dateFormatter = new Intl.DateTimeFormat(i18n.language, { timeZone: APP_TIME_ZONE, dateStyle: "medium" }); // Single-select facets on a multi-select control: picking the active option // again clears it, which is what the chip's X does too. function toggleFacet(facetKey: string, value: string) { switch (facetKey) { case "mime": return applyPatch({ mimeGroup: filter.mimeGroup === value ? null : value }); case "entity": return applyPatch({ entityType: filter.entityType === value ? null : value }); case "tag": return applyPatch({ tag: filter.tags[0] === value ? null : value }); case "assignee": return applyPatch({ assignedToUserId: filter.assignedToUserId === value ? null : value }); default: return undefined; } } function resetFilters() { setSearch(""); actions.onApply({ mimeGroup: null, entityType: null, tag: null, assignedToUserId: null, includeArchived: false, q: "", viewMode, }); } async function downloadZip(event: FormEvent) { event.preventDefault(); setDownloadingZip(true); try { const response = await fetch(bulkZipAction, { method: "POST", body: new FormData(event.currentTarget), }); if (!response.ok) throw new Error("bulk zip failed"); const href = URL.createObjectURL(await response.blob()); const link = document.createElement("a"); link.href = href; link.download = "dateien.zip"; link.click(); window.setTimeout(() => URL.revokeObjectURL(href), 0); } catch { setDownloadError({ intent: "bulk-zip", error: "files.browser.bulk.downloadError", }); } finally { setDownloadingZip(false); } } const allFacets: ClientFacet[] = [ { key: "mime", label: t("files.browser.filter.mime.label"), icon: , tone: "blue-subtle", options: MIME_GROUPS.map((group) => ({ value: group, label: t(`files.browser.filter.mime.${group}`) })), selected: new Set(filter.mimeGroup ? [filter.mimeGroup] : []), }, { key: "entity", label: t("files.browser.filter.entity.label"), icon: , tone: "violet-subtle", options: filterOptions.entityTypes.map((type) => ({ value: type, label: t(`files.entityType.${type}`, { defaultValue: t("files.entityType.unknown") }), })), selected: new Set(filter.entityType ? [filter.entityType] : []), }, { key: "tag", label: t("files.browser.filter.tag.label"), icon: , tone: "neutral-subtle", options: filterOptions.tags.map((tag) => ({ value: tag, label: tag })), selected: new Set(filter.tags), }, { key: "assignee", label: t("files.browser.filter.assignee.label"), icon: , tone: "sky-subtle", options: filterOptions.assignees.map((assignee) => ({ value: assignee.id, label: assignee.name })), selected: new Set(filter.assignedToUserId ? [filter.assignedToUserId] : []), }, ]; // A facet with nothing to pick is a dead button; the tenant may simply have // no tags or no linked entities yet. const facets = allFacets.filter((facet) => facet.options.length > 0); return ( } title={t("files.browser.title")} subtitle={t("files.browser.subtitle")} actions={ <> { if (value === "table" || value === "grid") applyPatch({ viewMode: value }); }} > } value="table" aria-label={t("files.browser.viewMode.table")}> {t("files.browser.viewMode.table")} } value="grid" aria-label={t("files.browser.viewMode.grid")}> {t("files.browser.viewMode.grid")} {canWrite && upload ? ( ) : null} } /> {/* --- Filter bar: search box + facet dropdowns, the same strip the boards use, so a filter looks and behaves the same on both screens. --- */} applyPatch({ includeArchived: checked })} data-ui-id="ui.files.browser.filter.archived" /> } /> {/* Filter bar (server-side, navigation on change) */} {rows.length > 0 && viewMode === "table" && selectedIds.length > 0 ? (
{selectedIds.map((id) => ( ))} {t("files.browser.bulk.selected", { count: selectedIds.length })}
) : null} {rows.length === 0 ? ( setUploadOpen(true)} headlineKey={data.emptyHeadlineKey} bodyKey={data.emptyBodyKey} /> ) : viewMode === "grid" ? ( ) : ( )} {/* Page footer: how many files there are, which page of how many, and the way in both directions — in both views, since paging is a property of the result set, not of how it is drawn. */}
{t("files.browser.pagination.total", { count: pagination.total })} {rows.length > 0 ? (
{t("files.browser.pagination.position", { page: pagination.page, pageCount: pagination.pageCount })}
) : null}
{/* Uploading stays on this page: the browser is where the new file is expected to appear, and a separate upload route took the reader away from it. */} {upload ? ( { setUploadOpen(open); if (!open) upload.onClose(); }} items={upload.items} onFiles={upload.onFiles} uploading={upload.uploading} /> ) : null}
); } function StatusBadges({ row }: { row: FileBrowserRow }) { const { t } = useTranslation(); const preview = previewBadge(row.previewStatus); const scan = scanBadge(row.scanStatus); return (
{scan ? ( {t(scan.key)} ) : null} {t(preview.key)}
); } function RowTags({ tags }: { tags: readonly string[] }) { if (tags.length === 0) return null; return (
{tags.map((tag) => ( {tag} ))}
); } function TableView({ rows, dateFormatter, selectedIds, onToggleSelect, onToggleSelectAll, }: { rows: readonly FileBrowserRow[]; dateFormatter: Intl.DateTimeFormat; selectedIds: readonly string[]; onToggleSelect: (id: string) => void; onToggleSelectAll: (ids: readonly string[], selectAll: boolean) => void; }) { const { t } = useTranslation(); const selectedSet = new Set(selectedIds); const allIds = rows.map((row) => row.id); const allSelected = allIds.length > 0 && allIds.every((id) => selectedSet.has(id)); return (
onToggleSelectAll(allIds, checked)} /> {t("files.browser.column.name")}{t("files.browser.column.type")}{t("files.browser.column.size")}{t("files.browser.column.date")}{t("files.browser.column.status")}{t("files.browser.column.tags")} } > {rows.map((row) => ( onToggleSelect(row.id)} /> {row.displayName} {t(fileTypeLabelKey(row.mimeType))} {formatBytes(row.sizeBytes)} {dateFormatter.format(new Date(row.createdAtIso))} ))}
); } function GridView({ rows }: { rows: readonly FileBrowserRow[] }) { return (
{rows.map((row) => (
{row.thumbnailUrl ? ( {row.displayName} ) : ( )}
{row.displayName}
))}
); } function EmptyBrowser({ canWrite, onUpload, headlineKey, bodyKey }: { canWrite: boolean; onUpload: () => void; headlineKey: string; bodyKey: string }) { const { t } = useTranslation(); return (
{t(headlineKey)} {t(bodyKey)}
{canWrite ? ( ) : null}
); }