SPB Git

Repository Public

ItemDetail.tsx 15.6 KB 235 lines tsx

1// Right pane: one item with its actions, attachments, password history and revision history.2import { useEffect, useRef, useState } from "react";3import { type AttachmentRef, type Item, TEMPLATES } from "../../../../packages/protocol/src/index.ts";4import type { ItemView, VaultView } from "../core/engine.ts";5import { bytesLabel, confirmAction, dateTime, downloadBlob, engine, relTime, reportError, toast } from "../state.ts";6import { Badge, Btn, Callout, Dialog, ErrorText, Field, Icon, IconBtn, Monogram, SecretValue, useAction } from "./common.tsx";7import { ItemBody, Row } from "./ItemBody.tsx";8import { canWrite, KIND_LABEL, subtitle, TYPE_ICON } from "./itemmeta.ts";9import { ShareDialog } from "./Relay.tsx";1011const MAX_ATTACHMENT = 100 * 1024 * 1024;1213export function ItemDetail({ view, vaults, onEdit, onBack, onOpen, onClosed }: {14  view: ItemView; vaults: VaultView[]; onEdit: () => void; onBack: () => void; onOpen: (key: string) => void; onClosed: () => void;15}) {16  const { item, vaultId, id } = view;17  const vault = vaults.find((v) => v.vaultId === vaultId);18  const writable = canWrite(vault), trashed = !!item.trashedAt;19  const [dialog, setDialog] = useState<"share" | "move" | null>(null);20  const act = useAction();21  const headRef = useRef<HTMLHeadingElement>(null);22  useEffect(() => { setDialog(null); act.setError(""); }, [vaultId, id]);2324  const run = (fn: () => Promise<unknown>, done?: string) => act.run(async () => { await fn(); if (done) toast(done, "ok"); });25  const favorite = () => run(() => engine.saveItem(vaultId, id, { ...item, favorite: !item.favorite }));26  const trash = () => run(() => engine.trashItem(vaultId, id), "Moved to trash");27  const restore = () => run(() => engine.restoreItem(vaultId, id), "Restored");28  const remove = async () => {29    if (!(await confirmAction({ title: "Delete permanently?", danger: true, confirmLabel: "Delete permanently", body: [`“${item.title || "Untitled"}” will be replaced by an authenticated tombstone on every device.`, "This cannot be undone from the app. Earlier revisions stay on the server only for the vault's retention period."] }))) return;30    await run(async () => { await engine.deleteItem(vaultId, id); onClosed(); }, "Deleted");31  };3233  return (34    <article className="detail" aria-labelledby="detail-title" data-testid="item-detail">35      <header className="detail-head">36        <IconBtn icon="back" label="Back to list" className="only-mobile" onClick={onBack} />37        <Monogram title={item.title || "?"} icon={item.type === "login" ? undefined : TYPE_ICON[item.type]} size={48} />38        <div className="detail-title">39          <h1 id="detail-title" ref={headRef} tabIndex={-1} data-testid="detail-title">{item.title || "Untitled"}</h1>40          <p className="muted">{TEMPLATES[item.type].label}{subtitle(item) !== TEMPLATES[item.type].label ? ` · ${subtitle(item)}` : ""}</p>41        </div>42        <div className="detail-actions">43          {!trashed && writable && <IconBtn icon="star" fill={item.favorite} label={item.favorite ? "Remove from favorites" : "Add to favorites"} aria-pressed={item.favorite} className={item.favorite ? "fav-on" : ""} onClick={favorite} disabled={act.busy} data-testid="favorite" />}44          {!trashed && writable && <Btn icon="edit" variant="primary" onClick={onEdit} data-testid="edit">Edit</Btn>}45        </div>46      </header>4748      {view.pending && <p className="pending-note"><span className="pending-dot" aria-hidden="true" /> Saved on this device — waiting to sync.</p>}49      {trashed && <Callout kind="warn" title="In the trash"><p>Moved to trash {relTime(item.trashedAt)}. Restore it to use it again, or delete it permanently.</p></Callout>}50      {item.conflictOf && !trashed && <ConflictBanner view={view} onOpen={onOpen} onClosed={onClosed} />}51      {!writable && <Callout kind="info"><p>This vault is read-only for you.</p></Callout>}52      <ErrorText text={act.error} />5354      <ItemBody item={item} />5556      {!trashed && <Attachments view={view} writable={writable} />}5758      {item.passwordHistory.length > 0 && (59        <details className="disclosure">60          <summary><Icon name="chevron" size={15} /> Password history <span className="muted">({item.passwordHistory.length})</span></summary>61          <div className="detail-group">62            {[...item.passwordHistory].reverse().map((h, i) => <Row key={i} label={`Replaced ${dateTime(h.at)}`}><SecretValue value={h.value} label="Previous password" /></Row>)}63          </div>64        </details>65      )}66      <History view={view} writable={writable && !trashed} />6768      <dl className="meta">69        <div><dt>Vault</dt><dd>{vault?.meta.name ?? "—"} {vault && <Badge>{KIND_LABEL[vault.meta.kind] ?? vault.meta.kind}</Badge>}</dd></div>70        <div><dt>Updated</dt><dd>{dateTime(item.updatedAt)}</dd></div>71        <div><dt>Created</dt><dd>{dateTime(item.createdAt)}</dd></div>72        {item.expiresAt && <div><dt>Expires</dt><dd><Expiry iso={item.expiresAt} /></dd></div>}73        {item.rotateEveryDays && <div><dt>Rotation</dt><dd><Rotation item={item} /></dd></div>}74      </dl>7576      <footer className="detail-foot">77        {trashed ? (78          <>{writable && <Btn icon="restore" variant="primary" onClick={restore} busy={act.busy} data-testid="restore">Restore</Btn>}{writable && <Btn icon="trash" variant="danger" onClick={remove} disabled={act.busy} data-testid="delete-forever">Delete permanently</Btn>}</>79        ) : (80          <>81            <Btn icon="share" onClick={() => setDialog("share")} data-testid="share">Share…</Btn>82            {writable && vaults.filter(canWrite).length > 1 && <Btn icon="move" onClick={() => setDialog("move")} data-testid="move">Move to vault</Btn>}83            {writable && <Btn icon="trash" variant="ghost" className="danger-text" onClick={trash} disabled={act.busy} data-testid="trash">Move to trash</Btn>}84          </>85        )}86      </footer>8788      {dialog === "share" && <ShareDialog item={item} onClose={() => setDialog(null)} />}89      {dialog === "move" && <MoveDialog view={view} vaults={vaults} onClose={() => setDialog(null)} onMoved={onOpen} />}90    </article>91  );92}9394function Expiry({ iso }: { iso: string }) {95  const t = Date.parse(iso), days = Math.ceil((t - Date.now()) / 86400_000);96  if (Number.isNaN(t)) return <>{iso}</>;97  const date = new Date(t).toLocaleDateString(undefined, { year: "numeric", month: "short", day: "numeric", timeZone: "UTC" });98  return <>{date} {days < 0 ? <Badge kind="danger" icon="alert">expired</Badge> : days <= 30 ? <Badge kind="brass" icon="clock">in {days} day{days === 1 ? "" : "s"}</Badge> : null}</>;99}100function Rotation({ item }: { item: Item }) {101  const last = item.passwordHistory.length ? Date.parse(item.passwordHistory[item.passwordHistory.length - 1]!.at) : Date.parse(item.createdAt);102  const due = last + item.rotateEveryDays! * 86400_000;103  return <>Every {item.rotateEveryDays} days · next {new Date(due).toLocaleDateString(undefined, { year: "numeric", month: "short", day: "numeric" })} {due < Date.now() && <Badge kind="brass" icon="alert">due</Badge>}</>;104}105106function ConflictBanner({ view, onOpen, onClosed }: { view: ItemView; onOpen: (key: string) => void; onClosed: () => void }) {107  const { item, vaultId, id } = view, original = engine.get(vaultId, item.conflictOf!);108  const act = useAction();109  const clean = (): Item => ({ ...item, title: item.title.replace(/ \(conflict copy\)$/, ""), conflictOf: undefined });110  const keep = () => act.run(async () => {111    if (original) { await engine.saveItem(vaultId, original.id, { ...clean(), attachments: original.item.attachments, trashedAt: undefined }); await engine.deleteItem(vaultId, id); onOpen(`${vaultId}/${original.id}`); }112    else await engine.saveItem(vaultId, id, clean());113    toast("Kept this version", "ok");114  });115  const discard = () => act.run(async () => { await engine.deleteItem(vaultId, id); toast("Conflict copy discarded"); if (original) onOpen(`${vaultId}/${original.id}`); else onClosed(); });116  return (117    <Callout kind="warn" title="Conflict copy">118      <p>This item was edited on two devices at the same time. The version that reached the server first stayed in place; the edit made on this device was kept here so that nothing is lost.</p>119      <ErrorText text={act.error} />120      <div className="row wrap">121        {original ? <Btn small onClick={() => onOpen(`${vaultId}/${original.id}`)}>Open the original</Btn> : <span className="muted">The original no longer exists.</span>}122        <Btn small variant="primary" onClick={keep} busy={act.busy} data-testid="conflict-keep">Keep this one</Btn>123        <Btn small variant="danger" onClick={discard} disabled={act.busy} data-testid="conflict-discard">Discard copy</Btn>124      </div>125    </Callout>126  );127}128129function Attachments({ view, writable }: { view: ItemView; writable: boolean }) {130  const { item, vaultId, id } = view;131  const input = useRef<HTMLInputElement>(null);132  const [progress, setProgress] = useState<{ name: string; done: number; total: number } | null>(null);133  const [busyId, setBusyId] = useState("");134  const act = useAction();135  if (!writable && item.attachments.length === 0) return null;136137  const upload = (file: File) => act.run(async () => {138    if (file.size > MAX_ATTACHMENT) throw new Error("This file is larger than 100 MB.");139    setProgress({ name: file.name, done: 0, total: 1 });140    try {141      const data = new Uint8Array(await file.arrayBuffer());142      const ref = await engine.upload(vaultId, file.name.slice(0, 200), file.type || "application/octet-stream", data, (done, total) => setProgress({ name: file.name, done, total }));143      const current = engine.get(vaultId, id)?.item ?? item;144      await engine.saveItem(vaultId, id, { ...current, attachments: [...current.attachments, ref] });145      toast("Attachment encrypted and added", "ok");146    } finally { setProgress(null); if (input.current) input.current.value = ""; }147  });148  const download = async (ref: AttachmentRef) => {149    setBusyId(ref.id);150    try { downloadBlob(await engine.download(ref) as unknown as BlobPart, ref.name || "attachment", "application/octet-stream"); }151    catch (e) { reportError(e); }152    finally { setBusyId(""); }153  };154  const remove = async (ref: AttachmentRef) => {155    if (!(await confirmAction({ title: "Remove attachment?", danger: true, confirmLabel: "Remove", body: `“${ref.name}” will be detached from this item.` }))) return;156    await act.run(async () => { const current = engine.get(vaultId, id)?.item ?? item; await engine.saveItem(vaultId, id, { ...current, attachments: current.attachments.filter((a) => a.id !== ref.id) }); });157  };158  return (159    <section className="detail-section" aria-label="Attachments">160      <div className="section-head"><h2>Attachments</h2>161        {writable && <><input ref={input} type="file" className="sr-only" tabIndex={-1} aria-hidden="true" data-testid="attach-input" onChange={(e) => { const f = e.target.files?.[0]; if (f) void upload(f); }} /><Btn small icon="upload" onClick={() => input.current?.click()} busy={act.busy}>Attach file</Btn></>}162      </div>163      <ErrorText text={act.error} />164      {progress && (165        <div className="progress-row" role="status"><span className="ellipsis">Encrypting and uploading {progress.name}</span><progress max={progress.total} value={progress.done} aria-label="Upload progress" /></div>166      )}167      {item.attachments.length === 0 && !progress ? <p className="muted small">Files are encrypted in this browser in 1 MiB chunks before upload. The server sees sizes only.</p> : (168        <ul className="attachments" data-testid="attachments">169          {item.attachments.map((a) => (170            <li key={a.id}>171              <Icon name="doc" /><span className="att-name ellipsis">{a.name || "attachment"}</span><span className="muted">{bytesLabel(a.size)}</span>172              <Btn small icon="download" onClick={() => download(a)} busy={busyId === a.id} data-testid="attach-download">Download</Btn>173              {writable && <IconBtn icon="x" label={`Remove ${a.name}`} onClick={() => remove(a)} />}174            </li>175          ))}176        </ul>177      )}178    </section>179  );180}181182function History({ view, writable }: { view: ItemView; writable: boolean }) {183  const { vaultId, id } = view;184  const [open, setOpen] = useState(false);185  const [rows, setRows] = useState<Awaited<ReturnType<typeof engine.history>> | null>(null);186  const [preview, setPreview] = useState<{ rev: number; at: string; item: Item } | null>(null);187  const act = useAction();188  useEffect(() => { setOpen(false); setRows(null); setPreview(null); }, [vaultId, id]);189  useEffect(() => { if (open) void act.run(async () => { setRows(await engine.history(vaultId, id)); }); }, [open, view.rev]);190  const restore = (h: { rev: number; item: Item }) => act.run(async () => {191    await engine.saveItem(vaultId, id, { ...h.item, trashedAt: undefined, conflictOf: undefined, attachments: view.item.attachments });192    setPreview(null); toast(`Revision ${h.rev} restored as a new revision`, "ok");193  });194  return (195    <details className="disclosure" open={open} onToggle={(e) => setOpen((e.target as HTMLDetailsElement).open)} data-testid="history">196      <summary><Icon name="chevron" size={15} /> Item history <span className="muted">(revision {view.rev})</span></summary>197      <ErrorText text={act.error} />198      {open && !rows && act.busy && <p className="muted small">Loading and decrypting earlier revisions…</p>}199      {rows && rows.length === 0 && <p className="muted small">No earlier revision is kept for this item.</p>}200      {rows && rows.length > 0 && (201        <ul className="rows compact">202          {rows.map((h) => (203            <li key={h.rev} className="row-card">204              <div className="row-main"><strong>Revision {h.rev}{h.rev === view.rev ? " (current)" : ""}</strong><span className="muted">{dateTime(h.at)} · {h.item.title || "Untitled"}{h.item.trashedAt ? " · in trash" : ""}</span></div>205              {h.rev !== view.rev && <Btn small onClick={() => setPreview(h)}>View</Btn>}206            </li>207          ))}208        </ul>209      )}210      {preview && (211        <Dialog title={`Revision ${preview.rev} — ${dateTime(preview.at)}`} wide onClose={() => setPreview(null)}212          footer={<><Btn onClick={() => setPreview(null)}>Close</Btn>{writable && <Btn variant="primary" icon="restore" onClick={() => restore(preview)} busy={act.busy} data-testid="history-restore">Restore this version</Btn>}</>}>213          <div className="stack"><h3 className="serif">{preview.item.title || "Untitled"}</h3><ItemBody item={preview.item} /></div>214        </Dialog>215      )}216    </details>217  );218}219220function MoveDialog({ view, vaults, onClose, onMoved }: { view: ItemView; vaults: VaultView[]; onClose: () => void; onMoved: (key: string) => void }) {221  const targets = vaults.filter((v) => canWrite(v) && v.vaultId !== view.vaultId);222  const [to, setTo] = useState(targets[0]?.vaultId ?? "");223  const act = useAction();224  const move = () => act.run(async () => { const id = await engine.moveItem(view.vaultId, view.id, to); toast("Moved", "ok"); onClose(); onMoved(`${to}/${id}`); });225  return (226    <Dialog title="Move to another vault" onClose={onClose} footer={<><Btn onClick={onClose}>Cancel</Btn><Btn variant="primary" onClick={move} busy={act.busy} disabled={!to} data-testid="move-go">Move</Btn></>}>227      <div className="stack">228        <p className="muted">The item is re-encrypted under the target vault's key and removed from this vault. Everyone with access to the target vault will be able to read it. Its revision history stays with the old vault.</p>229        <Field label="Target vault"><select className="input" value={to} onChange={(e) => setTo(e.target.value)} data-autofocus>{targets.map((v) => <option key={v.vaultId} value={v.vaultId}>{v.meta.name}</option>)}</select></Field>230        <ErrorText text={act.error} />231      </div>232    </Dialog>233  );234}235
Files main
Menu

Theme