"use client"; /** * Document detail on `ResponsiveSheet` (bottom sheet on phones, dialog on * desktop). Inline-class documents (PDF / browser-native images) preview * inline against the owner-scoped decrypt-and-serve route — skeleton first, * content on load, internal scroll only (`overscroll-contain`). Attachment- * class documents get NO fake preview: type glyph, filename, size, and a * prominent Download button. * * Metadata edits save on commit (title on Enter/blur, kind and filing date * on change, condition links on toggle — replace-set PATCH). Mutation * errors surface inline (`role="alert"`), never as a QueryErrorCard. * Delete soft-deletes with an Undo toast (restore endpoint); a restore * refusal maps `meta.reason` (`purged`, `duplicateExists`) to translated * copy. A Share action in the footer opens the clinician share-link create * flow (shared `ShareLinkCreateForm`) with this document pre-attached. */ import { useRecordCapabilities } from "@/hooks/use-record-capabilities"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { ArrowRight, Check, Download, FlaskConical, Pencil, Plus, Share2, Sparkles, Trash2, X, } from "lucide-react"; import Link from "next/link"; import { useEffect, useRef, useState } from "react"; import { toast } from "sonner"; import { useIllnessEpisodes } from "@/components/illness/use-illness"; import { useAuth } from "@/hooks/use-auth"; import { Button } from "@/components/ui/button"; import { DateField } from "@/components/ui/date-field"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Popover, PopoverContent, PopoverTrigger, } from "@/components/ui/popover"; import { ResponsiveSheet } from "@/components/ui/responsive-sheet"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { Skeleton } from "@/components/ui/skeleton"; import { apiDelete, ApiError, apiGet, apiPatch, apiPost, } from "@/lib/api/api-fetch"; import { encounterKindText } from "@/components/encounters/encounter-labels"; import { useFormatters, useTranslations } from "@/lib/i18n/context"; import type { EncounterKind } from "@/generated/prisma/client"; import { useCoachLaunch } from "@/lib/insights/coach-launch-context"; import { invalidateKeys, queryKeys } from "@/lib/query-keys"; import { createFencedBlobLoader, useFencedObjectUrl, } from "@/hooks/use-fenced-object-url"; import { cn } from "@/lib/utils"; import { INBOUND_DOCUMENT_KINDS, type DocumentSuggestionDto, type DocumentSummaryMode, type InboundDocumentDetailDto, type InboundDocumentKindValue, } from "@/lib/validations/inbound-documents"; import { DocumentAiSection } from "./document-ai-section"; import { DocumentEncounterSuggestion } from "./document-encounter-suggestion"; import { DocumentSummaryBlock } from "./document-summary-block"; import type { DocumentAiTarget } from "./document-ai-transport"; import { DocumentShareSheet } from "./document-share-sheet"; import { DOCUMENT_KIND_ICONS } from "./document-kind-meta"; import { useIndexDocument } from "./use-content-index"; import { documentAiErrorKey, useDocumentAiCapability, useDocumentsAutoAiRead, useDocumentSummary, useSuggestDetails, } from "./use-document-assist"; import { formatBytes } from "./vault-utils"; type PatchInput = { title?: string | null; kind?: InboundDocumentKindValue; documentDate?: string | null; episodeIds?: string[]; encounterIds?: string[]; }; /** * Download the stored original. * * v1.37.0 — a real button, not an anchor wearing `aria-disabled`. * * Two things were wrong with the anchor. `aria-disabled` tells a screen reader * the control is unavailable and stops nothing: `href="#"` is still activated * by a click and by Enter, so a person got a jump to the top of the page * instead of a file. And it ignored the failure flag entirely, so a document * whose original could not be fetched left a control that looked fine and * silently did nothing, for good. * * It also fetches at CLICK time unless the bytes are already in hand. The * sheet loads the original eagerly only for documents it is going to render * inline; for everything else — a large scan, a download-only format — nothing * is fetched or decrypted until somebody asks for it, which is what the plain * `href` used to cost and what the first fix accidentally gave up. */ function DocumentDownloadButton({ documentId, filename, readyUrl, unavailable, slot, ...buttonProps }: { documentId: string; filename: string | null; /** Already-fetched bytes to reuse (the inline preview's), or null. */ readyUrl: string | null; /** A prior fetch of these bytes failed for good. */ unavailable: boolean; slot: string; } & React.ComponentProps) { const { t } = useTranslations(); const [pending, setPending] = useState(false); const [failed, setFailed] = useState(false); const loaderRef = useRef | null>( null, ); useEffect(() => () => loaderRef.current?.dispose(), []); const save = (url: string) => { const anchor = document.createElement("a"); anchor.href = url; anchor.download = filename ?? "document"; anchor.click(); }; const onClick = async () => { if (readyUrl) { save(readyUrl); return; } setPending(true); setFailed(false); // One loader for the lifetime of the button: loading again revokes the // previous object URL, and unmounting revokes the live one. Without that a // decrypted health document stays in the tab's memory until it closes. loaderRef.current ??= createFencedBlobLoader(); const result = await loaderRef.current.load( `/api/documents/inbound/${documentId}/original`, ); setPending(false); if (result.kind === "loaded") save(result.url); else if (result.kind === "failed") setFailed(true); }; const blocked = unavailable || failed; return ( ); } /** Inline preview for Class A documents; skeleton until the blob paints. */ function InlinePreview({ src, failed, mimeType, title, }: { /** * v1.37.0 — the object URL, fetched ONCE by the sheet and handed down. * * The bytes come through the app transport because it carries the * record-session assertion and a browser-issued `src="/api/…"` cannot. What * changed since: this component used to fetch them itself while the sheet * fetched the SAME original again for the download link, so opening a * document decrypted and held two copies of it — and a large scan is a large * copy. One loader now, lifted to the sheet. */ src: string | null; failed: boolean; mimeType: string; title: string; }) { const [loaded, setLoaded] = useState(false); const isPdf = mimeType === "application/pdf"; // Chromium's PDF viewer grabs focus while it initialises — BEFORE the // frame's `load` event — stranding keyboard events inside the embedded // document, so Escape stops closing the sheet the moment a PDF preview // opens. While the guard window is open (armed at mount, extended at // load, ended early by a deliberate pointer interaction with the // preview), any focus landing on the frame bounces straight back to the // dialog container; a user who clicks into the PDF is left alone. const frameRef = useRef(null); const stealGuardUntil = useRef(0); const reclaimFocus = (frame: HTMLIFrameElement) => { if ( Date.now() < stealGuardUntil.current && document.activeElement === frame ) { frame.closest('[role="dialog"]')?.focus(); } }; useEffect(() => { // Arm at mount, then run a frame-by-frame sweep for the steal variants // that never dispatch a focus event on the frame element. // Self-terminates with the guard. stealGuardUntil.current = Date.now() + 3_000; let raf = 0; const sweep = () => { const frame = frameRef.current; if (!frame || Date.now() >= stealGuardUntil.current) return; if (document.activeElement === frame) { frame.closest('[role="dialog"]')?.focus(); } raf = requestAnimationFrame(sweep); }; raf = requestAnimationFrame(sweep); return () => cancelAnimationFrame(raf); }, []); return (
{failed ? ( // The preview could not be fetched — refused, offline, or still // rendering server-side. A permanent skeleton would read as "loading // forever"; the sheet's own metadata and the download control below // still work.

{title}

) : !loaded || src === null ? ( ) : null} {src === null || failed ? null : isPdf ? ( // No `sandbox` attribute by design: Chromium force-downloads PDFs // in sandboxed frames instead of rendering them. The serve // response itself carries `default-src 'none'` + // `frame-ancestors 'self'` + true Content-Type + nosniff, and the // upload policy denies every format whose inline render could // execute script.