Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

CustomModelEditor.tsx

380 lines12.6 KB

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