hooks.ts
Overview
The hooks.ts file contains a collection of custom React hooks designed to facilitate various functionalities related to question-answering workflows, data retrieval, UI state management, and asynchronous data fetching within a knowledge base or chat application context. These hooks abstract complex logic such as sending questions to backend APIs, retrieving relevant data chunks, managing pagination, fetching background images, and handling modal visibility for mind map visualizations.
Each hook encapsulates specific functionality, enabling reusable, composable logic that can be integrated into React components seamlessly.
Detailed Documentation
1. useSendQuestion(kbIds: string[], tenantId?: string)
Manages the lifecycle of sending a question to the backend and retrieving answers, related questions, and document chunks associated with a knowledge base.
Parameters:
kbIds: string[]— Array of knowledge base IDs used to scope the question.tenantId?: string — Optional tenant identifier for multi-tenant environments.
Returns:
An object containing:
sendQuestion(question: string): void — Function to send a question.
handleSearchStrChange: ChangeEventHandler — Handler for updating the search input.
handleClickRelatedQuestion(question: string): () => void — Returns a click handler to send a related question.
handleTestChunk(documentIds: string[], page?: number, size?: number): void — Fetches highlighted document chunks based on the current search string and selected documents.
setSelectedDocumentIds: React.Dispatch<React.SetStateAction<string[]>>— Setter for selected document IDs.loading: boolean— Loading state of chunk retrieval.sendingLoading: boolean— Loading state of sending the question.answer: IAnswer— Current answer object.relatedQuestions: string[] — Up to 5 related questions fetched.
searchStr: string— Current search string.setSearchStr: React.Dispatch<React.SetStateAction> — Setter for search string.
isFirstRender: boolean — Flag indicating if it is the first render.
selectedDocumentIds: string[]— Currently selected document IDs.isSearchStrEmpty: boolean — Boolean indicating if the trimmed search string is empty.
stopOutputMessage(): void — Function to stop receiving streamed answer data.
Usage Example:
const {
sendQuestion,
handleSearchStrChange,
answer,
relatedQuestions,
sendingLoading,
} = useSendQuestion(['kb1', 'kb2'], 'tenantA');
const onSubmit = () => {
sendQuestion('What is React?');
};
Implementation Details:
Uses
useSendMessageWithSseto send the question and receive real-time streamed answers.Calls
useTestChunkRetrievalanduseTestChunkAllRetrievalto fetch highlighted document chunks related to the question.Fetches related questions using
useFetchRelatedQuestions.Manages UI states such as loading and search string.
Handles pagination reset on new questions.
Prevents sending empty or whitespace-only questions.
2. useFetchBackgroundImage()
Fetches the daily Bing background image URL for display purposes.
Returns:
string— The full URL of the fetched background image.
Usage Example:
const backgroundImageUrl = useFetchBackgroundImage();
return <img src={backgroundImageUrl} alt="Background" />;
Implementation Details:
Calls the Bing API endpoint
/HPImageArchive.aspxto get image metadata.Extracts the image URL from the JSON response.
Returns a full URL prefixed with
https://cn.bing.com.Handles and logs any fetch errors gracefully.
3. useTestRetrieval(kbIds: string[], searchStr: string, sendingLoading: boolean)
Manages retrieval and highlighting of document chunks based on a search string and selected documents.
Parameters:
kbIds: string[]— Knowledge base IDs to query.searchStr: string— Current search string.sendingLoading: boolean— Boolean indicating if a question is currently being sent (used to avoid overlapping requests).
Returns:
loading: boolean— Loading state of chunk retrieval.selectedDocumentIds: string[]— Array of selected document IDs.setSelectedDocumentIds: React.Dispatch<React.SetStateAction<string[]>>— Setter for selected document IDs.
Usage Example:
const { loading, selectedDocumentIds, setSelectedDocumentIds } = useTestRetrieval(['kb1'], 'React hooks', false);
Implementation Details:
Calls
useTestChunkRetrievalto fetch highlighted chunks.Automatically triggers chunk retrieval when dependencies change.
Manages selection state of document IDs for filtering.
4. useShowMindMapDrawer(kbIds: string[], question: string, searchId?: string)
Controls the visibility and data fetching of a mind map modal drawer based on a question and knowledge base context.
Parameters:
kbIds: string[]— Knowledge base IDs.question: string— The question string for which the mind map is fetched.searchId?: string— Optional search identifier.
Returns:
mindMap: any— Data representing the fetched mind map.mindMapVisible: boolean— Visibility state of the mind map modal.mindMapLoading: boolean— Loading state for mind map fetching.showMindMapModal(): void— Function to show the mind map modal and fetch data.hideMindMapModal(): void— Function to hide the mind map modal.
Usage Example:
const { mindMap, mindMapVisible, showMindMapModal, hideMindMapModal } = useShowMindMapDrawer(['kb1'], 'Explain React hooks');
<button onClick={showMindMapModal}>Show Mind Map</button>
{mindMapVisible && <MindMapModal data={mindMap} onClose={hideMindMapModal} />}
Implementation Details:
Uses
useSetModalStateto manage modal show/hide state.Fetches mind map data using
useSearchFetchMindMap.Ensures data is only fetched if the question or kbIds have changed since last fetch.
Uses a
refto store last fetched parameters for comparison.
5. usePendingMindMap()
Provides a progress indicator for pending mind map generation.
Returns:
number— Progress percentage (0 to 100), incrementing every second until capped at ~93%.
Usage Example:
const progress = usePendingMindMap();
return <ProgressBar value={progress} />;
Implementation Details:
Uses an interval timer to increment a count every second.
Caps the count to prevent infinite increments.
Converts count to a percentage of the total expected duration (43 seconds).
Cleans up the interval on component unmount.
Important Implementation Details / Algorithms
Streaming Answer Reception: The
useSendQuestionhook leverages Server-Sent Events (SSE) viauseSendMessageWithSseto stream answers in real-time, updating the state as data arrives.Debouncing / Early Termination: Prevents sending or fetching data if the search string is empty or if a request is currently being processed (
sendingLoading).Caching with Refs:
useShowMindMapDrawerusesuseRefto avoid redundant mind map fetches for identical parameters.Pagination Integration: Pagination state is synchronized with the router via
useGetPaginationWithRouter, allowing consistent navigation and data loading.Background Image Fetching: A simple async fetch with error handling to retrieve daily Bing images, useful for dynamic UI backgrounds.
Interaction with Other Parts of the System
API Utilities: Uses
api.askandapi.askSharefor question submission endpoints.Other Custom Hooks:
useFetchRelatedQuestionsto get related queries.useTestChunkRetrievalanduseTestChunkAllRetrievalfor document chunk retrieval.useGetPaginationWithRouterto manage pagination state synced with routing.useSendMessageWithSsefor SSE-based streaming messages.useSetModalStatefor modal visibility management.useSearchFetchMindMapto fetch mind map data.
Interfaces: Uses
IAnswerinterface to type chat answers.Third-party Libraries: Utilizes lodash for utility functions (
get,isEmpty,isEqual,trim).React Core: Hooks like
useState,useEffect,useCallback,useRef, and event handlers for controlled input.
File Structure and Workflow Diagram
flowchart TD
A[useSendQuestion] --> B[useSendMessageWithSse]
A --> C[useTestChunkRetrieval]
A --> D[useTestChunkAllRetrieval]
A --> E[useFetchRelatedQuestions]
A --> F[useGetPaginationWithRouter]
G[useFetchBackgroundImage] --> H[fetch Bing API]
I[useTestRetrieval] --> C[useTestChunkRetrieval]
I --> F[useGetPaginationWithRouter]
J[useShowMindMapDrawer] --> K[useSetModalState]
J --> L[useSearchFetchMindMap]
M[usePendingMindMap] --> N[setInterval timer]
style A fill:#f9f,stroke:#333,stroke-width:2px
style G fill:#ccf,stroke:#333,stroke-width:2px
style I fill:#9f9,stroke:#333,stroke-width:2px
style J fill:#fc9,stroke:#333,stroke-width:2px
style M fill:#cff,stroke:#333,stroke-width:2px
Summary
The hooks.ts file is a centralized place for React hooks that manage:
Sending and streaming answers to user questions.
Retrieving and highlighting relevant document chunks.
Managing search input and related questions.
Fetching UI assets like background images.
Showing and controlling mind map modal dialogs.
Tracking progress in mind map generation.
These hooks integrate tightly with backend APIs, application routing, and UI modals, offering a clean abstraction layer for business logic in the application.
If you need further details on any specific hook or integration, please let me know!