use-import-json.ts
Overview
The use-import-json.ts file defines a custom React hook named useHandleImportJsonFile that facilitates importing and processing JSON files within a React application. Its primary responsibility is to manage the user interaction flow related to uploading JSON files representing graph data, validate the file type and content, parse the JSON into a specific data structure, and then update the application state accordingly.
This hook integrates modal visibility state management, file validation, JSON parsing, error handling, and toast notifications to provide a seamless user experience when importing JSON files, particularly for setting or updating an "agent" configuration within the app.
Detailed Explanation
Hook: useHandleImportJsonFile
export const useHandleImportJsonFile = () => { ... }
Description
This custom hook exposes functionality for handling the import process of a JSON file containing graph data. It manages modal visibility for file upload, validates the uploaded file type and content, parses the JSON, and updates the agent state if successful.
Returned Object Properties
Property | Type | Description |
|---|---|---|
|
| Indicates whether the file upload modal is currently visible. |
|
| Function to show the file upload modal (trigger import dialog). |
|
| Function to hide the file upload modal. |
|
| Async handler called when the user confirms file upload; validates and processes the file. |
|
| Represents the loading state during the agent setting operation. |
Internal Dependencies
useSetModalState: Custom hook providing modal state (visible,showModal,hideModal).useTranslation: React i18n hook for localization.useToast: Custom hook for toast notification display.useSetAgent: Custom hook to update the agent configuration and loading state.FileMimeType.Json: Constant string representing the MIME type "application/json".EmptyDsl: Default DSL (domain-specific language) object template.antdmessage: UI feedback for errors.lodash/isEmpty: Utility to check empty objects.React's
useCallbackfor memoization.
Method: onFileUploadOk
async ({ fileList, name }: FormSchemaType) => void
Description
This asynchronous callback is triggered when the user confirms the file upload in the modal. It performs several key steps:
Checks if any files were uploaded.
Validates the MIME type of the first file is JSON.
Reads the file content as text.
Attempts to parse the JSON string.
Checks the parsed object to ensure it contains a non-empty
nodesarray.If valid, merges the parsed graph into the
EmptyDsltemplate and updates the agent state.If invalid or an error occurs, shows error messages via toast or antd message.
Parameters
Parameter | Type | Description |
|---|---|---|
|
| Array of files uploaded by the user. |
|
| The name/title associated with the uploaded file. |
Returns
Promise<void> — completes after processing or error handling.
Usage Example
const {
fileUploadVisible,
handleImportJson,
hideFileUploadModal,
onFileUploadOk,
loading,
} = useHandleImportJsonFile();
// To open the file import modal
handleImportJson();
// When a file is selected and confirmed in the modal form:
await onFileUploadOk({ fileList: [selectedFile], name: selectedFile.name });
Important Implementation Details
File Type Validation: The hook strictly enforces that only JSON files (MIME type
"application/json") are accepted. If the file type does not match, a localized toast error message is shown.Content Validation: After parsing JSON, the hook verifies that the data contains a
nodesarray which is non-empty. This ensures the file represents a valid graph structure expected by the application.Error Handling: Both parsing errors and validation failures are handled gracefully with user feedback via Ant Design's
message.erroror toast notifications.State Management: The hook relies on other hooks for managing modal visibility (
useSetModalState), agent state (useSetAgent), and toast notifications (useToast), promoting separation of concerns and modularity.Localization: Uses
react-i18nextfor all user-facing strings, enabling internationalization.
Interaction with Other Parts of the System
Modal Management: Uses
useSetModalStateto control the display of the JSON file upload modal dialog, coordinating UI visibility.Agent Configuration: Uses
useSetAgentto update the central agent state with the imported graph DSL, thus affecting downstream components or workflows that consume this agent data.Toast and Message Notifications: Uses both a custom
useToasthook and Ant Design'smessagecomponent to provide user feedback, integrating with the app's notification system.Constants and Types: Relies on shared constants like
FileMimeType.Jsonand types likeFormSchemaTypeto ensure consistent validation and form handling.Localization System: Integrates with
react-i18nextfor translation support, ensuring messages are localized.
Visual Diagram
Below is a Mermaid flowchart showing the main functions and their relationships within use-import-json.ts:
flowchart TD
A[useHandleImportJsonFile Hook]
A --> B[fileUploadVisible state]
A --> C[handleImportJson (show modal)]
A --> D[hideFileUploadModal (hide modal)]
A --> E[onFileUploadOk(fileList, name)]
A --> F[loading state]
E --> G{fileList.length > 0?}
G -- No --> H[Do nothing]
G -- Yes --> I[file = fileList[0]]
I --> J{file.type === JSON?}
J -- No --> K[toast error: invalid file type]
J -- Yes --> L[Read file.text()]
L --> M[Parse JSON]
M --> N{Valid graph?}
N -- Yes --> O[Create DSL with graph]
O --> P[setAgent({title, dsl})]
P --> Q[hideFileUploadModal()]
N -- No --> R[message.error(content error)]
M -->|catch| R
Summary
The use-import-json.ts file encapsulates the logic for importing and validating JSON files representing graph data within a React application. It provides a reusable hook that manages modal visibility, user interactions, file validation, JSON parsing, error handling, and updates the application's agent state accordingly. By modularizing this functionality, it enables other components or pages to easily integrate JSON import features with consistent user feedback and localization support.
If you have any questions or need further clarification on specific parts of this file, feel free to ask!