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

553 lines
24 KiB
TypeScript

// R-UX4 interim UI (AD-28). The screen receives a secret-free VM and injected
// commands. Reveal/copy plaintext exists only in short-lived component state.
import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { FeatherArchive, FeatherLock, FeatherPlus, FeatherRotateCcw } from "@subframe/core";
import type { EntryRow, VaultDetailVM } from "@hivegrid/view-models";
import { PAGE_HEADER_ICON_CLASS, PageBody, PageHeader, PageShell } from "../shared/PageShell";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
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 { EmptyState } from "~/ui/components/EmptyState";
import { Select } from "~/ui/components/Select";
import { Tabs } from "~/ui/components/Tabs";
import { Tag_Label } from "~/ui/components/Tag_Label";
import { TextInput } from "~/ui/components/TextInput";
export type VaultSecretField = "username" | "password" | "notes";
export type VaultAccessLevel = "read" | "write" | "admin";
type EntryDraft = {
entryId?: string;
title: string;
url: string;
username: string;
password: string;
notes: string;
};
export type HrVaultDetailActions = {
onReveal: (entryId: string, field: VaultSecretField) => Promise<string | null>;
onCopy: (entryId: string, field: VaultSecretField) => Promise<string | null>;
onCreateEntry: (input: Omit<EntryDraft, "entryId">) => void;
onUpdateEntry: (input: EntryDraft & { entryId: string }) => void;
onArchiveEntry: (entryId: string) => void;
onRestoreEntry: (entryId: string) => void;
onGrantAccess: (input: { targetUserId: string; permissionLevel: VaultAccessLevel }) => void;
onRevokeAccess: (targetUserId: string) => void;
onExport: () => Promise<boolean>;
};
export type HrVaultDetailPageProps = {
vm: VaultDetailVM;
submitting: boolean;
actionFeedback?: { status: "success" | "error"; messageKey: string } | null;
actions: HrVaultDetailActions;
};
function SecretField({
entryId,
field,
labelKey,
autoClearMs,
onReveal,
onCopy,
}: {
entryId: string;
field: VaultSecretField;
labelKey: string;
autoClearMs: number;
onReveal: HrVaultDetailActions["onReveal"];
onCopy: HrVaultDetailActions["onCopy"];
}) {
const { t } = useTranslation();
const [value, setValue] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const [copied, setCopied] = useState(false);
const [error, setError] = useState(false);
const revealTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const clipboardTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
function hide() {
setValue(null);
if (revealTimer.current) clearTimeout(revealTimer.current);
revealTimer.current = null;
}
useEffect(() => {
const onVisibilityChange = () => {
if (document.visibilityState === "hidden") hide();
};
document.addEventListener("visibilitychange", onVisibilityChange);
return () => {
document.removeEventListener("visibilitychange", onVisibilityChange);
if (revealTimer.current) clearTimeout(revealTimer.current);
if (clipboardTimer.current) clearTimeout(clipboardTimer.current);
};
}, []);
async function reveal() {
setLoading(true);
setError(false);
try {
const revealed = await onReveal(entryId, field);
if (revealed == null) {
setError(true);
return;
}
setValue(revealed);
if (revealTimer.current) clearTimeout(revealTimer.current);
revealTimer.current = setTimeout(hide, autoClearMs);
} finally {
setLoading(false);
}
}
async function copy() {
setLoading(true);
setError(false);
try {
const copyValue = await onCopy(entryId, field);
if (copyValue == null) {
setError(true);
return;
}
if (!navigator.clipboard) {
setError(true);
return;
}
try {
await navigator.clipboard.writeText(copyValue);
} catch {
setError(true);
return;
}
setCopied(true);
if (clipboardTimer.current) clearTimeout(clipboardTimer.current);
clipboardTimer.current = setTimeout(() => {
void navigator.clipboard?.writeText("").catch(() => {});
setCopied(false);
}, autoClearMs);
} finally {
setLoading(false);
}
}
return (
<div className="border-border-default grid w-full gap-3 rounded-md border p-3 sm:grid-cols-[8rem_minmax(0,1fr)_auto]" data-ui-id={`ui.hr.vault.field.${field}`}>
<span className="text-body-small-medium-150 text-text-neutral-secondary">{t(labelKey)}</span>
<span className="text-body-default-regular-0 text-text-neutral-primary min-w-0 break-all font-mono" data-ui-id={value == null ? undefined : "ui.hr.vault.revealed"}>
{value ?? t("hr.passwordSafe.detail.concealed")}
</span>
<div className="flex flex-wrap justify-end gap-2" data-ui-id="ui.hr.vault.fieldActions">
{value == null ? (
<Button variant="tertiary" size="small" loading={loading} onClick={reveal} aria-label={`${t(labelKey)}: ${t("hr.passwordSafe.detail.reveal")}`} data-ui-id="ui.hr.vault.reveal">
{t("hr.passwordSafe.detail.reveal")}
</Button>
) : (
<Button variant="tertiary" size="small" onClick={hide} aria-label={`${t(labelKey)}: ${t("hr.passwordSafe.detail.hide")}`}>
{t("hr.passwordSafe.detail.hide")}
</Button>
)}
<Button variant="tertiary" size="small" loading={loading} onClick={copy} aria-label={`${t(labelKey)}: ${t("hr.passwordSafe.detail.copy")}`} data-ui-id="ui.hr.vault.copy">
{t("hr.passwordSafe.detail.copy")}
</Button>
</div>
<span className="text-body-small-regular-0 text-text-feedback-warning sm:col-start-2" aria-live="polite">
{error
? t("hr.passwordSafe.detail.secretActionFailed")
: copied
? t("hr.passwordSafe.detail.copyCleared")
: value != null
? t("hr.passwordSafe.detail.revealExpires")
: ""}
</span>
</div>
);
}
function EntryCard({
entry,
autoClearMs,
canWrite,
submitting,
actions,
onEdit,
}: {
entry: EntryRow;
autoClearMs: number;
canWrite: boolean;
submitting: boolean;
actions: HrVaultDetailActions;
onEdit: (entry: EntryRow) => void;
}) {
const { t } = useTranslation();
return (
<Card data-row-id={entry.id}>
<div className="flex w-full flex-wrap items-start justify-between gap-4">
<div className="flex min-w-0 flex-col gap-2">
<span className="text-body-default-medium-0 text-text-neutral-primary">{entry.title}</span>
{entry.url ? <a href={entry.url} target="_blank" rel="noreferrer" className="text-text-feedback-link-default break-all">{entry.url}</a> : null}
<div className="flex flex-wrap gap-1">
{entry.tags.map((tag) => <Tag_Label key={tag} tone="neutral-subtle" size="small" noAction>{tag}</Tag_Label>)}
</div>
</div>
{canWrite ? (
<div className="flex gap-2">
<Button variant="tertiary" size="small" onClick={() => onEdit(entry)}>{t("hr.passwordSafe.detail.editEntry")}</Button>
<Button
icon={<FeatherArchive />}
variant="tertiary"
size="small"
loading={submitting}
onClick={() => {
if (window.confirm(t("hr.passwordSafe.confirm.archiveEntry", { title: entry.title }))) actions.onArchiveEntry(entry.id);
}}
>
{t("hr.passwordSafe.detail.archiveEntry")}
</Button>
</div>
) : null}
</div>
<div className="flex w-full flex-col gap-2">
{entry.hasUsername ? <SecretField entryId={entry.id} field="username" labelKey="hr.passwordSafe.field.username" autoClearMs={autoClearMs} onReveal={actions.onReveal} onCopy={actions.onCopy} /> : null}
{entry.hasPassword ? <SecretField entryId={entry.id} field="password" labelKey="hr.passwordSafe.field.password" autoClearMs={autoClearMs} onReveal={actions.onReveal} onCopy={actions.onCopy} /> : null}
{entry.hasNotes ? <SecretField entryId={entry.id} field="notes" labelKey="hr.passwordSafe.field.notes" autoClearMs={autoClearMs} onReveal={actions.onReveal} onCopy={actions.onCopy} /> : null}
</div>
</Card>
);
}
export function HrVaultDetailPage({ vm, submitting, actionFeedback, actions }: HrVaultDetailPageProps) {
const { t } = useTranslation();
const [tab, setTab] = useState<"entries" | "access" | "activities">("entries");
const [entryOpen, setEntryOpen] = useState(false);
const [accessOpen, setAccessOpen] = useState(false);
const [exportOpen, setExportOpen] = useState(false);
const [exporting, setExporting] = useState(false);
const [exportStatus, setExportStatus] = useState<"success" | "error" | null>(null);
const [entry, setEntry] = useState<EntryDraft>({ title: "", url: "", username: "", password: "", notes: "" });
const [access, setAccess] = useState<{ targetUserId: string; permissionLevel: VaultAccessLevel }>({ targetUserId: "", permissionLevel: "read" });
if (vm.status !== "ready" || !vm.data) {
return (
<PageShell uiId="ui.hr.vault">
<PageHeader
icon={<FeatherLock className={PAGE_HEADER_ICON_CLASS} />}
title={t("hr.passwordSafe.title")}
subtitle={t("hr.passwordSafe.detail.subtitle")}
subtitleTone="secondary"
/>
<PageBody>
<EmptyState title={t(vm.status === "error" ? vm.error.messageKey : "hr.passwordSafe.loading")} body={t("hr.passwordSafe.loadingBody")} />
</PageBody>
</PageShell>
);
}
const data = vm.data;
const availableMembers = data.memberOptions.filter((member) => !member.hasAccess);
const tabItems = ["entries", "access", "activities"] as const;
function resetEntry() {
setEntry({ title: "", url: "", username: "", password: "", notes: "" });
}
function submitEntry() {
if (entry.entryId) actions.onUpdateEntry({ ...entry, entryId: entry.entryId });
else actions.onCreateEntry(entry);
setEntryOpen(false);
resetEntry();
}
return (
<PageShell uiId="ui.hr.vault">
<PageHeader
icon={<FeatherLock className={PAGE_HEADER_ICON_CLASS} />}
title={data.vaultName}
subtitle={t("hr.passwordSafe.detail.subtitle")}
subtitleTone="secondary"
actions={
<>
<BadgeFeedback farbe="subtle-neutral" size="small">{t(`hr.passwordSafe.access.${data.accessLevel}`)}</BadgeFeedback>
{data.canExport ? <Button variant="secondary" onClick={() => setExportOpen(true)}>{t("hr.passwordSafe.detail.export")}</Button> : null}
{data.canManageAccess ? <Button variant="secondary" onClick={() => setAccessOpen(true)}>{t("hr.passwordSafe.detail.manageAccess")}</Button> : null}
{data.canWrite ? <Button icon={<FeatherPlus />} onClick={() => { resetEntry(); setEntryOpen(true); }}>{t("hr.passwordSafe.detail.newEntry")}</Button> : null}
</>
}
/>
<PageBody>
{actionFeedback ? (
<Alert
variant={actionFeedback.status}
notDismissible
title={t(actionFeedback.messageKey)}
data-ui-id={`ui.hr.vault.feedback.${actionFeedback.status}`}
/>
) : null}
{exportStatus ? (
<Alert
variant={exportStatus}
notDismissible
title={t(`hr.passwordSafe.export.${exportStatus}`)}
data-ui-id={`ui.hr.vault.export.${exportStatus}`}
/>
) : null}
<Tabs role="tablist" aria-label={t("hr.passwordSafe.tabs.label")}>
{tabItems.map((item, index) => (
<Tabs.Item
key={item}
id={`password-safe-tab-${item}`}
active={tab === item}
role="tab"
tabIndex={tab === item ? 0 : -1}
aria-selected={tab === item}
aria-controls={`password-safe-panel-${item}`}
onClick={() => setTab(item)}
onKeyDown={(event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
setTab(item);
return;
}
if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") return;
event.preventDefault();
const offset = event.key === "ArrowRight" ? 1 : -1;
const nextIndex = (index + offset + tabItems.length) % tabItems.length;
setTab(tabItems[nextIndex]);
const tabs = event.currentTarget.parentElement?.querySelectorAll<HTMLElement>('[role="tab"]');
tabs?.[nextIndex]?.focus();
}}
>
{t(`hr.passwordSafe.tabs.${item}`)}
</Tabs.Item>
))}
</Tabs>
{tab === "entries" ? (
<section
id="password-safe-panel-entries"
className="flex w-full flex-col gap-4"
role="tabpanel"
aria-labelledby="password-safe-tab-entries"
data-ui-id="ui.hr.vault.entries"
>
{data.rows.length === 0 && data.archivedRows.length === 0 ? (
<EmptyState title={t(data.emptyHeadlineKey)} body={t(data.canWrite ? "hr.passwordSafe.entries.empty.writerBody" : data.emptyBodyKey)} />
) : null}
{data.rows.map((row) => (
<EntryCard
key={row.id}
entry={row}
autoClearMs={data.copyAutoClearMs}
canWrite={data.canWrite}
submitting={submitting}
actions={actions}
onEdit={(selected) => {
setEntry({ entryId: selected.id, title: selected.title, url: selected.url ?? "", username: "", password: "", notes: "" });
setEntryOpen(true);
}}
/>
))}
{data.canWrite && data.archivedRows.length > 0 ? (
<section className="bg-surface-neutral-secondary border-border-default flex flex-col gap-3 rounded-md border p-4">
<h2 className="text-heading-3 text-text-neutral-primary">{t("hr.passwordSafe.detail.archivedEntries")}</h2>
{data.archivedRows.map((row) => (
<Card key={row.id} data-archived-row-id={row.id}>
<div className="flex w-full items-center justify-between gap-3">
<span>{row.title}</span>
<Button icon={<FeatherRotateCcw />} variant="tertiary" size="small" onClick={() => actions.onRestoreEntry(row.id)} data-ui-id="ui.hr.vault.restoreEntry">
{t("hr.passwordSafe.detail.restoreEntry")}
</Button>
</div>
</Card>
))}
</section>
) : null}
</section>
) : null}
{tab === "access" ? (
<section
id="password-safe-panel-access"
className="flex w-full flex-col gap-3"
role="tabpanel"
aria-labelledby="password-safe-tab-access"
data-ui-id="ui.hr.vault.access"
>
{!data.canManageAccess ? (
<EmptyState title={t("hr.passwordSafe.accessDeniedTitle")} body={t("hr.passwordSafe.accessDeniedBody")} />
) : data.accessRows.length === 0 ? (
<EmptyState title={t("hr.passwordSafe.accessEmptyTitle")} body={t("hr.passwordSafe.accessEmptyBody")} />
) : (
data.accessRows.map((row) => (
<Card key={row.userId}>
<div className="flex w-full flex-wrap items-center justify-between gap-3">
<div className="flex min-w-0 flex-col">
<span className="text-body-default-medium-0 text-text-neutral-primary">{row.displayName}</span>
<span className="text-body-small-regular-0 text-text-neutral-secondary">{row.email}</span>
<span className="text-body-small-regular-0 text-text-neutral-tertiary">{row.roleNames.join(", ") || t("hr.passwordSafe.noRole")}</span>
</div>
<div className="flex flex-wrap items-center gap-2">
<Select
value={row.permissionLevel}
highContrastText
triggerAriaLabel={`${row.displayName}: ${t("hr.passwordSafe.field.permissionLevel")}`}
onValueChange={(permissionLevel: string) =>
actions.onGrantAccess({ targetUserId: row.userId, permissionLevel: permissionLevel as VaultAccessLevel })
}
>
<Select.Item value="read">{t("hr.passwordSafe.access.read")}</Select.Item>
<Select.Item value="write">{t("hr.passwordSafe.access.write")}</Select.Item>
<Select.Item value="admin">{t("hr.passwordSafe.access.admin")}</Select.Item>
</Select>
<Button
variant="destructive"
size="small"
onClick={() => {
if (window.confirm(t("hr.passwordSafe.confirm.revokeAccess", { name: row.displayName }))) actions.onRevokeAccess(row.userId);
}}
>
{t("hr.passwordSafe.revokeAccess")}
</Button>
</div>
</div>
</Card>
))
)}
</section>
) : null}
{tab === "activities" ? (
<section
id="password-safe-panel-activities"
className="flex w-full flex-col gap-3"
role="tabpanel"
aria-labelledby="password-safe-tab-activities"
data-ui-id="ui.hr.vault.activities"
>
{data.activityRows.length === 0 ? (
<EmptyState title={t("hr.passwordSafe.activity.emptyTitle")} body={t("hr.passwordSafe.activity.emptyBody")} />
) : (
data.activityRows.map((activity) => (
<Card key={activity.id}>
<div className="flex w-full flex-wrap items-center justify-between gap-2">
<span className="text-body-default-medium-0 text-text-neutral-primary">{t(activity.actionLabelKey)}</span>
<span className="text-body-small-regular-0 text-text-neutral-secondary">{activity.actorLabel} · {activity.createdAtLabel}</span>
</div>
</Card>
))
)}
</section>
) : null}
</PageBody>
<Dialog
open={entryOpen}
onOpenChange={setEntryOpen}
title={t(entry.entryId ? "hr.passwordSafe.detail.editEntry" : "hr.passwordSafe.detail.newEntry")}
>
<Dialog.Content className="w-full max-w-[560px] p-4" data-ui-id="ui.hr.vault.entryDialog">
<div className="flex flex-col gap-5 p-2">
<h2 className="text-heading-3 text-text-neutral-primary">{t(entry.entryId ? "hr.passwordSafe.detail.editEntry" : "hr.passwordSafe.detail.newEntry")}</h2>
{(["title", "url", "username", "password", "notes"] as const).map((field) => (
<TextInput key={field} label={t(`hr.passwordSafe.field.${field === "title" ? "entryTitle" : field}`)} showLabel fillContainer>
<TextInput.Input
type={field === "password" ? "password" : "text"}
value={entry[field]}
onChange={(event) => setEntry((current) => ({ ...current, [field]: event.target.value }))}
/>
</TextInput>
))}
{entry.entryId ? <p className="text-body-small-regular-0 text-text-neutral-secondary">{t("hr.passwordSafe.detail.editSecretsHint")}</p> : null}
<div className="flex justify-end gap-2">
<Button variant="neutral" onClick={() => setEntryOpen(false)}>{t("hr.action.cancel")}</Button>
<Button loading={submitting} disabled={!entry.title.trim()} onClick={submitEntry}>{t("hr.action.save")}</Button>
</div>
</div>
</Dialog.Content>
</Dialog>
<Dialog open={accessOpen} onOpenChange={setAccessOpen} title={t("hr.passwordSafe.detail.manageAccess")}>
<Dialog.Content className="w-full max-w-[560px] p-4" data-ui-id="ui.hr.vault.grantAccess">
<div className="flex flex-col gap-5 p-2">
<h2 className="text-heading-3 text-text-neutral-primary">{t("hr.passwordSafe.detail.manageAccess")}</h2>
<Select
label={t("hr.passwordSafe.field.targetUser")}
triggerAriaLabel={t("hr.passwordSafe.field.targetUser")}
highContrastText
showLabel
value={access.targetUserId}
onValueChange={(targetUserId: string) => setAccess((current) => ({ ...current, targetUserId }))}
>
{availableMembers.map((member) => (
<Select.Item key={member.userId} value={member.userId}>{member.displayName} · {member.email} · {member.roleNames.join(", ") || t("hr.passwordSafe.noRole")}</Select.Item>
))}
</Select>
<Select
label={t("hr.passwordSafe.field.permissionLevel")}
triggerAriaLabel={t("hr.passwordSafe.field.permissionLevel")}
highContrastText
showLabel
value={access.permissionLevel}
onValueChange={(permissionLevel: string) => setAccess((current) => ({ ...current, permissionLevel: permissionLevel as VaultAccessLevel }))}
>
<Select.Item value="read">{t("hr.passwordSafe.access.read")}</Select.Item>
<Select.Item value="write">{t("hr.passwordSafe.access.write")}</Select.Item>
<Select.Item value="admin">{t("hr.passwordSafe.access.admin")}</Select.Item>
</Select>
{availableMembers.length === 0 ? <p>{t("hr.passwordSafe.allMembersGranted")}</p> : null}
<div className="flex justify-end gap-2">
<Button variant="neutral" onClick={() => setAccessOpen(false)}>{t("hr.action.cancel")}</Button>
<Button
loading={submitting}
disabled={!access.targetUserId}
onClick={() => {
actions.onGrantAccess(access);
setAccessOpen(false);
setAccess({ targetUserId: "", permissionLevel: "read" });
}}
>
{t("hr.passwordSafe.detail.grantAccess.submit")}
</Button>
</div>
</div>
</Dialog.Content>
</Dialog>
<Dialog open={exportOpen} onOpenChange={setExportOpen} title={t("hr.passwordSafe.export.title")}>
<Dialog.Content className="w-full max-w-[520px] p-4" data-ui-id="ui.hr.vault.exportConfirm">
<div className="flex flex-col gap-5 p-2">
<h2 className="text-heading-3 text-text-neutral-primary">{t("hr.passwordSafe.export.title")}</h2>
<p className="text-body-default-regular-0 text-text-neutral-secondary">{t("hr.passwordSafe.export.body")}</p>
<div className="flex justify-end gap-2">
<Button variant="neutral" onClick={() => setExportOpen(false)}>{t("hr.action.cancel")}</Button>
<Button
variant="destructive"
loading={submitting || exporting}
onClick={async () => {
setExporting(true);
setExportStatus(null);
try {
const exported = await actions.onExport();
setExportStatus(exported ? "success" : "error");
if (exported) setExportOpen(false);
} finally {
setExporting(false);
}
}}
data-ui-id="ui.hr.vault.exportConfirm.submit"
>
{t("hr.passwordSafe.export.confirm")}
</Button>
</div>
</div>
</Dialog.Content>
</Dialog>
</PageShell>
);
}