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