use-export-json.ts
Overview
The use-export-json.ts file defines a custom React hook useHandleExportOrImportJsonFile that manages the import and export of flow graph data in JSON format within a React application. This hook provides functionalities to:
Export the current flow graph data as a downloadable JSON file.
Import a flow graph JSON file uploaded by the user, validate its content and update the application state accordingly.
Control the visibility of the file upload modal dialog used for importing JSON files.
This hook integrates with other hooks and utilities in the system to enable seamless serialization and deserialization of flow graph data, facilitating persistence and restoration of flow states.
Detailed Explanation
useHandleExportOrImportJsonFile
Description
This is a React custom hook that encapsulates the logic for exporting and importing flow graph JSON files. It manages modal visibility state, file validation, parsing, and updates the flow graph state on successful import.
Returns
An object containing:
Property | Type | Description |
|---|---|---|
|
| Controls the visibility state of the import JSON file modal. |
| Function to export the current flow graph data to a JSON file. | |
| Function to show the file upload modal for importing JSON files. | |
| Function to hide the file upload modal. | |
| Async function to handle the file upload confirmation, parse and validate JSON, and update graph state. |
Internal Hook Dependencies
useBuildDslData: Provides a methodbuildDslDatato generate the DSL (Domain Specific Language) representation of the graph.useSetModalState: Manages modal visibility state withshowModal,hideModal, andvisible.useSetGraphInfo: Setter hook to update the flow graph state.useFetchFlow: Fetches the current flow data, including metadata like flow title.useTranslation: Provides i18n translation functiont.
Parameters
The hook itself takes no parameters, but internally:
onFileUploadOkreceives an array of Ant DesignUploadFileobjects representing files selected by the user.
Usage Example
import React from 'react';
import { Button, Modal, Upload } from 'antd';
import { useHandleExportOrImportJsonFile } from './use-export-json';
const FlowExportImportComponent = () => {
const {
fileUploadVisible,
handleExportJson,
handleImportJson,
hideFileUploadModal,
onFileUploadOk,
} = useHandleExportOrImportJsonFile();
return (
<>
<Button onClick={handleExportJson}>Export Flow JSON</Button>
<Button onClick={handleImportJson}>Import Flow JSON</Button>
<Modal
visible={fileUploadVisible}
onCancel={hideFileUploadModal}
footer={null}
title="Import Flow JSON"
>
<Upload
accept=".json"
beforeUpload={() => false} // Prevent automatic upload
onChange={({ fileList }) => onFileUploadOk(fileList)}
maxCount={1}
>
<Button>Select JSON File</Button>
</Upload>
</Modal>
</>
);
};
Implementation Details
Importing JSON
When a user selects a file and confirms upload,
onFileUploadOkis triggered.It checks if the file type is JSON (
application/json).Reads the file content asynchronously using
File.text().Parses the JSON string into an object, then validates:
The parsed object is non-empty.
It includes a
nodesproperty which is an array.
If validation passes, updates the graph state using
setGraphInfo.Shows error messages using Ant Design's
message.errorand translated strings if validation or parsing fails.
Exporting JSON
The
handleExportJsonfunction obtains the current graph DSL data by callingbuildDslData().Uses
downloadJsonFileutility to trigger a browser download of the JSON file.The filename is based on the current flow's title with
.jsonextension.
Modal Control
useSetModalStatemanages the modal visibility:fileUploadVisible,showFileUploadModal, andhideFileUploadModal.handleImportJsonsimply callsshowFileUploadModalto open the modal.
Interaction With Other System Parts
Flow Data Fetching: Uses
useFetchFlowto get the current flow metadata, such as the title, which is used in naming the exported file.Graph State Management: Uses
useSetGraphInfoto update the flow graph stored in application state.DSL Construction: Uses
useBuildDslDatato generate the DSL representation of the graph for export.File Utilities: Uses
downloadJsonFileutility to download files in JSON format.UI Components: Ant Design's
messagefor notifications andUploadFiletype for file upload handling.Localization: Uses
react-i18nextfor translating user-facing messages.
Mermaid Flowchart Diagram
The following flowchart outlines the main functions and their relationships in use-export-json.ts:
flowchart TD
A[useHandleExportOrImportJsonFile] --> B[buildDslData()]
A --> C[useFetchFlow.data]
A --> D[useSetGraphInfo]
A --> E[useSetModalState]
A --> F[useTranslation.t]
A --> G[onFileUploadOk(fileList)]
A --> H[handleExportJson()]
A --> I[handleImportJson()]
G --> J[Validate file type]
J --> K{Is JSON?}
K -- No --> L[Show error: Invalid file type]
K -- Yes --> M[Read file text]
M --> N[Parse JSON]
N --> O{Valid graph object?}
O -- No --> P[Show error: Invalid content]
O -- Yes --> Q[Update graph state (setGraphInfo)]
Q --> R[Hide upload modal (hideFileUploadModal)]
H --> S[Generate DSL data]
S --> T[Download JSON file with flow title]
I --> U[Show upload modal (showFileUploadModal)]
Summary
use-export-json.ts provides a focused, reusable hook to handle the export and import of flow graphs in JSON format. It abstracts file validation, modal management, and state synchronization, while integrating with other hooks and utilities in the application. This helps maintain clean separation of concerns and enhances maintainability and user experience for flow persistence features.