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