use-watch-form-change.ts


Overview

use-watch-form-change.ts provides a custom React hook, useWatchFormChange, designed to synchronize changes in a form managed by react-hook-form with an external state store (useGraphStore). This hook watches form values and, when the form is dirty (i.e., has unsaved changes), it updates a corresponding node's form data in the global graph state. The main use case is to keep a visual canvas or graph representation in sync with user inputs on a form in real-time.


Detailed Explanation

useWatchFormChange

export function useWatchFormChange(id?: string, form?: UseFormReturn<any>)

Purpose

A React hook that watches changes in a form and updates the corresponding node's form data in the global graph store whenever the form becomes dirty.

Parameters

Returns

Usage Example

import { useForm } from 'react-hook-form';
import { useWatchFormChange } from './use-watch-form-change';

function NodeForm({ nodeId }) {
  const form = useForm({
    defaultValues: {
      delimiters: '',
      method: 'Split', // example default
    },
  });

  // Synchronize form changes with node state
  useWatchFormChange(nodeId, form);

  return (
    <form>
      {/* form inputs here */}
    </form>
  );
}

Implementation Details


Interaction with Other System Parts


Visual Diagram

flowchart TD
    A[useWatchFormChange Hook] --> B[useWatch -> Watches form values]
    A --> C[useEffect -> on form dirty & id change]
    C --> D{Check conditions}
    D -- isDirty true & id exists --> E[Get current form values]
    E --> F{Check method}
    F -- method === Merge --> G[Transform delimiters into array]
    F -- otherwise --> H[Use values as-is]
    G & H --> I[Call updateNodeForm(id, nextValues)]
    I --> J[Update global graph store]
    J --> K[Graph / Canvas nodes update]

Summary

This hook is a critical piece for maintaining bi-directional synchronization between user input forms and a visual graph or canvas representation in the application.