hooks.ts
Overview
The hooks.ts file contains several custom React hooks and utility functions designed to support document-related UI features in a React application. These hooks primarily handle dynamic resizing of document containers, text highlighting within PDF documents, and generating URLs for fetching document data from an API.
The file facilitates key functionalities such as:
Observing and responding to container size changes for document rendering.
Highlighting search terms in PDF text content.
Constructing document retrieval URLs based on route parameters.
This modular approach using hooks promotes reusability and clean separation of concerns in UI logic related to documents.
Exports and Functionality Details
1. useDocumentResizeObserver
Description
A custom React hook that observes the size of a document container element and provides the current container width. It leverages the useSize hook from the ahooks library, which listens for resize events on DOM elements.
Parameters
None
Returns
An object with:
containerWidth(number | undefined): The current width of the observed container element.setContainerRef((element: HTMLElement | null) => void): A setter function to assign the container element to be observed.
Usage Example
const { containerWidth, setContainerRef } = useDocumentResizeObserver();
return (
<div ref={setContainerRef}>
<SomeDocumentComponent width={containerWidth} />
</div>
);
Implementation Details
Uses React's
useStateto store the container width and container reference.Uses
useSizeto subscribe to resize events on the DOM element referenced bycontainerRef.The
onResizecallback updates thecontainerWidthstate when the size changes.useEffecttriggersonResizewhenever the width changes to keep the state synchronized.
2. highlightPattern
Description
A utility function that wraps matching text patterns in HTML <mark> tags for highlighting purposes, primarily used for PDF text highlighting.
Parameters
text(string): The text snippet to be potentially highlighted.pattern(string): The search pattern or regex string to match against the text.pageNumber(number): The current PDF page number (used for special highlighting logic).
Returns
(
string): The input text wrapped in<mark>tags if matching conditions are met; otherwise, the original or partially marked text.
Usage Notes
Special case: If
pageNumber === 2, the entire text is wrapped in<mark>.If
textis non-empty and matchespattern, the text is wrapped in<mark>.Otherwise, performs a regex replacement to highlight matching parts.
3. useHighlightText
Description
A custom hook that returns a CustomTextRenderer callback for PDF text rendering, which highlights occurrences of a search string within the document.
Parameters
searchText(string, optional): The text pattern to search and highlight in the PDF text. Defaults to an empty string.
Returns
CustomTextRenderer: A callback function compatible with PDF rendering libraries that transforms text items by highlighting matched search terms.
Usage Example
const highlightTextRenderer = useHighlightText("react");
<PdfViewer textRenderer={highlightTextRenderer} />
Implementation Details
Uses
useCallbackto memoize the text renderer function.The renderer applies
highlightPatternto each text item, passing the search text and page number.
4. useGetDocumentUrl
Description
A custom hook that builds the API URL for fetching a document by extracting the documentId from route parameters.
Parameters
None
Returns
(
string): The full URL string to fetch the document JSON or data from the backend API.
Usage Example
const url = useGetDocumentUrl();
// url might be "https://api.example.com/document/get/12345"
Implementation Details
Uses the
useGetKnowledgeSearchParamshook to get the currentdocumentIdfrom the route.Uses
useMemoto memoize the URL string for performance optimization.Concatenates the base API host URL with the document endpoint and ID.
Important Implementation Details
Reactivity and Performance: The hooks utilize React hooks like
useState,useEffect,useCallback, anduseMemoto manage state and avoid unnecessary computations or re-renders.Integration with External Hooks: The file uses
useSizefromahooksto track DOM element resizing anduseGetKnowledgeSearchParamsto interface with route parameters, showing modular integration with other parts of the codebase.Text Highlighting Logic: The highlighting strategy is simple but effective, wrapping matched text in
<mark>tags for CSS-based highlighting. A special-case page number condition is hardcoded, which may reflect a UI requirement.TypeScript Usage: The code is typed, ensuring type safety for parameters and return types, improving maintainability.
Interaction with Other System Components
Route Hook (
useGetKnowledgeSearchParams): This hook depends onuseGetKnowledgeSearchParamsto obtain the current document ID from the routing context, linking document fetching with application navigation.API Utilities (
api_host): The document URL construction relies onapi_hostfrom a utility module, centralizing API endpoint management.PDF Rendering: The
useHighlightTexthook produces aCustomTextRenderercompatible with thereact-pdflibrary, indicating this file is part of a PDF viewer or document reader feature.UI Resizing: The
useDocumentResizeObserverprovides responsive layout support, enabling other components to adapt their rendering based on container dimensions.
Mermaid Diagram
flowchart TD
A[useDocumentResizeObserver] --> B[useSize]
B --> C[containerRef HTMLElement]
A --> D[containerWidth: number]
E[highlightPattern(text, pattern, pageNumber)] -->|returns| F[highlighted string]
G[useHighlightText(searchText)] --> H[highlightPattern]
G --> I[CustomTextRenderer callback]
J[useGetDocumentUrl] --> K[useGetKnowledgeSearchParams]
J --> L[api_host]
J --> M[documentId]
J --> N[document URL string]
style A fill:#f9f,stroke:#333,stroke-width:1px
style E fill:#ccf,stroke:#333,stroke-width:1px
style G fill:#cfc,stroke:#333,stroke-width:1px
style J fill:#fcf,stroke:#333,stroke-width:1px
Summary
The hooks.ts file is a utility-focused module providing essential hooks and helper functions for document-related UI features in a React application. It enables responsive container sizing, text highlighting in PDFs, and API URL generation based on routing context, integrating cleanly with other system parts like routing hooks, API configuration, and PDF rendering components. The code is well-structured, making good use of React hooks and TypeScript for maintainability and performance.