hooks.ts
Overview
This file hooks.ts provides a collection of custom React hooks that manage the state and behavior related to "chunks" within a knowledge/document management system. A "chunk" represents a segment or portion of a document, possibly with associated highlights and metadata. The hooks facilitate interactions such as selecting chunks, displaying chunk highlights, toggling chunk text display modes, deleting chunks, and updating chunk information.
These hooks abstract and encapsulate complex logic related to chunk operations, enabling components to easily manage chunk-related UI states and CRUD (Create, Read, Update, Delete) operations while interacting with backend services through other hooks.
Detailed Explanation of Exports
1. useHandleChunkCardClick
Purpose
Manages the selection state of a chunk card by storing the currently selected chunk's ID.
API
const { handleChunkCardClick, selectedChunkId } = useHandleChunkCardClick();
handleChunkCardClick(chunkId: string): void
Callback to update the selected chunk ID.selectedChunkId: string
Currently selected chunk's ID.
Usage Example
const { handleChunkCardClick, selectedChunkId } = useHandleChunkCardClick();
return (
<div onClick={() => handleChunkCardClick(chunk.chunk_id)}>
{chunk.title} {selectedChunkId === chunk.chunk_id && "(Selected)"}
</div>
);
2. useGetSelectedChunk
Purpose
Retrieves the chunk data object corresponding to a selected chunk ID from the global chunk list.
Parameters
selectedChunkId: string— The ID of the currently selected chunk.
Returns
IChunk— The chunk object matching the given ID, or an empty chunk object if not found.
Usage Example
const selectedChunk = useGetSelectedChunk(selectedChunkId);
console.log(selectedChunk.text);
3. useGetChunkHighlights
Purpose
Computes and returns the highlight annotations for the currently selected chunk, along with a setter to update the display size (width and height), which influences highlight positioning.
Parameters
selectedChunkId: string— ID of the currently selected chunk.
Returns
{
highlights: IHighlight[], // Array of highlight objects related to the chunk
setWidthAndHeight: (width: number, height: number) => void // Setter for display size
}
Important Implementation Details
Internally, it uses
buildChunkHighlights(selectedChunk, size)from a utility to build highlight data based on the chunk content and display size.The highlights are memoized with
useMemofor performance optimization.The display size state (
widthandheight) defaults to 849x1200 and can be updated by the consumer.
Usage Example
const { highlights, setWidthAndHeight } = useGetChunkHighlights(selectedChunkId);
// On PDF viewer resize event:
setWidthAndHeight(newWidth, newHeight);
4. useChangeChunkTextMode
Purpose
Manages the display mode of chunk text content, allowing toggling between showing full text or an ellipsized (truncated) preview.
Returns
{
textMode: ChunkTextMode, // Current text mode (Full or Ellipse)
changeChunkTextMode: (mode: ChunkTextMode) => void // Function to change the mode
}
Usage Example
const { textMode, changeChunkTextMode } = useChangeChunkTextMode();
return (
<button onClick={() => changeChunkTextMode(ChunkTextMode.Ellipse)}>Show Less</button>
);
5. useDeleteChunkByIds
Purpose
Provides a function to delete one or multiple chunks by their IDs, showing a confirmation modal before deletion.
Returns
{
removeChunk: (chunkIds: string[], documentId: string) => Promise<number>
}
removeChunk(chunkIds, documentId)
Initiates the delete process for specified chunk IDs belonging to a document. It first shows a confirmation modal, then calls the backend deletion hook.
Important Implementation Details
Uses
useDeleteChunk()for the actual delete API call.Uses
useShowDeleteConfirm()to display a confirmation dialog.The deletion is only performed if the user confirms the action.
Usage Example
const { removeChunk } = useDeleteChunkByIds();
await removeChunk(['chunk1', 'chunk2'], 'doc123');
6. useUpdateChunk
Purpose
Handles the updating or creating of a chunk, including managing the modal state for the update form and invoking the chunk creation API.
Returns
{
chunkUpdatingLoading: boolean, // Loading state during chunk update
onChunkUpdatingOk: (params: IChunk) => Promise<void>, // Handler to execute chunk update
chunkUpdatingVisible: boolean, // Modal visibility state
hideChunkUpdatingModal: () => void, // Function to hide the modal
showChunkUpdatingModal: (id?: string) => void, // Function to show the modal, optionally with chunk ID
chunkId: string | undefined, // Current chunk ID being edited
documentId: string | undefined // Current document ID from route params
}
Important Implementation Details
Uses
useCreateChunk()to perform the create/update call.Uses
useSetModalState()to control modal visibility.Retrieves the current
documentIdfrom route parameters viauseGetKnowledgeSearchParams().On successful update (indicated by a return code
0), the modal is hidden.
Usage Example
const {
chunkUpdatingLoading,
onChunkUpdatingOk,
chunkUpdatingVisible,
showChunkUpdatingModal,
hideChunkUpdatingModal,
chunkId,
} = useUpdateChunk();
const handleSave = async (chunkData) => {
await onChunkUpdatingOk(chunkData);
};
Important Implementation Details and Algorithms
Highlight Building:
The file uses a utility functionbuildChunkHighlightswhich converts chunk data and display dimensions into highlight annotations compatible with thereact-pdf-highlighterformat (IHighlight[]).State Management:
Most hooks rely on React'suseStateanduseCallbackto manage and memoize stateful logic, optimizing performance and preventing unnecessary re-renders.Modal State:
Modal visibility and control is consistently managed through the shareduseSetModalStatehook, ensuring a standard approach for modal dialogs across the app.API Interaction:
Chunk CRUD operations delegate to hooks likeuseCreateChunkanduseDeleteChunk, which presumably handle asynchronous interaction with backend services. The hooks here wrap those calls with UI logic like confirmation dialogs and loading states.Route Parameters:
ThedocumentIdis fetched from the routing context (useGetKnowledgeSearchParams) and used to associate chunk operations with the correct document.
Interaction With Other Parts of the System
Chunk Hooks (
chunk-hooks):
Provides low-level data fetching and mutation hooks such asuseCreateChunk,useDeleteChunk, anduseSelectChunkList.Common Hooks (
common-hooks):
Manages modal state and confirmation dialogs through hooks likeuseSetModalStateanduseShowDeleteConfirm.Route Hooks (
route-hook):
Supplies route-specific parameters (e.g.,documentId) usinguseGetKnowledgeSearchParams.Utilities (
document-util):
ContainsbuildChunkHighlightsutility to convert chunk data into highlight representations.Interfaces:
UsesIChunkinterface for chunk data structure andIHighlightfor PDF highlight annotations.Constants:
UsesChunkTextModeenum to manage text display modes.
These interactions indicate that hooks.ts acts as a higher-level orchestrator, combining data access, UI state, and user interactions related to document chunks.
Mermaid Diagram
The following flowchart illustrates the relationships and data flow between the main custom hooks in this file and their key interactions:
flowchart TD
subgraph ChunkSelection
A1[useHandleChunkCardClick]
A2[useGetSelectedChunk]
A3[useGetChunkHighlights]
end
subgraph TextDisplay
B1[useChangeChunkTextMode]
end
subgraph ChunkModification
C1[useDeleteChunkByIds]
C2[useUpdateChunk]
end
subgraph ExternalHooks
D1[useCreateChunk]
D2[useDeleteChunk]
D3[useSelectChunkList]
D4[useSetModalState]
D5[useShowDeleteConfirm]
D6[useGetKnowledgeSearchParams]
D7[buildChunkHighlights]
end
A1 --> A2
A2 --> A3
A3 --> D7
C1 --> D2
C1 --> D5
C2 --> D1
C2 --> D4
C2 --> D6
A2 --> D3
Summary
Purpose: Manage chunk selection, highlighting, text display mode, deletion, and update operations in a centralized manner.
Techniques: Uses React hooks (
useState,useCallback,useMemo) to manage state and side effects.Integration: Interfaces smoothly with backend API hooks and UI modal/confirmation hooks.
Benefit: Simplifies chunk-related UI logic for components, promotes code reuse, and maintains separation of concerns.
This file is a crucial part of the chunk management feature in the application, serving as the bridge between UI components, backend APIs, and utility functions related to document chunk handling.