All files / src/components/document DownloadPdfButton.tsx

100% Statements 8/8
100% Branches 11/11
100% Functions 3/3
100% Lines 8/8

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                        23x       18x 18x 2x 2x 2x   18x     2x                                        
import { Download, Loader2 } from "lucide-react";
import React, { useState } from "react";
 
export interface DownloadPdfButtonProps {
  /** Fetch and save the PDF; resolves false when it failed. */
  download: () => Promise<boolean>;
  label?: string;
}
 
/** A record's PDF download — a skill run's result, a dashboard tile's latest
 *  answer — with its busy and failed states. Rendered by svc-core from what
 *  the record stored; this only asks for it. */
const DownloadPdfButton: React.FC<DownloadPdfButtonProps> = ({
  download,
  label = "Download PDF",
}) => {
  const [state, setState] = useState<"idle" | "busy" | "failed">("idle");
  const run = async () => {
    setState("busy");
    const ok = await download();
    setState(ok ? "idle" : "failed");
  };
  return (
    <button
      type="button"
      onClick={() => void run()}
      disabled={state === "busy"}
      title={state === "failed" ? "Download failed — try again" : undefined}
      className={`flex items-center gap-1.5 text-xs px-2.5 py-1.5 rounded-lg border transition-colors disabled:opacity-40 ${
        state === "failed"
          ? "border-red-200 dark:border-red-800 text-red-500 dark:text-red-400"
          : "border-gray-200 dark:border-gray-600 text-gray-600 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700"
      }`}
    >
      {state === "busy" ? (
        <Loader2 className="size-3 animate-spin" />
      ) : (
        <Download className="size-3" />
      )}
      {state === "failed" ? "Retry PDF" : label}
    </button>
  );
};
 
export default DownloadPdfButton;