pdf-preview.tsx
Overview
pdf-preview.tsx is a React functional component designed to render a PDF document with interactive text and area highlights. It leverages the third-party library react-pdf-highlighter to enable PDF loading, rendering, and user interactions such as highlighting text or areas in the PDF. The component also supports displaying popup comments on highlights and integrates with application-specific hooks and UI elements for error handling and loading states.
This file primarily serves as a PDF previewer with highlight visualization, allowing users to view a PDF document, see existing highlights, and interact with them by hovering to reveal comments. It is memoized for performance optimization, avoiding unnecessary re-renders.
Detailed Description
Interfaces
IProps
interface IProps {
highlights: IHighlight[];
setWidthAndHeight: (width: number, height: number) => void;
url: string;
}
highlights: An array of
IHighlightobjects representing the highlights to display on the PDF.setWidthAndHeight: Callback function that receives the width and height of the first PDF page viewport once loaded.
url: The URL of the PDF document to be loaded and previewed.
Components and Functions
HighlightPopup
const HighlightPopup = ({
comment,
}: {
comment: { text: string; emoji: string };
}) => JSX.Element | null
Purpose: Renders a small popup displaying the comment associated with a highlight, optionally showing an emoji.
Parameters:
comment: Object containing:text(string): The comment text.emoji(string): An emoji symbol representing the comment.
Returns: A
divelement with comment content ifcomment.textexists; otherwise, returnsnull.Usage: Used inside each highlight popup to display the user’s annotation.
Example:
<HighlightPopup comment={{ text: "Important note", emoji: "📝" }} />
PdfPreview
const PdfPreview = ({ highlights: state, setWidthAndHeight, url }: IProps) => JSX.Element
Purpose: Main component to load, render, and display a PDF with interactive highlights and popups.
Parameters:
highlights(aliased asstate): The array of highlights to render.setWidthAndHeight: Callback function to set the dimensions of the first PDF page.url: URL string pointing to the PDF file.
Returns: A JSX element containing the PDF preview with highlights.
Internal Implementation Details
Error Handling: Uses a custom hook
useCatchDocumentError(url)to detect loading errors in the PDF and displays aFileErrorcomponent if an error occurs.Loading State: While the PDF is loading, a spinner (
Spincomponent) is shown centered in the container.PDF Loading: Uses
PdfLoaderfromreact-pdf-highlighterto fetch and parse the PDF document.Page Viewport Measurement: On loading the first page, it calculates the viewport size (
widthandheight) and passes it back viasetWidthAndHeight.Highlighting:
Uses
PdfHighlighterto render highlights.Supports two highlight types:
Text highlights (
Highlightcomponent).Area highlights (
AreaHighlightcomponent).
Highlights are interactive:
Popups display on hover containing the comment via
HighlightPopup.Area selection to add new highlights is enabled when
Altkey is held during mouse selection.
Scrolling & Selection:
Stores a reference to a scroll-to-highlight function (
ref).On highlight state changes, scrolls to the first highlight automatically.
Resets any URL hash or similar state on scroll.
Styling: Uses CSS module styles imported as
stylesfor container styling (e.g., rounded corners, overflow control).
Usage Example
import PdfPreview from './pdf-preview';
const highlights = [
{
position: { /* position data */ },
content: { text: "Example highlight" },
comment: { text: "Important section", emoji: "⭐" },
// other IHighlight properties...
}
];
const handleSetDimensions = (width: number, height: number) => {
console.log("PDF page dimensions:", width, height);
};
function App() {
return (
<PdfPreview
url="https://example.com/sample.pdf"
highlights={highlights}
setWidthAndHeight={handleSetDimensions}
/>
);
}
Interaction with Other System Parts
Hooks:
useCatchDocumentError- custom hook likely defined elsewhere in the project to handle error detection during PDF loading.UI Components:
Spin- loading spinner used while the PDF loads.FileError- displays error messages when the PDF fails to load.
Styles: Local CSS module
index.lessfor styling the PDF container.PDFJS Worker: Specifies the worker source for PDF.js via
/pdfjs-dist/pdf.worker.min.js.Highlight Data Model: Uses
IHighlightinterface fromreact-pdf-highlighterfor highlights' shape.
This component is likely embedded inside a document viewer page or a previewer UI where PDF documents are rendered with annotations.
Important Implementation Notes
The component memoizes
PdfPreviewusingReact.memoto optimize rendering.The
resetHashfunction is defined but empty (placeholder), suggesting future URL hash or scroll state reset functionality.The highlight transformation uses the
Popupcomponent to wrap highlights with mouseover and mouseout handlers to show/hide comment popups.Area selection to create new highlights is conditionally enabled only when the
Altkey is pressed during selection (enableAreaSelection).The
scrollRefcallback stores a method to programmatically scroll to a highlight, used to scroll to the first highlight on initial render or highlight changes.
Mermaid Diagram
componentDiagram
component PdfPreview {
+highlights: IHighlight[]
+setWidthAndHeight(width: number, height: number): void
+url: string
-ref: React.Ref<(highlight: IHighlight) => void>
-error: any
-resetHash(): void
}
component PdfLoader {
+url: string
+beforeLoad: JSX.Element
+workerSrc: string
+errorMessage: JSX.Element
}
component PdfHighlighter {
+pdfDocument: PDFDocumentProxy
+enableAreaSelection(event): boolean
+onScrollChange(): void
+scrollRef(callback): void
+onSelectionFinished(): void
+highlightTransform(...)
+highlights: IHighlight[]
}
component HighlightPopup {
+comment: { text: string, emoji: string }
}
PdfPreview --> PdfLoader: Loads PDF
PdfLoader --> PdfHighlighter: Provides pdfDocument
PdfHighlighter --> HighlightPopup: Displays comment popup
Summary
pdf-preview.tsx is a React component for rendering PDFs with interactive highlights and popups. It integrates PDF loading, error handling, and highlight rendering using react-pdf-highlighter. This component is an integral UI piece in a document viewer application, enabling users to view and interact with annotations on PDF files.