use-watch-change.ts


Overview

The use-watch-change.ts file provides a custom React hook designed to monitor changes in a form managed by react-hook-form and propagate those changes to a global state store. Specifically, it listens for changes in form data, performs a transformation on part of that data (the inputs array), and updates a node's form state within a graph store. This file is integral to synchronizing form state with the application's state management, enabling reactive UI updates and consistent data flow.


Detailed Explanation

1. transferInputsArrayToObject

function transferInputsArrayToObject(inputs: BeginQuery[] = []): Record<string, Omit<BeginQuery, 'key'>>

Purpose

Transforms an array of BeginQuery objects into an object indexed by the key property of each element. The transformation omits the key property from the value objects.

Parameters

Returns

Usage Example

const inputsArray = [
  { key: 'input1', type: 'text', value: 'Hello' },
  { key: 'input2', type: 'number', value: 42 }
];

const inputsObject = transferInputsArrayToObject(inputsArray);
/*
inputsObject = {
  input1: { type: 'text', value: 'Hello' },
  input2: { type: 'number', value: 42 }
}
*/

Implementation Details


2. useWatchFormChange

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

Purpose

A React hook that watches a form's state changes and updates the related node's form data inside a global graph store.

Parameters

Returns

Behavior and Usage

Usage Example

function NodeEditor({ nodeId }: { nodeId: string }) {
  const form = useForm({ defaultValues: { inputs: [], outputs: [] } });

  useWatchFormChange(nodeId, form);

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

Implementation Notes


Important Implementation Details and Algorithms


Interaction with Other System Components


Visual Diagram

classDiagram
    class transferInputsArrayToObject {
        +inputs: BeginQuery[]
        +return: Record<string, Omit<BeginQuery, 'key'>>
    }

    class useWatchFormChange {
        +id?: string
        +form?: UseFormReturn
        +void
    }

    useWatchFormChange --> transferInputsArrayToObject : calls
    useWatchFormChange --> useGraphStore : uses updateNodeForm
    useWatchFormChange ..> useEffect : React hook
    useWatchFormChange ..> useWatch : React hook

Summary

The use-watch-change.ts file encapsulates logic for synchronizing form changes with the global application state in a graph-based model. It transforms form inputs, watches changes efficiently with React hooks, and updates the relevant node's form data in the store. This mechanism is key to maintaining consistent state between user input and application data models, enabling responsive and reactive UI behavior in complex form-driven interfaces.