hooks.ts
Overview
The hooks.ts file provides several custom React hooks primarily aimed at enhancing document rendering and interaction within a React application. These hooks facilitate responsive document container sizing, dynamic text highlighting within documents, and retrieval of document URLs based on route parameters.
This file is designed to work with PDF-like documents or other text-heavy content rendered in a React environment, supporting features such as automatic container resizing and keyword highlighting for improved user experience.
Exports and Their Functionalities
1. useDocumentResizeObserver
A custom hook that tracks the width of a document container element and updates its value reactively as the container resizes.
Purpose:
To provide the current width of a container element and a reference setter to attach to that container, enabling responsive and adaptive UI components based on container size.
API:
const { containerWidth, setContainerRef } = useDocumentResizeObserver();
Returns:
containerWidth: number | undefined— The current width of the observed container element.setContainerRef: (element: HTMLElement | null) => void— Setter function to assign the container element to observe.
Implementation Details:
Utilizes the
useSizehook from theahookslibrary to listen for size changes on the container element.Internally stores the container element reference and its width in state.
Updates the width state whenever the container's width changes.
Uses
useCallbackanduseEffectto optimize callback references and side effects.
Usage Example:
const DocumentContainer = () => {
const { containerWidth, setContainerRef } = useDocumentResizeObserver();
return (
<div ref={setContainerRef} style={{ width: '100%' }}>
<p>Container width: {containerWidth}px</p>
{/* Render document or PDF here, potentially adjusting layout based on containerWidth */}
</div>
);
};
2. useHighlightText
A custom hook that returns a text renderer function for highlighting search terms within a document's text.
Purpose:
To generate highlighted text snippets by wrapping matching text with HTML <mark> tags, enhancing search term visibility in rendered documents.
API:
const textRenderer: CustomTextRenderer = useHighlightText(searchText);
Parameters:
searchText: string— The search pattern/text to highlight within the document's text.
Returns:
textRenderer: CustomTextRenderer— A callback function compatible with PDF text rendering components that receives text items and returns HTML strings with highlighted matches.
Implementation Details:
Internally uses the helper function
highlightPatternto apply highlighting.highlightPattern:Marks all occurrences of the pattern in the text with
<mark>tags.Has a specific condition to highlight all text on page 2 regardless of pattern matching.
Utilizes
useCallbackto memoize the renderer function based on thesearchTextdependency.
Usage Example:
import { useHighlightText } from './hooks';
const MyPdfViewer = ({ searchText }) => {
const textRenderer = useHighlightText(searchText);
return (
<PDFViewer textRenderer={textRenderer} />
);
};
3. useGetDocumentUrl
A custom hook that constructs and returns the full URL to retrieve a document based on route parameters.
Purpose:
To abstract the logic of forming the API endpoint URL for fetching a document, relying on the current route's documentId parameter.
API:
const url = useGetDocumentUrl();
Returns:
url: string— The full URL string pointing to the document's API endpoint.
Implementation Details:
Uses the
useGetKnowledgeSearchParamshook (imported from another module) to extractdocumentIdfrom the current route or query parameters.Uses
useMemoto recompute the URL only whendocumentIdchanges.Concatenates the base API host URL (
api_host) with the endpoint path anddocumentId.
Usage Example:
const DocumentDownloader = () => {
const url = useGetDocumentUrl();
useEffect(() => {
fetch(url).then(...);
}, [url]);
return <a href={url} download>Download Document</a>;
};
Internal Helper Function: highlightPattern
A utility function for applying highlight markup to matching text strings.
function highlightPattern(text: string, pattern: string, pageNumber: number): string
Parameters:
text: string— The text string to potentially highlight.pattern: string— The search pattern used for matching text.pageNumber: number— The current page number of the document where the text resides.
Returns:
A string with matched portions wrapped in
<mark>tags for highlighting.
Behavior:
On page 2, highlights the entire text unconditionally.
Otherwise, attempts to match the pattern against the text and applies
<mark>to matches.Contains commented-out logic hinting at future or alternate replacement strategies.
Interaction with Other System Parts
useGetKnowledgeSearchParams(imported hook):
Used byuseGetDocumentUrlto extract query or route parameters. This ties the hook to the routing and URL handling logic of the app.api_host(imported constant):
Provides the base URL for API requests, ensuring consistent endpoint formation.ahookslibrary'suseSize:
Enables reactive size detection for HTML elements, crucial foruseDocumentResizeObserver.CustomTextRenderertype fromreact-pdf:
Ensures compatibility of the text rendering function with PDF rendering components.
Mermaid Diagram: Flowchart of Hook Relationships and Data Flow
flowchart TD
A[useDocumentResizeObserver] --> B[containerRef (HTMLElement)]
B --> C[useSize(containerRef)]
C --> A
A --> D[containerWidth (number)]
E[useHighlightText(searchText)] --> F[textRenderer (CustomTextRenderer)]
F --> G[highlightPattern(text, pattern, pageNumber)]
H[useGetDocumentUrl] --> I[useGetKnowledgeSearchParams()]
I --> J[documentId]
J --> K[url = api_host + /document/get/ + documentId]
style A fill:#f9f,stroke:#333,stroke-width:2px
style E fill:#bbf,stroke:#333,stroke-width:2px
style H fill:#bfb,stroke:#333,stroke-width:2px
Summary
The hooks.ts file encapsulates important UI and data-fetching utilities for document display and interaction in a React application:
Responsive container sizing for adaptive document rendering.
Dynamic text highlighting for search-enhanced document views.
API URL generation based on route parameters for data retrieval.
These hooks are modular, reusable, and integrate with external utilities and routing logic, making them essential building blocks for document-centric features within the broader application.