hooks.ts
Overview
The hooks.ts file provides a collection of custom React hooks designed to manage and interact with "chunk" data entities within a knowledge/document management system. These hooks encapsulate state management, data fetching, mutation operations, UI state controls (such as modals and confirmations), and data transformations related to chunks.
Chunks represent segments or pieces of a document or knowledge base, and this file facilitates their selection, creation, updating, deletion, display modes, and highlight rendering. The hooks leverage external utilities, React Query for server state management, and i18n for localization.
Detailed Documentation
1. useHandleChunkCardClick
Purpose
Manages the state of the currently selected chunk ID when a chunk card is clicked.
Returns
handleChunkCardClick(chunkId: string): void
Callback function to update the selected chunk ID.selectedChunkId: string
The currently selected chunk ID.
Usage Example
const { handleChunkCardClick, selectedChunkId } = useHandleChunkCardClick();
return (
<ChunkCard onClick={() => handleChunkCardClick(chunk.id)} isSelected={chunk.id === selectedChunkId} />
);
2. useGetSelectedChunk
Purpose
Retrieves the chunk data object corresponding to a given selectedChunkId.
Parameters
selectedChunkId: string— The ID of the chunk to retrieve.
Returns
IChunk— The chunk object matching the ID or an empty chunk object if not found.
Usage Example
const chunk = useGetSelectedChunk(selectedChunkId);
console.log(chunk.content);
3. useGetChunkHighlights
Purpose
Generates PDF highlights for the selected chunk based on its content and the current display size.
Parameters
selectedChunkId: string— The ID of the chunk whose highlights are to be generated.
Returns
highlights: IHighlight[]— Array of highlight objects formatted for PDF rendering.setWidthAndHeight(width: number, height: number): void— Updates the dimensions used to build highlights (e.g., when the PDF viewer resizes).
Implementation Details
Uses internal state
sizeto track width and height.Calls
buildChunkHighlightsutility to generate highlights based on the chunk and size.
Usage Example
const { highlights, setWidthAndHeight } = useGetChunkHighlights(selectedChunkId);
useEffect(() => {
setWidthAndHeight(containerWidth, containerHeight);
}, [containerWidth, containerHeight]);
4. useChangeChunkTextMode
Purpose
Manages the display mode of chunk text, toggling between fully displayed and truncated (ellipsis) states.
Returns
textMode: ChunkTextMode— Current text display mode (FullorEllipsis).changeChunkTextMode(mode: ChunkTextMode): void— Function to update the text mode.
Usage Example
const { textMode, changeChunkTextMode } = useChangeChunkTextMode();
<button onClick={() => changeChunkTextMode(ChunkTextMode.Ellipsis)}>Show Less</button>
<div className={textMode === ChunkTextMode.Full ? 'full-text' : 'ellipsis-text'}>
{chunk.content}
</div>
5. useDeleteChunkByIds
Purpose
Provides functionality to delete chunks by their IDs, with user confirmation.
Returns
removeChunk(chunkIds: string[], documentId: string): Promise<number>
Initiates the deletion process after showing a confirm dialog. Resolves to a status code.
Implementation Details
Uses
useDeleteChunkhook to perform actual deletion.Uses
useShowDeleteConfirmhook to display a confirmation modal before deletion.Returns a function wrapped in
useCallbackto maintain stable references.
Usage Example
const { removeChunk } = useDeleteChunkByIds();
await removeChunk(['chunk1', 'chunk2'], 'doc123');
6. useUpdateChunk
Purpose
Manages the modal state and mutation logic for creating or updating a chunk.
Returns
chunkUpdatingLoading: boolean— Indicates if the update/create operation is in progress.onChunkUpdatingOk(params: IChunk): Promise<void>— Callback to invoke chunk creation or update.chunkUpdatingVisible: boolean— Modal visibility state.hideChunkUpdatingModal(): void— Function to hide the modal.showChunkUpdatingModal(id?: string): void— Function to show the modal; optionally sets chunk ID for update.chunkId: string | undefined— The current chunk ID being updated.documentId: string— The ID of the document to which the chunk belongs.
Implementation Details
Uses
useCreateChunkhook to perform chunk creation.Retrieves current document ID from route parameters.
On successful creation/update (
code === 0), hides the modal.
Usage Example
const {
chunkUpdatingLoading,
onChunkUpdatingOk,
chunkUpdatingVisible,
hideChunkUpdatingModal,
showChunkUpdatingModal,
} = useUpdateChunk();
if (chunkUpdatingVisible) {
return (
<ChunkUpdateModal
loading={chunkUpdatingLoading}
onOk={onChunkUpdatingOk}
onCancel={hideChunkUpdatingModal}
/>
);
}
7. useFetchParserList
Purpose
Placeholder hook intended to manage fetching state for a list of parsers.
Returns
loading: boolean— Loading state, currently always false.
Note
The implementation is minimal and likely a stub for future expansion.
8. useRerunDataflow
Purpose
Placeholder hook intended to manage rerunning a dataflow operation with loading state.
Returns
loading: boolean— Loading state, currently always false.
9. useFetchPaserText
Purpose
Manages fetching and storing of text data (likely parsed text), with an initial hardcoded multiline string.
Returns
data: string— The current text data.loading: boolean— The loading status of the fetch operation.rerun: (payload: any) => Promise<void>— Function to re-run the mutation to fetch new data.
Implementation Details
Uses React Query's
useMutationto simulate a create chunk operation.Shows a success message on completion.
Invalidates the
fetchChunkListquery after a delay to refresh cached data.Contains commented-out code suggesting integration with a backend service.
Usage Example
const { data, loading, rerun } = useFetchPaserText();
useEffect(() => {
rerun({ somePayload });
}, []);
Important Implementation Details and Algorithms
Highlight Building:
TheuseGetChunkHighlightshook usesbuildChunkHighlightsutility, which presumably processes chunk content and display size to generate highlight objects compatible with PDF rendering. This suggests a spatial mapping algorithm between text content and PDF coordinates.State Management:
Hooks likeuseHandleChunkCardClick,useChangeChunkTextMode, anduseUpdateChunkuse React'suseStateanduseCallbackto maintain and update UI-related state efficiently.Data Mutation and Query Invalidation:
useFetchPaserTextdemonstrates integration with React Query's mutation handling, including cache invalidation (queryClient.invalidateQueries) to keep UI data consistent post-mutations.User Interaction Handling:
useDeleteChunkByIdswraps deletion logic with a confirmation dialog to prevent accidental data loss, enhancing UX safety.
Interaction with Other System Parts
Chunk Data Access:
Hooks likeuseSelectChunkList,useCreateChunk, anduseDeleteChunk(imported from '@/hooks/chunk-hooks') interface with chunk data sources, possibly making API calls or interacting with a global store.Modal and Confirmation UI:
useSetModalStateanduseShowDeleteConfirm(from '@/hooks/common-hooks') manage modal visibility and confirmation dialogs, indicating that this file relies on shared UI state management hooks.Route Parameters:
useGetKnowledgeSearchParamsextracts current document identifiers from routing context, tying chunk operations to the active document.Localization:
TheuseTranslationhook from 'react-i18next' enables localized messages (e.g., success notifications).Utilities:
buildChunkHighlightsassists in transforming chunk data into highlight formats, abstracting away complex highlight calculations.Third-Party Libraries:
Usesreact-queryfor server state,react-pdf-highlighterfor PDF highlights, and a UI message component for notifications.
Mermaid Diagram - Hook Flowchart
flowchart TD
A[useHandleChunkCardClick]
B[useGetSelectedChunk]
C[useGetChunkHighlights]
D[useChangeChunkTextMode]
E[useDeleteChunkByIds]
F[useUpdateChunk]
G[useFetchParserList]
H[useRerunDataflow]
I[useFetchPaserText]
A --> B
B --> C
E -->|calls| useDeleteChunk
F -->|calls| useCreateChunk
F -->|uses| useSetModalState
E -->|uses| useShowDeleteConfirm
F -->|uses| useGetKnowledgeSearchParams
I -->|uses| useMutation
I -->|uses| useQueryClient
style A fill:#f9f,stroke:#333,stroke-width:2px
style B fill:#bbf,stroke:#333,stroke-width:2px
style C fill:#bbf,stroke:#333,stroke-width:2px
style D fill:#f96,stroke:#333,stroke-width:2px
style E fill:#fc9,stroke:#333,stroke-width:2px
style F fill:#9cf,stroke:#333,stroke-width:2px
style G fill:#eee,stroke:#333,stroke-width:1px
style H fill:#eee,stroke:#333,stroke-width:1px
style I fill:#9f9,stroke:#333,stroke-width:2px
Summary
The hooks.ts file centralizes chunk-related business logic and UI state management in a React environment. It abstracts complex interactions with chunk data including selection, display, mutation, and deletion, while integrating with UI modals, confirmations, and localized messaging. This modular design promotes reusability and separation of concerns across the application layers that manage knowledge/document chunks.