hooks.ts
Overview
The hooks.ts file provides a collection of custom React hooks used primarily for managing document-related workflows within a knowledge management or dataset application. These hooks abstract and encapsulate UI state management (e.g., modal visibility), asynchronous operations (e.g., API calls for creating, renaming, uploading documents), and navigation actions related to document handling, uploading, parsing, and crawling web content.
Each hook typically combines state management (using React's useState and useCallback) with API interaction hooks imported from shared modules like document-hooks and modal state hooks from common-hooks. This modular approach improves code reusability and keeps component code clean by separating concerns of document operations and UI state.
Exports: Detailed Explanation of Hooks
1. useNavigateToOtherPage
Purpose:
Provides navigation functions to switch between knowledge dataset upload pages and document chunk pages, incorporating the current knowledge context.
Functions:
linkToUploadPage: Navigates to the dataset upload page with the current knowledge ID as a query parameter.toChunk(id: string): Navigates to the chunk view page for a specific document ID with the current knowledge ID.
Usage Example:
const { linkToUploadPage, toChunk } = useNavigateToOtherPage();
linkToUploadPage(); // navigates to upload page
toChunk('doc123'); // navigates to chunk page for document 'doc123'
2. useRenameDocument
Parameters:
documentId: string- The ID of the document to rename.
Returns:
renameLoading: boolean- Loading state of the rename operation.onRenameOk(name: string): Promise<void>- Function to call when renaming is confirmed.Modal control booleans and functions:
renameVisible,hideRenameModal,showRenameModal.
Description:
Manages modal visibility and handles renaming a document by calling saveName. If rename succeeds (returns code 0), modal is hidden.
Usage Example:
const { renameLoading, onRenameOk, renameVisible, showRenameModal, hideRenameModal } = useRenameDocument('docId');
showRenameModal();
if (!renameLoading) {
await onRenameOk('New Document Name');
}
3. useCreateEmptyDocument
Returns:
createLoading: boolean- Loading indicator for document creation.onCreateOk(name: string): Promise<void>- Function to create a new document with the given name.Modal control:
createVisible,hideCreateModal,showCreateModal.
Description:
Manages modal state and document creation process via createDocument hook. Hides modal on success.
4. useChangeDocumentParser
Parameters:
documentId: string- The document whose parser configuration is to be changed.
Returns:
changeParserLoading: boolean- Loading state for parser change.onChangeParserOk(parserId: string, parserConfig: IChangeParserConfigRequestBody): Promise<void>- Executes parser change.Modal control:
changeParserVisible,hideChangeParserModal,showChangeParserModal.
Description:
Handles showing/hiding modal and changing the document parser config via setDocumentParser. Modal closes on success.
5. useGetRowSelection
Returns:
rowSelection: TableRowSelection<IDocumentInfo>- Ant Design table row selection object.
Description:
Manages selected row keys state for table row selection, exposing the selection object compatible with Ant Design tables.
6. useHandleUploadDocument
Returns:
documentUploadLoading: boolean- Loading state of the upload process.onDocumentUploadOk(params: { parseOnCreation: boolean; directoryFileList: UploadFile[] }): Promise<number | undefined>- Handles document upload logic.Modal control:
documentUploadVisible,hideDocumentUploadModal,showDocumentUploadModal.Upload state:
uploadFileList(current files),setUploadFileList(setter),uploadProgress(percent),setUploadProgress.
Description:
This is a complex hook managing multi-step file upload with progress status updates and batch processing in chunks of 10 files. It updates UI file upload statuses, handles directory uploads, and optionally triggers parsing after upload. The upload is done using uploadDocument, and documents can be run/executed after upload via runDocumentByIds.
Important Algorithm Details:
Files are processed in batches of 10 to avoid large payloads.
Upload statuses (
uploading,done,error) are dynamically updated per file.Upload progress percentage is calculated and updated during batch processing.
After successful upload, documents can be automatically parsed if
parseOnCreationis true.
7. useHandleWebCrawl
Returns:
webCrawlUploadLoading: boolean- Loading indicator for web crawl.onWebCrawlUploadOk(name: string, url: string): Promise<number>- Performs web crawling upload.Modal control:
webCrawlUploadVisible,hideWebCrawlUploadModal,showWebCrawlUploadModal.
Description:
Handles the modal and API interaction for crawling web content by name and URL, using webCrawl hook.
8. useHandleRunDocumentByIds
Parameters:
id: string- Document ID to track loading state.
Returns:
handleRunDocumentByIds(documentId: string, isRunning: boolean, shouldDelete?: boolean): Promise<void>- Function to run or stop running a document by ID.loading: boolean- Loading state specific to the current tracked document ID.
Description:
Manages running/stopping document processing by IDs, with loading state scoped to a single document to avoid concurrent runs.
9. useShowMetaModal
Parameters:
documentId: string- Document ID for setting metadata.
Returns:
setMetaLoading: boolean- Loading state for meta update.onSetMetaModalOk(meta: string): Promise<void>- Sets metadata for the document.Modal control:
setMetaVisible,hideSetMetaModal,showSetMetaModal.
Description:
Manages modal visibility and setting document metadata via setDocumentMeta. Modal closes on success.
Implementation Details & Algorithms
Modal State Management:
Most hooks useuseSetModalStatefromcommon-hooksto handle modal visibility (visible,showModal,hideModal) uniformly.Batch File Uploading (in
useHandleUploadDocument):
Splits file uploads into batches of 10 for controlled uploading. Updates progress and file statuses dynamically. Handles errors by marking files as 'error' and successful files as 'done'.Optimistic UI Updates:
File statuses and progress are updated immediately when upload starts to provide responsive feedback.Loading State Scoped by ID:
useHandleRunDocumentByIdstracks loading state scoped to the current document ID to prevent running multiple operations on different documents simultaneously.
Interaction with Other Parts of the System
Common Hooks:
ImportsuseSetModalStatefor modal control.Document Hooks:
Imports multiple hooks from@/hooks/document-hooksthat perform API operations such as creating documents, uploading, parsing, renaming, running, setting meta, and web crawling.Route Hook:
UsesuseGetKnowledgeSearchParamsto extract query parameters for navigation.UI Library:
Interfaces with Ant Design components, particularly for file uploads (UploadFile) and table row selection (TableRowSelection).Routing:
UsesuseNavigatefromumifor page navigation.Constants:
UsesKnowledgeRouteKeyfor constructing route URLs.
The file acts as an intermediary layer that bridges UI components and API hooks, managing UI state, side effects, and user interactions related to knowledge documents and datasets.
Mermaid Diagram: Hook Structure and Relationships
flowchart TD
A[useNavigateToOtherPage]
B[useRenameDocument]
C[useCreateEmptyDocument]
D[useChangeDocumentParser]
E[useGetRowSelection]
F[useHandleUploadDocument]
G[useHandleWebCrawl]
H[useHandleRunDocumentByIds]
I[useShowMetaModal]
subgraph ModalState [Modal State Management]
MS[useSetModalState]
end
subgraph DocumentHooks [Document API Hooks]
CD[useCreateNextDocument]
RN[useSaveNextDocumentName]
UP[useUploadNextDocument]
RP[useRunNextDocument]
SP[useSetNextDocumentParser]
SM[useSetDocumentMeta]
WC[useNextWebCrawl]
end
subgraph Routing [Routing & Params]
UN[useNavigate]
GP[useGetKnowledgeSearchParams]
end
A --> UN
A --> GP
B --> RN
B --> MS
C --> CD
C --> MS
D --> SP
D --> MS
E
F --> UP
F --> RP
F --> MS
G --> WC
G --> MS
H --> RP
I --> SM
I --> MS
Summary
hooks.ts is a centralized utility file providing custom React hooks to manage document lifecycle actions such as navigation, creation, renaming, uploading, parsing, running, metadata updates, and web crawling. It cleverly combines modal state management, file upload batching, API interactions, and navigation to streamline UI logic related to knowledge dataset management in a React + Umi + Ant Design environment.
This modular design promotes maintainability and clarity by abstracting common document workflows into reusable hooks, easing integration into React components.