All files / src/components/chat/ExportPdf SaveAsPdfButton.tsx

100% Statements 11/11
100% Branches 7/7
100% Functions 4/4
100% Lines 10/10

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65                                                    14x             503x   503x 4x 4x 3x 3x 1x 3x     503x                                        
import { AI_DISCLOSURE } from "@/util/aiDisclosure";
import { exportNodeToPdf } from "@/util/pdfExport";
import { FileDown, Loader2 } from "lucide-react";
import React from "react";
import toast from "react-hot-toast";
 
export interface SaveAsPdfButtonProps {
  /** The rendered node to print — the response bubble, or the whole thread. */
  targetRef: React.RefObject<HTMLElement | null>;
  /** Document title; seeds the browser's save-dialog filename. */
  title: string;
  /** Optional line under the title, e.g. the model and when it answered. */
  subtitle?: string;
  className?: string;
  /** Text beside the icon; icon-only when omitted. */
  label?: string;
}
 
/** Save a rendered chat response as a PDF.
 *
 *  The printed document is the response exactly as it appears on screen —
 *  Mermaid diagrams, charts, network graphs, maps, tables and math included —
 *  because {@link exportNodeToPdf} prints the live DOM rather than re-deriving
 *  a document from the markdown. Every page it prints is chat output, so each
 *  closes with the AI disclosure.
 */
const SaveAsPdfButton: React.FC<SaveAsPdfButtonProps> = ({
  targetRef,
  title,
  subtitle,
  className = "",
  label,
}) => {
  const [busy, setBusy] = React.useState(false);
 
  const save = () => {
    const node = targetRef.current;
    if (!node || busy) return;
    setBusy(true);
    exportNodeToPdf({ node, title, subtitle, footer: AI_DISCLOSURE.document })
      .catch(() => toast.error("Could not open the print view for this PDF."))
      .finally(() => setBusy(false));
  };
 
  return (
    <button
      type="button"
      onClick={save}
      disabled={busy}
      title="Save as PDF"
      aria-label="Save as PDF"
      className={className}
    >
      {busy ? (
        <Loader2 className="w-3.5 h-3.5 animate-spin" />
      ) : (
        <FileDown className="w-3.5 h-3.5" />
      )}
      {label}
    </button>
  );
};
 
export default SaveAsPdfButton;