|
| 1 | +import { VSCodeCheckbox, VSCodeTextField } 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 SeedControlProps { |
| 7 | + value: number | string | undefined | null |
| 8 | + onChange: (value: number | string | undefined | null) => void |
| 9 | +} |
| 10 | + |
| 11 | +export const SeedControl = ({ value, onChange }: SeedControlProps) => { |
| 12 | + const { t } = useAppTranslation() |
| 13 | + const [isCustomSeed, setIsCustomSeed] = useState(value !== undefined && value !== null && value !== "") |
| 14 | + const [inputValue, setInputValue] = useState<string>(value?.toString() ?? "") |
| 15 | + |
| 16 | + useDebounce( |
| 17 | + () => { |
| 18 | + if (inputValue === "") { |
| 19 | + onChange(null) |
| 20 | + } else { |
| 21 | + const numValue = parseInt(inputValue, 10) |
| 22 | + if (!isNaN(numValue)) { |
| 23 | + onChange(numValue) |
| 24 | + } |
| 25 | + } |
| 26 | + }, |
| 27 | + 50, |
| 28 | + [onChange, inputValue] |
| 29 | + ) |
| 30 | + |
| 31 | + // Sync internal state with prop changes when switching profiles. |
| 32 | + useEffect(() => { |
| 33 | + const hasCustomSeed = value !== undefined && value !== null && value !== "" |
| 34 | + setIsCustomSeed(hasCustomSeed) |
| 35 | + setInputValue(value?.toString() ?? "") |
| 36 | + }, [value]) |
| 37 | + |
| 38 | + const handleCheckboxChange = (e: React.ChangeEvent<HTMLInputElement>) => { |
| 39 | + const isChecked = e.target.checked |
| 40 | + setIsCustomSeed(isChecked) |
| 41 | + |
| 42 | + if (!isChecked) { |
| 43 | + setInputValue("") |
| 44 | + } else { |
| 45 | + setInputValue(value?.toString() ?? "") |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => { |
| 50 | + setInputValue(e.target.value) |
| 51 | + } |
| 52 | + |
| 53 | + return ( |
| 54 | + <> |
| 55 | + <div> |
| 56 | + <VSCodeCheckbox |
| 57 | + checked={isCustomSeed} |
| 58 | + onChange={handleCheckboxChange}> |
| 59 | + <label className="block font-medium mb-1">{t("settings:seed.useCustom")}</label> |
| 60 | + </VSCodeCheckbox> |
| 61 | + <div className="text-sm text-vscode-descriptionForeground mt-1"> |
| 62 | + {t("settings:seed.description")} |
| 63 | + </div> |
| 64 | + </div> |
| 65 | + |
| 66 | + {isCustomSeed && ( |
| 67 | + <div className="flex flex-col gap-3 pl-3 border-l-2 border-vscode-button-background"> |
| 68 | + <div> |
| 69 | + <VSCodeTextField |
| 70 | + type="text" |
| 71 | + value={inputValue} |
| 72 | + onInput={handleInputChange} |
| 73 | + className="w-full" |
| 74 | + /> |
| 75 | + <div className="text-vscode-descriptionForeground text-sm mt-1"> |
| 76 | + {t("settings:seed.label")} |
| 77 | + </div> |
| 78 | + </div> |
| 79 | + </div> |
| 80 | + )} |
| 81 | + </> |
| 82 | + ) |
| 83 | +} |
0 commit comments