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:


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

Returns

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:

This ensures that UI changes on the form immediately reflect on the corresponding visual node representation.

Parameters

Returns

Implementation Details

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


Interaction with Other Parts of the System


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.