Feat: Use one-way data flow to synchronize the form data to the canvas #3221 (#7977)

### What problem does this PR solve?

Feat: Use one-way data flow to synchronize the form data to the canvas
#3221

### Type of change


- [x] New Feature (non-breaking change which adds functionality)
This commit is contained in:
balibabu
2025-05-30 16:02:27 +08:00
committed by GitHub
parent bd4678bca6
commit 9f38b22a3f
16 changed files with 460 additions and 90 deletions

View File

@ -9,14 +9,37 @@ import {
FormLabel,
FormMessage,
} from '@/components/ui/form';
import { zodResolver } from '@hookform/resolvers/zod';
import { X } from 'lucide-react';
import { useFieldArray } from 'react-hook-form';
import { useFieldArray, useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { z } from 'zod';
import { INextOperatorForm } from '../../interface';
import { useValues } from './use-values';
import { useWatchFormChange } from './use-watch-change';
const MessageForm = ({ form }: INextOperatorForm) => {
const MessageForm = ({ node }: INextOperatorForm) => {
const { t } = useTranslation();
const values = useValues(node);
const FormSchema = z.object({
content: z
.array(
z.object({
value: z.string(),
}),
)
.optional(),
});
const form = useForm({
defaultValues: values,
resolver: zodResolver(FormSchema),
});
useWatchFormChange(node?.id, form);
const { fields, append, remove } = useFieldArray({
name: 'content',
control: form.control,

View File

@ -0,0 +1,25 @@
import { RAGFlowNodeType } from '@/interfaces/database/flow';
import { isEmpty } from 'lodash';
import { useMemo } from 'react';
import { convertToObjectArray } from '../../utils';
const defaultValues = {
content: [],
};
export function useValues(node?: RAGFlowNodeType) {
const values = useMemo(() => {
const formData = node?.data?.form;
if (isEmpty(formData)) {
return defaultValues;
}
return {
...formData,
content: convertToObjectArray(formData.content),
};
}, [node]);
return values;
}

View File

@ -0,0 +1,24 @@
import { useEffect } from 'react';
import { UseFormReturn, useWatch } from 'react-hook-form';
import useGraphStore from '../../store';
import { convertToStringArray } from '../../utils';
export function useWatchFormChange(id?: string, form?: UseFormReturn) {
let values = useWatch({ control: form?.control });
const updateNodeForm = useGraphStore((state) => state.updateNodeForm);
useEffect(() => {
// Manually triggered form updates are synchronized to the canvas
if (id && form?.formState.isDirty) {
values = form?.getValues();
let nextValues: any = values;
nextValues = {
...values,
content: convertToStringArray(values.content),
};
updateNodeForm(id, nextValues);
}
}, [form?.formState.isDirty, id, updateNodeForm, values]);
}