Skip to content

LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows

6.5 KB
Raw Blame
import { Viewer, Worker } from "@react-pdf-viewer/core";
import { defaultLayoutPlugin } from "@react-pdf-viewer/default-layout";
import { highlightPlugin } from "@react-pdf-viewer/highlight";
import { pageNavigationPlugin } from "@react-pdf-viewer/page-navigation";
import { FileWarning, RotateCw } from "lucide-react";
import PropTypes from "prop-types";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Button } from "@/components/ui/shims/antd-button";
import { Result } from "@/components/ui/shims/antd-structure";

import "@react-pdf-viewer/core/lib/styles/index.css";
import "@react-pdf-viewer/default-layout/lib/styles/index.css";
import "@react-pdf-viewer/highlight/lib/styles/index.css";
import "./Highlight.css";
import { PDF_WORKER_URL } from "../../../helpers/pdfWorkerConfig";

let RenderHighlights;
try {
  const mod = await import("../../../plugins/pdf-highlight/RenderHighlights");
  RenderHighlights = mod.RenderHighlights;
} catch {
  // Do nothing, no plugin will be loaded.
}

function PdfLoadError({ error, onRetry, reportError }) {
  useEffect(() => {
    reportError(error);
  }, [error, reportError]);

  const errorMessage =
    error?.message ||
    "Failed to load PDF document. The file may be corrupted or inaccessible.";

  return (
    <div className="pdf-viewer-error">
      <Result
        icon={<FileWarning style={{ color: "#ff4d4f" }} />}
        title="Failed to Load PDF"
        subTitle={errorMessage}
        extra={
          <Button type="primary" icon={<RotateCw />} onClick={onRetry}>
            Retry
          </Button>
        }
      />
    </div>
  );
}

function PdfViewer({ fileUrl, highlightData, currentHighlightIndex, onError }) {
  const newPlugin = defaultLayoutPlugin();
  const pageNavigationPluginInstance = pageNavigationPlugin();
  const { jumpToPage } = pageNavigationPluginInstance;
  const parentRef = useRef(null);

  // Retry key to force re-render when retrying
  const [retryKey, setRetryKey] = useState(0);
  const [loadError, setLoadError] = useState(null);

  // Clear error state when fileUrl changes to prevent stale notifications
  useEffect(() => {
    setLoadError(null);
  }, [fileUrl]);

  const handleRetry = useCallback(() => {
    setRetryKey((prev) => prev + 1);
    setLoadError(null);
  }, []);

  // Notify parent of load errors via useEffect to avoid side effects during render
  useEffect(() => {
    if (loadError && onError) {
      onError(loadError);
    }
  }, [loadError, onError]);

  // Render error fallback for PDF load failures — pure render, no side effects
  const renderError = useCallback(
    (error) => (
      <PdfLoadError
        error={error}
        onRetry={handleRetry}
        reportError={setLoadError}
      />
    ),
    [handleRetry],
  );

  function removeZerosAndDeleteIfAllZero(highlightData) {
    if (Array.isArray(highlightData)) {
      return highlightData
        ?.filter((innerArray) => {
          if (!Array.isArray(innerArray)) {
            return false;
          }
          // Strip 5th element (confidence) if present, keep only first 4 elements
          const coordsOnly =
            innerArray.length >= 5 ? innerArray.slice(0, 4) : innerArray;
          return coordsOnly.some((value) => value !== 0);
        })
        .map((innerArray) => {
          // Return only the first 4 elements (strip confidence)
          return innerArray.length >= 5 ? innerArray.slice(0, 4) : innerArray;
        });
    }
  }

  const processHighlightData = highlightData
    ? removeZerosAndDeleteIfAllZero(highlightData)
    : [];

  const processedHighlightData =
    processHighlightData?.length > 0 ? processHighlightData : [[0, 0, 0, 0]];

  // Determine current highlight data
  const currentHighlightData = useMemo(() => {
    if (
      RenderHighlights &&
      Array.isArray(processedHighlightData) &&
      processedHighlightData?.length > 0
    ) {
      return currentHighlightIndex !== null &&
        currentHighlightIndex < processedHighlightData.length
        ? [processedHighlightData[currentHighlightIndex]]
        : processedHighlightData;
    }
    return null;
  }, [processedHighlightData, currentHighlightIndex]);

  // Always create both plugins at top level to maintain hook order
  const baseHighlightPlugin = highlightPlugin();
  const customHighlightPlugin = highlightPlugin({
    renderHighlights:
      currentHighlightData && RenderHighlights
        ? (props) => (
            <RenderHighlights {...props} highlightData={currentHighlightData} />
          )
        : undefined,
  });

  // Choose which plugin to use
  const highlightPluginInstance = currentHighlightData
    ? customHighlightPlugin
    : baseHighlightPlugin;

  // Jump to page when highlightData changes or when navigating through highlights
  useEffect(() => {
    const cleanedHighlightData = removeZerosAndDeleteIfAllZero(highlightData);
    if (cleanedHighlightData && cleanedHighlightData.length > 0) {
      // Use currentHighlightIndex if provided, otherwise default to first highlight
      const index =
        currentHighlightIndex !== null &&
        currentHighlightIndex < cleanedHighlightData.length
          ? currentHighlightIndex
          : 0;
      const pageNumber = cleanedHighlightData[index][0]; // Get page number from current highlight

      if (pageNumber !== null && pageNumber !== undefined && jumpToPage) {
        setTimeout(() => {
          jumpToPage(pageNumber); // jumpToPage is 0-indexed
        }, 100); // Add a slight delay to ensure proper page rendering
      }
    }
  }, [highlightData, jumpToPage, currentHighlightIndex]); // Changed dependency to highlightData instead of processedHighlightData

  // Show empty state when no URL is provided
  if (!fileUrl) {
    return (
      <div ref={parentRef} className="doc-manager-body pdf-viewer-error">
        <Result
          icon={<FileWarning style={{ color: "var(--warning)" }} />}
          title="No PDF Available"
          subTitle="The PDF document URL is not available. Please ensure the document has been processed correctly."
        />
      </div>
    );
  }

  return (
    <div ref={parentRef} className="doc-manager-body" key={retryKey}>
      <Worker workerUrl={PDF_WORKER_URL}>
        <Viewer
          fileUrl={fileUrl}
          plugins={[
            newPlugin,
            pageNavigationPluginInstance,
            highlightPluginInstance,
          ]}
          renderError={renderError}
        />
      </Worker>
    </div>
  );
}

PdfViewer.propTypes = {
  fileUrl: PropTypes.any,
  highlightData: PropTypes.array,
  currentHighlightIndex: PropTypes.number,
  onError: PropTypes.func,
};

export { PdfViewer };