|
| 1 | +import { VSCodeCheckbox } from "@vscode/webview-ui-toolkit/react" |
| 2 | +import { useEffect, useState } from "react" |
| 3 | +import { useAppTranslation } from "@/i18n/TranslationContext" |
| 4 | +import { useDebounce } from "react-use" |
| 5 | + |
| 6 | +interface RateLimitControlProps { |
| 7 | + value: number | undefined | null |
| 8 | + onChange: (value: number | undefined | null) => void |
| 9 | + maxValue?: number |
| 10 | +} |
| 11 | + |
| 12 | +export const RateLimitControl = ({ value, onChange, maxValue = 60 }: RateLimitControlProps) => { |
| 13 | + const { t } = useAppTranslation() |
| 14 | + const [isCustomRateLimit, setIsCustomRateLimit] = useState(value !== undefined) |
| 15 | + const [inputValue, setInputValue] = useState(value) |
| 16 | + useDebounce(() => onChange(inputValue), 50, [onChange, inputValue]) |
| 17 | + // Sync internal state with prop changes when switching profiles |
| 18 | + useEffect(() => { |
| 19 | + const hasCustomRateLimit = value !== undefined && value !== null |
| 20 | + setIsCustomRateLimit(hasCustomRateLimit) |
| 21 | + setInputValue(value) |
| 22 | + }, [value]) |
| 23 | + |
| 24 | + return ( |
| 25 | + <> |
| 26 | + <div> |
| 27 | + <VSCodeCheckbox |
| 28 | + checked={isCustomRateLimit} |
| 29 | + onChange={(e: any) => { |
| 30 | + const isChecked = e.target.checked |
| 31 | + setIsCustomRateLimit(isChecked) |
| 32 | + if (!isChecked) { |
| 33 | + setInputValue(null) // Unset the rate limit, note that undefined is unserializable |
| 34 | + } else { |
| 35 | + setInputValue(value ?? 0) // Use the value from apiConfiguration, if set |
| 36 | + } |
| 37 | + }}> |
| 38 | + <span className="font-medium">{t("settings:rateLimit.useCustom")}</span> |
| 39 | + </VSCodeCheckbox> |
| 40 | + <div className="text-sm text-vscode-descriptionForeground"> |
| 41 | + {t("settings:advanced.rateLimit.description")} |
| 42 | + </div> |
| 43 | + </div> |
| 44 | + |
| 45 | + {isCustomRateLimit && ( |
| 46 | + <div |
| 47 | + style={{ |
| 48 | + marginLeft: 0, |
| 49 | + paddingLeft: 10, |
| 50 | + borderLeft: "2px solid var(--vscode-button-background)", |
| 51 | + }}> |
| 52 | + <div style={{ display: "flex", alignItems: "center", gap: "5px" }}> |
| 53 | + <input |
| 54 | + type="range" |
| 55 | + min="0" |
| 56 | + max={maxValue} |
| 57 | + step="1" |
| 58 | + value={inputValue ?? 0} |
| 59 | + className="h-2 focus:outline-0 w-4/5 accent-vscode-button-background" |
| 60 | + onChange={(e) => setInputValue(parseInt(e.target.value))} |
| 61 | + /> |
| 62 | + <span>{inputValue}s</span> |
| 63 | + </div> |
| 64 | + <p className="text-vscode-descriptionForeground text-sm mt-1"> |
| 65 | + {t("settings:advanced.rateLimit.description")} |
| 66 | + </p> |
| 67 | + </div> |
| 68 | + )} |
| 69 | + </> |
| 70 | + ) |
| 71 | +} |
0 commit comments