hooks.ts
Overview
The hooks.ts file contains several custom React hooks designed to facilitate document-related UI behaviors and data fetching within a React application. The main functionalities provided by this file include:
Observing and reacting to container width changes dynamically (
useDocumentResizeObserver).Highlighting specific text patterns within document text renderers (
useHighlightText).Constructing the URL to fetch a document resource based on dynamic route parameters (
useGetDocumentUrl).
These hooks abstract common logic related to document rendering, resizing, and fetching, improving reusability and separation of concerns in the application.
Detailed Explanations
1. useDocumentResizeObserver
A React hook that tracks the width of a DOM element and updates state accordingly. It uses the useSize hook from the ahooks library to listen to size changes of a referenced container element.
Purpose
To provide responsive UI behavior by monitoring the width of a container element dynamically and exposing this width to consuming components.
Implementation Details
Maintains two pieces of state:
containerWidth— current width of the container (number, in pixels).containerRef— a ref callback to attach to the container DOM element.
Uses
useSizeto detect size changes for the referenced container element.Uses
useEffectto updatecontainerWidthwhenever the detected width changes.The
onResizecallback ensures that width updates only happen when a valid width is available.
Return Value
An object with:
containerWidth— the current width of the observed container.setContainerRef— a setter function to assign the DOM element whose size is to be observed.
Usage Example
const MyComponent = () => {
const { containerWidth, setContainerRef } = useDocumentResizeObserver();
return (
<div ref={setContainerRef}>
<p>The container width is: {containerWidth}px</p>
</div>
);
};
2. highlightPattern
A utility function that wraps matched text patterns with HTML <mark> tags to highlight them.
Parameters
text: string— The text content to search within.pattern: string— The pattern to match for highlighting.pageNumber: number— The current page number, used for conditional logic.
Return Value
A string representing the original text with matched substrings wrapped in
<mark>tags.
Implementation Details
If the page number is exactly 2, highlights the entire
textby wrapping it in<mark>.Otherwise, if the text is non-empty and fully matches the pattern (via
.match()), the entire text is wrapped in<mark>.If neither condition applies, it attempts to replace occurrences of the pattern inside the text with highlighted versions.
Note: The function currently uses simple string replacement and matching; regex or more sophisticated parsing might be needed for advanced use cases.
3. useHighlightText
A React hook that returns a text renderer function compatible with react-pdf's custom text rendering API, applying text highlighting based on a search string.
Parameters
searchText: string(optional, default'') — The text pattern to highlight in the PDF document.
Return Value
A
CustomTextRenderercallback function that receives atextItemand returns an HTML string with matched text highlighted.
Implementation Details
Uses
useCallbackto memoize the text renderer function for performance.Delegates the highlighting logic to the
highlightPatternfunction, passing the text content, the search text, and the page number.
Usage Example
const MyPdfViewer = ({ searchText }) => {
const textRenderer = useHighlightText(searchText);
return (
<Document file="sample.pdf">
<Page pageNumber={1} customTextRenderer={textRenderer} />
</Document>
);
};
4. useGetDocumentUrl
A hook that computes the URL from which a document can be fetched, based on the document ID extracted from route parameters.
Implementation Details
Uses the
useGetKnowledgeSearchParamshook (imported from@/hooks/route-hook) to get the currentdocumentIdfrom the URL or search parameters.Uses
useMemoto compute the full URL string only whendocumentIdchanges.Constructs the URL by combining a global API host (
api_host) with a fixed endpoint path including the document ID.
Return Value
A string representing the document fetch URL.
Usage Example
const DocumentLoader = () => {
const url = useGetDocumentUrl();
useEffect(() => {
fetch(url)
.then(response => response.blob())
.then(blob => {
// handle the document blob
});
}, [url]);
return <div>Loading document...</div>;
};
Important Implementation Details and Algorithms
Resize Observation: The
useDocumentResizeObserverhook leverages theuseSizehook fromahooksto automatically detect size changes without manually setting up aResizeObserver, simplifying the resize logic.Text Highlighting: The
highlightPatternfunction uses basic string matching and replacement to wrap matched text with<mark>tags. This approach works for straightforward cases but may have limitations with complex patterns or overlapping matches.Memoization & Callbacks: Hooks use React's
useCallbackanduseMemoto optimize performance by memoizing functions and computed values, reducing unnecessary recalculations or rerenders.Dependency on Route Params: The
useGetDocumentUrlhook depends on another custom hook (useGetKnowledgeSearchParams), indicating that this file fits within a routing-aware application where document IDs are passed via URL parameters.
Interaction with Other System Parts
Routing: The
useGetDocumentUrlhook depends onuseGetKnowledgeSearchParamsfrom the route-hook file, implying integration with the app's routing logic to extract document identifiers.API Layer: The
api_hostimport from@/utils/apishows this file uses a configured API base URL, ensuring consistent endpoint construction across the app.PDF Rendering: The
useHighlightTexthook’s return type corresponds toreact-pdf’sCustomTextRenderer, suggesting that components rendering PDF documents consume this hook to enable search term highlighting.UI Responsiveness: The
useDocumentResizeObserverhook is intended to be used in UI components that need to respond to container size changes, e.g., for responsive layouts or adaptive rendering.
Mermaid Diagram
flowchart TD
A[useDocumentResizeObserver] -->|uses| B[useSize (ahooks)]
A --> C[State: containerWidth, containerRef]
A --> D[Callback: onResize]
A --> E[Effect: update containerWidth on size change]
F[highlightPattern] --> G[Input: text, pattern, pageNumber]
F --> H[Output: highlighted string]
I[useHighlightText] --> J[useCallback: textRenderer]
J -->|calls| F[highlightPattern]
K[useGetDocumentUrl] --> L[useGetKnowledgeSearchParams]
K --> M[useMemo: url based on documentId]
K --> N[Returns: document fetch URL]
style A fill:#f9f,stroke:#333,stroke-width:2px
style F fill:#bbf,stroke:#333,stroke-width:2px
style I fill:#f9f,stroke:#333,stroke-width:2px
style K fill:#f9f,stroke:#333,stroke-width:2px
Summary
The hooks.ts file encapsulates reusable logic related to document UI and data fetching:
It abstracts container resize detection to handle responsive layouts.
It provides text highlighting utilities for PDF rendering.
It dynamically builds document URLs from route parameters.
This modular design enables clean, maintainable, and efficient integration of document-related features in the broader React application.