diff --git a/packages/web/components/common/Textarea/JsonEditor/index.tsx b/packages/web/components/common/Textarea/JsonEditor/index.tsx index eac015d23..e958ef3ae 100644 --- a/packages/web/components/common/Textarea/JsonEditor/index.tsx +++ b/packages/web/components/common/Textarea/JsonEditor/index.tsx @@ -1,4 +1,4 @@ -import React, { useEffect, useCallback, useRef, useState } from 'react'; +import React, { useEffect, useCallback, useRef, useState, useMemo } from 'react'; import Editor, { type Monaco, loader, useMonaco } from '@monaco-editor/react'; import { Box, type BoxProps } from '@chakra-ui/react'; import MyIcon from '../../Icon'; @@ -169,10 +169,27 @@ const JSONEditor = ({ document.addEventListener('mouseup', handleMouseUp); }, []); + const formatedValue = useMemo(() => { + if (typeof value === 'string') { + return value; + } + + if (value === undefined || value === null) { + return ''; + } + + try { + return JSON.stringify(value, null, 2); + } catch (error) { + console.error('JSON stringify error:', error); + return String(value) || ''; + } + }, [value]); + const onBlur = useCallback(() => { - if (!value) return; + if (!formatedValue) return; // replace {{xx}} to true - const replaceValue = value?.replace(/{{(.*?)}}/g, 'true'); + const replaceValue = formatedValue?.replace(/{{(.*?)}}/g, 'true'); try { JSON.parse(replaceValue); } catch (error) { @@ -181,7 +198,8 @@ const JSONEditor = ({ title: t('common:json_parse_error') }); } - }, [value]); + }, [formatedValue, toast, t]); + const beforeMount = useCallback((monaco: Monaco) => { monaco.languages.json.jsonDefaults.setDiagnosticsOptions({ validate: false, @@ -241,7 +259,7 @@ const JSONEditor = ({ theme="JSONEditorTheme" beforeMount={beforeMount} defaultValue={defaultValue} - value={value} + value={formatedValue} onChange={(e) => { onChange?.(e || ''); if (!e) { diff --git a/projects/app/src/web/core/chat/context/chatItemContext.tsx b/projects/app/src/web/core/chat/context/chatItemContext.tsx index e7d2fc560..001157cfb 100644 --- a/projects/app/src/web/core/chat/context/chatItemContext.tsx +++ b/projects/app/src/web/core/chat/context/chatItemContext.tsx @@ -151,7 +151,9 @@ const ChatItemContextProvider = ({ }); } - variablesForm.setValue('variables', newVariableValue); + Object.entries(newVariableValue).forEach(([key, value]) => { + variablesForm.setValue(`variables.${key}`, value); + }); }, [variablesForm] );