import { Listbox } from "@headlessui/react"; import { ChevronDownIcon, Cog6ToothIcon, CubeIcon, PlusIcon, TrashIcon, } from "@heroicons/react/24/outline"; import { useContext, useEffect, useRef, useState } from "react"; import { useDispatch, useSelector } from "react-redux"; import styled from "styled-components"; import { defaultBorderRadius, Divider, lightGray, vscInputBackground, } from ".."; import { IdeMessengerContext } from "../../context/IdeMessenger"; import AddModelForm from "../../forms/AddModelForm"; import { defaultModelSelector } from "../../redux/selectors/modelSelectors"; import { setDefaultModel } from "../../redux/slices/stateSlice"; import { setDialogMessage, setShowDialog, } from "../../redux/slices/uiStateSlice"; import { RootState } from "../../redux/store"; import { getFontSize, getMetaKeyLabel, isMetaEquivalentKeyPressed, } from "../../util"; import ConfirmationDialog from "../dialogs/ConfirmationDialog"; interface ModelOptionProps { option: Option; idx: number; showMissingApiKeyMsg: boolean; showDelete?: boolean; } interface Option { value: string; title: string; apiKey: string; } const MAX_HEIGHT_PX = 300; const StyledListboxButton = styled(Listbox.Button)` font-family: inherit; display: flex; align-items: center; gap: 2px; border: none; cursor: pointer; font-size: ${getFontSize() - 2}px; background: transparent; color: ${lightGray}; &:focus { outline: none; } `; const StyledListboxOptions = styled(Listbox.Options)<{ $showabove: boolean }>` margin-top: 4px; position: absolute; list-style: none; padding: 0px; white-space: nowrap; cursor: default; display: flex; flex-direction: column; border-radius: ${defaultBorderRadius}; border: 0.5px solid ${lightGray}; background-color: ${vscInputBackground}; max-height: ${MAX_HEIGHT_PX}px; overflow-y: scroll; scrollbar-width: none; ${(props) => (props.$showabove ? "bottom: 100%;" : "top: 100%;")} `; const StyledListboxOption = styled(Listbox.Option)<{ isDisabled?: boolean }>` border-radius: ${defaultBorderRadius}; padding: 6px 12px; ${({ isDisabled }) => !isDisabled && ` cursor: pointer; &:hover { background: ${lightGray}33; } `} ${({ isDisabled }) => isDisabled && ` opacity: 0.5; `} `; const IconBase = styled.div<{ hovered: boolean }>` width: 1.2em; height: 1.2em; cursor: pointer; padding: 4px; border-radius: ${defaultBorderRadius}; opacity: ${(props) => (props.hovered ? 0.75 : 0)}; visibility: ${(props) => (props.hovered ? "visible" : "hidden")}; &:hover { opacity: 1; background-color: ${lightGray}33; } `; const StyledTrashIcon = styled(IconBase).attrs({ as: TrashIcon })``; const StyledCog6ToothIcon = styled(IconBase).attrs({ as: Cog6ToothIcon })``; function modelSelectTitle(model: any): string { if (model?.title) return model?.title; if (model?.model !== undefined && model?.model.trim() !== "") { if (model?.class_name) { return `${model?.class_name} - ${model?.model}`; } return model?.model; } return model?.class_name; } function ModelOption({ option, idx, showDelete, showMissingApiKeyMsg, }: ModelOptionProps) { const ideMessenger = useContext(IdeMessengerContext); const dispatch = useDispatch(); const [hovered, setHovered] = useState(false); function onClickDelete(e) { e.stopPropagation(); e.preventDefault(); dispatch(setShowDialog(true)); dispatch( setDialogMessage( { ideMessenger.post("config/deleteModel", { title: option.title, }); }} />, ), ); } function onClickGear(e) { e.stopPropagation(); e.preventDefault(); ideMessenger.post("config/openProfile", { profileId: "local", }); } function handleOptionClick(e) { if (showMissingApiKeyMsg) { e.preventDefault(); e.stopPropagation(); } } return ( setHovered(true)} onMouseLeave={() => setHovered(false)} onClick={handleOptionClick} >
{option.title} {showMissingApiKeyMsg && ( (Missing API key) )}
{showDelete && ( )}
); } function ModelSelect() { const dispatch = useDispatch(); const defaultModel = useSelector(defaultModelSelector); const allModels = useSelector( (state: RootState) => state.state.config.models, ); const ideMessenger = useContext(IdeMessengerContext); const [showAbove, setShowAbove] = useState(false); const buttonRef = useRef(null); const [options, setOptions] = useState([]); const [sortedOptions, setSortedOptions] = useState([]); const selectedProfileId = useSelector( (store: RootState) => store.state.selectedProfileId, ); // Sort so that options without an API key are at the end useEffect(() => { const enabledOptions = options.filter((option) => option.apiKey !== ""); const disabledOptions = options.filter((option) => option.apiKey === ""); const sorted = [...enabledOptions, ...disabledOptions]; setSortedOptions(sorted); }, [options]); useEffect(() => { setOptions( allModels.map((model) => { return { value: model.title, title: modelSelectTitle(model), apiKey: model.apiKey, }; }), ); }, [allModels]); useEffect(() => { const handleResize = () => calculatePosition(); window.addEventListener("resize", handleResize); return () => window.removeEventListener("resize", handleResize); }, []); useEffect(() => { const handleKeyDown = (event: KeyboardEvent) => { if (event.key === "'" && isMetaEquivalentKeyPressed(event as any)) { const direction = event.shiftKey ? -1 : 1; const currentIndex = options.findIndex( (option) => option.value === defaultModel?.title, ); let nextIndex = (currentIndex + 1 * direction) % options.length; if (nextIndex < 0) nextIndex = options.length - 1; dispatch(setDefaultModel({ title: options[nextIndex].value })); } }; window.addEventListener("keydown", handleKeyDown); return () => { window.removeEventListener("keydown", handleKeyDown); }; }, [options, defaultModel]); function calculatePosition() { const rect = buttonRef.current.getBoundingClientRect(); const spaceBelow = window.innerHeight - rect.bottom; const spaceAbove = rect.top; const dropdownHeight = MAX_HEIGHT_PX; setShowAbove(spaceBelow < dropdownHeight && spaceAbove > spaceBelow); } function onClickAddModel(e) { e.stopPropagation(); e.preventDefault(); // Close the dropdown if (buttonRef.current) { buttonRef.current.click(); } dispatch(setShowDialog(true)); dispatch( setDialogMessage( { dispatch(setShowDialog(false)); }} />, ), ); } return ( { if (val === defaultModel?.title) return; dispatch(setDefaultModel({ title: val })); await ideMessenger.request("update/modelChange", val); }} >
{modelSelectTitle(defaultModel) || "Select model"}{" "}
{sortedOptions.map((option, idx) => ( 1} showMissingApiKeyMsg={option.apiKey === ""} /> ))}
{selectedProfileId === "local" && ( <>
Add Chat model
)} {getMetaKeyLabel()} + ' to toggle
); } export default ModelSelect;