Open History to see the last commit
1import {
2 type ProviderInstanceId,
3 type ProviderDriverKind,
4 type ResolvedKeybindingsConfig,
5} from "@t3tools/contracts";
6import { memo, useEffect, useMemo, useState } from "react";
7import type { VariantProps } from "class-variance-authority";
8import { ChevronDownIcon } from "lucide-react";
9import { Button, buttonVariants } from "../ui/button";
10import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
11import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
12import { cn } from "~/lib/utils";
13import { ModelPickerContent } from "./ModelPickerContent";
14import { ProviderInstanceIcon } from "./ProviderInstanceIcon";
15import {
16 ModelEsque,
17 getTriggerDisplayModelLabel,
18 getTriggerDisplayModelName,
19} from "./providerIconUtils";
20import type { ProviderInstanceEntry } from "../../providerInstances";
21
22export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
23 /**
24 * The instance currently selected in the composer. Drives the trigger
25 * icon, label and the default-highlighted combobox row.
26 */
27 activeInstanceId: ProviderInstanceId;
28 model: string;
29 lockedProvider: ProviderDriverKind | null;
30 lockedContinuationGroupKey?: string | null;
31 /** Instance entries rendered in the sidebar + used to resolve display name. */
32 instanceEntries: ReadonlyArray<ProviderInstanceEntry>;
33 keybindings?: ResolvedKeybindingsConfig;
34 modelOptionsByInstance: ReadonlyMap<ProviderInstanceId, ReadonlyArray<ModelEsque>>;
35 activeProviderIconClassName?: string;
36 compact?: boolean;
37 disabled?: boolean;
38 terminalOpen?: boolean;
39 open?: boolean;
40 triggerVariant?: VariantProps<typeof buttonVariants>["variant"];
41 triggerClassName?: string;
42 onOpenChange?: (open: boolean) => void;
43 getModelDisabledReason?: (instanceId: ProviderInstanceId, model: string) => string | null;
44 onInstanceModelChange: (instanceId: ProviderInstanceId, model: string) => void;
45}) {
46 const [uncontrolledIsMenuOpen, setUncontrolledIsMenuOpen] = useState(false);
47 const isMenuOpen = props.open ?? uncontrolledIsMenuOpen;
48
49 // Resolve the active instance entry by exact routing key. The composer
50 // resolves fallbacks before rendering this component; if the selected
51 // instance disappears, do not infer a replacement from its driver kind.
52 const activeEntry = useMemo(() => {
53 return (
54 props.instanceEntries.find((entry) => entry.instanceId === props.activeInstanceId) ?? null
55 );
56 }, [props.activeInstanceId, props.instanceEntries]);
57
58 const activeInstanceId = props.activeInstanceId;
59 const selectedInstanceOptions = props.modelOptionsByInstance.get(activeInstanceId) ?? [];
60 // If the current slug belongs to a different instance (for example after
61 // a provider switch or disable), prefer the active instance's first
62 // option so the trigger icon and label stay in sync instead of showing
63 // a stale foreign slug.
64 const selectedModel =
65 selectedInstanceOptions.find((option) => option.slug === props.model) ??
66 selectedInstanceOptions[0];
67 const triggerTitle = selectedModel ? getTriggerDisplayModelName(selectedModel) : props.model;
68 const triggerLabel = selectedModel ? getTriggerDisplayModelLabel(selectedModel) : props.model;
69 const duplicateDriverCount = props.instanceEntries.filter(
70 (entry) => activeEntry !== null && entry.driverKind === activeEntry.driverKind,
71 ).length;
72 const showInstanceBadge = Boolean(activeEntry?.accentColor) || duplicateDriverCount > 1;
73
74 const setIsMenuOpen = (open: boolean) => {
75 props.onOpenChange?.(open);
76 if (props.open === undefined) {
77 setUncontrolledIsMenuOpen(open);
78 }
79 };
80
81 useEffect(() => {
82 if (!isMenuOpen) {
83 return;
84 }
85
86 const { documentElement, body } = document;
87 const previousDocumentOverscrollBehavior = documentElement.style.overscrollBehavior;
88 const previousBodyOverflow = body.style.overflow;
89 const previousBodyPaddingRight = body.style.paddingRight;
90 const scrollbarWidth = window.innerWidth - documentElement.clientWidth;
91
92 documentElement.style.overscrollBehavior = "contain";
93 body.style.overflow = "hidden";
94 if (scrollbarWidth > 0) {
95 body.style.paddingRight = `${scrollbarWidth}px`;
96 }
97
98 const shouldAllowOverlayScroll = (target: EventTarget | null) => {
99 return target instanceof Element && target.closest("[data-model-picker-content]");
100 };
101 const preventBackgroundWheel = (event: WheelEvent) => {
102 if (shouldAllowOverlayScroll(event.target)) {
103 return;
104 }
105 event.preventDefault();
106 };
107 const preventBackgroundTouchMove = (event: TouchEvent) => {
108 if (shouldAllowOverlayScroll(event.target)) {
109 return;
110 }
111 event.preventDefault();
112 };
113
114 document.addEventListener("wheel", preventBackgroundWheel, { capture: true, passive: false });
115 document.addEventListener("touchmove", preventBackgroundTouchMove, {
116 capture: true,
117 passive: false,
118 });
119
120 return () => {
121 document.removeEventListener("wheel", preventBackgroundWheel, { capture: true });
122 document.removeEventListener("touchmove", preventBackgroundTouchMove, { capture: true });
123 documentElement.style.overscrollBehavior = previousDocumentOverscrollBehavior;
124 body.style.overflow = previousBodyOverflow;
125 body.style.paddingRight = previousBodyPaddingRight;
126 };
127 }, [isMenuOpen]);
128
129 const handleInstanceModelChange = (instanceId: ProviderInstanceId, model: string) => {
130 if (props.disabled) return;
131 props.onInstanceModelChange(instanceId, model);
132 setIsMenuOpen(false);
133 };
134
135 return (
136 <Popover
137 open={isMenuOpen}
138 onOpenChange={(open) => {
139 if (props.disabled) {
140 setIsMenuOpen(false);
141 return;
142 }
143 setIsMenuOpen(open);
144 }}
145 >
146 <PopoverTrigger
147 render={
148 <Button
149 size="sm"
150 variant={props.triggerVariant ?? "ghost"}
151 data-chat-provider-model-picker="true"
152 className={cn(
153 "min-w-0 justify-between whitespace-nowrap px-2 text-muted-foreground/70 hover:text-foreground/80",
154 props.compact ? "max-w-42 shrink-0" : "max-w-48 shrink sm:max-w-56 sm:px-3",
155 props.triggerClassName,
156 )}
157 disabled={props.disabled}
158 />
159 }
160 >
161 <span className="flex min-w-0 flex-1 items-center gap-2">
162 {activeEntry ? (
163 <ProviderInstanceIcon
164 driverKind={activeEntry.driverKind}
165 displayName={activeEntry.displayName}
166 accentColor={activeEntry.accentColor}
167 showBadge={showInstanceBadge}
168 className={showInstanceBadge ? "size-5" : "size-4"}
169 iconClassName={cn("size-4", props.activeProviderIconClassName)}
170 indicatorBackground="var(--input)"
171 badgeClassName={cn(
172 "right-[-0.125rem] bottom-[-0.125rem] h-3 min-w-3",
173 "px-0.5 text-[7px]",
174 )}
175 />
176 ) : null}
177 <Tooltip>
178 <TooltipTrigger render={<span className="min-w-0 flex-1 overflow-hidden truncate" />}>
179 {triggerTitle}
180 </TooltipTrigger>
181 <TooltipPopup side="top">{triggerLabel}</TooltipPopup>
182 </Tooltip>
183 </span>
184 <span aria-hidden="true" className="flex items-center">
185 <ChevronDownIcon aria-hidden="true" className="!ms-0 !-me-1 size-3 shrink-0 opacity-60" />
186 </span>
187 </PopoverTrigger>
188 <PopoverPopup
189 align="start"
190 className="border-0 bg-transparent p-0 shadow-none before:hidden [--viewport-inline-padding:0]"
191 viewportClassName="!overflow-hidden p-0"
192 >
193 <ModelPickerContent
194 activeInstanceId={activeInstanceId}
195 model={props.model}
196 lockedProvider={props.lockedProvider}
197 lockedContinuationGroupKey={props.lockedContinuationGroupKey ?? null}
198 instanceEntries={props.instanceEntries}
199 {...(props.keybindings ? { keybindings: props.keybindings } : {})}
200 modelOptionsByInstance={props.modelOptionsByInstance}
201 terminalOpen={props.terminalOpen ?? false}
202 onRequestClose={() => setIsMenuOpen(false)}
203 {...(props.getModelDisabledReason
204 ? { getModelDisabledReason: props.getModelDisabledReason }
205 : {})}
206 onInstanceModelChange={handleInstanceModelChange}
207 />
208 </PopoverPopup>
209 </Popover>
210 );
211});