index.tsx
Overview
index.tsx is a React functional component file that provides an interactive PDF document preview with highlight capabilities. It leverages the react-pdf-highlighter library to render PDF pages, display text and area highlights, and show contextual popups on hover. The component fetches a PDF document URL and associated highlight data from external hooks and manages loading states, error handling, and user interactions such as scrolling and selection.
This file's primary purpose is to enable users to view specific chunks of a document with visual highlights and comments, enhancing document review and navigation workflows within the application.
Detailed Explanation
Interfaces and Types
IProps
interface IProps {
chunk: IChunk | IReferenceChunk;
documentId: string;
visible: boolean;
}
Description: Defines the props expected by the
DocumentPreviewercomponent.Parameters:
chunk: An object representing a portion of the document, either a knowledge chunk (IChunk) or a referenced chunk (IReferenceChunk).documentId: The ID of the document to preview.visible: Boolean flag indicating whether the previewer should be visible (used for lazy loading or conditional rendering).
Components
HighlightPopup
const HighlightPopup = ({
comment,
}: {
comment: { text: string; emoji: string };
}) => comment.text ? (
<div className="Highlight__popup">
{comment.emoji} {comment.text}
</div>
) : null;
Purpose: Renders a small popup showing a highlight comment with an emoji.
Props:
comment: An object containing:text: The comment text string.emoji: An emoji string representing the comment visually.
Returns: A
divwith the comment text and emoji if text exists, otherwisenull.Usage: Used inside the PDF highlight popup to show user annotations.
DocumentPreviewer
const DocumentPreviewer = ({ chunk, documentId, visible }: IProps) => { ... }
Purpose: Main component rendering the PDF preview with highlights for a given document chunk.
Props: As defined in
IProps.Internal Hooks and State:
getDocumentUrl: Hook to get the URL of the PDF document bydocumentId.useGetChunkHighlights: Retrieves highlight data for the givenchunk.useCatchDocumentError: Custom hook to catch and handle errors related to document loading.useRef: Stores a callback function to scroll to a highlight.useState: Manages aloadedstate indicating if the document is ready to display.
Key Functions:
resetHash: Empty stub function that can be used to reset URL hash or internal state on scroll.
Side Effects:
useEffectto set loaded state based onvisibleprop.useEffectto auto-scroll to the first highlight when highlights data updates and document is loaded.
Render Logic and Interaction
The component wraps the PDF rendering inside a container styled with CSS modules (
styles.documentContainer).Uses
PdfLoaderfromreact-pdf-highlighterto asynchronously load the PDF document from the URL.Displays an Ant Design
Skeletoncomponent as a loading placeholder.Displays a
FileErrorcomponent if an error occurs.
Once loaded, it queries the first page of the PDF to get viewport dimensions (width/height), which it sets via
setWidthAndHeightfor layout purposes.Renders
PdfHighlighterwith:enableAreaSelection: Allows area highlights only when theAltkey is pressed.onScrollChange: CallsresetHashon scrolling.scrollRef: Passes a function to capture a scroll-to-highlight callback.highlightTransform: Custom function to render each highlight:Distinguishes between text highlights and area highlights.
Wraps highlight components (
HighlightorAreaHighlight) inside aPopup.Popupdisplays theHighlightPopupcomponent on hover.
highlights: Array of highlights from the chunk state.
Implementation Details and Algorithms
Highlight Differentiation:
The code checks if a highlight is a text highlight by verifying
highlight.content.imagepresence.If no image is present, it renders a text highlight; otherwise, it renders an area highlight.
Highlight Auto-Scroll:
On highlights data or loaded state change, the component triggers scrolling to the first highlight using a stored callback in a React
ref.
Lazy Loading and Visibility:
The component listens to the
visibleprop to control the loaded state, enabling lazy loading or conditional display.
Error Handling:
Uses
useCatchDocumentErrorhook to detect errors related to PDF fetching/loading and renders theFileErrorcomponent accordingly.
Interaction with Other System Parts
Hooks Used:
useGetDocumentUrl(documentId): Fetches the PDF document URL, likely from a backend or cloud storage.useGetChunkHighlights(chunk): Retrieves all highlights related to the current document chunk.useCatchDocumentError(url): Handles errors during PDF fetching.
UI Components:
Imports UI elements such as
Skeleton(loading placeholder) andFileError(error display) from other parts of the application.
Interfaces:
Uses
IChunkandIReferenceChunkinterfaces to define the data structure for document chunks.
Styling:
Uses CSS Modules (
index.less) scoped styles for layout and popup styling.
Usage Example
import DocumentPreviewer from './index';
const chunk = {
id: 'chunk123',
text: 'Sample text from document...',
// other IChunk or IReferenceChunk properties
};
const MyComponent = () => (
<DocumentPreviewer
chunk={chunk}
documentId="doc456"
visible={true}
/>
);
This will render the PDF preview of document doc456 highlighting the provided chunk with interactive highlights and popups.
Visual Diagram
componentDiagram
component DocumentPreviewer {
+chunk: IChunk | IReferenceChunk
+documentId: string
+visible: boolean
-- useGetDocumentUrl(documentId)
-- useGetChunkHighlights(chunk)
-- useCatchDocumentError(url)
-- state: loaded:boolean
-- ref: scrollToHighlight function
-- resetHash()
}
component PdfLoader {
+url: string
+beforeLoad: ReactNode
+workerSrc: string
+errorMessage: ReactNode
}
component PdfHighlighter {
+pdfDocument
+enableAreaSelection(event)
+onScrollChange()
+scrollRef()
+onSelectionFinished()
+highlightTransform()
+highlights
}
component HighlightPopup {
+comment: {text, emoji}
}
DocumentPreviewer --> PdfLoader : loads PDF document
PdfLoader --> PdfHighlighter : renders PDF with highlights
PdfHighlighter --> HighlightPopup : shows comment popups on highlights
Summary
index.tsx implements a robust PDF preview component with highlighting and annotation display capabilities, integrating document fetching, highlight retrieval, error handling, and interactive UI elements. It is a key UI piece for document review features in the application and is designed to be reusable for any document chunk with associated highlights.