use-watch-change.ts


Overview

The use-watch-change.ts file provides a custom React hook, useWatchFormChange, designed to monitor changes in a form managed by react-hook-form and synchronize those changes to a global graph store. This synchronization ensures that updates made in the form UI are reflected in the application's canvas or graph state, maintaining consistency between form data and visual nodes.

The hook leverages React's useEffect for side-effect management, useWatch from react-hook-form for reactive form value tracking, and a Zustand-based store (useGraphStore) for global state updates. It specifically watches for changes in the form's "dirty" state (i.e., if the form has unsaved changes) and propagates those changes to an external node identified by id.


Detailed Explanation

useWatchFormChange

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

Purpose

A React hook that watches for changes in a react-hook-form instance and updates a corresponding node in the global graph store whenever the form is dirty (i.e., modified).

Parameters

Parameter

Type

Description

id

string (optional)

The unique identifier of the node that needs its form data updated in the graph store. If not provided, no update occurs.

form

UseFormReturn<any> (optional)

The form instance returned by useForm from react-hook-form. Provides control and state for the form being watched.

Returns

Usage Example

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

function NodeForm({ nodeId }) {
  const form = useForm({
    defaultValues: {
      prompts: '',
    },
  });

  // Automatically sync changes to the global graph state
  useWatchFormChange(nodeId, form);

  return (
    <form>
      <input {...form.register("prompts")} />
      {/* other form controls */}
    </form>
  );
}

Implementation Details


Interaction with Other System Components


Visual Diagram

flowchart TD
    A[useWatchFormChange Hook]
    B[useWatch(form.control)]
    C[useEffect]
    D[Check: id && form.formState.isDirty]
    E[Get current form values]
    F[Transform values: wrap prompts with PromptRole.User]
    G[updateNodeForm(id, transformedValues) from useGraphStore]

    A --> B
    A --> C
    C --> D
    D -->|true| E
    E --> F
    F --> G
    D -->|false| C

Summary

The use-watch-change.ts file encapsulates a custom React hook that seamlessly bridges form state changes with a global graph data store. It listens for user edits in a form, formats the data suitably, and updates the corresponding graph node. This ensures UI consistency without manual event handling or state duplication, promoting a reactive and declarative programming style in managing node forms within the canvas environment.