All files / src/components/document DocumentImages.tsx

97.05% Statements 33/34
76% Branches 19/25
100% Functions 10/10
96.77% Lines 30/31

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 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147                                              23x   23x     6x           23x 24x   23x 4x 4x 4x             23x 9x                                 23x       10x 10x 10x 10x 4x 4x                   1x                                                 23x 6x         23x         6x 6x 3x             1x                   23x     14x 14x 5x    
import {
  DocumentImage,
  findDocumentImage,
  unavailableImage,
} from "@/objects/Document";
import { ImageOff } from "lucide-react";
import React, { createContext, useContext, useState } from "react";
import { DocumentImageUrl } from "./DocumentDownload";
 
/**
 * The images of the one document whose text is being drawn.
 *
 * Inside a document's text, an image is the copy svc-ai stored when it made
 * the document, served by svc-core — never the link the body names, which
 * would tell that image's site who is reading. Outside one (an ordinary chat
 * answer) there is no provider, and an image is drawn as the answer wrote it.
 */
interface DocumentImages {
  images: DocumentImage[];
  /** Null when the record is not stored yet: every image is its alt text. */
  imageUrl: DocumentImageUrl | null;
}
 
const DocumentImagesContext = createContext<DocumentImages | null>(null);
 
export const DocumentImagesProvider: React.FC<
  DocumentImages & { children: React.ReactNode }
> = ({ images, imageUrl, children }) => (
  <DocumentImagesContext.Provider value={{ images, imageUrl }}>
    {children}
  </DocumentImagesContext.Provider>
);
 
/** The images of the document being drawn, or null outside one. */
export const useDocumentImages = (): DocumentImages | null =>
  useContext(DocumentImagesContext);
 
const hostOf = (src: string): string | null => {
  try {
    const url = new URL(src);
    return url.protocol === "https:" ? url.hostname : null;
  } catch {
    return null;
  }
};
 
/** What an image is when it cannot be shown: said so, with its alt text. Makes no request. */
const AltText: React.FC<{ alt?: string }> = ({ alt }) => (
  <span
    data-testid="document-image-alt"
    className="inline-flex items-center gap-1 text-xs italic text-gray-500 dark:text-gray-400"
  >
    <ImageOff aria-hidden className="size-3.5 shrink-0" />
    {unavailableImage(alt)}
  </span>
);
 
/**
 * One image in a document's text: its stored copy with a caption saying
 * where it came from, as the PDF draws it, or its alt text when it was not
 * embedded, the record is not saved yet, or the copy will not load.
 *
 * Spans throughout: Markdown puts an image inside a paragraph, where a
 * `<figure>` or `<div>` is invalid.
 */
export const DocumentFigure: React.FC<{ src?: string; alt?: string }> = ({
  src,
  alt,
}) => {
  const context = useDocumentImages();
  const [failed, setFailed] = useState(false);
  const image = context ? findDocumentImage(context.images, src) : undefined;
  if (!context?.imageUrl || !image || failed) return <AltText alt={alt} />;
  const host = hostOf(image.src);
  return (
    <span data-testid="document-figure" className="not-prose block my-3 text-center">
      <span className="inline-block max-w-full rounded-lg bg-white p-1 ring-1 ring-gray-200 dark:ring-gray-700">
        <img
          src={context.imageUrl(image.asset)}
          alt={alt ?? ""}
          width={image.width}
          height={image.height}
          loading="lazy"
          decoding="async"
          onError={() => setFailed(true)}
          className="mx-auto h-auto max-h-96 w-auto max-w-full rounded"
        />
      </span>
      <span className="mt-1 block text-xs text-gray-500 dark:text-gray-400">
        {alt ? `${alt} — ` : ""}
        {host ? (
          <a
            href={image.src}
            target="_blank"
            rel="noopener noreferrer"
            className="text-indigo-600 dark:text-indigo-400 no-underline hover:underline"
          >
            Image: {host}
          </a>
        ) : (
          "Image"
        )}
      </span>
    </span>
  );
};
 
/** Whether `src` is an image an answer may load: an http(s) URL. A model's
 *  `![x]([https://…])` arrives as `[https:…`, which react-markdown blanks. */
const loadable = (src: string | undefined): src is string =>
  !!src && /^https?:\/\//i.test(src);
 
/** An answer's image, loaded from where it lives — or its alt text when the
 *  link is not an image URL or the image will not load, never a broken
 *  picture. */
const AnswerImage: React.FC<React.ImgHTMLAttributes<HTMLImageElement>> = ({
  src,
  alt,
  title,
}) => {
  const [failed, setFailed] = useState(false);
  if (!loadable(src) || failed) return <AltText alt={alt} />;
  return (
    <img
      src={src}
      alt={alt ?? ""}
      title={title}
      loading="lazy"
      decoding="async"
      onError={() => setFailed(true)}
      className="max-w-full h-auto"
    />
  );
};
 
/**
 * An image in Markdown: inside a document's text, its stored copy
 * (`DocumentFigure`); anywhere else, the image as written (`AnswerImage`).
 */
export const MarkdownImage: React.FC<
  React.ImgHTMLAttributes<HTMLImageElement>
> = (props) => {
  const context = useDocumentImages();
  if (context) return <DocumentFigure src={props.src} alt={props.alt} />;
  return <AnswerImage {...props} />;
};