fix(frontend): prevent false "Invalid JSON" errors in config editor

This commit is contained in:
wenjie 2026-03-06 20:12:26 +08:00
parent ea5401cf0a
commit ceec9e5417

View file

@ -71,13 +71,13 @@ function RawJsonPanel() {
throw new Error("Failed to save config") throw new Error("Failed to save config")
} }
}, },
onSuccess: () => { onSuccess: (_, submittedConfig) => {
toast.success( toast.success(
t("pages.config.save_success", "Configuration saved successfully."), t("pages.config.save_success", "Configuration saved successfully."),
) )
// Update last saved config and reset dirty state // Update last saved config and reset dirty state
try { try {
const savedConfig = JSON.parse(editorValue) const savedConfig = JSON.parse(submittedConfig)
setLastSavedConfig(savedConfig) setLastSavedConfig(savedConfig)
setIsDirty(false) setIsDirty(false)
// Important: Invalidate the query to refresh the cached data // Important: Invalidate the query to refresh the cached data
@ -101,21 +101,14 @@ function RawJsonPanel() {
unknown unknown
> | null>(null) > | null>(null)
// Initialize editor value when config is first loaded const effectiveEditorValue =
const getInitialEditorValue = () => { editorValue || (config ? JSON.stringify(config, null, 2) : "")
if (config && !editorValue) {
return JSON.stringify(config, null, 2)
}
return editorValue
}
const displayValue = getInitialEditorValue()
const handleSave = () => { const handleSave = () => {
try { try {
// Validate JSON before saving // Validate JSON before saving
JSON.parse(editorValue) JSON.parse(effectiveEditorValue)
mutation.mutate(editorValue) mutation.mutate(effectiveEditorValue)
} catch (error) { } catch (error) {
toast.error( toast.error(
t( t(
@ -128,7 +121,11 @@ function RawJsonPanel() {
const handleFormat = () => { const handleFormat = () => {
try { try {
const formatted = JSON.stringify(JSON.parse(editorValue), null, 2) const formatted = JSON.stringify(
JSON.parse(effectiveEditorValue),
null,
2,
)
setEditorValue(formatted) setEditorValue(formatted)
toast.success( toast.success(
t("pages.config.format_success", "JSON formatted successfully."), t("pages.config.format_success", "JSON formatted successfully."),
@ -191,7 +188,7 @@ function RawJsonPanel() {
<div className="bg-muted/30 relative rounded-lg border"> <div className="bg-muted/30 relative rounded-lg border">
<ScrollArea className="h-[calc(100vh-20rem)] min-h-[200px]"> <ScrollArea className="h-[calc(100vh-20rem)] min-h-[200px]">
<Textarea <Textarea
value={displayValue} value={effectiveEditorValue}
onChange={(e) => { onChange={(e) => {
setEditorValue(e.target.value) setEditorValue(e.target.value)
setIsDirty(true) setIsDirty(true)