AutocompleteCombobox.tsx 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import { Autocomplete, AutocompleteItem, Tooltip } from "@nextui-org/react";
  2. import React from "react";
  3. import { useTranslation } from "react-i18next";
  4. import { I18nKey } from "#/i18n/declaration";
  5. type Label = "model" | "agent" | "language" | "securityanalyzer";
  6. const LABELS: Record<Label, I18nKey> = {
  7. model: I18nKey.CONFIGURATION$MODEL_SELECT_LABEL,
  8. agent: I18nKey.CONFIGURATION$AGENT_SELECT_LABEL,
  9. language: I18nKey.CONFIGURATION$LANGUAGE_SELECT_LABEL,
  10. securityanalyzer: I18nKey.CONFIGURATION$SECURITY_SELECT_LABEL,
  11. };
  12. const PLACEHOLDERS: Record<Label, I18nKey> = {
  13. model: I18nKey.CONFIGURATION$MODEL_SELECT_PLACEHOLDER,
  14. agent: I18nKey.CONFIGURATION$AGENT_SELECT_PLACEHOLDER,
  15. language: I18nKey.CONFIGURATION$LANGUAGE_SELECT_PLACEHOLDER,
  16. securityanalyzer: I18nKey.CONFIGURATION$SECURITY_SELECT_PLACEHOLDER,
  17. };
  18. type AutocompleteItemType = {
  19. value: string;
  20. label: string;
  21. };
  22. interface AutocompleteComboboxProps {
  23. ariaLabel: Label;
  24. items: AutocompleteItemType[];
  25. defaultKey: string;
  26. onChange: (key: string) => void;
  27. tooltip: string;
  28. allowCustomValue?: boolean;
  29. disabled?: boolean;
  30. }
  31. export function AutocompleteCombobox({
  32. ariaLabel,
  33. items,
  34. defaultKey,
  35. onChange,
  36. tooltip,
  37. allowCustomValue = false,
  38. disabled = false,
  39. }: AutocompleteComboboxProps) {
  40. const { t } = useTranslation();
  41. return (
  42. <Tooltip
  43. content={
  44. disabled
  45. ? `${tooltip} ${t(I18nKey.SETTINGS$DISABLED_RUNNING)}`
  46. : tooltip
  47. }
  48. closeDelay={100}
  49. delay={500}
  50. >
  51. <Autocomplete
  52. aria-label={ariaLabel}
  53. label={t(LABELS[ariaLabel])}
  54. placeholder={t(PLACEHOLDERS[ariaLabel])}
  55. defaultItems={items}
  56. defaultSelectedKey={defaultKey}
  57. inputValue={
  58. // Find the label for the default key, otherwise use the default key itself
  59. // This is useful when the default key is not in the list of items, in the case of a custom LLM model
  60. items.find((item) => item.value === defaultKey)?.label || defaultKey
  61. }
  62. onInputChange={(val) => {
  63. onChange(val);
  64. }}
  65. isDisabled={disabled}
  66. allowsCustomValue={allowCustomValue}
  67. >
  68. {(item) => (
  69. <AutocompleteItem key={item.value}>{item.label}</AutocompleteItem>
  70. )}
  71. </Autocomplete>
  72. </Tooltip>
  73. );
  74. }