hooks.ts
Overview
The hooks.ts file provides a set of custom React hooks designed to manage and interface with "chunks" of data within a knowledge/document management system. A "chunk" here represents a discrete piece or segment of knowledge or document content, with associated metadata and highlights. These hooks facilitate chunk selection, highlight rendering, text display modes, chunk creation/update, and deletion workflows, encapsulating related state management and side effects for use in React functional components.
This modular approach abstracts chunk-related logic into reusable hooks, promoting separation of concerns and code maintainability in the broader application.
Detailed Descriptions
1. useHandleChunkCardClick
Purpose:
Manages the state of the currently selected chunk ID when a chunk card UI element is clicked.
API:
const { handleChunkCardClick, selectedChunkId } = useHandleChunkCardClick();
handleChunkCardClick(chunkId: string): void
Callback to set the selected chunk ID.selectedChunkId: string
Current selected chunk ID.
Usage Example:
const { handleChunkCardClick, selectedChunkId } = useHandleChunkCardClick();
return (
<ChunkCard onClick={() => handleChunkCardClick(chunk.id)} isSelected={chunk.id === selectedChunkId} />
);
2. useGetSelectedChunk
Purpose:
Retrieves the full chunk data object for a given selected chunk ID from a globally selected chunk list.
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.
Implementation Details:
Uses useSelectChunkList hook to obtain the chunk list and finds the chunk by chunk_id.
Usage Example:
const selectedChunk = useGetSelectedChunk(selectedChunkId);
console.log(selectedChunk.title);
3. useGetChunkHighlights
Purpose:
Generates and manages highlights for the selected chunk based on the current display size. Highlights are used for rendering visual annotations in a PDF/highlight viewer.
Parameters:
selectedChunkId: string— The ID of the chunk for which to build highlights.
Returns:
highlights: IHighlight[]— Array of highlight objects for rendering.setWidthAndHeight(width: number, height: number): void— Setter to update the size, which recalculates highlights.
Implementation Details:
Initializes with default size
{ width: 849, height: 1200 }.Uses
buildChunkHighlightsutility to generate highlights based on the chunk data and size.Memoizes highlights to optimize recalculation only when the chunk or size changes.
Usage Example:
const { highlights, setWidthAndHeight } = useGetChunkHighlights(selectedChunkId);
// On window resize or container resize
setWidthAndHeight(newWidth, newHeight);
4. useChangeChunkTextMode
Purpose:
Manages the display mode of chunk text, toggling between full display and ellipsed (truncated) views.
Returns:
textMode: ChunkTextMode— Current text display mode (enumFullorEllipsis).changeChunkTextMode(mode: ChunkTextMode): void— Function to change the text mode.
Usage Example:
const { textMode, changeChunkTextMode } = useChangeChunkTextMode();
<button onClick={() => changeChunkTextMode(ChunkTextMode.Ellipsis)}>Show Less</button>
5. useDeleteChunkByIds
Purpose:
Provides a function to delete chunks by their IDs with a confirmation modal workflow.
Returns:
removeChunk(chunkIds: string[], documentId: string): Promise<number>
Function that triggers a confirmation modal and, upon confirmation, deletes the specified chunks from the document. Returns a promise resolving to a status code.
Implementation Details:
Uses the
useDeleteChunkhook to perform deletion.Uses
useShowDeleteConfirmto show a confirmation modal before deletion.Wraps deletion in a callback to ensure dependencies are tracked properly.
Usage Example:
const { removeChunk } = useDeleteChunkByIds();
await removeChunk(['chunk1', 'chunk2'], 'doc123');
6. useUpdateChunk
Purpose:
Manages the lifecycle of chunk creation and updating, including modal visibility and form submission handling.
Returns:
chunkUpdatingLoading: boolean— Loading state during chunk creation/update.onChunkUpdatingOk(params: IChunk): Promise<void>— Handler to submit chunk data for creation/update.chunkUpdatingVisible: boolean— Modal visibility state.hideChunkUpdatingModal(): void— Function to hide the modal.showChunkUpdatingModal(id?: string): void— Function to show the modal, optionally for editing an existing chunk by ID.chunkId: string | undefined— Current chunk ID being edited (if any).documentId: string— Current document ID from route params.
Implementation Details:
Uses
useSetModalStatefor modal visibility.Uses
useCreateChunkfor chunk creation/updating API call.Uses
useGetKnowledgeSearchParamsto extract the current document ID from the route.On successful creation/update (
code === 0), hides the modal.
Usage Example:
const {
chunkUpdatingLoading,
onChunkUpdatingOk,
chunkUpdatingVisible,
hideChunkUpdatingModal,
showChunkUpdatingModal,
} = useUpdateChunk();
return (
<>
<button onClick={() => showChunkUpdatingModal()}>Add Chunk</button>
{chunkUpdatingVisible && (
<ChunkUpdateModal
loading={chunkUpdatingLoading}
onOk={onChunkUpdatingOk}
onCancel={hideChunkUpdatingModal}
/>
)}
</>
);
Important Implementation Details and Algorithms
Highlight Generation:
Highlights are generated using thebuildChunkHighlightsutility function, which takes the selected chunk and the current display size to calculate highlight positions and metadata. Memoization (useMemo) is used to prevent unnecessary recalculations.State Management:
Each hook encapsulates local React state (useState) for managing its internal data, such as selected chunk IDs, modal visibility, and text display modes.Modal Handling:
Modal visibility and lifecycle are managed viauseSetModalStateanduseShowDeleteConfirmhooks, abstracting common modal logic.Data Fetching and Mutation:
Hooks likeuseCreateChunk,useDeleteChunk, anduseSelectChunkListabstract API data fetching and mutation operations related to chunks, enabling these hooks to focus on UI logic.
Interaction With Other Parts of the Application
Chunk Data Layer:
Hooks interact with chunk data via imported hooks (useCreateChunk,useDeleteChunk,useSelectChunkList) which likely connect to APIs or global state stores.Modal Management:
Uses common modal management hooks (useSetModalState,useShowDeleteConfirm) for consistent user interactions.Routing:
useGetKnowledgeSearchParamsprovides route-based parameters such asdocumentId, suggesting integration with routing logic (e.g., React Router).Utility Functions:
UsesbuildChunkHighlightsutility to calculate visual highlights, indicating a separation of UI logic and data processing.Constants and Interfaces:
ImportsChunkTextModeenum andIChunkinterface, ensuring type safety and consistent mode values.
Mermaid Diagram - Hook Structure and Relationships
flowchart TD
A[useHandleChunkCardClick]
B[useGetSelectedChunk]
C[useGetChunkHighlights]
D[useChangeChunkTextMode]
E[useDeleteChunkByIds]
F[useUpdateChunk]
A --> B
B --> C
E -->|uses| G[useDeleteChunk]
E -->|uses| H[useShowDeleteConfirm]
F -->|uses| I[useCreateChunk]
F -->|uses| J[useSetModalState]
F -->|uses| K[useGetKnowledgeSearchParams]
style A fill:#f9f,stroke:#333,stroke-width:2px
style B fill:#ccf,stroke:#333,stroke-width:2px
style C fill:#cfc,stroke:#333,stroke-width:2px
style D fill:#fcf,stroke:#333,stroke-width:2px
style E fill:#fcc,stroke:#333,stroke-width:2px
style F fill:#cff,stroke:#333,stroke-width:2px
Summary
The hooks.ts file is a collection of React hooks focusing on managing chunk entities within a knowledge/document application. It encapsulates selection, rendering, updating, and deletion behaviors. The hooks leverage custom imported hooks for data access and modal management, providing a clean interface to components that need chunk-related functionality. The utility-driven approach and React hooks best practices ensure efficient and maintainable UI state logic.
This file forms a critical part of the system's chunk management feature, interfacing with document display components, modal dialogs, and backend APIs.