fix monaco editor default value (#4793)

* fix monaco editor default value

* fix
This commit is contained in:
heheer
2025-05-12 23:09:15 +08:00
committed by GitHub
parent 0ef3d40296
commit cac4b1d435
2 changed files with 26 additions and 6 deletions

View File

@@ -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) {

View File

@@ -151,7 +151,9 @@ const ChatItemContextProvider = ({
});
}
variablesForm.setValue('variables', newVariableValue);
Object.entries(newVariableValue).forEach(([key, value]) => {
variablesForm.setValue(`variables.${key}`, value);
});
},
[variablesForm]
);