SPB Git

Repository Public

ItemBody.tsx 6.2 KB 95 lines tsx

1// Read-only rendering of an item's content. Used by the detail pane, received shares and the public share page.2import { useEffect, useMemo, useState } from "react";3import { type FieldKind, type Item, parseOrigin, parseTotp, TEMPLATES, totp, type TotpParams } from "../../../../packages/protocol/src/index.ts";4import { copyText } from "../state.ts";5import { Badge, CopyValue, Icon, IconBtn, SecretValue } from "./common.tsx";6import { MULTILINE_SECRETS, SENSITIVE_KEYS } from "./itemmeta.ts";78/** Live TOTP code with a circular countdown. The seed is never rendered. */9export function TotpRow({ value, label = "One-time code" }: { value: string; label?: string }) {10  const params = useMemo<TotpParams | null>(() => { try { return parseTotp(value); } catch { return null; } }, [value]);11  const [state, setState] = useState<{ code: string; remaining: number } | null>(null);12  useEffect(() => {13    if (!params) return;14    let live = true;15    const tick = () => totp(params).then((s) => { if (live) setState(s); }, () => { if (live) setState(null); });16    void tick();17    const t = setInterval(tick, 1000);18    return () => { live = false; clearInterval(t); };19  }, [params]);20  if (!params) return <div className="value-row"><div className="value"><Badge kind="danger" icon="alert">Invalid one-time code setup</Badge></div></div>;21  const R = 9, C = 2 * Math.PI * R, frac = state ? state.remaining / params.period : 1, low = !!state && state.remaining <= 5;22  const code = state?.code ?? "";23  const half = Math.ceil(code.length / 2);24  return (25    <div className="value-row">26      <div className="value totp" data-testid="totp">27        <span className={`totp-code mono${low ? " low" : ""}`} data-testid="totp-code" aria-label={label}>{code ? <><span>{code.slice(0, half)}</span><span>{code.slice(half)}</span></> : "······"}</span>28        <span className={`totp-ring${low ? " low" : ""}`} role="timer" aria-label={state ? `${state.remaining} seconds left` : "loading"}>29          <svg viewBox="0 0 24 24" width="26" height="26" aria-hidden="true">30            <circle className="ring-bg" cx="12" cy="12" r={R} fill="none" strokeWidth="2.500" />31            <circle className="ring-fg" cx="12" cy="12" r={R} fill="none" strokeWidth="2.500" strokeLinecap="round" strokeDasharray={C} strokeDashoffset={C * (1 - frac)} transform="rotate(-90 12 12)" />32          </svg>33          <span className="totp-sec mono">{state?.remaining ?? ""}</span>34        </span>35      </div>36      <div className="value-actions"><IconBtn icon="copy" label={`Copy ${label}`} onClick={() => code && copyText(code, label)} /></div>37    </div>38  );39}4041export function UrlRow({ url, match }: { url: string; match?: string }) {42  const o = parseOrigin(url);43  const insecure = /^http:\/\//i.test(url.trim());44  const href = o ? (/^[a-z][a-z0-9+.-]*:\/\//i.test(url.trim()) ? url.trim() : `https://${url.trim()}`) : null;45  return (46    <div className="value-row">47      <div className="value url">48        <span className="url-host" title={url}>{o ? o.display : url}</span>49        {insecure && <Badge kind="danger" icon="alert">insecure (http)</Badge>}50        {o?.mixedScript && <Badge kind="danger" icon="alert">mixed scripts</Badge>}51        {!o && <Badge kind="brass">not a web address</Badge>}52        {match && match !== "domain" && <Badge>{match === "never" ? "never fill" : `match: ${match}`}</Badge>}53      </div>54      <div className="value-actions">55        {href && <a className="icon-btn" href={href} target="_blank" rel="noopener noreferrer" aria-label={`Open ${o!.display} in a new tab`} title="Open in a new tab"><Icon name="external" /></a>}56        <IconBtn icon="copy" label="Copy address" onClick={() => copyText(url, "Address", false)} />57      </div>58    </div>59  );60}6162function FieldValue({ kind, value, label, fieldKey }: { kind: FieldKind; value: string; label: string; fieldKey?: string }) {63  if (kind === "totp") return <TotpRow value={value} label={label} />;64  if (kind === "secret" || (fieldKey && SENSITIVE_KEYS.has(fieldKey))) return <SecretValue value={value} label={label} multiline={(fieldKey && MULTILINE_SECRETS.has(fieldKey)) || value.includes("\n")} />;65  if (kind === "url") return <UrlRow url={value} />;66  if (kind === "multiline") return <CopyValue value={value} label={label} multiline mono />;67  if (kind === "date") { const t = Date.parse(value); return <CopyValue value={value} label={label}>{Number.isNaN(t) ? value : new Date(t).toLocaleDateString(undefined, { year: "numeric", month: "long", day: "numeric", timeZone: "UTC" })}</CopyValue>; }68  return <CopyValue value={value} label={label} />;69}7071export function Row({ label, children }: { label: string; children: React.ReactNode }) {72  return <div className="detail-row"><div className="detail-label">{label}</div>{children}</div>;73}7475export function ItemBody({ item }: { item: Item }) {76  const tpl = TEMPLATES[item.type];77  const known = new Set(tpl.fields.map((f) => f.key));78  const extra = Object.keys(item.fields).filter((k) => !known.has(k) && item.fields[k]);79  const fields = tpl.fields.filter((f) => item.fields[f.key]);80  return (81    <div className="item-body">82      {(fields.length > 0 || extra.length > 0) && (83        <div className="detail-group">84          {fields.map((f) => <Row key={f.key} label={f.label}><FieldValue kind={f.kind} value={item.fields[f.key]!} label={f.label} fieldKey={f.key} /></Row>)}85          {extra.map((k) => <Row key={k} label={k}><FieldValue kind="secret" value={item.fields[k]!} label={k} /></Row>)}86        </div>87      )}88      {item.urls.length > 0 && <div className="detail-group">{item.urls.map((u, i) => <Row key={i} label={i === 0 ? "Website" : `Website ${i + 1}`}><UrlRow url={u.url} match={u.match} /></Row>)}</div>}89      {item.custom.length > 0 && <div className="detail-group">{item.custom.map((c, i) => <Row key={i} label={c.label || "Custom field"}><FieldValue kind={c.kind} value={c.value} label={c.label || "Custom field"} /></Row>)}</div>}90      {item.notes && <div className="detail-group"><Row label="Notes"><div className="value-row"><div className="value notes">{item.notes}</div></div></Row></div>}91      {item.tags.length > 0 && <div className="tags" aria-label="Tags">{item.tags.map((t) => <span key={t} className="chip"><Icon name="tag" size={12} />{t}</span>)}</div>}92    </div>93  );94}95
Files main
Menu

Theme