use-watch-form-change.ts
Overview
The use-watch-form-change.ts file provides utility functions and a React custom hook designed to monitor changes in a form managed by react-hook-form. This hook synchronizes form state updates with a global graph store (likely representing a visual node-based editor or similar application). The key goal is to keep the form data and the visual representation (the "canvas") consistent whenever the user modifies form inputs.
The file exports:
transferToObject: A utility function to transform an array of output definitions into a structured object.useWatchFormChange: A React hook that monitors form changes viareact-hook-form'suseWatch, and pushes updated form values into a central graph store when the form is dirty.
Detailed Explanation
Function: transferToObject
export function transferToObject(list: OutputArray): OutputObject
Purpose
Transforms an array of output entries into an object keyed by each entry's name. Each key points to an object containing references and type information for the output.
Parameters
list(OutputArray): An array of output objects. Each object is expected to have at least the properties:name(string): The unique identifier for the output.ref(any): A reference, possibly to a React element or other resource.type(string): The type of the output.
Returns
OutputObject: An object where keys are outputnames, and values are objects containing{ ref, type }.
Usage Example
const outputs = [
{ name: 'out1', ref: someRef1, type: 'number' },
{ name: 'out2', ref: someRef2, type: 'string' }
];
const outputObject = transferToObject(outputs);
/*
{
out1: { ref: someRef1, type: 'number' },
out2: { ref: someRef2, type: 'string' }
}
*/
Hook: useWatchFormChange
export function useWatchFormChange(id?: string, form?: UseFormReturn): void
Purpose
This custom React hook watches for changes in a form's values managed by react-hook-form and synchronizes these changes with a global graph store's node form data. It triggers updates only when:
A valid node
idis provided.The form state is marked as dirty (i.e., changed since last reset/submit).
This ensures that UI changes on the form immediately reflect on the corresponding visual node representation.
Parameters
id(optionalstring): The identifier of the node whose form data is being watched and updated.form(optionalUseFormReturn): The form instance returned byreact-hook-form'suseFormhook. Contains form state, control, and helper methods.
Returns
void: This hook does not return any value. It operates via side effects to update the node form in the store.
Implementation Details
Uses
useWatchfromreact-hook-formto subscribe to all form value changes.Uses
useEffectwith dependencies on form dirtiness, node id, the update function, and current form values.When triggered, it fetches fresh form values via
form.getValues().Converts the
outputsarray in form values to a keyed object usingtransferToObject.Calls
updateNodeFormfrom theuseGraphStoreto update the node's form data in the global state.Contains a
console.logstatement for debugging form values upon update.
Usage Example
import { useForm } from 'react-hook-form';
function NodeEditor({ nodeId }) {
const form = useForm({
defaultValues: {
name: '',
outputs: []
}
});
// Synchronize form changes to the node store
useWatchFormChange(nodeId, form);
return (
<form>
{/* form fields */}
</form>
);
}
Important Implementation Notes
State synchronization: The hook only updates the store when
formState.isDirtyis true. This prevents unnecessary writes on initial render or unchanged data.Outputs transformation: The form's outputs are stored as an array but the graph store expects an object keyed by output names. The helper function
transferToObjecthandles this transformation cleanly.Store interaction: The hook interacts with a Zustand store (
useGraphStore) that manages graph nodes and their forms. TheupdateNodeFormmethod is used to update the node's data.Reactivity: The dependencies array of
useEffectincludes all variables that can trigger update: form dirtiness, node id, the store update function, and the watched values.Debugging aid: The console log helps developers trace form updates and diagnose synchronization issues.
Interaction with Other Parts of the System
react-hook-form: The hook relies on this library to manage and watch form state.
Zustand store (
useGraphStore): Provides the global state management for graph nodes, allowing form changes to update node data.Interface definitions (
OutputArray,OutputObject): Define the shape of output data handled by the form and store.Graphical node editor (implied): The form likely edits properties of a node in a graphical editor or workflow builder. This file ensures form updates are reflected on the canvas or node visualization.
Visual Diagram: Function and Hook Relationship Flow
flowchart TD
A[Form Values (react-hook-form)] -->|useWatch| B[values]
B --> C{useEffect triggers when}
C -->|formState.isDirty && id exists| D[Get latest values from form.getValues()]
D --> E[Transform outputs using transferToObject()]
E --> F[Call updateNodeForm(id, transformedValues)]
F --> G[Update graph store's node form data]
subgraph Utilities
E
transferToObject
end
subgraph Store Interaction
F
G
useGraphStore
end
Summary
The use-watch-form-change.ts file is a crucial connector between form state and the application's graph node data. By leveraging react-hook-form's reactive capabilities and a centralized state store, it ensures that user edits in a form are promptly and efficiently reflected in the visual graph representation. The modular design and clear separation of concerns make the file reusable and maintainable within a React-based node editing system.