hooks.ts
Overview
The hooks.ts file exports a collection of custom React hooks primarily designed to facilitate file and folder management functionalities within a frontend application. These hooks abstract common UI and data management patterns such as modal state handling, file operations (create, rename, delete, move, upload), navigation between folders, and integration with external knowledge bases.
The hooks leverage React's useState, useCallback, and useMemo for state and performance optimizations, alongside utility hooks from libraries such as umi for routing and Ant Design for UI components. The hooks also interact with backend operations through imported API hooks (e.g., useRenameFile, useDeleteFile) encapsulating the actual data fetching and mutations.
This file acts as a middle layer connecting UI components with business logic and backend services, simplifying component code by encapsulating complex behaviors and state management related to file/folder operations.
Detailed Hook Descriptions
useGetFolderId
Purpose:
Extracts the current folder ID from the URL search parameters.
Parameters:
None.
Returns:
string: The folder ID from the current URL’s query parameterfolderId. Returns an empty string if no ID is present.
Usage Example:
const folderId = useGetFolderId();
console.log(folderId); // e.g., "12345"
useGetRowSelection
Purpose:
Manages the selection state of file rows in a table, providing selection control and disabling selection of files originating from the 'knowledgebase'.
Parameters:
None.
Returns:
rowSelection: TableRowSelection<IFile>— Object for Ant Design table row selection config, including disabled checkboxes for knowledgebase files.setSelectedRowKeys: React.Dispatch<React.SetStateAction<React.Key[]>>— Setter function for selected keys.
Implementation Details:
Uses React's useState to track selected rows. Disables selection for rows where source_type === 'knowledgebase'.
Usage Example:
const { rowSelection, setSelectedRowKeys } = useGetRowSelection();
// Pass rowSelection to Ant Design Table component
<Table rowSelection={rowSelection} />
useNavigateToOtherFolder
Purpose:
Provides a function to navigate programmatically to a different folder by updating the URL.
Parameters:
None.
Returns:
(folderId: string) => void— Function to navigate to a folder URL with the given folderId.
Implementation Details:
Uses useNavigate from umi to navigate.
Usage Example:
const navigateToOtherFolder = useNavigateToOtherFolder();
navigateToOtherFolder('folder123'); // Navigates to /file?folderId=folder123
useRenameCurrentFile
Purpose:
Manages the state and modal logic for renaming a file.
Parameters:
None.
Returns:
An object containing:
fileRenameLoading: boolean— Loading state of rename operation.initialFileName: string— Initial name of the file to pre-fill in the rename modal.onFileRenameOk: (name: string) => Promise<void>— Callback to execute when rename confirmed.fileRenameVisible: boolean— Modal visibility state.hideFileRenameModal: () => void— Function to hide the modal.showFileRenameModal: (record: IFile) => void— Function to show modal with the selected file.
Implementation Details:
Uses
useStateto keep track of the current file being renamed.Uses
useSetModalStateto handle modal visibility state.Calls
renameFilemutation hook to perform rename operation and closes modal on success.
Usage Example:
const {
fileRenameLoading,
initialFileName,
onFileRenameOk,
fileRenameVisible,
hideFileRenameModal,
showFileRenameModal,
} = useRenameCurrentFile();
showFileRenameModal(selectedFile);
useSelectBreadcrumbItems
Purpose:
Generates breadcrumb navigation items based on the current folder's parent hierarchy.
Parameters:
None.
Returns:
Array<{ title: string; path: string }>— List of breadcrumb items, with root folder renamed from '/' to 'root'.
Implementation Details:
Fetches parent folder list via useFetchParentFolderList hook and transforms it into breadcrumb objects.
Usage Example:
const breadcrumbItems = useSelectBreadcrumbItems();
// [{ title: 'root', path: '/file?folderId=rootId' }, {...}]
useHandleCreateFolder
Purpose:
Handles the creation of a new folder within the current folder context, including modal state and operation status.
Parameters:
None.
Returns:
An object containing:
folderCreateLoading: boolean— Loading state for folder creation.onFolderCreateOk: (name: string) => Promise<void>— Callback to create a folder with given name.folderCreateModalVisible: boolean— Modal visibility.hideFolderCreateModal: () => void— Hide modal function.showFolderCreateModal: () => void— Show modal function.
Implementation Details:
Uses current folder ID (useGetFolderId) as the parent for new folders.
Usage Example:
const {
folderCreateLoading,
onFolderCreateOk,
folderCreateModalVisible,
hideFolderCreateModal,
showFolderCreateModal,
} = useHandleCreateFolder();
showFolderCreateModal();
useHandleDeleteFile
Purpose:
Provides functionality to delete selected files with a confirmation dialog.
Parameters:
fileIds: string[]— Array of IDs for files to delete.setSelectedRowKeys: (keys: string[]) => void— Setter to clear selection after deletion.
Returns:
handleRemoveFile: () => void— Function to trigger deletion after confirmation.
Implementation Details:
Shows a confirmation modal via useShowDeleteConfirm. Calls removeDocument mutation hook to delete files and clears selection on success.
Usage Example:
const { handleRemoveFile } = useHandleDeleteFile(selectedFileIds, setSelectedRowKeys);
handleRemoveFile();
useHandleUploadFile
Purpose:
Manages file upload modal and uploading process.
Parameters:
None.
Returns:
An object containing:
fileUploadLoading: boolean— Upload loading state.onFileUploadOk: (fileList: UploadFile[]) => Promise<number | undefined>— Upload callback for files.fileUploadVisible: boolean— Modal visibility.hideFileUploadModal: () => void— Hide modal function.showFileUploadModal: () => void— Show modal function.
Implementation Details:
Uses current folder ID for upload destination. Uploads files via uploadFile mutation hook.
Usage Example:
const {
fileUploadLoading,
onFileUploadOk,
fileUploadVisible,
hideFileUploadModal,
showFileUploadModal,
} = useHandleUploadFile();
showFileUploadModal();
useHandleConnectToKnowledge
Purpose:
Handles connecting a file to one or more knowledge bases, including modal state and connection logic.
Parameters:
None.
Returns:
An object containing:
initialValue: string[]— Initial knowledge base IDs connected to the file.connectToKnowledgeLoading: boolean— Loading state for connection operation.onConnectToKnowledgeOk: (knowledgeIds: string[]) => Promise<number>— Handler to connect file to knowledge bases.connectToKnowledgeVisible: boolean— Modal visibility state.hideConnectToKnowledgeModal: () => void— Hide modal function.showConnectToKnowledgeModal: (record: IFile) => void— Show modal with selected file record.
Implementation Details:
Stores the selected file in local state. Maps kbs_info to extract knowledge base IDs.
Usage Example:
const {
initialValue,
connectToKnowledgeLoading,
onConnectToKnowledgeOk,
connectToKnowledgeVisible,
hideConnectToKnowledgeModal,
showConnectToKnowledgeModal,
} = useHandleConnectToKnowledge();
showConnectToKnowledgeModal(selectedFile);
useHandleBreadcrumbClick
Purpose:
Provides a handler to navigate when a breadcrumb element is clicked.
Parameters:
None.
Returns:
handleBreadcrumbClick: (path?: string) => void— Function to navigate to a given path.
Implementation Details:
Uses useNavigate from umi.
Usage Example:
const { handleBreadcrumbClick } = useHandleBreadcrumbClick();
handleBreadcrumbClick('/file?folderId=123');
useHandleMoveFile
Purpose:
Manages moving files from one folder to another, including modal display and operation handling.
Parameters:
setSelectedRowKeys: (keys: string[]) => void— Setter to clear selection post-move.
Returns:
An object containing:
initialValue: string— Initial target folder ID (empty string).moveFileLoading: boolean— Loading state for move operation.onMoveFileOk: (targetFolderId: string) => Promise<number>— Handler to move files to target folder.moveFileVisible: boolean— Modal visibility.hideMoveFileModal: () => void— Hide modal function.showMoveFileModal: (ids: string[]) => void— Show modal with selected source file IDs.
Implementation Details:
Keeps track of source file IDs in state. Calls moveFile mutation hook and clears selection on success.
Usage Example:
const {
moveFileLoading,
onMoveFileOk,
moveFileVisible,
hideMoveFileModal,
showMoveFileModal,
} = useHandleMoveFile(setSelectedRowKeys);
showMoveFileModal(['fileId1', 'fileId2']);
Important Implementation Details and Algorithms
Modal State Management:
Most hooks managing UI modals use theuseSetModalStatehook (imported from common hooks) to encapsulate visibility state and functions to show/hide modals. This promotes consistent modal behavior and reduces boilerplate.API Operation Hooks:
All data mutations or fetches (e.g.,renameFile,createFolder,deleteFile,uploadFile,moveFile,connectFileToKnowledge) are abstracted into separate hooks imported fromfile-manager-hooks. This separation keeps UI logic decoupled from API logic.React Performance Optimizations:
Hooks utilizeuseCallbackto memoize event handlers to prevent unnecessary re-renders anduseMemoto compute derived data likeinitialValuefor knowledge base IDs.Selective Row Disabling:
InuseGetRowSelection, rows representing files from the knowledge base are disabled for selection, enforcing business rules on what files can be operated on.
Interaction with Other System Components
Common Hooks (
common-hooks):
Provides modal management and delete confirmation utilities leveraged by multiple hooks in this file.File Manager Hooks (
file-manager-hooks):
Contains API-related hooks that perform CRUD operations on files and folders, whichhooks.tsuses to implement higher-level UI logic.Interfaces (
IFile):
Defines the shape of file objects used throughout the hooks.Routing (
umi):
React router utilities (useNavigate,useSearchParams) are used for URL navigation and query parameter parsing.UI Components (Ant Design):
Table row selection types and upload file abstractions from Ant Design are used for type safety and UI integration.
This file acts as a bridge between UI components (such as tables, modals, and navigation bars) and backend services, enabling a modular and maintainable approach to file management features.
Visual Diagram
flowchart TD
useGetFolderId["useGetFolderId()"]
useGetRowSelection["useGetRowSelection()"]
useNavigateToOtherFolder["useNavigateToOtherFolder()"]
useRenameCurrentFile["useRenameCurrentFile()"]
useSelectBreadcrumbItems["useSelectBreadcrumbItems()"]
useHandleCreateFolder["useHandleCreateFolder()"]
useHandleDeleteFile["useHandleDeleteFile(fileIds, setSelectedRowKeys)"]
useHandleUploadFile["useHandleUploadFile()"]
useHandleConnectToKnowledge["useHandleConnectToKnowledge()"]
useHandleBreadcrumbClick["useHandleBreadcrumbClick()"]
useHandleMoveFile["useHandleMoveFile(setSelectedRowKeys)"]
subgraph ModalStateHooks["Modal State Management"]
useRenameCurrentFile
useHandleCreateFolder
useHandleUploadFile
useHandleConnectToKnowledge
useHandleMoveFile
end
subgraph FileOperations["File & Folder Operations"]
useRenameCurrentFile
useHandleCreateFolder
useHandleDeleteFile
useHandleUploadFile
useHandleConnectToKnowledge
useHandleMoveFile
end
subgraph Navigation["Navigation & Selection"]
useGetFolderId
useGetRowSelection
useNavigateToOtherFolder
useSelectBreadcrumbItems
useHandleBreadcrumbClick
end
%% Relationships
useRenameCurrentFile --> FileOperations
useHandleCreateFolder --> FileOperations
useHandleDeleteFile --> FileOperations
useHandleUploadFile --> FileOperations
useHandleConnectToKnowledge --> FileOperations
useHandleMoveFile --> FileOperations
useRenameCurrentFile --> ModalStateHooks
useHandleCreateFolder --> ModalStateHooks
useHandleUploadFile --> ModalStateHooks
useHandleConnectToKnowledge --> ModalStateHooks
useHandleMoveFile --> ModalStateHooks
useNavigateToOtherFolder --> Navigation
useSelectBreadcrumbItems --> Navigation
useHandleBreadcrumbClick --> Navigation
useGetRowSelection --> Navigation
useGetFolderId --> Navigation
Summary
The hooks.ts file provides a comprehensive suite of reusable hooks that manage complex UI state and backend interactions for file and folder management in a React application. By abstracting logic into these hooks, the system achieves modularity, ease of maintenance, and clear separation between UI and data operations. The file integrates tightly with modal management utilities, API hooks, and navigation utilities to provide an efficient developer experience when building file management features.