Update hivegrid-cloud reference to latest main

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
davidandClaude Fable 5 committed 2026-07-08 16:15:37 +02:00
1 parent e98d38e716
commit 7b21524c86
3781 files changed
+373484 -225607

No files matched your search

@@ -0,0 +1,85 @@
import { vi, describe, it, expect } from "vitest";
import "@testing-library/jest-dom";
import { render } from "@testing-library/react";
import { BrowserRouter as Router } from "react-router";
import { buildFileDetailVM } from "@hivegrid/view-models";
import { FileDetailPage } from "./FileDetailPage";
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (str: string) => str, i18n: { language: "de" } }),
}));
const ENTITY_TYPES = ["contact", "company", "lead"] as const;
function detailData(overrides: Record<string, unknown> = {}) {
const vm = buildFileDetailVM({
id: "f1",
displayName: "vertrag.pdf",
mimeType: "application/pdf",
sizeBytes: 4096,
createdAtIso: "2026-01-02T10:00:00.000Z",
tags: ["wichtig"],
notes: "Bitte prüfen",
source: "upload",
previewStatus: "ready",
scanStatus: "clean",
previewUrl: "/acme/media/f1/preview",
downloadUrl: "/acme/media/f1/original",
assignedToUserId: null,
linkedEntities: [{ entityType: "contact", entityId: "c1", linkRole: "owner", href: null }],
canWrite: true,
canDelete: true,
canAdmin: false,
...overrides,
});
if (vm.status !== "ready" || !vm.data) throw new Error("fixture VM not ready");
return vm.data;
}
describe("FileDetailPage (interim-UI)", () => {
it("renders the detail surface, download link and linked entities", () => {
const { container, getAllByText } = render(
<Router>
<FileDetailPage data={detailData()} entityTypes={ENTITY_TYPES} filesHref=".." />
</Router>,
);
expect(container.querySelector('[data-ui-id="ui.files.detail"]')).toBeInTheDocument();
expect(container.querySelector('[data-ui-id="ui.files.detail.download"]')).toBeInTheDocument();
expect(container.querySelector('[data-ui-id="ui.files.detail.links"]')).toBeInTheDocument();
expect(container.querySelector('[data-link-id="contact-c1"]')).toBeInTheDocument();
// displayName appears in both the breadcrumb and the header.
expect(getAllByText("vertrag.pdf").length).toBeGreaterThan(0);
});
it("shows the scan notice (fail-closed) for infected files", () => {
const { container } = render(
<Router>
<FileDetailPage data={detailData({ scanStatus: "infected" })} entityTypes={ENTITY_TYPES} filesHref=".." />
</Router>,
);
expect(container.querySelector('[data-ui-id="ui.files.detail.scanNotice"]')).toBeInTheDocument();
});
it("renders the tag editor (updateMeta form, pre-filled) when the user can write", () => {
const { container } = render(
<Router>
<FileDetailPage data={detailData()} entityTypes={ENTITY_TYPES} filesHref=".." />
</Router>,
);
const form = container.querySelector('[data-ui-id="ui.files.detail.tags.edit"]');
expect(form).toBeInTheDocument();
expect(form?.querySelector('input[type="hidden"][name="intent"][value="updateMeta"]')).toBeInTheDocument();
const input = form?.querySelector('input[name="tags"]') as HTMLInputElement | null;
expect(input?.value).toBe("wichtig");
});
it("hides the tag editor for read-only users", () => {
const { container } = render(
<Router>
<FileDetailPage data={detailData({ canWrite: false })} entityTypes={ENTITY_TYPES} filesHref=".." />
</Router>,
);
expect(container.querySelector('[data-ui-id="ui.files.detail.tags.edit"]')).not.toBeInTheDocument();
});
});
@@ -0,0 +1,254 @@
// AK-P4a Interim-UI (AD-28) — File detail preview screen composed from ~/ui.
// Presentational: renders the unwrapped FileDetailData; mutations stay server-driven
// (<form method="post"> + intent, exactly like the baseline route action). Modals are
// real ~/ui Dialogs (David standard), not Card fakes. No useLoaderData / server imports.
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { FeatherArchive, FeatherDownload, FeatherLink, FeatherRefreshCw, FeatherTrash2, FeatherX } from "@subframe/core";
import type { FileDetailData } from "@hivegrid/view-models";
import { Alert } from "~/ui/components/Alert";
import { Breadcrumbs } from "~/ui/components/Breadcrumbs";
import { Button } from "~/ui/components/Button";
import { Card } from "~/ui/components/Card";
import { Dialog } from "~/ui/components/Dialog";
import { IconButton } from "~/ui/components/IconButton";
import { Select } from "~/ui/components/Select";
import { Tag_Label } from "~/ui/components/Tag_Label";
import { TextInput } from "~/ui/components/TextInput";
export type FileDetailPageProps = {
data: FileDetailData;
/** Allowed polymorphic entity types for the add-link form. */
entityTypes: readonly string[];
/** Href back to the files browser (breadcrumb). */
filesHref: string;
};
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]}`;
}
function MetaRow({ label, value }: { label: string; value: string }) {
return (
<div className="flex flex-col gap-1">
<span className="text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-tertiary">{label}</span>
<span className="text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-primary">{value}</span>
</div>
);
}
export function FileDetailPage({ data, entityTypes, filesHref }: FileDetailPageProps) {
const { t, i18n } = useTranslation();
const [addLinkOpen, setAddLinkOpen] = useState(false);
const [deleteOpen, setDeleteOpen] = useState(false);
const dateFormatter = new Intl.DateTimeFormat(i18n.language, { dateStyle: "medium" });
return (
<div className="flex w-full max-w-[960px] flex-col gap-6 p-6" data-ui-id="ui.files.detail">
<Breadcrumbs>
<a href={filesHref} className="no-underline">
<Breadcrumbs.Item>{t("files.nav.title")}</Breadcrumbs.Item>
</a>
<Breadcrumbs.Divider />
<Breadcrumbs.Item active>{data.displayName}</Breadcrumbs.Item>
</Breadcrumbs>
{/* Header + action bar */}
<div className="flex flex-wrap items-start justify-between gap-4">
<div className="flex flex-col gap-1">
<span className="text-heading-2 font-heading-2 text-text-neutral-primary">{data.displayName}</span>
<span className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary">
{data.mimeType} · {dateFormatter.format(new Date(data.createdAtIso))}
</span>
</div>
<div className="flex flex-wrap items-center gap-2">
<a href={data.downloadUrl} className="no-underline" data-ui-id="ui.files.detail.download">
<Button variant="tertiary" icon={<FeatherDownload />}>
{t("files.detail.actions.download")}
</Button>
</a>
{data.canWrite && data.canRegeneratePreview ? (
<form method="post">
<Button type="submit" name="intent" value="regeneratePreview" variant="tertiary" icon={<FeatherRefreshCw />}>
{t("files.detail.actions.regeneratePreview")}
</Button>
</form>
) : null}
{data.canWrite ? (
<form method="post">
<Button type="submit" name="intent" value="archive" variant="tertiary" icon={<FeatherArchive />} data-ui-id="ui.files.detail.archive">
{t("files.detail.actions.archive")}
</Button>
</form>
) : null}
{data.canDelete ? (
<Button type="button" variant="destructive" icon={<FeatherTrash2 />} onClick={() => setDeleteOpen(true)} data-ui-id="ui.files.detail.delete">
{t("files.detail.actions.delete")}
</Button>
) : null}
</div>
</div>
{data.scanNoticeKey ? (
<div data-ui-id="ui.files.detail.scanNotice">
<Alert variant={data.scanStatus === "infected" ? "error" : "warning"} description={t(data.scanNoticeKey)} notDismissible />
</div>
) : null}
{/* Preview */}
<div data-ui-id="ui.files.detail.preview">
{data.previewUrl ? (
<div className="flex w-full items-center justify-center overflow-hidden rounded-md border border-solid border-border-default bg-surface-neutral-tertiary p-4">
<img src={data.previewUrl} alt={data.displayName} className="max-h-96 w-auto rounded-sm object-contain" />
</div>
) : data.previewFallbackKey ? (
<Alert variant="neutral" description={t(data.previewFallbackKey)} notDismissible />
) : null}
</div>
{/* Metadata */}
<Card>
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">{t("files.detail.section.metadata")}</span>
<div className="grid w-full grid-cols-1 gap-4 sm:grid-cols-2">
<MetaRow label={t("files.detail.meta.type")} value={data.mimeType} />
<MetaRow label={t("files.detail.meta.size")} value={formatBytes(data.sizeBytes)} />
<MetaRow label={t("files.detail.meta.created")} value={dateFormatter.format(new Date(data.createdAtIso))} />
<MetaRow label={t("files.detail.meta.source")} value={data.source} />
</div>
{data.notes ? (
<div className="flex flex-col gap-1">
<span className="text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-tertiary">{t("files.detail.section.notes")}</span>
<span className="whitespace-pre-wrap text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-primary">{data.notes}</span>
</div>
) : null}
</Card>
{/* Tags */}
{data.tags.length > 0 || data.canWrite ? (
<div className="flex flex-col gap-2" data-ui-id="ui.files.detail.tags">
<span className="text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-tertiary">{t("files.detail.section.tags")}</span>
{data.tags.length > 0 ? (
<div className="flex flex-wrap items-center gap-1">
{data.tags.map((tag) => (
<Tag_Label key={tag} tone="neutral-subtle" size="small" noAction>
{tag}
</Tag_Label>
))}
</div>
) : null}
{data.canWrite ? (
<form method="post" className="flex flex-wrap items-end gap-2" data-ui-id="ui.files.detail.tags.edit">
<input type="hidden" name="intent" value="updateMeta" />
<TextInput label={t("files.detail.tags.editLabel")} showLabel className="min-w-[240px] flex-1">
<TextInput.Input name="tags" defaultValue={data.tags.join(", ")} placeholder={t("files.detail.tags.placeholder")} />
</TextInput>
<Button type="submit" variant="secondary">
{t("files.detail.tags.save")}
</Button>
</form>
) : null}
</div>
) : null}
{/* Linked entities */}
<div className="flex flex-col gap-3" data-ui-id="ui.files.detail.links">
<div className="flex items-center justify-between gap-3">
<span className="text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-tertiary">{t("files.detail.section.links")}</span>
{data.canWrite ? (
<Button type="button" variant="tertiary" size="small" icon={<FeatherLink />} onClick={() => setAddLinkOpen(true)}>
{t("files.detail.actions.link")}
</Button>
) : null}
</div>
{data.linkedEntities.length > 0 ? (
<ul className="flex flex-col gap-2">
{data.linkedEntities.map((link) => (
<li
key={`${link.entityType}-${link.entityId}`}
className="flex items-center justify-between gap-3 rounded-md border border-solid border-border-default bg-surface-neutral-primary px-3 py-2"
data-link-id={`${link.entityType}-${link.entityId}`}
>
<span className="text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-primary">
{link.entityType}
{link.linkRole ? ` · ${link.linkRole}` : ""}
</span>
{data.canWrite ? (
<form method="post">
<input type="hidden" name="intent" value="unlink" />
<input type="hidden" name="entityType" value={link.entityType} />
<input type="hidden" name="entityId" value={link.entityId} />
<IconButton type="submit" variant="ghost" size="small" icon={<FeatherX />} aria-label={t("files.detail.actions.unlink")} />
</form>
) : null}
</li>
))}
</ul>
) : (
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">{t("files.detail.links.empty")}</span>
)}
</div>
{/* Add-link dialog (real ~/ui Dialog, size S) */}
<Dialog open={addLinkOpen} onOpenChange={setAddLinkOpen}>
<Dialog.Content className="w-[560px] max-w-[90vw] p-8">
<form method="post" className="flex w-full flex-col gap-6" data-ui-id="ui.files.detail.linkForm">
<input type="hidden" name="intent" value="link" />
<span className="text-heading-3 font-heading-3 text-text-neutral-primary">{t("files.detail.addLink.title")}</span>
<div className="flex flex-col gap-4">
<Select name="entityType" label={t("files.detail.link.entityType")} showLabel defaultValue={entityTypes[0]}>
{entityTypes.map((type) => (
<Select.Item key={type} value={type}>
{type}
</Select.Item>
))}
</Select>
<TextInput label={t("files.detail.link.entityId")} showLabel>
<TextInput.Input name="entityId" required />
</TextInput>
<TextInput label={t("files.detail.link.role")} showLabel>
<TextInput.Input name="linkRole" />
</TextInput>
</div>
<div className="flex items-center justify-end gap-2">
<Button type="button" variant="tertiary" onClick={() => setAddLinkOpen(false)}>
{t("files.detail.dialog.cancel")}
</Button>
<Button type="submit">{t("files.detail.actions.link")}</Button>
</div>
</form>
</Dialog.Content>
</Dialog>
{/* Delete confirmation dialog (real ~/ui Dialog, size XS) */}
<Dialog open={deleteOpen} onOpenChange={setDeleteOpen}>
<Dialog.Content className="w-[420px] max-w-[90vw] p-8">
<div className="flex w-full flex-col gap-6">
<div className="flex flex-col gap-2">
<span className="text-heading-3 font-heading-3 text-text-neutral-primary">{t("files.detail.delete.title")}</span>
<span className="text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-secondary">{t("files.detail.delete.body")}</span>
</div>
<div className="flex items-center justify-end gap-2">
<Button type="button" variant="tertiary" onClick={() => setDeleteOpen(false)}>
{t("files.detail.dialog.cancel")}
</Button>
<form method="post">
<Button type="submit" name="intent" value="delete" variant="destructive" icon={<FeatherTrash2 />}>
{t("files.detail.delete.confirm")}
</Button>
</form>
</div>
</div>
</Dialog.Content>
</Dialog>
</div>
);
}
@@ -0,0 +1,42 @@
import { vi, describe, it, expect } from "vitest";
import "@testing-library/jest-dom";
import { render } from "@testing-library/react";
import { BrowserRouter as Router } from "react-router";
import { buildFileUploadVM } from "@hivegrid/view-models";
import { FileUploadPage, type FileUploadDisplayItem } from "./FileUploadPage";
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (str: string) => str, i18n: { language: "de" } }),
}));
describe("FileUploadPage (interim-UI)", () => {
it("renders the dropzone + empty queue", () => {
const vm = buildFileUploadVM({ canWrite: true });
const { container } = render(
<Router>
<FileUploadPage vm={vm} items={[]} actions={{ onFiles: vi.fn() }} />
</Router>,
);
expect(container.querySelector('[data-ui-id="ui.files.upload"]')).toBeInTheDocument();
expect(container.querySelector('[data-ui-id="ui.files.upload.dropzone"]')).toBeInTheDocument();
expect(container.querySelector('[data-ui-id="ui.files.upload.input"]')).toBeInTheDocument();
expect(container.querySelector('[data-ui-id="ui.files.upload.queue"]')).toBeInTheDocument();
});
it("renders per-file queue items with status markers", () => {
const items: FileUploadDisplayItem[] = [
{ clientId: "a-1-2", filename: "rechnung.pdf", sizeBytes: 1024, status: "uploading", progressPercent: 40, errorKey: null },
{ clientId: "b-3-4", filename: "kaputt.pdf", sizeBytes: 512, status: "error", progressPercent: 0, errorKey: "files.error.uploadIncomplete" },
];
const vm = buildFileUploadVM({ canWrite: true });
const { container, getByText } = render(
<Router>
<FileUploadPage vm={vm} items={items} actions={{ onFiles: vi.fn() }} />
</Router>,
);
expect(container.querySelector('[data-row-id="a-1-2"][data-status="uploading"]')).toBeInTheDocument();
expect(container.querySelector('[data-row-id="b-3-4"][data-status="error"]')).toBeInTheDocument();
expect(getByText("rechnung.pdf")).toBeInTheDocument();
});
});
@@ -0,0 +1,114 @@
// AK-P4a Interim-UI (AD-28) — Files upload preview screen composed from ~/ui.
// Presentational: the chunked upload pipeline + queue state live in the route and are
// injected as `items` + `onFiles`. The dashed dropzone is a custom interactive target
// (no i18n-able ~/ui dropzone exists — the ~/ui FileUpload component bakes in English
// copy), everything else (Button, Progress, Alert) is composed from ~/ui.
import { useRef } from "react";
import { useTranslation } from "react-i18next";
import { FeatherUpload } from "@subframe/core";
import type { FileUploadVM } from "@hivegrid/view-models";
import { Alert } from "~/ui/components/Alert";
import { Button } from "~/ui/components/Button";
import { Progress } from "~/ui/components/Progress";
export type FileUploadDisplayItem = {
clientId: string;
filename: string;
sizeBytes: number;
status: "queued" | "uploading" | "processing" | "done" | "error";
progressPercent: number;
errorKey: string | null;
};
export type FileUploadActions = {
onFiles: (files: FileList | null) => void;
};
export type FileUploadPageProps = {
vm: FileUploadVM;
items: readonly FileUploadDisplayItem[];
actions: FileUploadActions;
};
function progressState(status: FileUploadDisplayItem["status"]): "uploading" | "success" | "error" {
if (status === "done") return "success";
if (status === "error") return "error";
return "uploading";
}
export function FileUploadPage({ vm, items, actions }: FileUploadPageProps) {
const { t } = useTranslation();
const inputRef = useRef<HTMLInputElement>(null);
if (vm.status !== "ready" || !vm.data) {
return <div className="flex w-full flex-col gap-6 p-6" data-ui-id="ui.files.upload" />;
}
const { dropzoneHeadlineKey, dropzoneBodyKey, heicNoticeKey } = vm.data;
function statusText(item: FileUploadDisplayItem): string {
if (item.status === "error") return t(item.errorKey ?? "files.error.uploadIncomplete");
if (item.status === "done") return t("files.upload.status.done");
if (item.status === "processing") return t("files.upload.status.processing");
if (item.status === "queued") return t("files.upload.status.queued");
return `${item.progressPercent}%`;
}
return (
<div className="flex w-full max-w-[720px] flex-col gap-6 p-6" data-ui-id="ui.files.upload">
<div className="flex flex-col gap-0">
<span className="text-heading-2 font-heading-2 text-text-neutral-primary">{t("files.upload.title")}</span>
</div>
{/* Dropzone (custom interactive target; i18n copy from the VM) */}
<button
type="button"
onClick={() => inputRef.current?.click()}
onDragOver={(event) => event.preventDefault()}
onDrop={(event) => {
event.preventDefault();
actions.onFiles(event.dataTransfer.files);
}}
className="flex w-full flex-col items-center gap-4 rounded-lg border-2 border-dashed border-border-strong bg-surface-neutral-primary px-6 py-16 hover:border-brand-brand-border-solid-hover hover:bg-surface-neutral-secondary"
data-ui-id="ui.files.upload.dropzone"
>
<FeatherUpload className="text-heading-1 font-heading-1 text-icon-neutral-secondary" />
<div className="flex flex-col items-center gap-1">
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">{t(dropzoneHeadlineKey)}</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary">{t(dropzoneBodyKey)}</span>
</div>
<Button icon={<FeatherUpload />} variant="tertiary">
{t("files.upload.actions.select")}
</Button>
</button>
<input ref={inputRef} type="file" multiple className="hidden" onChange={(event) => actions.onFiles(event.target.files)} data-ui-id="ui.files.upload.input" />
<Alert variant="information" textSize="small" description={t(heicNoticeKey)} notDismissible />
<ul className="flex flex-col gap-4" data-ui-id="ui.files.upload.queue">
{items.length === 0 ? (
<li className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">{t("files.upload.queue.empty")}</li>
) : (
items.map((item) => (
<li key={item.clientId} className="flex flex-col gap-2" data-row-id={item.clientId} data-status={item.status}>
<div className="flex items-center justify-between gap-3">
<span className="line-clamp-1 text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-primary">{item.filename}</span>
<span
className={
item.status === "error"
? "text-body-small-regular-0 font-body-small-regular-0 text-text-feedback-negative"
: "text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary"
}
>
{statusText(item)}
</span>
</div>
<Progress className="w-full" value={item.progressPercent} state={progressState(item.status)} hideLabel />
</li>
))
)}
</ul>
</div>
);
}
@@ -0,0 +1,119 @@
import { vi, describe, it, expect } from "vitest";
import "@testing-library/jest-dom";
import { render } from "@testing-library/react";
import { BrowserRouter as Router } from "react-router";
import { buildFileBrowserVM, type FileBrowserFilterOptions, type FileBrowserRow } from "@hivegrid/view-models";
import { FilesBrowserPage } from "./FilesBrowserPage";
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (str: string) => str, i18n: { language: "de" } }),
}));
function row(overrides: Partial<FileBrowserRow> = {}): FileBrowserRow {
return {
id: "f1",
displayName: "foto.heic",
mimeType: "image/heic",
sizeBytes: 2048,
createdAtIso: "2026-01-02T10:00:00.000Z",
tags: ["monteur"],
source: "upload",
previewStatus: "ready",
scanStatus: "clean",
thumbnailUrl: "/acme/media/f1/thumb",
detailHref: "/acme/files/f1",
linkedEntityLabelKey: null,
...overrides,
};
}
const filter = { entityType: null, mimeGroup: null, tags: [], assignedToUserId: null, includeArchived: false };
// Shared defaults for the props added by extended filters + bulk-ZIP selection.
function baseProps(selectedIds: string[] = []) {
return {
uploadHref: "upload",
nextHref: null,
bulkZipAction: "/acme/files/bulk-zip",
selectedIds,
actions: { onApply: vi.fn(), onToggleSelect: vi.fn(), onToggleSelectAll: vi.fn() },
};
}
describe("FilesBrowserPage (interim-UI)", () => {
it("renders the browser surface + table rows from the VM", () => {
const vm = buildFileBrowserVM({ rows: [row()], filter, canWrite: true, canDelete: false });
const { container, getByText } = render(
<Router>
<FilesBrowserPage vm={vm} {...baseProps()} />
</Router>,
);
expect(container.querySelector('[data-ui-id="ui.files.browser"]')).toBeInTheDocument();
expect(container.querySelector('[data-ui-id="ui.files.browser.table"]')).toBeInTheDocument();
expect(container.querySelector('[data-row-id="f1"]')).toBeInTheDocument();
expect(getByText("foto.heic")).toBeInTheDocument();
});
it("shows the empty state when there are no rows", () => {
const vm = buildFileBrowserVM({ rows: [], filter, canWrite: true, canDelete: false });
const { container } = render(
<Router>
<FilesBrowserPage vm={vm} {...baseProps()} />
</Router>,
);
expect(container.querySelector('[data-ui-id="ui.files.browser.empty"]')).toBeInTheDocument();
expect(container.querySelector('[data-ui-id="ui.files.browser.table"]')).not.toBeInTheDocument();
});
it("renders the grid view when viewMode=grid", () => {
const vm = buildFileBrowserVM({ viewMode: "grid", rows: [row()], filter, canWrite: true, canDelete: false });
const { container } = render(
<Router>
<FilesBrowserPage vm={vm} {...baseProps()} />
</Router>,
);
expect(container.querySelector('[data-ui-id="ui.files.browser.grid"]')).toBeInTheDocument();
expect(container.querySelector('[data-ui-id="ui.files.browser.table"]')).not.toBeInTheDocument();
});
it("renders the entity/tag/assignee filter selects when options are present", () => {
const filterOptions: FileBrowserFilterOptions = {
entityTypes: ["contact", "project"],
tags: ["monteur", "rechnung"],
assignees: [{ id: "u1", name: "Alex Meier" }],
};
const vm = buildFileBrowserVM({ rows: [row()], filter, filterOptions, canWrite: true, canDelete: false });
const { getByText } = render(
<Router>
<FilesBrowserPage vm={vm} {...baseProps()} />
</Router>,
);
expect(getByText("files.browser.filter.entity.label")).toBeInTheDocument();
expect(getByText("files.browser.filter.tag.label")).toBeInTheDocument();
expect(getByText("files.browser.filter.assignee.label")).toBeInTheDocument();
});
it("shows the bulk-ZIP bar (posting to the action URL) when rows are selected", () => {
const vm = buildFileBrowserVM({ rows: [row()], filter, canWrite: true, canDelete: false });
const { container } = render(
<Router>
<FilesBrowserPage vm={vm} {...baseProps(["f1"])} />
</Router>,
);
const bar = container.querySelector('[data-ui-id="ui.files.browser.bulkbar"]');
expect(bar).toBeInTheDocument();
expect(bar?.getAttribute("action")).toBe("/acme/files/bulk-zip");
expect(container.querySelector('input[type="hidden"][name="fileIds"][value="f1"]')).toBeInTheDocument();
});
it("hides the bulk-ZIP bar when nothing is selected", () => {
const vm = buildFileBrowserVM({ rows: [row()], filter, canWrite: true, canDelete: false });
const { container } = render(
<Router>
<FilesBrowserPage vm={vm} {...baseProps([])} />
</Router>,
);
expect(container.querySelector('[data-ui-id="ui.files.browser.bulkbar"]')).not.toBeInTheDocument();
});
});
@@ -0,0 +1,408 @@
// 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 { useTranslation } from "react-i18next";
import { FeatherDownload, FeatherFile, FeatherGrid, FeatherList, FeatherUpload } from "@subframe/core";
import type { FileBrowserRow, FileBrowserVM, FilePreviewStatus, FileScanStatus, FileViewMode } from "@hivegrid/view-models";
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 { Select } from "~/ui/components/Select";
import { Table } from "~/ui/components/Table";
import { Tag_Label } from "~/ui/components/Tag_Label";
import { ToggleGroup } from "~/ui/components/ToggleGroup";
export type FilesBrowserQuery = {
mimeGroup: string | null;
entityType: string | null;
tag: string | null;
assignedToUserId: string | null;
includeArchived: boolean;
viewMode: FileViewMode;
};
export type FilesBrowserActions = {
/** Navigate (GET) to the same route with the given filter/view state. */
onApply: (query: FilesBrowserQuery) => 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 FilesBrowserPageProps = {
vm: FileBrowserVM;
uploadHref: string;
/** Href for the next cursor page, or null on the last page. */
nextHref: string | null;
/** 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;
};
const MIME_ALL = "all";
// Shared "no filter" sentinel for the entity/tag/assignee Selects (empty string
// is not a valid Select value, so a non-empty sentinel maps back to null).
const FILTER_ALL = "__all__";
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, uploadHref, nextHref, bulkZipAction, selectedIds, actions }: FilesBrowserPageProps) {
const { t, i18n } = useTranslation();
// Loading / not-ready: keep the marker so the shell + e2e see a stable surface.
if (vm.status !== "ready" || !vm.data) {
return <div className="flex w-full flex-col gap-6 p-6" data-ui-id="ui.files.browser" />;
}
const { rows, viewMode, filter, filterOptions, canWrite } = vm.data;
const dateFormatter = new Intl.DateTimeFormat(i18n.language, { dateStyle: "medium" });
function applyPatch(patch: Partial<FilesBrowserQuery>) {
actions.onApply({
mimeGroup: filter.mimeGroup,
entityType: filter.entityType,
tag: filter.tags[0] ?? null,
assignedToUserId: filter.assignedToUserId,
includeArchived: filter.includeArchived,
viewMode,
...patch,
});
}
return (
<div className="flex w-full flex-col gap-6 p-6" data-ui-id="ui.files.browser">
{/* Header: title + subtitle (0px rhythm), view toggle + upload CTA */}
<div className="flex flex-wrap items-start justify-between gap-4">
<div className="flex flex-col gap-0">
<span className="text-heading-2 font-heading-2 text-text-neutral-primary">{t("files.browser.title")}</span>
<span className="text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-secondary">
{t("files.browser.subtitle")}
</span>
</div>
<div className="flex items-center gap-3">
<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 ? (
<a href={uploadHref} className="no-underline" data-ui-id="ui.files.browser.upload">
<Button icon={<FeatherUpload />}>{t("files.browser.actions.upload")}</Button>
</a>
) : null}
</div>
</div>
{/* Filter bar (server-side, navigation on change) */}
<div className="flex flex-wrap items-center gap-4" data-ui-id="ui.files.browser.filter">
<Select
className="max-w-[240px]"
label={t("files.browser.filter.mime.label")}
showLabel
value={filter.mimeGroup ?? MIME_ALL}
onValueChange={(value: string) => applyPatch({ mimeGroup: value === MIME_ALL ? null : value })}
>
<Select.Item value={MIME_ALL}>{t("files.browser.filter.mime.all")}</Select.Item>
<Select.Item value="image">{t("files.browser.filter.mime.image")}</Select.Item>
<Select.Item value="pdf">{t("files.browser.filter.mime.pdf")}</Select.Item>
<Select.Item value="text">{t("files.browser.filter.mime.text")}</Select.Item>
</Select>
{filterOptions.entityTypes.length > 0 ? (
<Select
className="max-w-[240px]"
label={t("files.browser.filter.entity.label")}
showLabel
value={filter.entityType ?? FILTER_ALL}
onValueChange={(value: string) => applyPatch({ entityType: value === FILTER_ALL ? null : value })}
>
<Select.Item value={FILTER_ALL}>{t("files.browser.filter.entity.all")}</Select.Item>
{filterOptions.entityTypes.map((type) => (
<Select.Item key={type} value={type}>
{t(`files.entityType.${type}`, { defaultValue: type })}
</Select.Item>
))}
</Select>
) : null}
{filterOptions.tags.length > 0 ? (
<Select
className="max-w-[240px]"
label={t("files.browser.filter.tag.label")}
showLabel
value={filter.tags[0] ?? FILTER_ALL}
onValueChange={(value: string) => applyPatch({ tag: value === FILTER_ALL ? null : value })}
>
<Select.Item value={FILTER_ALL}>{t("files.browser.filter.tag.all")}</Select.Item>
{filterOptions.tags.map((tag) => (
<Select.Item key={tag} value={tag}>
{tag}
</Select.Item>
))}
</Select>
) : null}
{filterOptions.assignees.length > 0 ? (
<Select
className="max-w-[240px]"
label={t("files.browser.filter.assignee.label")}
showLabel
value={filter.assignedToUserId ?? FILTER_ALL}
onValueChange={(value: string) => applyPatch({ assignedToUserId: value === FILTER_ALL ? null : value })}
>
<Select.Item value={FILTER_ALL}>{t("files.browser.filter.assignee.all")}</Select.Item>
{filterOptions.assignees.map((assignee) => (
<Select.Item key={assignee.id} value={assignee.id}>
{assignee.name}
</Select.Item>
))}
</Select>
) : null}
<Checkbox
label={t("files.browser.filter.archived")}
checked={filter.includeArchived}
onCheckedChange={(checked: boolean) => applyPatch({ includeArchived: checked })}
/>
</div>
{rows.length > 0 && viewMode === "table" && selectedIds.length > 0 ? (
<form
method="post"
action={bulkZipAction}
className="flex flex-wrap items-center gap-3 rounded-md border border-solid border-border-default bg-surface-neutral-secondary 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 />}>
{t("files.browser.bulk.downloadZip")}
</Button>
</form>
) : null}
{rows.length === 0 ? (
<EmptyBrowser canWrite={canWrite} uploadHref={uploadHref} vm={vm} />
) : viewMode === "grid" ? (
<GridView rows={rows} />
) : (
<TableView
rows={rows}
dateFormatter={dateFormatter}
selectedIds={selectedIds}
onToggleSelect={actions.onToggleSelect}
onToggleSelectAll={actions.onToggleSelectAll}
/>
)}
{nextHref ? (
<div className="flex justify-center pt-2" data-ui-id="ui.files.browser.pagination">
<a href={nextHref} className="no-underline">
<Button variant="tertiary">{t("files.browser.pagination.next")}</Button>
</a>
</div>
) : null}
</div>
);
}
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>
<a href={row.detailHref} className="text-body-default-medium-0 font-body-default-medium-0 text-text-feedback-link-default">
{row.displayName}
</a>
</Table.Cell>
<Table.Cell>
<span className="text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary">{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) => (
<a key={row.id} href={row.detailHref} className="no-underline" data-row-id={row.id}>
<Card>
<div className="flex h-32 w-full items-center justify-center overflow-hidden rounded-md bg-surface-neutral-tertiary">
{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="line-clamp-1 text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">{row.displayName}</span>
<StatusBadges row={row} />
<RowTags tags={row.tags} />
</div>
</Card>
</a>
))}
</div>
);
}
function EmptyBrowser({ canWrite, uploadHref, vm }: { canWrite: boolean; uploadHref: string; vm: Extract<FileBrowserVM, { status: "ready" }> }) {
const { t } = useTranslation();
const headlineKey = vm.data.emptyHeadlineKey;
const bodyKey = vm.data.emptyBodyKey;
return (
<div className="flex flex-col items-center gap-4 rounded-md border border-solid border-border-default bg-surface-neutral-primary 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 ? (
<a href={uploadHref} className="no-underline">
<Button icon={<FeatherUpload />}>{t("files.browser.actions.upload")}</Button>
</a>
) : null}
</div>
);
}