index.tsx
Overview
index.tsx is a React functional component file that implements the Chunk page of a document management or chunk processing application. The primary purpose of this file is to:
Display a paginated list of document "chunks" (segments or parts of a document).
Allow users to select, edit, delete, enable/disable, and paginate through chunks.
Provide a preview of the document (specifically for PDFs).
Manage chunk-related UI state and interactions, including multi-selection and mode switching.
Integrate with various hooks and child components to handle chunk data fetching, updates, deletion, and UI behavior.
The component leverages Ant Design (antd) for UI elements such as Pagination, Spin, and message, and also uses custom hooks for data fetching and chunk state management.
Component and Hook Details
Component: Chunk
The default exported React functional component that handles the chunk management UI and logic.
State Variables
selectedChunkIds: string[]
Holds the IDs of currently selected chunks for batch operations.
Imported Hooks and Their Roles
useFetchNextChunkList()
Fetches chunk data with pagination and filtering support. Returns chunk list, total count, loading state, pagination controls, and search-related handlers.useDeleteChunkByIds()
Provides a method to remove chunks by their IDs.useHandleChunkCardClick()
Manages the currently selected chunk ID and click behavior on chunk cards.useChangeChunkTextMode()
Toggles the text display mode of chunks (e.g., plain text vs rich text).useSwitchChunk()
Enables toggling the availability status of chunks (e.g., enable/disable).useUpdateChunk()
Handles chunk update modal visibility, loading state, and update confirmation.useGetChunkHighlights(chunkId: string | undefined)
Returns highlighting information for the selected chunk to be used in the document preview.
Detailed Explanation of Functions and Methods
Pagination Change Handler
const onPaginationChange: PaginationProps['onShowSizeChange'] = (page, size) => {
setSelectedChunkIds([]);
pagination.onChange?.(page, size);
};
Purpose: Clears selected chunks and triggers page/size change in pagination.
Parameters:
page: number- New page number.size: number- Number of items per page.
Returns: void
Usage: Passed to the
Paginationcomponent'sonChangehandler.
Select or Deselect All Chunks
const selectAllChunk = useCallback(
(checked: boolean) => {
setSelectedChunkIds(checked ? data.map((x) => x.chunk_id) : []);
},
[data],
);
Purpose: Selects all chunks if
checkedis true, otherwise deselects all.Parameters:
checked: boolean- Whether to select (true) or deselect (false) all.
Returns: void
Usage: Used by toolbar checkbox to select/deselect all chunks.
Handle Single Chunk Checkbox Click
const handleSingleCheckboxClick = useCallback(
(chunkId: string, checked: boolean) => {
setSelectedChunkIds((previousIds) => {
const idx = previousIds.findIndex((x) => x === chunkId);
const nextIds = [...previousIds];
if (checked && idx === -1) {
nextIds.push(chunkId);
} else if (!checked && idx !== -1) {
nextIds.splice(idx, 1);
}
return nextIds;
});
},
[],
);
Purpose: Adds or removes a chunk ID from
selectedChunkIdsbased on checkbox state.Parameters:
chunkId: string- The ID of the chunk clicked.checked: boolean- Whether the chunk is being selected (true) or deselected (false).
Returns: void
Usage: Passed to individual
ChunkCardcomponents to update selection.
Show Warning Message if No Chunk Selected
const showSelectedChunkWarning = useCallback(() => {
message.warning(t('message.pleaseSelectChunk'));
}, [t]);
Purpose: Displays a warning to prompt the user to select at least one chunk before performing batch operations.
Returns: void
Usage: Called before batch operations like delete or switch if no chunks are selected.
Remove Selected Chunks
const handleRemoveChunk = useCallback(async () => {
if (selectedChunkIds.length > 0) {
const resCode: number = await removeChunk(selectedChunkIds, documentId);
if (resCode === 0) {
setSelectedChunkIds([]);
}
} else {
showSelectedChunkWarning();
}
}, [selectedChunkIds, documentId, removeChunk, showSelectedChunkWarning]);
Purpose: Deletes selected chunks from the backend and clears selection if successful.
Returns: Promise
Usage: Invoked when the user clicks the remove button on the toolbar.
Switch Availability Status of Chunks
const handleSwitchChunk = useCallback(
async (available?: number, chunkIds?: string[]) => {
let ids = chunkIds;
if (!chunkIds) {
ids = selectedChunkIds;
if (selectedChunkIds.length === 0) {
showSelectedChunkWarning();
return;
}
}
const resCode: number = await switchChunk({
chunk_ids: ids,
available_int: available,
doc_id: documentId,
});
if (!chunkIds && resCode === 0) {
// Optional post-success behavior
}
},
[switchChunk, documentId, selectedChunkIds, showSelectedChunkWarning],
);
Purpose: Toggles availability for one or multiple chunks.
Parameters:
available?: number- Availability status to set (e.g., 0 or 1).chunkIds?: string[]- List of chunk IDs to apply change; defaults to selected chunks.
Returns: Promise
Usage: Used by toolbar and chunk cards to enable/disable chunks.
Rendered UI Structure
Toolbar (
ChunkToolBar): Controls for selecting all, creating, removing, switching availability, text mode toggling, and searching chunks.Divider: Visual separator.
Chunk List:
Paginated list of chunks rendered via
ChunkCardcomponents.Loading spinner shown during data fetching.
Pagination Component: Controls page navigation and page size.
Document Preview (
DocumentPreview): Shows document preview if it is a PDF.Chunk Update Modal (
CreatingModal): Modal dialog for creating or editing chunks, shown conditionally.
Important Implementation Details
State Synchronization: The component maintains chunk selection state locally, synchronized with user interactions on checkboxes and batch actions.
Conditional Rendering: The document preview is only visible if the document type is PDF.
Performance Optimization: Uses
useCallbackhooks to memoize handlers and prevent unnecessary re-renders.Integration of Custom Hooks: Each custom hook encapsulates a specific responsibility (fetching, deleting, updating, switching chunks), promoting modularity and separation of concerns.
Internationalization: Uses
react-i18nextfor localized messages.UI Consistency: Styling is applied through CSS modules (
stylesimported fromindex.less), andclassnamesis used for conditional class management.
Interaction with Other System Parts
Hooks: Interacts heavily with custom hooks located in the same module or shared hooks (
@/hooks/chunk-hooks), which handle API calls and business logic.Child Components:
ChunkCard— Individual chunk item UI.CreatingModal— Modal for chunk creation/editing.ChunkToolBar— Toolbar with batch operation controls.DocumentPreview— Visual preview of PDF documents.
Ant Design Components: Provides UI elements like pagination, loading spinner, and messages.
Translation Layer: Uses
react-i18nextfor multi-language support.CSS Module: Styling and layout are managed via
index.less.
Usage Example
import React from 'react';
import Chunk from './index';
const App = () => {
return (
<div>
<h1>Document Chunk Manager</h1>
<Chunk />
</div>
);
};
export default App;
This renders the Chunk management interface where users can view, select, edit, paginate, and preview chunks of a document.
Mermaid Component Diagram
componentDiagram
Chunk <|-- ChunkToolBar
Chunk <|-- ChunkCard
Chunk <|-- CreatingModal
Chunk <|-- DocumentPreview
ChunkToolBar : selectAllChunk()
ChunkToolBar : createChunk()
ChunkToolBar : removeChunk()
ChunkToolBar : switchChunk()
ChunkToolBar : changeChunkTextMode()
ChunkCard : editChunk()
ChunkCard : handleCheckboxClick()
ChunkCard : switchChunk()
ChunkCard : clickChunkCard()
CreatingModal : visible
CreatingModal : loading
CreatingModal : onOk()
CreatingModal : hideModal()
DocumentPreview : highlights
DocumentPreview : setWidthAndHeight()
Summary
index.tsx defines a comprehensive React component for managing document chunks with features like multi-selection, batch actions, pagination, real-time updates, and PDF document preview. It integrates multiple custom hooks and child components to deliver a modular, maintainable, and user-friendly interface. The file serves as the core chunk management UI in the broader application.