All files / src/components/document DocumentDownload.tsx

100% Statements 8/8
100% Branches 1/1
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 47 48                                                    23x 23x   23x           292x             23x 25x   23x 14x  
import { DocumentSpec } from "@/objects/Document";
import React, { createContext, useContext } from "react";
 
/**
 * How a document drawn inside some content is downloaded as a PDF.
 *
 * A ```document fence is rendered deep inside `RichMarkdown`, which knows
 * nothing about where its content came from — but the PDF is made by svc-core
 * from the *stored* record (a chat message, a skill run), so the download
 * needs that record's ids. Whoever renders the content provides them here.
 *
 * No provider means no stored record yet (a reply still streaming), and the
 * card says so instead of offering a button that could only fail.
 */
export type DocumentDownloader = (
  index: number,
  document: DocumentSpec,
) => Promise<boolean>;
 
/**
 * Where a document's stored images are drawn from: svc-core's URL for the
 * copy `asset` names, under the same record. Like the download, only a
 * stored record has one; without it every image is its alt text.
 */
export type DocumentImageUrl = (asset: string) => string;
 
const DocumentDownloadContext = createContext<DocumentDownloader | null>(null);
const DocumentImageUrlContext = createContext<DocumentImageUrl | null>(null);
 
export const DocumentDownloadProvider: React.FC<{
  download: DocumentDownloader | null;
  /** Where the record's document images are served; none when omitted. */
  imageUrl?: DocumentImageUrl | null;
  children: React.ReactNode;
}> = ({ download, imageUrl = null, children }) => (
  <DocumentDownloadContext.Provider value={download}>
    <DocumentImageUrlContext.Provider value={imageUrl}>
      {children}
    </DocumentImageUrlContext.Provider>
  </DocumentDownloadContext.Provider>
);
 
export const useDocumentDownload = (): DocumentDownloader | null =>
  useContext(DocumentDownloadContext);
 
export const useDocumentImageUrl = (): DocumentImageUrl | null =>
  useContext(DocumentImageUrlContext);