Open History to see the last commit
1"use client";
2
3import { PlusIcon, XIcon } from "lucide-react";
4import { useMemo, useState } from "react";
5import type { ProviderDriverKind, ServerProviderModel } from "@t3tools/contracts";
6import type { CustomModelDefinition } from "@t3tools/shared/model";
7
8import { cn } from "../../lib/utils";
9import { Button } from "../ui/button";
10import { Input } from "../ui/input";
11import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
12import { Switch } from "../ui/switch";
13import {
14 DESCRIPTOR_PRESETS_BY_KIND,
15 type CustomModelDraft,
16 type EditorChoice,
17 type EditorDescriptor,
18 choiceFromPreset,
19 definitionFromDraft,
20 descriptorFromPreset,
21 descriptorsFromCapabilities,
22 draftFromDefinition,
23 emptyEditorChoice,
24 emptyEditorDescriptor,
25 validateDraft,
26} from "./customModelEditor.logic";
27
28const CUSTOM_ID_VALUE = "__custom__";
29const START_FROM_NONE = "__none__";
30
31interface CustomModelEditorProps {
32 readonly instanceId: string;
33 readonly driverKind: ProviderDriverKind | null;
34 readonly entry: CustomModelDefinition;
35 /** Built-in models whose descriptors can be copied as a starting point. */
36 readonly builtInModels: ReadonlyArray<ServerProviderModel>;
37 readonly onSave: (next: CustomModelDefinition) => void;
38 readonly onCancel: () => void;
39}
40
41/**
42 * Inline editor for one custom model: display name plus the option
43 * descriptors the composer should offer for it (Reasoning effort, Fast
44 * mode, ...). Draft state is local; nothing is persisted until Save.
45 */
46export function CustomModelEditor({
47 instanceId,
48 driverKind,
49 entry,
50 builtInModels,
51 onSave,
52 onCancel,
53}: CustomModelEditorProps) {
54 const [draft, setDraft] = useState<CustomModelDraft>(() => draftFromDefinition(entry));
55 const [error, setError] = useState<string | null>(null);
56 const presets = useMemo(
57 () => (driverKind ? (DESCRIPTOR_PRESETS_BY_KIND[driverKind] ?? []) : []),
58 [driverKind],
59 );
60 const startFromCandidates = useMemo(
61 () => builtInModels.filter((model) => (model.capabilities?.optionDescriptors?.length ?? 0) > 0),
62 [builtInModels],
63 );
64 const domId = (suffix: string) => `provider-instance-${instanceId}-custom-model-${suffix}`;
65
66 const updateDescriptor = (key: string, patch: Partial<EditorDescriptor>) => {
67 setError(null);
68 setDraft((current) => ({
69 ...current,
70 descriptors: current.descriptors.map((descriptor) =>
71 descriptor.key === key ? { ...descriptor, ...patch } : descriptor,
72 ),
73 }));
74 };
75
76 const updateChoice = (descriptorKey: string, choiceKey: string, patch: Partial<EditorChoice>) => {
77 setError(null);
78 setDraft((current) => ({
79 ...current,
80 descriptors: current.descriptors.map((descriptor) => {
81 if (descriptor.key !== descriptorKey) return descriptor;
82 return {
83 ...descriptor,
84 choices: descriptor.choices.map((choice) => {
85 if (choice.key === choiceKey) return { ...choice, ...patch };
86 // Only one choice can be the default.
87 return patch.isDefault ? { ...choice, isDefault: false } : choice;
88 }),
89 };
90 }),
91 }));
92 };
93
94 const removeDescriptor = (key: string) => {
95 setError(null);
96 setDraft((current) => ({
97 ...current,
98 descriptors: current.descriptors.filter((descriptor) => descriptor.key !== key),
99 }));
100 };
101
102 const addDescriptor = (descriptor: EditorDescriptor) => {
103 setError(null);
104 setDraft((current) => ({ ...current, descriptors: [...current.descriptors, descriptor] }));
105 };
106
107 // Selecting a preset id replaces the descriptor's label/type/choices so the
108 // usual values are one click away; "Custom…" leaves the row blank to type into.
109 const applyPresetId = (descriptor: EditorDescriptor, value: string | null) => {
110 if (value === null) return;
111 if (value === CUSTOM_ID_VALUE) {
112 updateDescriptor(descriptor.key, { id: "" });
113 return;
114 }
115 const preset = presets.find((candidate) => candidate.id === value);
116 if (!preset) return;
117 updateDescriptor(descriptor.key, {
118 id: preset.id,
119 label: preset.label,
120 type: preset.type,
121 choices: (preset.choices ?? []).map(choiceFromPreset),
122 currentBooleanValue: undefined,
123 description: undefined,
124 });
125 };
126
127 const handleStartFrom = (slug: string | null) => {
128 if (slug === null || slug === START_FROM_NONE) return;
129 const model = startFromCandidates.find((candidate) => candidate.slug === slug);
130 if (!model) return;
131 setError(null);
132 setDraft((current) => ({
133 ...current,
134 descriptors: descriptorsFromCapabilities(model.capabilities, driverKind),
135 }));
136 };
137
138 const handleSave = () => {
139 const problem = validateDraft(draft);
140 if (problem) {
141 setError(problem);
142 return;
143 }
144 onSave(definitionFromDraft(draft));
145 };
146
147 const idSelectValue = (descriptor: EditorDescriptor) =>
148 presets.some((preset) => preset.id === descriptor.id) ? descriptor.id : CUSTOM_ID_VALUE;
149
150 const renderChoice = (descriptor: EditorDescriptor, choice: EditorChoice) => (
151 <div key={choice.key} className="flex items-center gap-2">
152 <Input
153 size="compact"
154 value={choice.id}
155 onChange={(event) => updateChoice(descriptor.key, choice.key, { id: event.target.value })}
156 placeholder="value"
157 className="w-28 font-mono"
158 spellCheck={false}
159 aria-label="Choice value"
160 />
161 <Input
162 size="compact"
163 value={choice.label}
164 onChange={(event) =>
165 updateChoice(descriptor.key, choice.key, { label: event.target.value })
166 }
167 placeholder="Label"
168 className="min-w-0 flex-1"
169 aria-label="Choice label"
170 />
171 <label className="flex shrink-0 items-center gap-1.5 text-[11px] text-muted-foreground">
172 <Switch
173 size="sm"
174 checked={choice.isDefault}
175 onCheckedChange={(checked) =>
176 updateChoice(descriptor.key, choice.key, { isDefault: checked })
177 }
178 aria-label="Default choice"
179 />
180 Default
181 </label>
182 <Button
183 size="icon-micro"
184 variant="ghost-muted"
185 aria-label="Remove choice"
186 onClick={() =>
187 updateDescriptor(descriptor.key, {
188 choices: descriptor.choices.filter((candidate) => candidate.key !== choice.key),
189 })
190 }
191 >
192 <XIcon className="size-3" />
193 </Button>
194 </div>
195 );
196
197 const renderDescriptor = (descriptor: EditorDescriptor, index: number) => (
198 <div
199 key={descriptor.key}
200 className="flex flex-col gap-2 rounded-md border border-border/60 bg-background/40 p-2.5"
201 >
202 <div className="flex flex-wrap items-center gap-2">
203 <span className="w-14 shrink-0 text-[11px] text-muted-foreground">Option {index + 1}</span>
204 {presets.length > 0 ? (
205 <Select
206 value={idSelectValue(descriptor)}
207 onValueChange={(value) => applyPresetId(descriptor, value)}
208 >
209 <SelectTrigger size="compact" className="w-40" aria-label="Option id">
210 <SelectValue>
211 {idSelectValue(descriptor) === CUSTOM_ID_VALUE ? "Custom…" : descriptor.id}
212 </SelectValue>
213 </SelectTrigger>
214 <SelectPopup align="start" alignItemWithTrigger={false}>
215 {presets.map((preset) => (
216 <SelectItem key={preset.id} value={preset.id}>
217 <span className="flex items-baseline gap-2">
218 <code className="font-mono text-xs">{preset.id}</code>
219 <span className="text-muted-foreground">{preset.label}</span>
220 </span>
221 </SelectItem>
222 ))}
223 <SelectItem value={CUSTOM_ID_VALUE}>Custom…</SelectItem>
224 </SelectPopup>
225 </Select>
226 ) : null}
227 {idSelectValue(descriptor) === CUSTOM_ID_VALUE ? (
228 <Input
229 size="compact"
230 value={descriptor.id}
231 onChange={(event) => updateDescriptor(descriptor.key, { id: event.target.value })}
232 placeholder="optionId"
233 className="w-36 font-mono"
234 spellCheck={false}
235 aria-label="Option id"
236 />
237 ) : null}
238 <Input
239 size="compact"
240 value={descriptor.label}
241 onChange={(event) => updateDescriptor(descriptor.key, { label: event.target.value })}
242 placeholder="Label"
243 className="min-w-0 flex-1"
244 aria-label="Option label"
245 />
246 <Select
247 value={descriptor.type}
248 onValueChange={(value) =>
249 updateDescriptor(descriptor.key, { type: value === "boolean" ? "boolean" : "select" })
250 }
251 >
252 <SelectTrigger size="compact" className="w-24" aria-label="Option type">
253 <SelectValue>{descriptor.type === "boolean" ? "Toggle" : "Choices"}</SelectValue>
254 </SelectTrigger>
255 <SelectPopup align="end" alignItemWithTrigger={false}>
256 <SelectItem value="select">Choices</SelectItem>
257 <SelectItem value="boolean">Toggle</SelectItem>
258 </SelectPopup>
259 </Select>
260 <Button
261 size="icon-micro"
262 variant="ghost-muted"
263 aria-label={`Remove option ${index + 1}`}
264 onClick={() => removeDescriptor(descriptor.key)}
265 >
266 <XIcon className="size-3" />
267 </Button>
268 </div>
269 {descriptor.type === "select" ? (
270 <div className="flex flex-col gap-1.5 pl-16">
271 {descriptor.choices.map((choice) => renderChoice(descriptor, choice))}
272 <Button
273 type="button"
274 size="xs"
275 variant="ghost-muted"
276 className="-ml-2 self-start"
277 onClick={() =>
278 updateDescriptor(descriptor.key, {
279 choices: [...descriptor.choices, emptyEditorChoice()],
280 })
281 }
282 >
283 <PlusIcon className="size-3" />
284 Add choice
285 </Button>
286 </div>
287 ) : null}
288 </div>
289 );
290
291 return (
292 <div
293 className="mx-2 mt-1 mb-2 flex flex-col gap-3 rounded-md border border-border bg-muted/20 p-3"
294 onKeyDown={(event) => {
295 if (event.key === "Escape") {
296 event.preventDefault();
297 onCancel();
298 }
299 }}
300 >
301 <div className="flex flex-col gap-1">
302 <label htmlFor={domId("name")} className="text-xs text-muted-foreground">
303 Display name
304 </label>
305 <Input
306 id={domId("name")}
307 size="sm"
308 autoFocus
309 value={draft.name}
310 onChange={(event) => setDraft((current) => ({ ...current, name: event.target.value }))}
311 placeholder={draft.slug}
312 className="sm:w-72"
313 spellCheck={false}
314 />
315 </div>
316
317 <div className="flex flex-col gap-2">
318 <div className="flex flex-wrap items-center justify-between gap-2">
319 <span className="text-xs text-muted-foreground">Options shown in the composer</span>
320 {startFromCandidates.length > 0 ? (
321 <Select value={START_FROM_NONE} onValueChange={handleStartFrom}>
322 <SelectTrigger
323 size="compact"
324 className="w-44"
325 aria-label="Copy options from a built-in model"
326 >
327 <SelectValue>Copy from…</SelectValue>
328 </SelectTrigger>
329 <SelectPopup align="end" alignItemWithTrigger={false}>
330 {startFromCandidates.map((model) => (
331 <SelectItem key={model.slug} value={model.slug}>
332 {model.name}
333 </SelectItem>
334 ))}
335 </SelectPopup>
336 </Select>
337 ) : null}
338 </div>
339 {draft.descriptors.length === 0 ? (
340 <p className="text-xs text-muted-foreground/70">
341 No custom options. The composer uses the provider's default options.
342 </p>
343 ) : null}
344 {draft.descriptors.map(renderDescriptor)}
345 <div className="flex flex-wrap gap-1">
346 {presets
347 .filter(
348 (preset) => !draft.descriptors.some((descriptor) => descriptor.id === preset.id),
349 )
350 .map((preset) => (
351 <Button
352 key={preset.id}
353 type="button"
354 size="xs"
355 variant="ghost-muted"
356 className={cn("-ml-2 first:ml-0")}
357 onClick={() => addDescriptor(descriptorFromPreset(preset))}
358 >
359 <PlusIcon className="size-3" />
360 {preset.label}
361 </Button>
362 ))}
363 <Button
364 type="button"
365 size="xs"
366 variant="ghost-muted"
367 onClick={() => addDescriptor(emptyEditorDescriptor())}
368 >
369 <PlusIcon className="size-3" />
370 Custom option
371 </Button>
372 </div>
373 </div>
374
375 {error ? <p className="text-xs text-destructive">{error}</p> : null}
376
377 <div className="flex gap-2">
378 <Button size="sm" variant="outline" onClick={handleSave}>
379 Save
380 </Button>
381 <Button size="sm" variant="ghost" onClick={onCancel}>
382 Cancel
383 </Button>
384 </div>
385 </div>
386 );
387}