use-watch-change.ts
Overview
The use-watch-change.ts file provides React hooks and utility functions designed to synchronize and manage form state changes within a graphical node-based editor environment. It primarily integrates with react-hook-form to watch form inputs and updates a graph store representing nodes on a canvas. The file also manages language-dependent form adjustments, such as changing code templates and output formats depending on the selected programming language.
This file plays a critical role in keeping the form UI and the underlying node data model synchronized, enabling a seamless and reactive user experience in applications involving dynamic code/script editing and multi-language support.
Detailed Documentation
Utility Functions
convertToObject(list: FormSchemaType['arguments'] = []): Record<string, string>
Converts an array of argument objects to a key-value map where keys are argument names and values are their types.
Parameters:
list: Array of argument objects (FormSchemaType['arguments']), each having at leastnameandtypeproperties.
Returns: An object mapping argument names to their types.
Usage Example:
const args = [ { name: 'input1', type: 'string' }, { name: 'input2', type: 'number' }, ]; const obj = convertToObject(args); // obj = { input1: 'string', input2: 'number' }
convertOutputsToObject({ lang, outputs }: FormSchemaType): ICodeForm['outputs']
Transforms the form's outputs property into a normalized object format depending on the programming language:
For Python (
ProgrammingLanguage.Python), expectsoutputsas an array and converts it into an object where each output name maps to an object containing a default empty string value and its type.For other languages, expects a single output object and converts it into a similar shape but wrapped in an object keyed by the output's name.
Handles empty output gracefully by returning an empty object.
Parameters:
lang: Programming language string fromProgrammingLanguageenum.outputs: Outputs data from the form schema.
Returns: An object mapping output names to objects
{ value: string; type: string }.Usage Example:
// For Python (array outputs) const outputs = [ { name: 'result', type: 'string' }, { name: 'errorCode', type: 'number' }, ]; const normalized = convertOutputsToObject({ lang: 'python', outputs }); /* normalized = { result: { value: '', type: 'string' }, errorCode: { value: '', type: 'number' } } */
Hooks
useWatchFormChange(id?: string, form?: UseFormReturn<FormSchemaType>): void
A React hook that watches changes in a form's values and synchronizes those changes back to the graph node store.
Parameters:
id(optional): The unique identifier of the node whose form is being tracked.form(optional): Thereact-hook-formform instance managingFormSchemaType.
Behavior:
Uses
useWatchto track form value changes reactively.On any form dirty state change or value change, it converts the arguments and outputs into a normalized object format.
Calls
updateNodeForm(id, nextValues)to update the graph store, thereby reflecting changes on the canvas.
Usage Example:
function MyNodeComponent({ nodeId }) { const form = useForm<FormSchemaType>({ defaultValues: {...} }); useWatchFormChange(nodeId, form); // ... }Implementation Details:
Uses
useEffectwith dependencies on form dirty state,id,updateNodeFormfunction, and watched values.Ensures that manual form updates are persisted to the graph store.
useHandleLanguageChange(id?: string, form?: UseFormReturn<FormSchemaType>): (lang: string) => void
A hook that returns a callback function to handle programming language changes within the form.
Parameters:
id(optional): Node identifier.form(optional):react-hook-formform instance of typeFormSchemaType.
Returns: A function
(lang: string) => voidthat updates the form and graph store when language changes.Behavior:
Sets the form's
scriptfield to a predefined template string based on the selected language.Resets the
outputsfield depending on the language (empty array for Python, empty object otherwise).Calls
updateNodeFormto update the graph store with the new script.
Usage Example:
const handleLanguageChange = useHandleLanguageChange(nodeId, form); // When language is changed by user: handleLanguageChange('python');Implementation Details:
Uses
useCallbackfor memoization based onid,form, andupdateNodeForm.Relies on a
CodeTemplateStrMapconstant that maps languages to their code templates.
Implementation Details and Algorithms
Form Value Normalization:
The file extensively normalizes form data, especially the arguments and outputs, into plain objects keyed by names with type and default value metadata. This normalization facilitates consistent graph store updates.Reactive Form Watching:
Leveragingreact-hook-form'suseWatchand React'suseEffect, the system reacts to any form changes and propagates those changes to the node representation on the canvas.Language-Specific Output Handling:
The output structure varies depending on the programming language, necessitating conditional transformations to maintain consistency.Graph Store Integration:
The hooks interact with a centralized graph store (useGraphStore), reflecting form changes directly in the application's node graph, ensuring state synchronization between UI and data.
Interaction with Other System Parts
Graph Store (
useGraphStore):
The key interaction is with the graph store that maintains the state of nodes on a canvas. The hooks update node data such as arguments, outputs, and script code in this store.Form Management (
react-hook-form):
The file depends onreact-hook-formfor managing complex form state and provides hooks that watch and handle form changes.Language Templates (
CodeTemplateStrMap):
Provides code templates per programming language; utilized when language changes trigger a script update.Schema and Types (
FormSchemaType):
Defines the shape of the form data, includingarguments,outputs, and other code-related fields.
Visual Diagram
classDiagram
class useWatchFormChange {
+id?: string
+form?: UseFormReturn<FormSchemaType>
+void
}
class useHandleLanguageChange {
+id?: string
+form?: UseFormReturn<FormSchemaType>
+(lang: string) => void
}
class convertToObject {
+list: FormSchemaType['arguments'][]
+Record<string, string>
}
class convertOutputsToObject {
+params: { lang: string; outputs: FormSchemaType['outputs'] }
+ICodeForm['outputs']
}
useWatchFormChange --> useGraphStore : updateNodeForm()
useHandleLanguageChange --> useGraphStore : updateNodeForm()
useHandleLanguageChange --> CodeTemplateStrMap : get template string
useWatchFormChange --> convertToObject
useWatchFormChange --> convertOutputsToObject
Summary
The use-watch-change.ts file is a utility and hook provider that enables reactive synchronization between form inputs and a graph-based node system in a React application. It abstracts the complexity of data normalization, language-specific adjustments, and state propagation to ensure consistent, real-time updates within a code editing or node programming interface. Its reliance on react-hook-form and a centralized graph store makes it a critical piece in maintaining the integrity and responsiveness of the application's node editing workflow.