document-hooks.ts
Overview
document-hooks.ts is a utility module containing custom React hooks primarily designed to manage document-related data and operations within a knowledge base or chat system. These hooks abstract asynchronous data fetching, mutation, and state management logic by leveraging React Query and other React utilities, allowing React components to easily interact with backend services related to documents.
The file provides hooks for:
Fetching and searching documents.
Managing document lifecycle: creation, renaming, removal, status updates.
Uploading, parsing, and crawling documents.
Fetching document metadata, thumbnails, and highlights.
Running document-related processes.
Interfacing with backend services (knowledge base and chat) via API calls.
This modular approach enhances code reuse, simplifies component integration, and maintains separation of concerns between UI and data logic.
Detailed Explanation of Exports
Hooks Summary
Hook Name | Purpose |
|---|---|
| Generate a URL to fetch a document file by ID. |
| Build and manage highlights for a document chunk. |
| Search and paginate through documents. |
| Update document active/inactive status. |
| Rename a document. |
| Create a new document in knowledge base. |
| Update parser settings for a document. |
| Upload files to create documents. |
| Initiate web crawl to create documents from web content. |
| Trigger document-related processing tasks. |
| Fetch metadata for multiple documents by IDs. |
| Fetch document thumbnails by IDs. |
| Remove (soft delete) documents. |
| Delete documents permanently. |
| Upload and parse documents, optionally using external service. |
| Parse a document from a URL. |
| Update document metadata. |
Hook Details
useGetDocumentUrl(documentId?: string): () => string
Generate a URL string to fetch a document file by its ID.
Parameters:
documentId(optional): The ID of the document.
Returns:
A function that takes an optional document ID and returns the full URL as a string.
Usage example:
const getUrl = useGetDocumentUrl('doc123');
const url = getUrl(); // Returns `${api_host}/document/get/doc123`
useGetChunkHighlights(selectedChunk: IChunk | IReferenceChunk): { highlights: IHighlight[]; setWidthAndHeight: (width: number, height: number) => void }
Build and manage highlights for a selected document chunk based on its size.
Parameters:
selectedChunk: The selected chunk or reference chunk object.
Returns:
highlights: Array ofIHighlightobjects representing highlights for rendering.setWidthAndHeight: Function to update the size (width & height) of the chunk, recalculating highlights as needed.
Implementation detail:
Uses React's
useStateto track chunk dimensions.Uses
useMemoto memoize highlight calculations for performance.Calls utility
buildChunkHighlightsto generate highlights.
useFetchNextDocumentList()
Manages fetching, searching, and pagination of documents in the current knowledge base.
Returns an object containing:
loading: Boolean indicating if fetching is in progress.searchString: Current search keyword.documents: Array ofIDocumentInfodocuments fetched.pagination: Pagination state including current page, page size, and total results.handleInputChange: Handler function to update search input.setPagination: Function to update pagination state.
Implementation detail:
Uses React Query's
useQueryto fetch documents vialistDocumentservice.Automatically refetches every 15 seconds.
Tied to URL params and search input for reactive data fetching.
useSetNextDocumentStatus()
Mutation hook to update the status (active/inactive) of one or more documents.
Returns:
setDocumentStatus: Async function accepting{ status: boolean, documentId: string | string[] }.data: Result data from the mutation.loading: Boolean indicating mutation in progress.
Implementation detail:
Calls
kbService.document_change_status.On success, shows success message and invalidates the
fetchDocumentListquery to refresh UI.
useSaveNextDocumentName()
Mutation hook to rename a document.
Returns:
saveName: Async function accepting{ name: string; documentId: string }.data: Result data.loading: Mutation loading flag.
Implementation detail:
Calls
kbService.document_rename.Invalidates document list cache on success.
useCreateNextDocument()
Mutation hook to create a new document linked to the current knowledge base.
Returns:
createDocument: Async function accepting document name (string).loading: Loading state.data: Result data.
Implementation detail:
Uses
kbService.document_create.On success, triggers pagination or invalidates document list query to refresh display.
useSetNextDocumentParser()
Mutation hook to update the parser configuration for a document.
Parameters for mutation:
parserId: ID of the parser.documentId: Document ID to update.parserConfig: Parser configuration object.
Returns:
setDocumentParser: Async mutation function.data: Mutation result.loading: Loading indicator.
useUploadNextDocument()
Mutation hook to upload one or multiple files to create or update documents.
Parameters:
Accepts an array of
UploadFileobjects.
Returns:
uploadDocument: Async function to upload files.loading: Upload progress state.data: Response data from server.
Implementation detail:
Uses
FormDatato append files and knowledge base ID.Calls
kbService.document_upload.Handles error and success feedback.
useNextWebCrawl()
Mutation hook to start a web crawling job that creates documents from the provided URL.
Parameters:
Object containing
name(string),url(string).
Returns:
webCrawl: Async mutation function.data: Result code.loading: Loading flag.
useRunNextDocument()
Mutation hook to initiate processing of documents by IDs with options to run or delete.
Parameters:
documentIds: Array of document IDs.run: Number indicating run mode.shouldDelete: Boolean indicating if the document should be deleted after running.
Returns:
runDocumentByIds: Mutation function.loading: Loading state.data: Result data.
useFetchDocumentInfosByIds()
Fetches metadata information for multiple documents by their IDs.
Returns:
data: Array ofIDocumentInfo.setDocumentIds: Setter function to update which document IDs to fetch.
useFetchDocumentThumbnailsByIds()
Fetches thumbnails for multiple documents by their IDs.
Returns:
data: Record mapping document ID to thumbnail URL.setDocumentIds: Setter function for document IDs.
useRemoveNextDocument()
Mutation hook to "remove" (soft delete) documents.
Parameters:
Accepts single or array of document IDs.
Returns:
removeDocument: Async mutation function.data: Response data.loading: Loading state.
useDeleteDocument()
Mutation hook to permanently delete documents.
Parameters:
Array of document IDs.
Returns:
deleteDocument: Async mutation function.data: Response data.loading: Loading state.
useUploadAndParseDocument(uploadMethod: string)
Mutation hook to upload and parse documents, either internally or via an external chat service, depending on uploadMethod.
Parameters:
uploadMethod: String controlling which upload API to use (upload_and_parseor external).
Returns:
uploadAndParseDocument: Mutation function that accepts{ conversationId, fileList }.data: Response data.loading: Loading flag.
useParseDocument()
Mutation hook to parse a document from a URL.
Parameters:
URL string.
Returns:
parseDocument: Mutation function.data: Response data.loading: Loading state.
useSetDocumentMeta()
Mutation hook to update metadata for a document.
Parameters:
An object of type
IDocumentMetaRequestBody.
Returns:
setDocumentMeta: Mutation function.data: Response data.loading: Loading flag.
Important Implementation Details
React Query (
useQuery,useMutation,useQueryClient) is heavily used for data fetching and mutation with built-in caching, background refetching, and cache invalidation.Ant Design's
messageis used for user feedback (success/error notifications).Backend service calls are abstracted through
kbServiceandchatServicemodules.Some hooks integrate with React Router's
useParamsand custom route/pagination hooks to synchronize UI state with URL parameters.Hooks like
useGetChunkHighlightsuse memoization and state to efficiently compute renderable highlights for PDF chunks.Error handling is minimal but present, logging warnings and showing error messages where appropriate.
The module imports TypeScript interfaces to type-check data structures and API payloads.
The file is primarily focused on the "Next" document flow, likely a version or module name in the application.
Interaction with Other Parts of the System
Backend services: Interacts with REST APIs through services such as
kbService(knowledge base) andchatService(chat-related uploads).UI Components: These hooks are designed to be used by React components that manage document views, editors, uploaders, and administrative interfaces.
Routing & Pagination: Integrates with routing hooks (
useParams,useGetPaginationWithRouter,useSetPaginationParams) to keep data in sync with navigation state.Localization: Uses
i18nfor internationalized user messages.Utilities: Uses utility functions like
buildChunkHighlightsto transform data for UI.
Visual Diagram
flowchart TD
A[useGetDocumentUrl]
B[useGetChunkHighlights]
C[useFetchNextDocumentList]
D[useSetNextDocumentStatus]
E[useSaveNextDocumentName]
F[useCreateNextDocument]
G[useSetNextDocumentParser]
H[useUploadNextDocument]
I[useNextWebCrawl]
J[useRunNextDocument]
K[useFetchDocumentInfosByIds]
L[useFetchDocumentThumbnailsByIds]
M[useRemoveNextDocument]
N[useDeleteDocument]
O[useUploadAndParseDocument]
P[useParseDocument]
Q[useSetDocumentMeta]
subgraph Fetching Hooks
C
K
L
end
subgraph Mutation Hooks
D
E
F
G
H
I
J
M
N
O
P
Q
end
A --> C
B --> C
C --> D
C --> E
C --> F
C --> G
C --> H
C --> I
C --> J
C --> M
C --> N
C --> K
C --> L
C --> Q
H --> O
P --> Q
style Fetching Hooks fill:#f9f,stroke:#333,stroke-width:1px,color:#333
style Mutation Hooks fill:#bbf,stroke:#333,stroke-width:1px,color:#333
Summary
document-hooks.ts encapsulates rich and reusable document management logic tailored for a React application using React Query. It streamlines interactions with backend document-related APIs, providing hooks that cover fetching, searching, creating, updating, deleting, uploading, parsing, and processing documents. This modular design facilitates maintainability and scalability of document features within the broader knowledge base or chat platform.