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

CustomModelEditor.tsx

408 lines13.9 KB

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