Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/components/screens/files/FileDetailPage.tsx
T

566 lines
27 KiB
TypeScript

// 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.
//
// The page wears the same dense header band as the board screens: the file name
// is the title and is edited in place there, the file's actions sit in the
// header's action slot, and paging to the neighbouring file happens next to the
// preview instead of via the browser's back button.
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { AppLink } from "~/components/app/AppLink";
import { fileTypeLabelKey } from "~/utils/files/fileTypeLabel";
import {
FeatherArchive,
FeatherChevronLeft,
FeatherChevronRight,
FeatherCheck,
FeatherDownload,
FeatherFileText,
FeatherLink,
FeatherRefreshCw,
FeatherSearch,
FeatherTags,
FeatherTrash2,
FeatherX,
} from "@subframe/core";
import type { FileDetailData } from "@hivegrid/view-models";
import { PAGE_HEADER_ICON_CLASS, PageBody, PageHeader, PageShell } from "../shared/PageShell";
import { Alert } from "~/ui/components/Alert";
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";
import { APP_TIME_ZONE } from "~/locale/format";
/** One pickable link target, as the link-targets resource returns it. */
export type FileLinkTargetOption = { id: string; label: string; hint: string | null };
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;
/** Loader-only JSON resource the link dialog searches for records. */
linkSearchHref: 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]}`;
}
/**
* Split "angebot.2026.pdf" into "angebot.2026" + ".pdf". A leading dot is part
* of the name (".gitignore" has no suffix), and a name without a dot keeps an
* empty suffix rather than inventing one.
*/
export function splitFileName(displayName: string): { stem: string; extension: string } {
const dot = displayName.lastIndexOf(".");
if (dot <= 0 || dot === displayName.length - 1) return { stem: displayName, extension: "" };
return { stem: displayName.slice(0, dot), extension: displayName.slice(dot) };
}
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, linkSearchHref }: FileDetailPageProps) {
const { t, i18n } = useTranslation();
const [addLinkOpen, setAddLinkOpen] = useState(false);
const [tagsOpen, setTagsOpen] = useState(false);
const [deleteOpen, setDeleteOpen] = useState(false);
const [draftTags, setDraftTags] = useState(data.tags.join(", "));
const [linkType, setLinkType] = useState<string>(entityTypes[0] ?? "contact");
const [linkQuery, setLinkQuery] = useState("");
const [pickedTarget, setPickedTarget] = useState<FileLinkTargetOption | null>(null);
const dateFormatter = new Intl.DateTimeFormat(i18n.language, { timeZone: APP_TIME_ZONE, dateStyle: "medium" });
// The file name is edited where the project name is edited: as a normal field
// in the first card, saved by the one save action in the header. No separate
// edit mode — the field is the field.
const renameFormId = "file-rename-form";
// Only the stem is editable. The suffix is what a download is saved as and
// what the reader's system picks an application by, so it is shown next to
// the field and put back on save instead of being left to a typo.
const { stem, extension } = splitFileName(data.displayName);
const [draftStem, setDraftStem] = useState(stem);
const nextName = `${draftStem.trim()}${extension}`;
return (
<PageShell uiId="ui.files.detail">
<PageHeader
uiId="ui.files.detail.header"
dense
icon={<FeatherFileText className={PAGE_HEADER_ICON_CLASS} />}
title={data.displayName}
subtitle={`${t(fileTypeLabelKey(data.mimeType))} · ${dateFormatter.format(new Date(data.createdAtIso))}`}
actions={
<>
<a href={data.downloadUrl} className="no-underline" data-ui-id="ui.files.detail.download">
<Button variant="tertiary" size="small" 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" size="small" icon={<FeatherRefreshCw />}>
{t("files.detail.actions.regeneratePreview")}
</Button>
</form>
) : null}
{data.canWrite ? (
<form method="post">
<Button type="submit" name="intent" value="archive" variant="tertiary" size="small" icon={<FeatherArchive />} data-ui-id="ui.files.detail.archive">
{t("files.detail.actions.archive")}
</Button>
</form>
) : null}
{data.canDelete ? (
<Button
type="button"
variant="destructive"
size="small"
icon={<FeatherTrash2 />}
onClick={() => setDeleteOpen(true)}
data-ui-id="ui.files.detail.delete"
>
{t("files.detail.actions.delete")}
</Button>
) : null}
{/* Save closes the row: it belongs to the field in the card below,
not to the file-wide actions in front of it. */}
{data.canWrite ? (
<Button
type="submit"
form={renameFormId}
size="small"
icon={<FeatherCheck />}
disabled={!nextName || nextName === data.displayName}
data-ui-id="ui.files.detail.save"
>
{t("shared.save")}
</Button>
) : null}
</>
}
/>
<PageBody>
{data.scanNoticeKey ? (
<div data-ui-id="ui.files.detail.scanNotice">
<Alert variant={data.scanStatus === "infected" ? "error" : "warning"} description={t(data.scanNoticeKey)} notDismissible />
</div>
) : null}
{/* The file itself on the left, everything the app knows about it in its
own card on the right. They stack below lg, where a 340px column next
to a preview would leave neither of them a usable width. */}
<div className="flex w-full flex-col items-start gap-4 lg:flex-row">
{/* Preview, with the neighbouring files one click away on either side.
Both buttons stay on screen and grey out at the ends, so the reader
can tell "no more files" from "this control is missing". */}
<div className="flex w-full min-w-0 grow items-center gap-3" data-ui-id="ui.files.detail.preview">
<NeighbourButton
href={data.previousHref}
icon={<FeatherChevronLeft />}
label={t("files.detail.nav.previous")}
uiId="ui.files.detail.nav.previous"
/>
<div className="flex min-w-0 grow flex-col items-center gap-3">
{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-[520px] w-auto rounded-sm object-contain" />
</div>
) : data.previewFallbackKey ? (
<Alert className="w-full" variant="neutral" description={t(data.previewFallbackKey)} notDismissible />
) : null}
</div>
<NeighbourButton href={data.nextHref} icon={<FeatherChevronRight />} label={t("files.detail.nav.next")} uiId="ui.files.detail.nav.next" />
</div>
<div className="flex w-full flex-col gap-4 lg:w-[360px] lg:flex-none">
{/* Card 1: Stammdaten — type, size, date, source, plus the tags and
notes that describe the same file. */}
<Card data-ui-id="ui.files.detail.metadata">
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">{t("files.detail.section.metadata")}</span>
{data.canWrite ? (
<form method="post" id={renameFormId} className="w-full" data-ui-id="ui.files.detail.rename">
<input type="hidden" name="intent" value="rename" />
{/* The suffix travels with the submitted value but never
through the field, so renaming cannot change it. */}
<input type="hidden" name="displayName" value={nextName} />
<TextInput className="w-full max-w-none" label={t("files.detail.rename.label")} showLabel>
<TextInput.Input
variant="small"
value={draftStem}
onChange={(event) => setDraftStem(event.target.value)}
data-ui-id="ui.files.detail.rename.input"
/>
</TextInput>
{extension ? (
<span
className="mt-1 block text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary"
data-ui-id="ui.files.detail.rename.extension"
>
{t("files.detail.rename.extensionHint", { extension })}
</span>
) : null}
</form>
) : null}
<div className="grid w-full grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-1">
<MetaRow label={t("files.detail.meta.type")} value={t(fileTypeLabelKey(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 w-full 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>
{/* Card 2: Schlagworte — the file's own labels, edited in a dialog
so the card stays a list and not half a form. */}
<Card data-ui-id="ui.files.detail.tags">
<div className="flex w-full items-center justify-between gap-3">
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">{t("files.detail.section.tags")}</span>
{data.canWrite ? (
<Button
type="button"
variant="tertiary"
size="small"
icon={<FeatherTags />}
onClick={() => {
setDraftTags(data.tags.join(", "));
setTagsOpen(true);
}}
data-ui-id="ui.files.detail.tags.open"
>
{t("shared.edit")}
</Button>
) : null}
</div>
{data.tags.length > 0 ? (
<div className="flex w-full flex-wrap items-center gap-1">
{data.tags.map((tag) => (
<Tag_Label key={tag} tone="neutral-subtle" size="small" noAction>
{tag}
</Tag_Label>
))}
</div>
) : (
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">{t("files.detail.tags.empty")}</span>
)}
</Card>
{/* Card 3: Verknuepfungen — what this file is attached to. */}
<Card data-ui-id="ui.files.detail.links">
<div className="flex w-full items-center justify-between gap-3">
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">{t("files.detail.section.links")}</span>
{data.canWrite ? (
<Button
type="button"
variant="tertiary"
size="small"
icon={<FeatherLink />}
onClick={() => setAddLinkOpen(true)}
data-ui-id="ui.files.detail.links.add"
>
{t("files.detail.actions.link")}
</Button>
) : null}
</div>
{data.linkedEntities.length > 0 ? (
<ul className="flex w-full 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="flex min-w-0 flex-col">
<span className="truncate text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-primary">
{link.label ?? t(`files.entityType.${link.entityType}`, { defaultValue: t("files.entityType.unknown") })}
</span>
<span className="truncate text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">
{t(`files.entityType.${link.entityType}`, { defaultValue: t("files.entityType.unknown") })}
{link.linkRole ? ` · ${link.linkRole}` : ""}
</span>
</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>
)}
</Card>
</div>
</div>
</PageBody>
{/* Tags dialog — same chrome as the other quick actions. The field takes a
comma-separated list, which is what the route's updateMeta expects. */}
<Dialog open={tagsOpen} onOpenChange={setTagsOpen}>
<Dialog.Content className="w-112 max-w-[92vw] p-4" data-ui-id="ui.files.detail.tagsDialog">
<form method="post" className="flex w-full flex-col items-start gap-5">
<input type="hidden" name="intent" value="updateMeta" />
<div className="flex w-full flex-col items-start gap-1">
<span className="text-heading-0 font-heading-0 text-text-neutral-primary">{t("files.detail.section.tags")}</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">{t("files.detail.tags.placeholder")}</span>
</div>
<TextInput className="w-full max-w-none" label={t("files.detail.tags.editLabel")} showLabel>
<TextInput.Input
autoFocus
name="tags"
value={draftTags}
onChange={(event) => setDraftTags(event.target.value)}
placeholder={t("files.detail.tags.placeholder")}
data-ui-id="ui.files.detail.tagsDialog.input"
/>
</TextInput>
<div className="flex w-full items-center justify-end gap-2">
<Button type="button" variant="tertiary" onClick={() => setTagsOpen(false)}>
{t("shared.cancel")}
</Button>
<Button type="submit" icon={<FeatherTags />} data-ui-id="ui.files.detail.tagsDialog.submit">
{t("files.detail.tags.save")}
</Button>
</div>
</form>
</Dialog.Content>
</Dialog>
{/* Add-link dialog */}
<Dialog open={addLinkOpen} onOpenChange={setAddLinkOpen}>
<Dialog.Content className="w-112 max-w-[92vw] p-4" data-ui-id="ui.files.detail.linkDialog">
<form method="post" className="flex w-full flex-col items-start gap-5" data-ui-id="ui.files.detail.linkForm">
<input type="hidden" name="intent" value="link" />
<div className="flex w-full flex-col items-start gap-1">
<span className="text-heading-0 font-heading-0 text-text-neutral-primary">{t("files.detail.addLink.title")}</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">{t("files.detail.addLink.subtitle")}</span>
</div>
<div className="flex w-full flex-col gap-4">
<Select
className="w-full max-w-none"
name="entityType"
label={t("files.detail.link.entityType")}
showLabel
value={linkType}
onValueChange={(value: string) => {
setLinkType(value);
// A record of the old type says nothing about the new one.
setLinkQuery("");
setPickedTarget(null);
}}
data-ui-id="ui.files.detail.linkDialog.type"
>
{entityTypes.map((type) => (
<Select.Item key={type} value={type}>
{t(`files.entityType.${type}`, { defaultValue: t("files.entityType.unknown") })}
</Select.Item>
))}
</Select>
<LinkTargetPicker
searchHref={linkSearchHref}
entityType={linkType}
query={linkQuery}
onQueryChange={setLinkQuery}
picked={pickedTarget}
onPick={setPickedTarget}
/>
{/* No role field: the action treats it as optional, and a free
text role nobody fills in only made the dialog longer. Existing
roles (set by other paths) still show on the link itself. */}
</div>
<div className="flex w-full items-center justify-end gap-2">
<Button type="button" variant="tertiary" onClick={() => setAddLinkOpen(false)}>
{t("shared.cancel")}
</Button>
<Button type="submit" icon={<FeatherLink />}>
{t("files.detail.actions.link")}
</Button>
</div>
</form>
</Dialog.Content>
</Dialog>
{/* Delete confirmation dialog */}
<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("shared.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>
</PageShell>
);
}
/**
* Picks the record a link points at. The dialog used to ask for a raw id, which
* nobody carries in their head; this searches the chosen type instead and
* submits the id of what was picked. A type the server cannot search (no name
* to search by) keeps the plain id field, which is honest about what it needs.
*/
function LinkTargetPicker({
searchHref,
entityType,
query,
onQueryChange,
picked,
onPick,
}: {
searchHref: string;
entityType: string;
query: string;
onQueryChange: (value: string) => void;
picked: FileLinkTargetOption | null;
onPick: (target: FileLinkTargetOption | null) => void;
}) {
const { t } = useTranslation();
const [rows, setRows] = useState<FileLinkTargetOption[]>([]);
const [searchable, setSearchable] = useState(true);
const [state, setState] = useState<"idle" | "loading" | "failed">("idle");
// Debounced, and aborted on the next keystroke: without the abort a slow
// early response can overwrite the results of a later, narrower query.
useEffect(() => {
const controller = new AbortController();
const timer = setTimeout(() => {
setState("loading");
fetch(`${searchHref}?type=${encodeURIComponent(entityType)}&q=${encodeURIComponent(query)}`, { signal: controller.signal })
.then((response) => (response.ok ? response.json() : Promise.reject(new Error(String(response.status)))))
.then((data: { rows: FileLinkTargetOption[]; searchable: boolean }) => {
setRows(data.rows);
setSearchable(data.searchable);
setState("idle");
})
.catch((error: unknown) => {
if (error instanceof DOMException && error.name === "AbortError") return;
setState("failed");
});
}, 250);
return () => {
controller.abort();
clearTimeout(timer);
};
}, [entityType, query, searchHref]);
if (!searchable) {
// No name to search by for this type — ask for the id and say so.
return (
<TextInput className="w-full max-w-none" label={t("files.detail.link.entityId")} showLabel helpText={t("files.detail.link.noSearch")}>
<TextInput.Input name="entityId" required data-ui-id="ui.files.detail.linkDialog.entityId" />
</TextInput>
);
}
return (
<div className="flex w-full flex-col gap-2" data-ui-id="ui.files.detail.linkDialog.picker">
{/* The picked id is what gets submitted; the search box itself is not a
form field, so a half-typed name can never be sent as an id. */}
<input type="hidden" name="entityId" value={picked?.id ?? ""} required />
<TextInput className="w-full max-w-none" label={t("files.detail.link.search")} showLabel icon={<FeatherSearch />}>
<TextInput.Input
value={picked ? picked.label : query}
placeholder={t("files.detail.link.searchPlaceholder")}
onChange={(event) => {
// Typing again means picking again.
if (picked) onPick(null);
onQueryChange(event.target.value);
}}
data-ui-id="ui.files.detail.linkDialog.search"
/>
</TextInput>
{picked ? (
<span className="text-body-small-regular-0 font-body-small-regular-0 text-text-feedback-positive" data-ui-id="ui.files.detail.linkDialog.picked">
{t("files.detail.link.picked", { label: picked.label })}
</span>
) : (
<div className="flex max-h-56 w-full flex-col overflow-y-auto rounded-md border border-solid border-border-default">
{state === "failed" ? (
<span className="px-3 py-2 text-body-small-regular-0 font-body-small-regular-0 text-text-feedback-negative">{t("shared.unexpectedError")}</span>
) : rows.length === 0 ? (
<span className="px-3 py-2 text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary">
{t(state === "loading" ? "shared.loading" : "files.detail.link.noResults")}
</span>
) : (
rows.map((row) => (
<button
key={row.id}
type="button"
className="flex w-full flex-col items-start gap-0.5 px-3 py-2 text-left hover:bg-surface-neutral-tertiary"
onClick={() => onPick(row)}
data-ui-id={`ui.files.detail.linkDialog.option.${row.id}`}
>
<span className="text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-primary">{row.label}</span>
{row.hint ? (
<span className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">{row.hint}</span>
) : null}
</button>
))
)}
</div>
)}
</div>
);
}
/** One paging arrow; disabled-looking and inert at either end of the library. */
function NeighbourButton({ href, icon, label, uiId }: { href: string | null; icon: React.ReactNode; label: string; uiId: string }) {
if (!href) {
return (
<IconButton variant="tertiary" size="medium" icon={icon} aria-label={label} title={label} disabled data-ui-id={uiId} />
);
}
return (
<AppLink href={href} className="no-underline" aria-label={label} title={label} data-ui-id={uiId}>
<IconButton variant="tertiary" size="medium" icon={icon} aria-label={label} />
</AppLink>
);
}