use-watch-change.ts
Overview
The use-watch-change.ts file provides React hooks and utility functions designed to facilitate reactive form state management within a graphical node-based editor, likely a workflow or pipeline builder. It primarily integrates react-hook-form's form watching capabilities with a global state management store (useGraphStore) to keep the UI canvas and form data synchronized.
The file handles:
Converting form argument and output schemas into structured objects for internal state representation.
Watching form changes and propagating updates to the global graph store.
Handling programming language changes by updating code templates and outputs accordingly.
This design ensures that when users modify form fields related to node configurations—such as changing parameters, outputs, or the scripting language—the visual representation and underlying data model remain consistent and up-to-date.
Detailed Explanations
Utility Functions
convertToObject
function convertToObject(list: FormSchemaType['arguments'] = []): Record<string, string>
Purpose: Converts an array of argument objects into an object keyed by argument names with values being their types.
Parameters:
list: An array of argument schemas, each with propertiesname(string) andtype(string). Defaults to an empty array if not provided.
Returns:
An object mapping argument names to their types, e.g.,
{ argName1: 'string', argName2: 'number' }.
Usage:
Used internally to transform form arguments into a shape suitable for updating node states.
convertOutputsToObject
function convertOutputsToObject({ lang, outputs }: FormSchemaType): ICodeForm['outputs']
Purpose: Converts the form output schema into a structured object keyed by output names, each containing a default
value(empty string) andtype.Parameters:
lang: The programming language selected (fromProgrammingLanguageenum).outputs: The outputs definition, which can be either an array or an object depending on the language.
Returns:
An object representing outputs with initialized
valueandtypefields, e.g.,{ outputName: { value: '', type: 'string' } }.
Implementation Details:
For Python, outputs are expected as an array, so it reduces the array into the object shape.
For other languages, outputs are expected as an object and handled accordingly.
Usage:
Prepares output data for synchronization with the graph store and UI.
React Hooks
useWatchFormChange
export function useWatchFormChange(
id?: string,
form?: UseFormReturn<FormSchemaType>,
): void
Purpose: React hook that watches form changes and updates the corresponding node's form data in the graph store whenever the form data changes.
Parameters:
id: The unique identifier of the node whose form data is being watched.form: The react-hook-form object representing the node's form.
Returns:
None.
Behavior:
Uses
useWatchfromreact-hook-formto observe form values.On form changes (
isDirty), it converts arguments and outputs into the required object formats.Calls
updateNodeFormfrom the global graph store to update the node's data.
Example Usage:
const form = useForm<FormSchemaType>();
useWatchFormChange(nodeId, form);
This hook ensures that any change in the form fields immediately reflects on the graphical node's state.
useHandleLanguageChange
export function useHandleLanguageChange(
id?: string,
form?: UseFormReturn<FormSchemaType>,
): (lang: string) => void
Purpose: Provides a callback to handle changes in the programming language selection, updating the code template and resetting outputs accordingly.
Parameters:
id: The node ID associated with the form.form: The react-hook-form instance.
Returns:
A callback function
(lang: string) => voidthat when called, updates thescriptandoutputsfields of the form and updates the graph store.
Behavior:
Retrieves the code template string associated with the selected language from
CodeTemplateStrMap.Sets the form's
scriptfield to the template.Resets the
outputsfield to an empty array for Python or an empty object for other languages.Calls
updateNodeFormto sync changes with the global graph state.
Example Usage:
const form = useForm<FormSchemaType>();
const handleLanguageChange = useHandleLanguageChange(nodeId, form);
// On language selection change:
handleLanguageChange('Python');
This hook abstracts the logic for updating language-dependent form fields and ensures consistency in the node data.
Important Implementation Details and Algorithms
Type-Dependent Output Conversion:
The outputs field of the form can be either an array or an object depending on the selected programming language. This duality is handled by type extraction (ExtractandExclude) and conditional logic to correctly transform outputs into the expected object shape.State Synchronization:
The form's local state is watched viauseWatch. On every relevant change (formState.isDirty), the hook forces a read of current values (getValues()) to ensure the update reflects the latest user input, then updates the global graph state usingupdateNodeForm.Global Store Interaction:
TheuseGraphStorehook is used to access and update the global graph-related state, particularly the form data associated with nodes identified byid.Immutable Update Pattern:
The update process creates new object structures for arguments and outputs, maintaining immutability best practices to avoid unintended side effects.
Interaction with Other System Parts
Graph Store (
useGraphStore):
This file interacts closely with the global graph state managed byuseGraphStore. It uses theupdateNodeFormmethod to synchronize form changes with the central store that presumably manages the canvas and node data.Constants and Interfaces:
It importsProgrammingLanguageandCodeTemplateStrMapfrom constants, which provide language enums and code templates, respectively. It also uses theFormSchemaTypeinterface to type the form data structure.Form Management (
react-hook-form):
The file leveragesreact-hook-formfor form state management and uses itsuseWatchhook to react to form changes efficiently.Utility (
lodash):
UsesisEmptyfrom lodash to safely check for empty output objects.
Visual Diagram
classDiagram
class useWatchFormChange {
+id?: string
+form?: UseFormReturn<FormSchemaType>
+void
}
class useHandleLanguageChange {
+id?: string
+form?: UseFormReturn<FormSchemaType>
+handleLanguageChange(lang: string): void
}
class convertToObject {
+list: FormSchemaType['arguments']
+Record<string, string>
}
class convertOutputsToObject {
+formSchema: FormSchemaType
+ICodeForm['outputs']
}
useWatchFormChange --> useGraphStore : calls updateNodeForm
useHandleLanguageChange --> useGraphStore : calls updateNodeForm
useWatchFormChange --> convertToObject : calls
useWatchFormChange --> convertOutputsToObject : calls
useHandleLanguageChange --> CodeTemplateStrMap : reads templates
Summary
The use-watch-change.ts file encapsulates core logic for synchronizing form data changes with a global graph state in a node-based editor environment. It provides:
Utility functions to transform form schemas into internal data structures.
React hooks to watch form changes and update the graph store.
Language change handlers to reset code templates and outputs appropriately.
This modular approach improves maintainability, ensures data consistency between the form UI and graphical nodes, and cleanly separates concerns between form state management and graph data synchronization.