#368·cmdk

[错误] v1.1.0 强制聚焦错误的输入

作者: Maher4Ever创建于 2025年6月17日更新于 2026年8月29日

import { useCallback, useEffect, useRef } from "react";

import { Command as CommandPrimitive } from "cmdk";

import { X } from "lucide-react";

import { Button } from "@/components/ui/button"; import { Skeleton } from "@/components/ui/skeleton"; import { CommandEmpty, CommandList } from "@/components/ui/command"; import { Popover, PopoverAnchor, PopoverContent, } from "@/components/ui/popover";

import { cn } from "@/lib/utils";

import type { Coordinates, Location } from "@/types";

type AutoCompleteInputProps = { className?: string; searchValue: string; onSelected?: () => void; onSearchValueChange?: (value: string) => void; autoCompleteOpen: boolean; setAutoCompleteOpen: (value: boolean) => void; placeholder?: string; };

const AutoCompleteInput = ({ className, searchValue, onSelected, onSearchValueChange, autoCompleteOpen, setAutoCompleteOpen, placeholder = "Zoeken...", }: AutoCompleteInputProps) => { const inputRef = useRef<HTMLInputElement | null>(null);

const onInputBlur = useCallback( (e: React.FocusEvent) => { if (!e.relatedTarget?.hasAttribute("cmdk-list")) { setAutoCompleteOpen(false); } }, [setAutoCompleteOpen], );

const openAutoCompleteWhenInputIsLongEnough = useCallback(() => { onSelected?.(); setAutoCompleteOpen(searchValue.length > 1); }, [searchValue, setAutoCompleteOpen, onSelected]);

const clearSearchValue = useCallback(() => { onSearchValueChange?.(""); }, [onSearchValueChange]);

useEffect(() => { // Automatically close the autocomplete popover when the user selects an item, // only if the search value is long enough to open the autocomplete in the first place. if (searchValue.length > 1 && !autoCompleteOpen) { inputRef.current?.blur(); } }, [searchValue, autoCompleteOpen]);

return (

<CommandPrimitive.Input ref={inputRef} asChild value={searchValue} onValueChange={(value) => { // Update the value first to prevent any preservable lag in the controlled input onSearchValueChange?.(value);

      // Then, open the autocomplete if the input is long enough