File size: 6,641 Bytes
4674012
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
/*
Copyright (C) 2025 QuantumNous

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.

For commercial licensing, please contact support@quantumnous.com
*/

import React, { useState, useEffect } from 'react';
import {
  TextArea,
  Typography,
  Button,
  Switch,
  Banner,
} from '@douyinfe/semi-ui';
import { Code, Edit, Check, X, AlertTriangle } from 'lucide-react';
import { useTranslation } from 'react-i18next';

const CustomRequestEditor = ({
  customRequestMode,
  customRequestBody,
  onCustomRequestModeChange,
  onCustomRequestBodyChange,
  defaultPayload,
}) => {
  const { t } = useTranslation();
  const [isValid, setIsValid] = useState(true);
  const [errorMessage, setErrorMessage] = useState('');
  const [localValue, setLocalValue] = useState(customRequestBody || '');

  // 当切换到自定义模式时,用默认payload初始化
  useEffect(() => {
    if (
      customRequestMode &&
      (!customRequestBody || customRequestBody.trim() === '')
    ) {
      const defaultJson = defaultPayload
        ? JSON.stringify(defaultPayload, null, 2)
        : '';
      setLocalValue(defaultJson);
      onCustomRequestBodyChange(defaultJson);
    }
  }, [
    customRequestMode,
    defaultPayload,
    customRequestBody,
    onCustomRequestBodyChange,
  ]);

  // 同步外部传入的customRequestBody到本地状态
  useEffect(() => {
    if (customRequestBody !== localValue) {
      setLocalValue(customRequestBody || '');
      validateJson(customRequestBody || '');
    }
  }, [customRequestBody]);

  // 验证JSON格式
  const validateJson = (value) => {
    if (!value.trim()) {
      setIsValid(true);
      setErrorMessage('');
      return true;
    }

    try {
      JSON.parse(value);
      setIsValid(true);
      setErrorMessage('');
      return true;
    } catch (error) {
      setIsValid(false);
      setErrorMessage(`JSON格式错误: ${error.message}`);
      return false;
    }
  };

  const handleValueChange = (value) => {
    setLocalValue(value);
    validateJson(value);
    // 始终保存用户输入,让预览逻辑处理JSON解析错误
    onCustomRequestBodyChange(value);
  };

  const handleModeToggle = (enabled) => {
    onCustomRequestModeChange(enabled);
    if (enabled && defaultPayload) {
      const defaultJson = JSON.stringify(defaultPayload, null, 2);
      setLocalValue(defaultJson);
      onCustomRequestBodyChange(defaultJson);
    }
  };

  const formatJson = () => {
    try {
      const parsed = JSON.parse(localValue);
      const formatted = JSON.stringify(parsed, null, 2);
      setLocalValue(formatted);
      onCustomRequestBodyChange(formatted);
      setIsValid(true);
      setErrorMessage('');
    } catch (error) {
      // 如果格式化失败,保持原样
    }
  };

  return (
    <div className='space-y-4'>
      {/* 自定义模式开关 */}
      <div className='flex items-center justify-between'>
        <div className='flex items-center gap-2'>
          <Code size={16} className='text-gray-500' />
          <Typography.Text strong className='text-sm'>
            自定义请求体模式
          </Typography.Text>
        </div>
        <Switch
          checked={customRequestMode}
          onChange={handleModeToggle}
          checkedText='开'
          uncheckedText='关'
          size='small'
        />
      </div>

      {customRequestMode && (
        <>
          {/* 提示信息 */}
          <Banner
            type='warning'
            description='启用此模式后,将使用您自定义的请求体发送API请求,模型配置面板的参数设置将被忽略。'
            icon={<AlertTriangle size={16} />}
            className='!rounded-lg'
            closeIcon={null}
          />

          {/* JSON编辑器 */}
          <div>
            <div className='flex items-center justify-between mb-2'>
              <Typography.Text strong className='text-sm'>
                请求体 JSON
              </Typography.Text>
              <div className='flex items-center gap-2'>
                {isValid ? (
                  <div className='flex items-center gap-1 text-green-600'>
                    <Check size={14} />
                    <Typography.Text className='text-xs'>
                      格式正确
                    </Typography.Text>
                  </div>
                ) : (
                  <div className='flex items-center gap-1 text-red-600'>
                    <X size={14} />
                    <Typography.Text className='text-xs'>
                      格式错误
                    </Typography.Text>
                  </div>
                )}
                <Button
                  theme='borderless'
                  type='tertiary'
                  size='small'
                  icon={<Edit size={14} />}
                  onClick={formatJson}
                  disabled={!isValid}
                  className='!rounded-lg'
                >
                  格式化
                </Button>
              </div>
            </div>

            <TextArea
              value={localValue}
              onChange={handleValueChange}
              placeholder='{"model": "gpt-4o", "messages": [...], ...}'
              autosize={{ minRows: 8, maxRows: 20 }}
              className={`custom-request-textarea !rounded-lg font-mono text-sm ${!isValid ? '!border-red-500' : ''}`}
              style={{
                fontFamily: 'Consolas, Monaco, "Courier New", monospace',
                lineHeight: '1.5',
              }}
            />

            {!isValid && errorMessage && (
              <Typography.Text type='danger' className='text-xs mt-1 block'>
                {errorMessage}
              </Typography.Text>
            )}

            <Typography.Text className='text-xs text-gray-500 mt-2 block'>
              请输入有效的JSON格式的请求体。您可以参考预览面板中的默认请求体格式。
            </Typography.Text>
          </div>
        </>
      )}
    </div>
  );
};

export default CustomRequestEditor;