hooks.ts
Overview
The hooks.ts file provides a set of custom React hooks designed primarily for document viewing and interaction within a React application. These hooks facilitate responsive UI behavior by monitoring container size changes, rendering highlighted search text within documents, and generating URLs to fetch documents based on route parameters.
Key functionalities include:
Observing and responding to container resize events to adjust document layout dynamically.
Highlighting search terms within document text based on a pattern matching.
Constructing document URLs from route-based parameters to load specific documents.
These hooks are essential utilities that enhance the document viewing experience by integrating UI responsiveness and search highlighting.
Detailed Explanation of Exports
1. useDocumentResizeObserver
Description
A React hook that tracks the width of a DOM element (container) and provides a resize observer that updates whenever the element's size changes. Useful for responsive components that need to adapt their layout or rendering based on available container width.
Parameters
None
Returns
containerWidth: number | undefined — The current width of the observed container element.
setContainerRef: (element: HTMLElement | null) => void — A setter function to assign the DOM element to be observed.
Usage Example
const MyComponent = () => {
const { containerWidth, setContainerRef } = useDocumentResizeObserver();
return (
<div ref={setContainerRef} style={{ width: '100%' }}>
<p>Container width: {containerWidth}px</p>
{/* Use containerWidth to adjust layout */}
</div>
);
};
Implementation Details
Uses the
useSizehook fromahooksto listen for size changes on the referenced container element.The
onResizecallback updates the statecontainerWidthwhenever the width changes.The hook returns the current container width and a setter function to assign the container element to observe.
2. useHighlightText
Description
Generates a custom text renderer function that highlights occurrences of a search pattern within document text items. This is specifically designed to be used with PDF rendering libraries or similar where text is rendered in pieces.
Parameters
searchText: string— The text pattern to highlight within the document. Defaults to an empty string.
Returns
textRenderer: CustomTextRenderer— A callback function that takes a text item object and returns the text with matched patterns wrapped in HTML<mark>tags.
Usage Example
const searchText = 'React';
const textRenderer = useHighlightText(searchText);
// Use `textRenderer` as a prop to a PDF viewer component that supports custom text rendering
<PDFViewer customTextRenderer={textRenderer} />;
Implementation Details
Defines an internal function
highlightPatternwhich wraps matched text in<mark>tags.Special case: highlights all text if the page number is 2 (likely a temporary or example condition).
Uses
useCallbackto memoize the text renderer based on thesearchText.The renderer function receives a
textItemcontaining the string and page number, applies highlighting, and returns HTML string with highlights.
3. useGetDocumentUrl
Description
Constructs the URL to fetch a document based on the current route's documentId parameter. This hook integrates route parameters with API endpoints.
Parameters
None
Returns
url: string— The full URL string to request the document resource from the API.
Usage Example
const documentUrl = useGetDocumentUrl();
// Use documentUrl to fetch or load the document
fetch(documentUrl).then(...);
Implementation Details
Uses
useGetKnowledgeSearchParamshook (imported from@/hooks/route-hook) to extract thedocumentIdfrom route parameters.Uses
useMemoto memoize the URL string and avoid recomputation unlessdocumentIdchanges.Combines a base API host URL (
api_host) with the document ID to form the complete endpoint.
Important Implementation Details and Algorithms
Resize Observation: Utilizes the
useSizehook from theahookslibrary, which internally uses the ResizeObserver API to monitor element size changes efficiently.Text Highlighting Logic:
The
highlightPatternfunction applies HTML<mark>tags to highlight matched patterns.Handles edge cases such as empty strings or page-based special highlighting.
Uses string replacement with regex pattern matching.
URL Construction: Leverages React's
useMemoto avoid unnecessary recalculations, ensuring efficient re-rendering.
Interaction with Other Parts of the System
Route Integration:
useGetDocumentUrldepends onuseGetKnowledgeSearchParamsfrom the routing hooks to extractdocumentId, showing coupling with routing logic.API Config: The
api_hostutility provides the base URL for API requests, centralizing API configuration.PDF Rendering: The
useHighlightTexthook is meant to be used with PDF viewer components, particularly those that allow custom text rendering (e.g.,react-pdf).UI Responsiveness:
useDocumentResizeObserverintegrates with UI components that must adapt to container size, enabling responsive designs.
Mermaid Diagram
flowchart TD
A[useDocumentResizeObserver]
B[useHighlightText]
C[useGetDocumentUrl]
A --> |uses| useSize
B --> |calls| highlightPattern
C --> |calls| useGetKnowledgeSearchParams
C --> |uses| api_host
style A fill:#f9f,stroke:#333,stroke-width:2px
style B fill:#bbf,stroke:#333,stroke-width:2px
style C fill:#bfb,stroke:#333,stroke-width:2px
Summary
The hooks.ts file is a utility module providing specialized React hooks to support document viewing features such as responsive resizing, search term highlighting, and API document URL construction. These hooks abstract common logic to be reused across components dealing with document rendering and interaction, improving maintainability and separation of concerns within the application.