use-watch-form-change.ts


Overview

This file provides utility functions and a custom React hook to monitor and synchronize changes in a React Hook Form instance with a graph node state managed in a centralized store. Specifically, it watches form value changes and updates a corresponding graph node's form data on a canvas or visualization.

This file is typically used in scenarios where form data edits need to be reflected live in a graphical representation, such as a node-based editor or workflow tool.


Detailed Documentation

1. transferToObject

export function transferToObject(list: OutputArray): OutputObject

Purpose

Transforms an array of output definitions into an object, where each output's name becomes a key, and the value is an object containing a reference and type. This transformation facilitates quick lookup and structured data storage.

Parameters

Returns

Usage Example

const outputsArray = [
  { name: 'output1', ref: someRef1, type: 'number' },
  { name: 'output2', ref: someRef2, type: 'string' },
];

const outputsObject = transferToObject(outputsArray);
// outputsObject = {
//   output1: { ref: someRef1, type: 'number' },
//   output2: { ref: someRef2, type: 'string' },
// }

2. useWatchFormChange

export function useWatchFormChange(id?: string, form?: UseFormReturn): void

Purpose

Custom React hook that listens to changes in a form controlled by react-hook-form and updates the form data for a corresponding graph node in a centralized graph store.

Parameters

Behavior and Implementation Details

Return Value

Usage Example

function NodeEditor({ nodeId, formInstance }: { nodeId: string; formInstance: UseFormReturn }) {
  useWatchFormChange(nodeId, formInstance);
  
  // Rest of the component rendering the form and node...
}

Important Implementation Details


Interaction with Other Parts of the System


Mermaid Diagram

Below is a flowchart showing the relationship between main functions and their interactions with external dependencies:

flowchart TD
    A[useWatchFormChange(id, form)] --> B[useWatch(form.control)]
    B --> C{form.formState.isDirty?}
    C -- Yes --> D[form.getValues()]
    D --> E[transferToObject(values.outputs)]
    E --> F[updateNodeForm(id, nextValues)]
    C -- No --> G[No update]
    
    subgraph External Dependencies
      B
      F[updateNodeForm(id, nextValues)] --- useGraphStore
      A --- react-hook-form
    end

Summary

This approach enables a reactive UI where form edits are immediately reflected in a graphical node editor, improving user experience and data consistency.