refactor: prevent apiKey field creation for official providers

Improved useApiKeyState hook to explicitly handle category parameter:
- Only create apiKey field for non-official providers in add mode
- Explicitly check category !== undefined to avoid unintended behavior
- Added comprehensive comments explaining the logic
- Updated dependency array to include category parameter

This ensures official provider configs remain clean without empty apiKey fields.
This commit is contained in:
Jason
2025-10-23 12:09:59 +08:00
parent 3504fae4cb
commit ae6d16ccae
2 changed files with 13 additions and 2 deletions

View File

@@ -121,6 +121,7 @@ export function ProviderForm({
initialConfig: form.watch("settingsConfig"), initialConfig: form.watch("settingsConfig"),
onConfigChange: (config) => form.setValue("settingsConfig", config), onConfigChange: (config) => form.setValue("settingsConfig", config),
selectedPresetId, selectedPresetId,
category,
}); });
// 使用 Base URL hook (仅 Claude 模式) // 使用 Base URL hook (仅 Claude 模式)

View File

@@ -1,4 +1,5 @@
import { useState, useCallback } from "react"; import { useState, useCallback } from "react";
import type { ProviderCategory } from "@/types";
import { import {
getApiKeyFromConfig, getApiKeyFromConfig,
setApiKeyInConfig, setApiKeyInConfig,
@@ -9,6 +10,7 @@ interface UseApiKeyStateProps {
initialConfig?: string; initialConfig?: string;
onConfigChange: (config: string) => void; onConfigChange: (config: string) => void;
selectedPresetId: string | null; selectedPresetId: string | null;
category?: ProviderCategory;
} }
/** /**
@@ -19,6 +21,7 @@ export function useApiKeyState({
initialConfig, initialConfig,
onConfigChange, onConfigChange,
selectedPresetId, selectedPresetId,
category,
}: UseApiKeyStateProps) { }: UseApiKeyStateProps) {
const [apiKey, setApiKey] = useState(() => { const [apiKey, setApiKey] = useState(() => {
if (initialConfig) { if (initialConfig) {
@@ -35,14 +38,21 @@ export function useApiKeyState({
initialConfig || "{}", initialConfig || "{}",
key.trim(), key.trim(),
{ {
// 最佳实践:仅在"新增模式"且"非官方类别"时补齐缺失字段
// - 新增模式selectedPresetId !== null
// - 非官方类别category !== undefined && category !== "official"
// - 官方类别不创建字段UI 也会禁用输入框)
// - 未传入 category不创建字段避免意外行为
createIfMissing: createIfMissing:
selectedPresetId !== null && selectedPresetId !== "custom", selectedPresetId !== null &&
category !== undefined &&
category !== "official",
}, },
); );
onConfigChange(configString); onConfigChange(configString);
}, },
[initialConfig, selectedPresetId, onConfigChange], [initialConfig, selectedPresetId, category, onConfigChange],
); );
const showApiKey = useCallback( const showApiKey = useCallback(