preview.tsx
Overview
preview.tsx defines a React component named Preview that serves as a PDF previewer with annotation/highlight capabilities. It leverages the react-pdf-highlighter library to render a PDF document, display user highlights or annotations, and provide interactive popups showing comments attached to those highlights.
Key features:
Loads a PDF document asynchronously from a URL obtained via a custom hook (
useGetDocumentUrl).Displays a loading skeleton or an error message if the document fails to load.
Renders text and area highlights on the PDF pages.
Shows popup comments associated with highlights on mouse hover.
Reports the width and height of the first PDF page to a parent component via a callback.
Supports highlight scrolling and resetting behaviors.
Memoized for performance optimization.
This component is likely part of a larger document viewing or annotation system, interacting with hooks and error handling components used elsewhere in the application.
Detailed Explanation
Interfaces
IProps
interface IProps {
highlights: IHighlight[];
setWidthAndHeight: (width: number, height: number) => void;
}
Purpose: Defines the props accepted by the
Previewcomponent.Properties:
highlights: An array ofIHighlightobjects representing the annotations/highlights to display on the PDF.setWidthAndHeight: Callback function invoked with the width and height of the first PDF page, allowing the parent component to adjust layout or styles accordingly.
Components and Functions
HighlightPopup
const HighlightPopup = ({
comment,
}: {
comment: { text: string; emoji: string };
}) => comment.text ? (
<div className="Highlight__popup">
{comment.emoji} {comment.text}
</div>
) : null;
Description: Functional component that renders a popup UI element showing the comment attached to a highlight.
Parameters:
comment: An object withtextandemojiproperties.
Returns: A
divcontaining the emoji and text ifcomment.textexists; otherwise, renders nothing (null).Usage: Used internally by the
Popupcomponent inPreviewto show highlight comments on hover.
Preview
const Preview = ({ highlights: state, setWidthAndHeight }: IProps) => { ... }
Description: Main React component rendering a PDF document with highlight annotations.
Props:
highlights(renamedstateinside component): List of highlight objects to render.setWidthAndHeight: Callback to report size of the PDF's first page.
Returns: JSX element rendering the PDF preview with highlights and popups.
Implementation Details
PDF URL Loading
The PDF URL is fetched using a custom hook
useGetDocumentUrl().Error handling for the document loading is managed via another hook
useCatchDocumentError(url).If an error occurs, the
FileErrorcomponent displays an error message.
PDF Loading & Rendering
Uses
PdfLoaderfromreact-pdf-highlighterto asynchronously load the PDF.While loading, an Ant Design
Skeletonspinner is shown.The PDF worker script is specified for efficient PDF parsing.
Page Dimension Measurement
Once the PDF document is loaded, the first page is fetched.
The viewport size of the first page is obtained using
page.getViewport({ scale: 1 }).The width and height are passed to the parent via
setWidthAndHeight.
Highlights Rendering
PdfHighlighterreceives the loaded document and the list ofhighlights.Highlights can be text or area-based:
Text highlights use
Highlightcomponent.Area highlights use
AreaHighlightcomponent.
The component listens for
altKeyto enable area selection (for creating new highlights).highlightTransformis responsible for rendering each highlight and wrapping it with aPopupthat shows comments on hover.
Scrolling and Selection
The component manages a ref (
ref) to a function that scrolls to a particular highlight.On initial render or highlight update, it scrolls to the first highlight.
resetHashis a placeholder function intended to handle scroll changes (currently empty).onSelectionFinishedis stubbed to() => null, potentially reserved for future selection functionality.
Performance
The
Previewcomponent is wrapped with React'smemoto avoid unnecessary re-renders when props have not changed.
Usage Example
import Preview from './preview';
// Sample highlight data
const highlights = [
{
id: '1',
position: { boundingRect: {...}, rects: [...], pageNumber: 1 },
comment: { text: 'Important note', emoji: '📝' },
content: { text: 'Sample highlighted text' },
},
// ... other highlights
];
const App = () => {
const [dimensions, setDimensions] = React.useState({ width: 0, height: 0 });
return (
<div>
<Preview highlights={highlights} setWidthAndHeight={(w, h) => setDimensions({ width: w, height: h })} />
<p>Page dimensions: {dimensions.width} x {dimensions.height}</p>
</div>
);
};
Interaction with Other Parts of the System
Hooks:
useGetDocumentUrl: Provides the URL of the PDF to render. Likely connected to application state or routing.useCatchDocumentError: Manages error states related to PDF loading.
Error Handling:
FileErrorcomponent displays user-friendly messages when the PDF fails to load.
Styling:
Uses CSS modules (
styles.documentContainer) for layout and styling.
Parent Component:
Receives page size info via
setWidthAndHeightfor layout adjustments.
External Libraries:
react-pdf-highlighterprovides PDF rendering, highlighting, and popup functionality.Ant Design's
Skeletoncomponent for loading states.
Visual Diagram
componentDiagram
component Preview {
+highlights: IHighlight[]
+setWidthAndHeight(width: number, height: number): void
-ref: React.RefObject
-resetHash()
}
component HighlightPopup {
+comment: { text: string; emoji: string }
}
component PdfLoader
component PdfHighlighter
component Highlight
component AreaHighlight
component Popup
component Skeleton
component FileError
component useGetDocumentUrl
component useCatchDocumentError
Preview --> PdfLoader : loads PDF by URL
Preview --> useGetDocumentUrl : fetches URL
Preview --> useCatchDocumentError : error detection
PdfLoader --> Skeleton : loading state
PdfLoader --> FileError : error display
PdfLoader --> PdfHighlighter : passes loaded PDF
PdfHighlighter --> Highlight : renders text highlights
PdfHighlighter --> AreaHighlight : renders area highlights
PdfHighlighter --> Popup : wraps highlights with popups
Popup --> HighlightPopup : popup content
Summary
The preview.tsx file implements a performant, interactive PDF previewer component with rich highlight and annotation support. It integrates tightly with application-specific hooks for document retrieval and error handling, uses third-party libraries for PDF rendering and UI components, and exposes a clean interface for parent components to react to page dimensions.
This file is a core part of the document viewing experience, enabling users to see and interact with highlights and their comments seamlessly within the app.