File size: 12,891 Bytes
f56a29b | 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 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 |
import { useState, useCallback, useMemo } from 'react';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogTitle, DialogDescription } from '@/components/ui/dialog';
import { useI18n } from '@/lib/hooks/use-i18n';
import { useSettingsStore } from '@/lib/store/settings';
import { VIDEO_PROVIDERS } from '@/lib/media/video-providers';
import {
Loader2,
CheckCircle2,
XCircle,
Eye,
EyeOff,
Zap,
Plus,
Settings2,
Trash2,
} from 'lucide-react';
import { cn } from '@/lib/utils';
import type { VideoProviderId } from '@/lib/media/types';
interface VideoSettingsProps {
selectedProviderId: VideoProviderId;
}
export function VideoSettings({ selectedProviderId }: VideoSettingsProps) {
const { t } = useI18n();
const videoModelId = useSettingsStore((state) => state.videoModelId);
const videoProvidersConfig = useSettingsStore((state) => state.videoProvidersConfig);
const setVideoProviderConfig = useSettingsStore((state) => state.setVideoProviderConfig);
const [showApiKey, setShowApiKey] = useState(false);
const [testLoading, setTestLoading] = useState(false);
const [testStatus, setTestStatus] = useState<'idle' | 'success' | 'error'>('idle');
const [testMessage, setTestMessage] = useState('');
// Model dialog state
const [showModelDialog, setShowModelDialog] = useState(false);
const [editingModelIndex, setEditingModelIndex] = useState<number | null>(null);
const [modelForm, setModelForm] = useState({ id: '', name: '' });
// Reset test state when provider changes (derived state pattern)
const [prevSelectedProviderId, setPrevSelectedProviderId] = useState(selectedProviderId);
if (selectedProviderId !== prevSelectedProviderId) {
setPrevSelectedProviderId(selectedProviderId);
setTestStatus('idle');
setTestMessage('');
}
const currentConfig = videoProvidersConfig[selectedProviderId];
const currentProvider = VIDEO_PROVIDERS[selectedProviderId];
const builtInModels = currentProvider?.models || [];
const customModels = useMemo(
() => currentConfig?.customModels || [],
[currentConfig?.customModels],
);
const isServerConfigured = !!currentConfig?.isServerConfigured;
const handleApiKeyChange = (apiKey: string) => {
setVideoProviderConfig(selectedProviderId, { apiKey });
};
const handleBaseUrlChange = (baseUrl: string) => {
setVideoProviderConfig(selectedProviderId, { baseUrl });
};
const handleTest = async () => {
setTestLoading(true);
setTestStatus('idle');
setTestMessage('');
try {
const response = await fetch('/api/verify-video-provider', {
method: 'POST',
headers: {
'x-video-provider': selectedProviderId,
'x-video-model': videoModelId || '',
'x-api-key': currentConfig?.apiKey || '',
'x-base-url': currentConfig?.baseUrl || '',
},
});
const data = await response.json();
if (data.success) {
setTestStatus('success');
setTestMessage(t('settings.videoConnectivitySuccess'));
} else {
setTestStatus('error');
setTestMessage(`${t('settings.videoConnectivityFailed')}: ${data.message}`);
}
} catch (err) {
setTestStatus('error');
setTestMessage(`${t('settings.videoConnectivityFailed')}: ${err}`);
} finally {
setTestLoading(false);
}
};
// Model CRUD
const handleOpenAddModel = () => {
setEditingModelIndex(null);
setModelForm({ id: '', name: '' });
setShowModelDialog(true);
};
const handleOpenEditModel = (index: number) => {
setEditingModelIndex(index);
setModelForm({ ...customModels[index] });
setShowModelDialog(true);
};
const handleSaveModel = useCallback(() => {
if (!modelForm.id.trim()) return;
const newCustomModels = [...customModels];
if (editingModelIndex !== null) {
newCustomModels[editingModelIndex] = {
id: modelForm.id.trim(),
name: modelForm.name.trim() || modelForm.id.trim(),
};
} else {
newCustomModels.push({
id: modelForm.id.trim(),
name: modelForm.name.trim() || modelForm.id.trim(),
});
}
setVideoProviderConfig(selectedProviderId, {
customModels: newCustomModels,
});
setShowModelDialog(false);
}, [modelForm, editingModelIndex, customModels, selectedProviderId, setVideoProviderConfig]);
const handleDeleteModel = (index: number) => {
const newCustomModels = customModels.filter((_, i) => i !== index);
setVideoProviderConfig(selectedProviderId, {
customModels: newCustomModels,
});
};
return (
<div className="space-y-6 max-w-3xl">
{/* Server-configured notice */}
{isServerConfigured && (
<div className="rounded-lg border border-blue-200 bg-blue-50 dark:border-blue-800 dark:bg-blue-950/30 p-3 text-sm text-blue-700 dark:text-blue-300">
{t('settings.serverConfiguredNotice')}
</div>
)}
{/* API Key + Test inline */}
<div className="space-y-2">
<Label>API Key</Label>
<div className="flex gap-2">
<div className="relative flex-1">
<Input
name={`video-api-key-${selectedProviderId}`}
type={showApiKey ? 'text' : 'password'}
autoComplete="new-password"
autoCapitalize="none"
autoCorrect="off"
spellCheck={false}
placeholder={
isServerConfigured
? t('settings.optionalOverride')
: selectedProviderId === 'kling'
? 'accessKey:secretKey'
: t('settings.enterApiKey')
}
value={currentConfig?.apiKey || ''}
onChange={(e) => handleApiKeyChange(e.target.value)}
className="h-8 pr-8"
/>
<button
type="button"
onClick={() => setShowApiKey(!showApiKey)}
className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
>
{showApiKey ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
</button>
</div>
<Button
variant="outline"
size="sm"
onClick={handleTest}
disabled={testLoading || (!currentConfig?.apiKey && !isServerConfigured)}
className="gap-1.5"
>
{testLoading ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<>
<Zap className="h-3.5 w-3.5" />
{t('settings.testConnection')}
</>
)}
</Button>
</div>
{testMessage && (
<div
className={cn(
'rounded-lg p-3 text-sm overflow-hidden',
testStatus === 'success' &&
'bg-green-50 text-green-700 border border-green-200 dark:bg-green-950/50 dark:text-green-400 dark:border-green-800',
testStatus === 'error' &&
'bg-red-50 text-red-700 border border-red-200 dark:bg-red-950/50 dark:text-red-400 dark:border-red-800',
)}
>
<div className="flex items-start gap-2 min-w-0">
{testStatus === 'success' && <CheckCircle2 className="h-4 w-4 mt-0.5 shrink-0" />}
{testStatus === 'error' && <XCircle className="h-4 w-4 mt-0.5 shrink-0" />}
<p className="flex-1 min-w-0 break-all">{testMessage}</p>
</div>
</div>
)}
</div>
{/* Base URL */}
<div className="space-y-2">
<Label>Base URL</Label>
<Input
name={`video-base-url-${selectedProviderId}`}
type="url"
autoComplete="off"
autoCapitalize="none"
autoCorrect="off"
spellCheck={false}
value={currentConfig?.baseUrl || ''}
onChange={(e) => handleBaseUrlChange(e.target.value)}
placeholder={
currentConfig?.serverBaseUrl ||
currentProvider?.defaultBaseUrl ||
t('settings.enterCustomBaseUrl')
}
className="h-8"
/>
{(() => {
const effectiveBaseUrl =
currentConfig?.baseUrl ||
currentConfig?.serverBaseUrl ||
currentProvider?.defaultBaseUrl ||
'';
if (!effectiveBaseUrl) return null;
return (
<p className="text-xs text-muted-foreground break-all">
{t('settings.requestUrl')}: {effectiveBaseUrl}
</p>
);
})()}
</div>
{/* Model list */}
<div className="space-y-3">
<div className="flex items-center justify-between flex-wrap gap-2">
<Label className="text-base">{t('settings.models')}</Label>
<Button variant="outline" size="sm" onClick={handleOpenAddModel} className="gap-1.5">
<Plus className="h-3.5 w-3.5" />
{t('settings.addNewModel')}
</Button>
</div>
<div className="space-y-1.5">
{/* Built-in models */}
{builtInModels.map((model) => (
<div
key={model.id}
className="flex items-center justify-between p-3 rounded-lg border border-border/50 bg-card"
>
<div className="flex-1 min-w-0">
<div className="font-mono text-sm font-medium">{model.name}</div>
<div className="text-xs text-muted-foreground font-mono mt-0.5">{model.id}</div>
</div>
</div>
))}
{/* Custom models */}
{customModels.map((model, index) => (
<div
key={`custom-${index}`}
className="flex items-center justify-between p-3 rounded-lg border border-border/50 bg-card"
>
<div className="flex-1 min-w-0">
<div className="font-mono text-sm font-medium">{model.name}</div>
<div className="text-xs text-muted-foreground font-mono mt-0.5">{model.id}</div>
</div>
<div className="flex items-center gap-1">
<Button
variant="outline"
size="sm"
className="h-8 px-2"
onClick={() => handleOpenEditModel(index)}
title={t('settings.editModel')}
>
<Settings2 className="h-3.5 w-3.5" />
</Button>
<Button
variant="outline"
size="sm"
className="h-8 px-2 text-destructive hover:text-destructive hover:bg-destructive/10"
onClick={() => handleDeleteModel(index)}
title={t('settings.deleteModel')}
>
<Trash2 className="h-3.5 w-3.5" />
</Button>
</div>
</div>
))}
</div>
</div>
{/* Add/Edit Model Dialog */}
<Dialog open={showModelDialog} onOpenChange={setShowModelDialog}>
<DialogContent className="sm:max-w-md">
<DialogTitle>
{editingModelIndex !== null ? t('settings.editModel') : t('settings.addNewModel')}
</DialogTitle>
<DialogDescription className="sr-only">
{editingModelIndex !== null ? t('settings.editModel') : t('settings.addNewModel')}
</DialogDescription>
<div className="space-y-4 pt-2">
<div className="space-y-2">
<Label>{t('settings.modelId')}</Label>
<Input
value={modelForm.id}
onChange={(e) => setModelForm((prev) => ({ ...prev, id: e.target.value }))}
placeholder="e.g. my-custom-model-v1"
className="h-8 font-mono text-sm"
/>
</div>
<div className="space-y-2">
<Label>{t('settings.modelName')}</Label>
<Input
value={modelForm.name}
onChange={(e) => setModelForm((prev) => ({ ...prev, name: e.target.value }))}
placeholder="e.g. My Custom Model"
className="h-8 text-sm"
/>
</div>
<div className="flex justify-end gap-2">
<Button variant="outline" size="sm" onClick={() => setShowModelDialog(false)}>
{t('settings.cancelEdit')}
</Button>
<Button size="sm" onClick={handleSaveModel} disabled={!modelForm.id.trim()}>
{t('settings.saveModel')}
</Button>
</div>
</div>
</DialogContent>
</Dialog>
</div>
);
}
|