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

CustomModelEditor.tsx

376 lines12.5 KB

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