use-watch-form-change.ts


Overview

The use-watch-form-change.ts file defines a custom React hook useWatchFormChange designed to synchronize changes from a form managed by react-hook-form with a centralized graph store. This hook listens for changes in the form state and, when the form becomes dirty (i.e., modified), it updates the corresponding node in the application's graph store with the latest form values. It also handles a specific transformation of form data when certain conditions are met.

This hook is primarily intended for use in React components that manage node forms within a graphical interface, ensuring that the UI and underlying data model remain consistent.


Detailed Explanation

useWatchFormChange

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

Purpose

A React hook that watches the state of a form and synchronizes its changes to a graph data store. It listens to changes in the form's values and updates the corresponding graph node when the form is modified.

Parameters

Name

Type

Description

id

`string \

undefined`

form

`UseFormReturn \

undefined`

Returns

Usage Example

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

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

  // Synchronizes form changes to the graph store for the given nodeId
  useWatchFormChange(nodeId, form);

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

Behavior and Implementation Details


Important Implementation Details


Interaction with Other Parts of the System


Mermaid Diagram

flowchart TD
    A[useWatchFormChange Hook]
    A --> B[useWatch(form.control)]
    A --> C[useGraphStore(updateNodeForm)]
    A --> D[useEffect]
    D --> E{if id && formState.isDirty}
    E -->|true| F[getValues()]
    F --> G{method === StringTransformMethod.Merge}
    G -->|true| H[Transform delimiters to array]
    G -->|false| I[Use values as-is]
    H --> J[updateNodeForm(id, nextValues)]
    I --> J

Summary

use-watch-form-change.ts provides a focused utility hook that bridges form management and centralized graph state management. It abstracts the complexity of synchronizing form changes to the data store, enabling React components to remain declarative and clean. Its conditional handling of specific form fields demonstrates tailored logic aligned with the application's domain (string transformation nodes).

This file is a crucial link in maintaining data consistency within the UI, especially for interactive graph-based editors or visualization tools that rely on form-driven input for node configuration.