Staff report: inline lightbox for image/PDF attachments

Adds a /api/staff/file proxy that re-streams Civi attachments with
Content-Disposition: inline so a native <dialog> lightbox can preview
images and PDFs in place. Office docs keep their plain download link
and gain a "View in Google Docs" secondary link (uses the Civi-signed
URL so Google can fetch without our staff key).

Also threads mime through /api/staff/report (Attachment.get mime_type)
so the dispatcher picks the right affordance without relying solely on
filename inference.
This commit is contained in:
Joel Brock
2026-06-15 11:56:45 -07:00
parent 5203dabeac
commit 6850ff9dee
8 changed files with 648 additions and 29 deletions
+31 -22
View File
@@ -19,6 +19,7 @@ import {
computeDateRange,
} from "./report/FieldHistory";
import { LoadingState, EmptyState, ErrorState } from "./report/ReportStates";
import { FileLink } from "./report/FileLink";
interface StaffReportViewProps {
org: number;
@@ -207,6 +208,8 @@ export function StaffReportView({
section={section}
options={data.options}
civiBaseUrl={civiBaseUrl}
org={org}
authKey={authKey}
/>
))}
@@ -271,10 +274,14 @@ function StaffSection({
section,
options,
civiBaseUrl,
org,
authKey,
}: {
section: StaffReportSection;
options: Record<number, SelectOption[]>;
civiBaseUrl: string;
org: number;
authKey: string;
}) {
const filled = section.fields.filter((f) => f.history.length > 0);
const empty = section.fields.filter((f) => f.history.length === 0);
@@ -328,6 +335,8 @@ function StaffSection({
field={f}
options={options}
civiBaseUrl={civiBaseUrl}
org={org}
authKey={authKey}
/>
))}
</ul>
@@ -374,10 +383,14 @@ function CompactFieldRow({
field,
options,
civiBaseUrl,
org,
authKey,
}: {
field: StaffReportField;
options: Record<number, SelectOption[]>;
civiBaseUrl: string;
org: number;
authKey: string;
}) {
const [open, setOpen] = useState(false);
const latest = field.history[0];
@@ -394,6 +407,8 @@ function CompactFieldRow({
entry={latest}
options={options}
civiBaseUrl={civiBaseUrl}
org={org}
authKey={authKey}
/>
</span>
{latest.date ? (
@@ -431,6 +446,8 @@ function CompactFieldRow({
entry={e}
options={options}
civiBaseUrl={civiBaseUrl}
org={org}
authKey={authKey}
/>
</span>
</li>
@@ -446,41 +463,33 @@ function FieldValue({
entry,
options,
civiBaseUrl,
org,
authKey,
}: {
field: StaffReportField;
entry: FieldHistoryEntry;
options: Record<number, SelectOption[]>;
civiBaseUrl: string;
org: number;
authKey: string;
}) {
if (field.descriptor.render === "file") {
const v = entry.value as
| { id?: number | string; file_name?: string; url?: string }
| { id?: number | string; file_name?: string; url?: string; mime?: string }
| null;
if (!v || v.id === undefined) return <span></span>;
const id = String(v.id);
const name = v.file_name ?? `file-${id}`;
// Prefer the Civi-signed URL (carries the fcs JWT) returned by
// Attachment.get. If absent, fall back to the WebForm-mw Civi extension's
// file-redirect route — it mints the fcs server-side and 302s to the
// real /civicrm/file URL. (Hitting /civicrm/file?id=X bare crashes Civi
// on a null fcs JWT decode.)
let href = "#";
if (v.url) {
href = v.url.startsWith("http")
? v.url
: `${civiBaseUrl}${v.url.startsWith("/") ? "" : "/"}${v.url}`;
} else if (civiBaseUrl) {
href = `${civiBaseUrl}/civicrm/webform-mw/file?id=${encodeURIComponent(id)}`;
}
return (
<a
href={href}
target="_blank"
rel="noopener noreferrer"
className="text-ink underline decoration-rule underline-offset-4 hover:decoration-ink"
>
{name}
</a>
<FileLink
fileId={id}
fileName={name}
civiSignedUrl={v.url}
mime={v.mime}
org={org}
authKey={authKey}
civiBaseUrl={civiBaseUrl}
/>
);
}
return (
+123
View File
@@ -0,0 +1,123 @@
"use client";
import { useEffect, useRef } from "react";
/**
* Modal preview for image and PDF attachments.
*
* Uses the native <dialog> element for focus trap, Esc-to-close, and
* inert-background semantics — saves ~100 lines of bespoke a11y wiring
* that we'd otherwise have to maintain.
*
* For an `image/*` mime, renders an <img>. For `application/pdf`, an
* <iframe>. Anything else should not reach this component — FileLink is
* responsible for branching office/other types to plain download links.
*/
export function AttachmentLightbox({
open,
onClose,
previewSrc,
downloadHref,
filename,
mime,
}: {
open: boolean;
onClose: () => void;
/** URL the <img>/<iframe> loads from. Should serve with Content-Disposition: inline. */
previewSrc: string;
/** Anchor target for the Download button. Serves with Content-Disposition: attachment. */
downloadHref: string;
filename: string;
/** Resolved mime; used to pick between <img> and <iframe>. */
mime: string;
}) {
const ref = useRef<HTMLDialogElement | null>(null);
// Drive the native <dialog>'s open state from our prop.
useEffect(() => {
const dlg = ref.current;
if (!dlg) return;
if (open && !dlg.open) {
dlg.showModal();
} else if (!open && dlg.open) {
dlg.close();
}
}, [open]);
// Native <dialog> fires a 'close' event on Esc and on form-method=dialog
// submit. Mirror that back into React state so the parent stays in sync.
useEffect(() => {
const dlg = ref.current;
if (!dlg) return;
const handle = () => onClose();
dlg.addEventListener("close", handle);
return () => dlg.removeEventListener("close", handle);
}, [onClose]);
// Close when the user clicks the backdrop (everything outside the inner
// panel). The dialog itself receives the click event when the backdrop
// is hit because the panel uses pointer-events the same way.
const onDialogClick = (e: React.MouseEvent<HTMLDialogElement>) => {
if (e.target === ref.current) onClose();
};
const isImage = mime.startsWith("image/");
const isPdf = mime === "application/pdf";
return (
<dialog
ref={ref}
onClick={onDialogClick}
aria-label={`Preview: ${filename}`}
className="m-0 h-full max-h-screen w-full max-w-screen-2xl rounded-none bg-transparent p-0 backdrop:bg-ink/70"
>
<div className="flex h-full flex-col">
<header className="flex items-center justify-between gap-4 bg-paper px-4 py-3 shadow-sm sm:px-6">
<p className="min-w-0 truncate font-display text-base text-ink">
{filename}
</p>
<div className="flex flex-shrink-0 items-center gap-3">
<a
href={downloadHref}
className="text-sm font-medium text-leaf-700 underline decoration-rule underline-offset-4 hover:decoration-ink hover:text-leaf-800"
target="_blank"
rel="noopener noreferrer"
>
Download
</a>
<button
type="button"
onClick={onClose}
className="rounded px-2 py-1 text-sm font-medium text-ink-soft hover:bg-rule-soft/40 focus:outline-none focus-visible:ring-2 focus-visible:ring-leaf-700"
aria-label="Close preview"
>
Close
</button>
</div>
</header>
<div className="flex flex-1 items-center justify-center overflow-hidden bg-ink/90 p-4">
{isImage ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={previewSrc}
alt={filename}
className="max-h-full max-w-full object-contain"
/>
) : isPdf ? (
<iframe
src={previewSrc}
title={filename}
className="h-full w-full max-w-screen-lg border-0 bg-paper"
/>
) : (
// Defensive: FileLink shouldn't open the lightbox for non-previewable
// types, but if it does, surface a clear message instead of an empty box.
<p className="px-6 text-paper">
Preview not available. Use Download above to open the file.
</p>
)}
</div>
</div>
</dialog>
);
}
+133
View File
@@ -0,0 +1,133 @@
"use client";
import { useState } from "react";
import { AttachmentLightbox } from "./AttachmentLightbox";
import { categoryFromMime, resolveMime } from "@/lib/mime.mjs";
/**
* Render an attachment row in the staff report with the right affordance
* for its type:
*
* - image / pdf -> button opens the inline lightbox
* - office -> download link + "View in Google Docs" secondary link
* - other -> plain download link
*
* The proxy URL is `/api/staff/file?id=&org=&key=` (re-streams with
* Content-Disposition: inline for previews, or `&dl=1` for downloads). The
* Civi-signed URL (carrying its short-lived fcs JWT) is passed straight to
* Google's Docs Viewer for office files; we deliberately don't proxy that
* one because Google's servers must fetch it without our staff key.
*/
export function FileLink({
fileId,
fileName,
civiSignedUrl,
mime: explicitMime,
org,
authKey,
civiBaseUrl,
}: {
fileId: number | string;
fileName: string;
/** From Attachment.get (includes fcs). Used for office Google Viewer + download fallback. */
civiSignedUrl?: string;
mime?: string;
org: number;
authKey: string;
civiBaseUrl: string;
}) {
const [open, setOpen] = useState(false);
const mime = resolveMime(explicitMime, fileName);
const category = categoryFromMime(mime);
const proxyBase =
`/api/staff/file?id=${encodeURIComponent(String(fileId))}` +
`&org=${encodeURIComponent(String(org))}` +
`&key=${encodeURIComponent(authKey)}`;
const previewSrc = proxyBase;
// Prefer Civi's signed URL for downloads when present (one fewer hop
// through our Lambda); the proxy is the fallback.
const downloadHref = civiSignedUrl
? absUrl(civiSignedUrl, civiBaseUrl)
: `${proxyBase}&dl=1`;
const linkClass =
"text-ink underline decoration-rule underline-offset-4 hover:decoration-ink";
if (category === "image" || category === "pdf") {
return (
<>
<button
type="button"
onClick={() => setOpen(true)}
className={
"bg-transparent p-0 text-left " +
linkClass +
" focus:outline-none focus-visible:ring-2 focus-visible:ring-leaf-700"
}
>
{fileName}
</button>
<AttachmentLightbox
open={open}
onClose={() => setOpen(false)}
previewSrc={previewSrc}
downloadHref={downloadHref}
filename={fileName}
mime={mime}
/>
</>
);
}
if (category === "office") {
// Google Docs Viewer renders DOC/DOCX/XLS/XLSX in a new tab. It fetches
// the source URL server-side, so the URL must be reachable without our
// staff key — that's why we pass the Civi-signed URL straight through.
const gview = civiSignedUrl
? `https://docs.google.com/viewer?url=${encodeURIComponent(absUrl(civiSignedUrl, civiBaseUrl))}`
: null;
return (
<span className="inline-flex flex-wrap items-baseline gap-x-2 gap-y-1">
<a
href={downloadHref}
target="_blank"
rel="noopener noreferrer"
className={linkClass}
>
{fileName}
</a>
{gview && (
<a
href={gview}
target="_blank"
rel="noopener noreferrer"
title="Opens in Google Docs Viewer (file bytes are sent to Google to render)"
className="text-xs font-medium text-leaf-700 underline decoration-rule underline-offset-4 hover:decoration-ink hover:text-leaf-800"
>
View in Google Docs
</a>
)}
</span>
);
}
// "other" — unknown types: just a download link.
return (
<a
href={downloadHref}
target="_blank"
rel="noopener noreferrer"
className={linkClass}
>
{fileName}
</a>
);
}
function absUrl(u: string, base: string): string {
if (u.startsWith("http")) return u;
if (!base) return u;
return `${base.replace(/\/+$/, "")}${u.startsWith("/") ? "" : "/"}${u}`;
}