Repository navigation
feat: Add visual editing mode for chat configurations - #1947
Conversation
WalkthroughAdded dual editing modes (visual and JSON) for chat configurations in SettingsChats.jsx. Implemented modal-based CRUD, search/filter with highlighting, validation and uniqueness checks, and bi-directional sync between structured configs and JSON. Replaced a simple JSON textarea with a table UI and a JSON editor modal, preserving existing submission and i18n hooks. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor U as User
participant SC as SettingsChats.jsx
participant T as Table UI
participant M as Modal (Add/Edit JSON)
participant V as Visual Config State
participant J as JSON State
rect rgba(230,245,255,0.6)
note over SC: Mode selection
U->>SC: Toggle editMode (Visual / JSON)
alt Visual mode
SC->>T: Render table + search + actions
U->>T: Search / Add / Edit / Delete
T->>M: Open modal for Add/Edit
M->>SC: Submit changes
SC->>V: Validate + update visual configs
SC->>J: Serialize and sync JSON
else JSON mode
SC->>M: Open JSON editor
U->>M: Edit JSON
M->>SC: Validate JSON
SC->>J: Update JSON state
SC->>V: Parse and sync visual configs
end
end
note over SC: On save (form submit)
SC-->>Server: Submit current JSON (unchanged flow)
Server-->>SC: Response
SC-->>U: Success / Error feedback
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
@seefs001 已同步pr更改,望 review |
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
web/src/pages/Setting/Chat/SettingsChats.jsx (2)
106-155: Blocker: onSubmit crashes in visual mode (refForm is undefined). Branch by editMode and validate accordingly.Call to
refForm.current.validate()must be gated; also validate visual configs (trim, empties, duplicates) and build payload before diffing.Apply:
- async function onSubmit() { - try { - console.log('Starting validation...'); - await refForm.current - .validate() - .then(() => { - console.log('Validation passed'); - const updateArray = compareObjects(inputs, inputsRow); + async function onSubmit() { + try { + let payloadInputs = inputs; + if (editMode === 'json') { + if (!refForm.current) { + showError(t('表单未就绪')); + return; + } + await refForm.current.validate(); + if (!verifyJSON(inputs.Chats)) { + showError(t('不是合法的 JSON 字符串')); + return; + } + } else { + // Visual mode validation + const trimmed = chatConfigs.map(c => ({ + ...c, + name: (c.name || '').trim(), + url: (c.url || '').trim(), + })); + if (trimmed.some(c => !c.name || !c.url)) { + showError(t('名称和URL不能为空')); + return; + } + const seen = new Set(); + for (const c of trimmed) { + const k = c.name.toLowerCase(); + if (seen.has(k)) { + showError(t('聊天应用名称已存在,请使用其他名称')); + return; + } + seen.add(k); + } + // Build payload synchronously to avoid setState race + payloadInputs = { ...inputs, Chats: configsToJson(trimmed) }; + } + + const updateArray = compareObjects(payloadInputs, inputsRow); if (!updateArray.length) return showWarning(t('你似乎并没有修改什么')); - const requestQueue = updateArray.map((item) => { + const requestQueue = updateArray.map((item) => { let value = ''; - if (typeof inputs[item.key] === 'boolean') { - value = String(inputs[item.key]); + if (typeof payloadInputs[item.key] === 'boolean') { + value = String(payloadInputs[item.key]); } else { - value = inputs[item.key]; + value = payloadInputs[item.key]; } return API.put('/api/option/', { key: item.key, value, }); }); setLoading(true); Promise.all(requestQueue) .then((res) => { if (requestQueue.length === 1) { if (res.includes(undefined)) return; } else if (requestQueue.length > 1) { if (res.includes(undefined)) return showError(t('部分保存失败,请重试')); } showSuccess(t('保存成功')); + // Keep local state consistent with saved payload + setInputs(payloadInputs); props.refresh(); }) .catch(() => { showError(t('保存失败,请重试')); }) .finally(() => { setLoading(false); }); - }) - .catch((error) => { - console.error('Validation failed:', error); - showError(t('请检查输入')); - }); } catch (error) { - showError(t('请检查输入')); console.error(error); + showError(t('请检查输入')); } }
157-178: Guard server JSON parsing; avoid page crash on bad options.Wrap
JSON.parse(props.options[key])with try/catch and default to[].- if (key === 'Chats') { - const obj = JSON.parse(props.options[key]); - currentInputs[key] = JSON.stringify(obj, null, 2); - } else { + if (key === 'Chats') { + try { + const obj = JSON.parse(props.options[key]); + currentInputs[key] = JSON.stringify(obj, null, 2); + } catch (e) { + console.error('Invalid Chats JSON from server', e); + showError(t('服务器返回的聊天配置不是合法 JSON')); + currentInputs[key] = '[]'; + } + } else { currentInputs[key] = props.options[key]; }
🧹 Nitpick comments (5)
web/src/pages/Setting/Chat/SettingsChats.jsx (5)
192-202: Remove setTimeout for modal form initialization.
modalFormRefis available; set values directly after opening modal.const handleAddConfig = () => { setEditingConfig({ name: '', url: '' }); setIsEdit(false); setModalVisible(true); - setTimeout(() => { - if (modalFormRef.current) { - modalFormRef.current.setValues({ name: '', url: '' }); - } - }, 100); + modalFormRef.current?.setValues({ name: '', url: '' }); }; const handleEditConfig = (config) => { setEditingConfig({ ...config }); setIsEdit(true); setModalVisible(true); - setTimeout(() => { - if (modalFormRef.current) { - modalFormRef.current.setValues(config); - } - }, 100); + modalFormRef.current?.setValues(config); };Also applies to: 203-212
214-219: Confirm before delete to prevent accidental data loss.- const handleDeleteConfig = (id) => { - const newConfigs = chatConfigs.filter((config) => config.id !== id); - setChatConfigs(newConfigs); - syncConfigsToJson(newConfigs); - showSuccess(t('删除成功')); - }; + const handleDeleteConfig = (id) => { + Modal.confirm({ + title: t('确认删除该配置?'), + content: t('删除后不可恢复'), + okText: t('删除'), + okType: 'danger', + onOk: () => { + const newConfigs = chatConfigs.filter((config) => config.id !== id); + setChatConfigs(newConfigs); + syncConfigsToJson(newConfigs); + showSuccess(t('删除成功')); + }, + }); + };
490-495: Strengthen URL validation (allow http(s) or placeholders).Stop obvious bad inputs; still allow
{address}/{key}.- <Form.Input + <Form.Input field='url' label={t('URL链接')} placeholder={t('请输入完整的URL链接')} - rules={[{ required: true, message: t('请输入URL链接') }]} + rules={[ + { required: true, message: t('请输入URL链接') }, + { + validator: (rule, value) => { + const v = (value || '').trim(); + if (!v) return false; + const urlLike = /^https?:\/\//i.test(v); + const hasPlaceholder = /\{address\}|\{key\}/.test(v); + return urlLike || hasPlaceholder; + }, + message: t('请输入以 http(s):// 开头的链接,或包含占位符 {address}/{key}'), + }, + ]} />
67-82: Make JSON→configs parsing more robust.Ignore non-object entries, multi-key objects, and non-string values to avoid producing broken rows.
- const jsonToConfigs = (jsonString) => { + const jsonToConfigs = (jsonString) => { try { - const configs = JSON.parse(jsonString); - return Array.isArray(configs) - ? configs.map((config, index) => ({ - id: index, - name: Object.keys(config)[0] || '', - url: Object.values(config)[0] || '', - })) - : []; + const data = JSON.parse(jsonString); + if (!Array.isArray(data)) return []; + const out = []; + data.forEach((item, index) => { + if (item && typeof item === 'object' && !Array.isArray(item)) { + const keys = Object.keys(item); + if (keys.length > 0) { + const name = String(keys[0] || '').trim(); + const url = typeof item[keys[0]] === 'string' ? item[keys[0]].trim() : ''; + if (name && url) out.push({ id: index, name, url }); + } + } + }); + return out; } catch (error) { console.error('JSON parse error:', error); return []; } };
281-301: Minor: improve placeholder emphasis and a11y.Consider wrapping
{address}/{key}in<code>and addingaria-labelto clarify they are placeholders, plus ensure colors meet WCAG contrast.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
web/src/pages/Setting/Chat/SettingsChats.jsx(3 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
web/src/pages/Setting/Chat/SettingsChats.jsx (1)
web/src/helpers/utils.jsx (2)
showSuccess(157-159)showError(122-151)
🔇 Additional comments (1)
web/src/pages/Setting/Chat/SettingsChats.jsx (1)
441-449: Use the correct Semi UI Form Field prop namestopValidateWithErrorinstead ofstopValidateWhenError.
| const handleModalOk = () => { | ||
| if (modalFormRef.current) { | ||
| modalFormRef.current | ||
| .validate() | ||
| .then((values) => { | ||
| // 检查名称是否重复 | ||
| const isDuplicate = chatConfigs.some( | ||
| (config) => | ||
| config.name === values.name && | ||
| (!isEdit || config.id !== editingConfig.id) | ||
| ); | ||
|
|
||
| if (isDuplicate) { | ||
| showError(t('聊天应用名称已存在,请使用其他名称')); | ||
| return; | ||
| } | ||
|
|
||
| if (isEdit) { | ||
| const newConfigs = chatConfigs.map((config) => | ||
| config.id === editingConfig.id | ||
| ? { ...editingConfig, name: values.name, url: values.url } | ||
| : config, | ||
| ); | ||
| setChatConfigs(newConfigs); | ||
| syncConfigsToJson(newConfigs); | ||
| } else { | ||
| const maxId = | ||
| chatConfigs.length > 0 | ||
| ? Math.max(...chatConfigs.map((c) => c.id)) | ||
| : -1; | ||
| const newConfig = { | ||
| id: maxId + 1, | ||
| name: values.name, | ||
| url: values.url, | ||
| }; | ||
| const newConfigs = [...chatConfigs, newConfig]; | ||
| setChatConfigs(newConfigs); | ||
| syncConfigsToJson(newConfigs); | ||
| } | ||
| setModalVisible(false); | ||
| setEditingConfig(null); | ||
| showSuccess(isEdit ? t('编辑成功') : t('添加成功')); | ||
| }) | ||
| .catch((error) => { | ||
| console.error('Modal form validation error:', error); | ||
| }); | ||
| } | ||
| }; |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major
Harden modal submit: trim inputs and make duplicate check case-insensitive.
Prevents “Name” vs “name”, trailing spaces, and empty values from slipping through.
- .then((values) => {
- // 检查名称是否重复
- const isDuplicate = chatConfigs.some(
- (config) =>
- config.name === values.name &&
- (!isEdit || config.id !== editingConfig.id)
- );
+ .then((values) => {
+ const name = (values.name || '').trim();
+ const url = (values.url || '').trim();
+ if (!name || !url) {
+ showError(t('名称和URL不能为空'));
+ return;
+ }
+ // 检查名称是否重复(不区分大小写,忽略空白)
+ const isDuplicate = chatConfigs.some(
+ (config) =>
+ (config.name || '').trim().toLowerCase() === name.toLowerCase() &&
+ (!isEdit || config.id !== editingConfig.id)
+ );
if (isDuplicate) {
showError(t('聊天应用名称已存在,请使用其他名称'));
return;
}
if (isEdit) {
const newConfigs = chatConfigs.map((config) =>
config.id === editingConfig.id
- ? { ...editingConfig, name: values.name, url: values.url }
+ ? { ...editingConfig, name, url }
: config,
);
setChatConfigs(newConfigs);
syncConfigsToJson(newConfigs);
} else {
const maxId =
chatConfigs.length > 0
? Math.max(...chatConfigs.map((c) => c.id))
: -1;
const newConfig = {
id: maxId + 1,
- name: values.name,
- url: values.url,
+ name,
+ url,
};
const newConfigs = [...chatConfigs, newConfig];
setChatConfigs(newConfigs);
syncConfigsToJson(newConfigs);
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const handleModalOk = () => { | |
| if (modalFormRef.current) { | |
| modalFormRef.current | |
| .validate() | |
| .then((values) => { | |
| // 检查名称是否重复 | |
| const isDuplicate = chatConfigs.some( | |
| (config) => | |
| config.name === values.name && | |
| (!isEdit || config.id !== editingConfig.id) | |
| ); | |
| if (isDuplicate) { | |
| showError(t('聊天应用名称已存在,请使用其他名称')); | |
| return; | |
| } | |
| if (isEdit) { | |
| const newConfigs = chatConfigs.map((config) => | |
| config.id === editingConfig.id | |
| ? { ...editingConfig, name: values.name, url: values.url } | |
| : config, | |
| ); | |
| setChatConfigs(newConfigs); | |
| syncConfigsToJson(newConfigs); | |
| } else { | |
| const maxId = | |
| chatConfigs.length > 0 | |
| ? Math.max(...chatConfigs.map((c) => c.id)) | |
| : -1; | |
| const newConfig = { | |
| id: maxId + 1, | |
| name: values.name, | |
| url: values.url, | |
| }; | |
| const newConfigs = [...chatConfigs, newConfig]; | |
| setChatConfigs(newConfigs); | |
| syncConfigsToJson(newConfigs); | |
| } | |
| setModalVisible(false); | |
| setEditingConfig(null); | |
| showSuccess(isEdit ? t('编辑成功') : t('添加成功')); | |
| }) | |
| .catch((error) => { | |
| console.error('Modal form validation error:', error); | |
| }); | |
| } | |
| }; | |
| const handleModalOk = () => { | |
| if (modalFormRef.current) { | |
| modalFormRef.current | |
| .validate() | |
| .then((values) => { | |
| // Trim and validate inputs | |
| const name = (values.name || '').trim(); | |
| const url = (values.url || '').trim(); | |
| if (!name || !url) { | |
| showError(t('名称和URL不能为空')); | |
| return; | |
| } | |
| // 检查名称是否重复(不区分大小写,忽略空白) | |
| const isDuplicate = chatConfigs.some( | |
| (config) => | |
| (config.name || '').trim().toLowerCase() === name.toLowerCase() && | |
| (!isEdit || config.id !== editingConfig.id) | |
| ); | |
| if (isDuplicate) { | |
| showError(t('聊天应用名称已存在,请使用其他名称')); | |
| return; | |
| } | |
| if (isEdit) { | |
| const newConfigs = chatConfigs.map((config) => | |
| config.id === editingConfig.id | |
| ? { ...editingConfig, name, url } | |
| : config, | |
| ); | |
| setChatConfigs(newConfigs); | |
| syncConfigsToJson(newConfigs); | |
| } else { | |
| const maxId = | |
| chatConfigs.length > 0 | |
| ? Math.max(...chatConfigs.map((c) => c.id)) | |
| : -1; | |
| const newConfig = { | |
| id: maxId + 1, | |
| name, | |
| url, | |
| }; | |
| const newConfigs = [...chatConfigs, newConfig]; | |
| setChatConfigs(newConfigs); | |
| syncConfigsToJson(newConfigs); | |
| } | |
| setModalVisible(false); | |
| setEditingConfig(null); | |
| showSuccess(isEdit ? t('编辑成功') : t('添加成功')); | |
| }) | |
| .catch((error) => { | |
| console.error('Modal form validation error:', error); | |
| }); | |
| } | |
| }; |
🤖 Prompt for AI Agents
In web/src/pages/Setting/Chat/SettingsChats.jsx around lines 221 to 268, the
modal submit currently allows names with differing case/whitespace and empty
values; fix by trimming values.name and values.url before validation and saving,
reject empty trimmed names with showError, perform the duplicate check using
trimmed name lowercased (e.g. compare config.name.trim().toLowerCase() to
trimmedName.toLowerCase()), and use the trimmed values when creating or updating
configs and when computing maxId/syncing.
| <RadioGroup | ||
| type='button' | ||
| value={editMode} | ||
| onChange={(e) => { | ||
| const newMode = e.target.value; | ||
| setEditMode(newMode); | ||
|
|
||
| // 确保模式切换时数据正确同步 | ||
| setTimeout(() => { | ||
| if (newMode === 'json' && refForm.current) { | ||
| refForm.current.setValues(inputs); | ||
| } | ||
| }, 100); | ||
| }} | ||
| > | ||
| <Radio value='visual'>{t('可视化编辑')}</Radio> | ||
| <Radio value='json'>{t('JSON编辑')}</Radio> | ||
| </RadioGroup> | ||
| </div> |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major
Prevent switch to visual when JSON is invalid; remove timing hack.
Block mode change if JSON is invalid; rely on effect to sync form on JSON mode. The setTimeout is unnecessary.
- <RadioGroup
+ <RadioGroup
type='button'
value={editMode}
onChange={(e) => {
const newMode = e.target.value;
- setEditMode(newMode);
-
- // 确保模式切换时数据正确同步
- setTimeout(() => {
- if (newMode === 'json' && refForm.current) {
- refForm.current.setValues(inputs);
- }
- }, 100);
+ if (newMode === 'visual') {
+ if (!verifyJSON(inputs.Chats)) {
+ showError(t('不是合法的 JSON 字符串'));
+ return;
+ }
+ syncJsonToConfigs();
+ }
+ setEditMode(newMode);
}}
>📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| <RadioGroup | |
| type='button' | |
| value={editMode} | |
| onChange={(e) => { | |
| const newMode = e.target.value; | |
| setEditMode(newMode); | |
| // 确保模式切换时数据正确同步 | |
| setTimeout(() => { | |
| if (newMode === 'json' && refForm.current) { | |
| refForm.current.setValues(inputs); | |
| } | |
| }, 100); | |
| }} | |
| > | |
| <Radio value='visual'>{t('可视化编辑')}</Radio> | |
| <Radio value='json'>{t('JSON编辑')}</Radio> | |
| </RadioGroup> | |
| </div> | |
| <RadioGroup | |
| type='button' | |
| value={editMode} | |
| onChange={(e) => { | |
| const newMode = e.target.value; | |
| if (newMode === 'visual') { | |
| if (!verifyJSON(inputs.Chats)) { | |
| showError(t('不是合法的 JSON 字符串')); | |
| return; | |
| } | |
| syncJsonToConfigs(); | |
| } | |
| setEditMode(newMode); | |
| }} | |
| > | |
| <Radio value='visual'>{t('可视化编辑')}</Radio> | |
| <Radio value='json'>{t('JSON编辑')}</Radio> | |
| </RadioGroup> |
🤖 Prompt for AI Agents
In web/src/pages/Setting/Chat/SettingsChats.jsx around lines 363 to 381, the
onChange handler currently switches modes unconditionally and uses a setTimeout
to sync the form; remove that timing hack and block switching to visual when the
JSON is invalid. Update onChange to: validate/parse the current JSON (or run the
JSON editor's validation) before allowing a change to 'visual' — if validation
fails, prevent setEditMode and surface an error; if switching from visual to
'json', just setEditMode('json'). Remove the setTimeout block entirely and
instead add/use an effect that watches editMode and when editMode becomes 'json'
sync the form via refForm.current.setValues(inputs) (and when leaving 'json'
ensure you parse and persist JSON back into inputs before switching).
feat: Add visual editing mode for chat configurations
feat: Add visual editing mode for chat configurations
feat: Add visual editing mode for chat configurations
支持可视化编辑聊天设置。ref: #1684

Summary by CodeRabbit
New Features
Improvements