| 1 | import { SettingsSelect } from "./SettingsSelect"; |
| 2 | import { protocolsForCatalog } from "../lib/providerCatalog"; |
| 3 | import { RotateCcw } from "lucide-react"; |
| 4 | import { providerProtocolLabel } from "../lib/providerProtocol"; |
| 5 | import { providerBrandIcons } from "../lib/providerBrandIcons"; |
| 6 | import { useId, useMemo, useState } from "react"; |
| 7 | import { useT, type DictKey } from "../lib/i18n"; |
| 8 | import type { ProviderCatalog } from "../lib/types"; |
| 9 | |
| 10 | export interface CatalogChoice { |
| 11 | id: string; |
| 12 | label?: string; |
| 13 | catalog: ProviderCatalog; |
| 14 | keyEnv: string; |
| 15 | keySet: boolean; |
| 16 | models: string[]; |
| 17 | canAdd: boolean; |
| 18 | status: string; |
| 19 | statusLabel: string; |
| 20 | actionLabel: string; |
| 21 | conflictName?: string; |
| 22 | } |
| 23 | |
| 24 | export const apiFormatLabel = providerProtocolLabel; |
| 25 | |
| 26 | const regionKeys: Record<string, DictKey> = { |
| 27 | cn: "settings.catalog.regionChina", global: "settings.catalog.regionGlobal", |
| 28 | sgp: "settings.catalog.regionSingapore", ams: "settings.catalog.regionEurope", |
| 29 | local: "settings.catalog.regionLocal", |
| 30 | }; |
| 31 | const productKeys: Record<string, DictKey> = { |
| 32 | api: "settings.catalog.productAPI", coding: "settings.catalog.productCoding", token: "settings.catalog.productToken", |
| 33 | go: "settings.catalog.productGo", zen: "settings.catalog.productZen", local: "settings.catalog.productLocal", |
| 34 | }; |
| 35 | const clusterKeys: Record<string, DictKey> = { |
| 36 | cn: "settings.catalog.clusterChina", sgp: "settings.catalog.clusterSingapore", ams: "settings.catalog.clusterEurope", |
| 37 | }; |
| 38 | |
| 39 | export function ProviderCatalogPicker({ choices, busy, onConnect, onView, onReset }: { |
| 40 | choices: CatalogChoice[]; |
| 41 | busy: boolean; |
| 42 | onConnect: (id: string, key: string, baseURL?: string, format?: string) => void; |
| 43 | onView: (name: string) => void; |
| 44 | onReset: (id: string) => void; |
| 45 | }) { |
| 46 | const t = useT(); |
| 47 | const uid = useId(); |
| 48 | const [selectedID, setSelectedID] = useState(choices.find(c => c.canAdd)?.id ?? choices[0]?.id ?? ""); |
| 49 | const [keyDraft, setKeyDraft] = useState({ id: "", keyEnv: "", value: "" }); |
| 50 | const [urlDrafts, setUrlDrafts] = useState<Record<string, string>>({}); |
| 51 | const [formatDrafts, setFormatDrafts] = useState<Record<string, string>>({}); |
| 52 | const [query, setQuery] = useState(""); |
| 53 | const [confirmReset, setConfirmReset] = useState(false); |
| 54 | const selected = choices.find(c => c.id === selectedID) ?? choices[0]; |
| 55 | const brands = useMemo(() => [...new Map(choices.map(c => [c.catalog.brandId, |
| 56 | c.catalog.brandId === "token-rhythm" ? t("settings.addProvider.preset.tokenRhythmLabel") : c.catalog.brandLabel])).entries()], [choices, t]); |
| 57 | if (!selected) return null; |
| 58 | const genericFormat = (value: string) => value === "dashscope-responses" ? "responses" : value; |
| 59 | // Official DeepSeek and MiMo connections start with Chat Completions regardless |
| 60 | // of which protocol-specific preset supplied the brand's first catalog row. |
| 61 | const defaultFormat = (selected.catalog.brandId === "deepseek" && selected.catalog.product === "api") || selected.catalog.brandId === "mimo" |
| 62 | ? "openai" : genericFormat(selected.catalog.format); |
| 63 | const format = formatDrafts[selected.id] ?? defaultFormat; |
| 64 | const protocols = protocolsForCatalog(selected.catalog); |
| 65 | const defaultURL = protocols[format]?.baseUrl ?? selected.catalog.baseUrl ?? ""; |
| 66 | const baseURL = urlDrafts[selected.id] ?? defaultURL; |
| 67 | let validURL = !selected.catalog.baseUrl; |
| 68 | try { const u = new URL(baseURL); validURL = (u.protocol === "https:" || u.protocol === "http:") && Boolean(u.hostname) && !u.username && !u.password; } catch { /* invalid draft */ } |
| 69 | const key = keyDraft.id === selected.id && keyDraft.keyEnv === selected.keyEnv ? keyDraft.value : ""; |
| 70 | const siblings = choices.filter(c => c.catalog.brandId === selected.catalog.brandId); |
| 71 | const productChoices = siblings.filter(c => c.catalog.product === selected.catalog.product); |
| 72 | const formatChoices = productChoices.filter(c => c.catalog.region === selected.catalog.region); |
| 73 | const pick = (choice: CatalogChoice | undefined) => { |
| 74 | if (!choice) return; |
| 75 | setSelectedID(choice.id); |
| 76 | setKeyDraft({id: "", keyEnv: "", value: ""}); |
| 77 | setConfirmReset(false); |
| 78 | }; |
| 79 | const chooseDimension = (dimension: "region" | "product", value: string) => { |
| 80 | const candidates = (dimension === "product" ? siblings : productChoices) |
| 81 | .filter(c => c.catalog[dimension] === value); |
| 82 | const choice = candidates.find(c => c.catalog.region === selected.catalog.region && genericFormat(c.catalog.format) === format) |
| 83 | ?? candidates.find(c => genericFormat(c.catalog.format) === format) |
| 84 | ?? candidates.find(c => c.catalog.region === selected.catalog.region) ?? candidates[0]; |
| 85 | pick(choice); |
| 86 | if (choice && genericFormat(choice.catalog.format) === format) { |
| 87 | setFormatDrafts(prev => ({...prev, [choice.id]: format})); |
| 88 | } |
| 89 | }; |
| 90 | const field = (dimension: "region" | "product", label: DictKey, candidates: CatalogChoice[]) => { |
| 91 | const values = [...new Set(candidates.map(c => c.catalog[dimension]))]; |
| 92 | const labels = dimension === "region" ? (label === "settings.catalog.cluster" ? clusterKeys : regionKeys) : productKeys; |
| 93 | return <div className="provider-catalog__field"> |
| 94 | <label className="set-label" htmlFor={`${uid}-${dimension}`}>{t(label)}</label> |
| 95 | <SettingsSelect id={`${uid}-${dimension}`} className="mem-select" disabled={busy || values.length < 2} |
| 96 | value={selected.catalog[dimension]} onValueChange={value => chooseDimension(dimension, value)}> |
| 97 | {values.map(value => <option key={value} value={value}>{labels[value] ? t(labels[value]) : value}</option>)} |
| 98 | </SettingsSelect> |
| 99 | </div>; |
| 100 | }; |
| 101 | const hasProducts = new Set(siblings.map(c => c.catalog.product)).size > 1; |
| 102 | const hasRegions = new Set(productChoices.map(c => c.catalog.region)).size > 1; |
| 103 | return <div className="provider-catalog"> |
| 104 | <aside className="provider-catalog__sidebar"> |
| 105 | <input className="mem-input" aria-label={t("settings.catalog.search")} placeholder={t("settings.catalog.search")} |
| 106 | value={query} onChange={e => setQuery(e.target.value)} /> |
| 107 | <div className="provider-catalog__brands" aria-label={t("settings.catalog.providers")}> |
| 108 | {brands.filter(([id, label]) => `${id} ${label}`.toLowerCase().includes(query.trim().toLowerCase())).map(([id, label]) => |
| 109 | <button key={id} type="button" className="provider-catalog__brand" aria-pressed={selected.catalog.brandId === id} |
| 110 | disabled={busy} onClick={() => pick(choices.find(c => c.catalog.brandId === id && c.canAdd) ?? choices.find(c => c.catalog.brandId === id))}> |
| 111 | {providerBrandIcons.has(id) |
| 112 | ? <span className="provider-catalog__icon" aria-hidden="true" style={{maskImage: `url(/provider-icons/${id}.svg)`, WebkitMaskImage: `url(/provider-icons/${id}.svg)`}} /> |
| 113 | : <span className="provider-catalog__monogram" aria-hidden="true">{label.slice(0, 1)}</span>}<span>{label}</span> |
| 114 | </button>)} |
| 115 | </div> |
| 116 | </aside> |
| 117 | <section className="provider-catalog__detail" aria-label={selected.catalog.brandLabel}> |
| 118 | <strong className="provider-catalog__title">{selected.catalog.brandLabel}</strong> |
| 119 | {(hasProducts || hasRegions) && <div className="provider-catalog__options"> |
| 120 | {hasProducts && field("product", "settings.catalog.product", siblings)} |
| 121 | {hasRegions && field("region", selected.catalog.brandId === "mimo" && selected.catalog.product === "token" ? "settings.catalog.cluster" : "settings.catalog.region", productChoices)} |
| 122 | </div>} |
| 123 | {selected.catalog.brandId === "mimo" && selected.catalog.product === "token" && <div className="mem-hint">{t("settings.catalog.mimoTokenPlanHint")}</div>} |
| 124 | <div className="provider-catalog__field"> |
| 125 | <label className="set-label" htmlFor={`${uid}-format`}>{t("settings.providerProtocol")}</label> |
| 126 | <SettingsSelect id={`${uid}-format`} className="mem-select" disabled={busy} value={format} |
| 127 | onValueChange={value => { |
| 128 | const next = value; |
| 129 | const match = formatChoices.find(c => genericFormat(c.catalog.format) === next); |
| 130 | if (match) { |
| 131 | if (Object.prototype.hasOwnProperty.call(urlDrafts, selected.id)) setUrlDrafts(prev => ({...prev, [match.id]: baseURL})); |
| 132 | else setUrlDrafts(prev => { const copy = {...prev}; delete copy[match.id]; return copy; }); |
| 133 | setKeyDraft({id: match.id, keyEnv: match.keyEnv, value: key}); |
| 134 | setSelectedID(match.id); |
| 135 | setFormatDrafts(prev => ({...prev, [match.id]: next})); |
| 136 | } else setFormatDrafts(prev => ({...prev, [selected.id]: next})); |
| 137 | }}> |
| 138 | {["openai", "responses", "anthropic"].map(value => <option key={value} value={value}>{apiFormatLabel(value)}</option>)} |
| 139 | {selected.catalog.format === "bundle" && <option value="bundle">{t("settings.catalog.formatBundle")}</option>} |
| 140 | </SettingsSelect> |
| 141 | {!protocols[format] && !formatChoices.some(c => genericFormat(c.catalog.format) === format) && <div className="mem-hint">{t("settings.catalog.verifyFormat")}</div>} |
| 142 | </div> |
| 143 | {formatChoices.filter(c => c.catalog.format === selected.catalog.format).length > 1 && <div className="provider-catalog__field"> |
| 144 | <label className="set-label" htmlFor={`${uid}-variant`}>{t("settings.catalog.variant")}</label> |
| 145 | <SettingsSelect id={`${uid}-variant`} className="mem-select" value={selected.id} disabled={busy} onValueChange={value => pick(choices.find(c => c.id === value))}> |
| 146 | {formatChoices.filter(c => c.catalog.format === selected.catalog.format).map(c => <option key={c.id} value={c.id}>{c.label || c.id}</option>)} |
| 147 | </SettingsSelect> |
| 148 | </div>} |
| 149 | {selected.catalog.brandId === "anthropic" && <div className="mem-hint">{t("settings.catalog.anthropicHint")}</div>} |
| 150 | {selected.catalog.region === "local" && <div className="mem-hint">{t("settings.catalog.localHint")}</div>} |
| 151 | {selected.catalog.baseUrl && <div className="provider-catalog__field"> |
| 152 | <label className="set-label" htmlFor={`${uid}-url`}>Base URL</label> |
| 153 | <div className="provider-catalog__url-control"> |
| 154 | <input id={`${uid}-url`} className="mem-input" value={baseURL} disabled={busy} aria-invalid={!validURL} onChange={e => setUrlDrafts(prev => ({...prev, [selected.id]:e.target.value}))} /> |
| 155 | {baseURL !== defaultURL && <button type="button" className="provider-catalog__restore" disabled={busy} aria-label={t("settings.catalog.restoreURL")} title={t("settings.catalog.restoreURL")} onClick={() => setUrlDrafts(prev => { const next = {...prev}; delete next[selected.id]; return next; })}><RotateCcw size={16}/></button>} |
| 156 | </div> |
| 157 | <div className="mem-hint">{t("settings.catalog.endpointHint")}</div> |
| 158 | </div>} |
| 159 | <label className="set-label" htmlFor={`${uid}-key`}>API Key</label> |
| 160 | <input id={`${uid}-key`} className="mem-input" type="password" autoComplete="off" |
| 161 | placeholder={t("settings.setKey", {env: selected.keyEnv})} value={key} |
| 162 | disabled={busy || !selected.canAdd} onChange={e => setKeyDraft({id: selected.id, keyEnv: selected.keyEnv, value: e.target.value})} /> |
| 163 | {selected.keySet && <div className="mem-hint">{t("settings.catalog.savedKey")}</div>} |
| 164 | <div className="provider-catalog__models"><span className="set-label">{t("settings.catalog.models")}</span> |
| 165 | <span>{selected.models.join(", ") || t("settings.catalog.modelsAfterConnect")}</span> |
| 166 | </div> |
| 167 | {selected.statusLabel && <div role="status" className="mem-hint">{selected.statusLabel}</div>} |
| 168 | <div className="prov-card__actions"> |
| 169 | {selected.conflictName && <button type="button" className="btn btn--small" disabled={busy} onClick={() => onView(selected.conflictName!)}>{t("settings.addProvider.viewPresetProvider")}</button>} |
| 170 | {(selected.status === "name_conflict" || selected.status === "installed_modified") && <button type="button" className="btn btn--small" disabled={busy} |
| 171 | onClick={() => { if (confirmReset) { onReset(selected.id); setConfirmReset(false); } else setConfirmReset(true); }}> |
| 172 | {t(confirmReset ? "settings.addProvider.confirmResetPreset" : "settings.addProvider.resetPreset")} |
| 173 | </button>} |
| 174 | <button type="button" className="btn btn--small btn--primary" disabled={busy || !selected.canAdd || !validURL} |
| 175 | onClick={() => onConnect(selected.id, key.trim(), baseURL.trim() || undefined, format === genericFormat(selected.catalog.format) ? undefined : format)}>{selected.actionLabel}</button> |
| 176 | </div> |
| 177 | </section> |
| 178 | </div>; |
| 179 | } |
| 180 |