Files

554 lines
22 KiB
TypeScript

// 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<SaveActionResult>();
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> = {}): 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<FilesBrowserQuery>) {
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 (
<PageShell uiId="ui.files.browser">
<PageHeader icon={<FeatherFileText className={PAGE_HEADER_ICON_CLASS} />} title={t("files.browser.title")} subtitle={t("files.browser.subtitle")} />
<PageBody>{null}</PageBody>
</PageShell>
);
}
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<HTMLFormElement>) {
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: <FeatherFile />,
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: <FeatherLink />,
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: <FeatherTag />,
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: <FeatherUser />,
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 (
<PageShell uiId="ui.files.browser">
<PageHeader
icon={<FeatherFileText className={PAGE_HEADER_ICON_CLASS} />}
title={t("files.browser.title")}
subtitle={t("files.browser.subtitle")}
actions={
<>
<ToggleGroup
value={viewMode}
onValueChange={(value: string) => {
if (value === "table" || value === "grid") applyPatch({ viewMode: value });
}}
>
<ToggleGroup.Item icon={<FeatherList />} value="table" aria-label={t("files.browser.viewMode.table")}>
{t("files.browser.viewMode.table")}
</ToggleGroup.Item>
<ToggleGroup.Item icon={<FeatherGrid />} value="grid" aria-label={t("files.browser.viewMode.grid")}>
{t("files.browser.viewMode.grid")}
</ToggleGroup.Item>
</ToggleGroup>
{canWrite && upload ? (
<Button icon={<FeatherUpload />} onClick={() => setUploadOpen(true)} data-ui-id="ui.files.browser.upload">
{t("files.browser.actions.upload")}
</Button>
) : null}
</>
}
/>
{/* --- Filter bar: search box + facet dropdowns, the same strip the
boards use, so a filter looks and behaves the same on both screens. --- */}
<FacetFilterBar
facets={facets}
onToggle={toggleFacet}
search={search}
onSearchChange={setSearch}
searchPlaceholder={t("files.browser.filter.searchPlaceholder")}
onReset={resetFilters}
labels={{ reset: t("files.browser.filter.reset"), removeChip: t("files.browser.filter.removeChip") }}
uiId="ui.files.browser.filter"
trailing={
<Checkbox
label={t("files.browser.filter.archived")}
checked={filter.includeArchived}
onCheckedChange={(checked: boolean) => applyPatch({ includeArchived: checked })}
data-ui-id="ui.files.browser.filter.archived"
/>
}
/>
<PageBody>
{/* Filter bar (server-side, navigation on change) */}
{rows.length > 0 && viewMode === "table" && selectedIds.length > 0 ? (
<form
method="post"
action={bulkZipAction}
onSubmit={downloadZip}
className="border-border-default bg-surface-neutral-secondary flex flex-wrap items-center gap-3 rounded-md border border-solid px-4 py-3"
data-ui-id="ui.files.browser.bulkbar"
>
{selectedIds.map((id) => (
<input key={id} type="hidden" name="fileIds" value={id} />
))}
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">
{t("files.browser.bulk.selected", { count: selectedIds.length })}
</span>
<Button type="submit" variant="secondary" icon={<FeatherDownload />} disabled={downloadingZip}>
{t("files.browser.bulk.downloadZip")}
</Button>
</form>
) : null}
{rows.length === 0 ? (
<EmptyBrowser
canWrite={canWrite && Boolean(upload)}
onUpload={() => setUploadOpen(true)}
headlineKey={data.emptyHeadlineKey}
bodyKey={data.emptyBodyKey}
/>
) : viewMode === "grid" ? (
<GridView rows={rows} />
) : (
<TableView
rows={rows}
dateFormatter={dateFormatter}
selectedIds={selectedIds}
onToggleSelect={actions.onToggleSelect}
onToggleSelectAll={actions.onToggleSelectAll}
/>
)}
{/* 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. */}
<div className="flex w-full items-center justify-between gap-2" data-ui-id="ui.files.browser.pagination">
<span className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary">
{t("files.browser.pagination.total", { count: pagination.total })}
</span>
{rows.length > 0 ? (
<div className="flex items-center gap-2">
<Button
variant="neutral"
size="small"
disabled={!pagination.hasPrevious}
onClick={() => actions.onGoToPage(currentQuery(), pagination.page - 1)}
data-ui-id="ui.files.browser.pagination.prev"
>
{t("files.browser.pagination.previous")}
</Button>
<span
className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary"
data-ui-id="ui.files.browser.pagination.position"
>
{t("files.browser.pagination.position", { page: pagination.page, pageCount: pagination.pageCount })}
</span>
<Button
variant="neutral"
size="small"
disabled={!pagination.hasNext}
onClick={() => actions.onGoToPage(currentQuery(), pagination.page + 1)}
data-ui-id="ui.files.browser.pagination.next"
>
{t("files.browser.pagination.next")}
</Button>
</div>
) : null}
</div>
</PageBody>
{/* 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 ? (
<FileUploadDialog
open={uploadOpen}
onOpenChange={(open) => {
setUploadOpen(open);
if (!open) upload.onClose();
}}
items={upload.items}
onFiles={upload.onFiles}
uploading={upload.uploading}
/>
) : null}
</PageShell>
);
}
function StatusBadges({ row }: { row: FileBrowserRow }) {
const { t } = useTranslation();
const preview = previewBadge(row.previewStatus);
const scan = scanBadge(row.scanStatus);
return (
<div className="flex flex-wrap items-center gap-1">
{scan ? (
<BadgeFeedback farbe={scan.farbe} size="small">
{t(scan.key)}
</BadgeFeedback>
) : null}
<BadgeFeedback farbe={preview.farbe} size="small">
{t(preview.key)}
</BadgeFeedback>
</div>
);
}
function RowTags({ tags }: { tags: readonly string[] }) {
if (tags.length === 0) return null;
return (
<div className="flex flex-wrap items-center gap-1">
{tags.map((tag) => (
<Tag_Label key={tag} tone="neutral-subtle" size="small" noAction>
{tag}
</Tag_Label>
))}
</div>
);
}
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 (
<div className="w-full overflow-x-auto" data-ui-id="ui.files.browser.table">
<Table
header={
<Table.HeaderRow>
<Table.HeaderCell>
<Checkbox
aria-label={t("files.browser.select.all")}
checked={allSelected}
onCheckedChange={(checked: boolean) => onToggleSelectAll(allIds, checked)}
/>
</Table.HeaderCell>
<Table.HeaderCell>{t("files.browser.column.name")}</Table.HeaderCell>
<Table.HeaderCell>{t("files.browser.column.type")}</Table.HeaderCell>
<Table.HeaderCell>{t("files.browser.column.size")}</Table.HeaderCell>
<Table.HeaderCell>{t("files.browser.column.date")}</Table.HeaderCell>
<Table.HeaderCell>{t("files.browser.column.status")}</Table.HeaderCell>
<Table.HeaderCell>{t("files.browser.column.tags")}</Table.HeaderCell>
</Table.HeaderRow>
}
>
{rows.map((row) => (
<Table.Row key={row.id} data-row-id={row.id}>
<Table.Cell>
<Checkbox aria-label={t("files.browser.select.row")} checked={selectedSet.has(row.id)} onCheckedChange={() => onToggleSelect(row.id)} />
</Table.Cell>
<Table.Cell>
<AppLink href={row.detailHref} className="text-body-default-medium-0 font-body-default-medium-0 text-text-feedback-link-default">
{row.displayName}
</AppLink>
</Table.Cell>
<Table.Cell>
<span className="text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary" title={row.mimeType}>
{t(fileTypeLabelKey(row.mimeType))}
</span>
</Table.Cell>
<Table.Cell>
<span className="text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary">{formatBytes(row.sizeBytes)}</span>
</Table.Cell>
<Table.Cell>
<span className="text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary">
{dateFormatter.format(new Date(row.createdAtIso))}
</span>
</Table.Cell>
<Table.Cell>
<StatusBadges row={row} />
</Table.Cell>
<Table.Cell>
<RowTags tags={row.tags} />
</Table.Cell>
</Table.Row>
))}
</Table>
</div>
);
}
function GridView({ rows }: { rows: readonly FileBrowserRow[] }) {
return (
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4" data-ui-id="ui.files.browser.grid">
{rows.map((row) => (
<AppLink key={row.id} href={row.detailHref} className="no-underline" data-row-id={row.id}>
<Card>
<div className="bg-surface-neutral-tertiary flex h-32 w-full items-center justify-center overflow-hidden rounded-md">
{row.thumbnailUrl ? (
<img src={row.thumbnailUrl} alt={row.displayName} className="h-full w-full object-cover" />
) : (
<FeatherFile className="text-heading-1 font-heading-1 text-icon-neutral-tertiary" />
)}
</div>
<div className="flex w-full flex-col gap-2">
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary line-clamp-1">{row.displayName}</span>
<StatusBadges row={row} />
<RowTags tags={row.tags} />
</div>
</Card>
</AppLink>
))}
</div>
);
}
function EmptyBrowser({ canWrite, onUpload, headlineKey, bodyKey }: { canWrite: boolean; onUpload: () => void; headlineKey: string; bodyKey: string }) {
const { t } = useTranslation();
return (
<div
className="border-border-default bg-surface-neutral-primary flex flex-col items-center gap-4 rounded-md border border-solid px-6 py-16 text-center"
data-ui-id="ui.files.browser.empty"
>
<FeatherFile className="text-heading-1 font-heading-1 text-icon-neutral-tertiary" />
<div className="flex flex-col gap-1">
<span className="text-body-large-0 font-body-large-0 text-text-neutral-primary">{t(headlineKey)}</span>
<span className="text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-secondary">{t(bodyKey)}</span>
</div>
{canWrite ? (
<Button icon={<FeatherUpload />} onClick={onUpload} data-ui-id="ui.files.browser.empty.upload">
{t("files.browser.actions.upload")}
</Button>
) : null}
</div>
);
}