// Importing necessary libraries and components import { useMemo, useRef, useState } from "@wordpress/element"; import { Select, Spin } from "antd"; import type { SelectProps } from "antd"; import debounce from "lodash/debounce"; import { __ } from "@wordpress/i18n"; // Import WordPress translation function import apiFetch from "@wordpress/api-fetch"; // Importing type for Element import type { Element } from "@wordpress/element"; // Define the UserValue type for use in the component interface UserValue { label: string; // Label for the option value: string; // Value for the option } // Interface for DebounceSelectProps // Extends Ant Design's SelectProps and adds custom properties export interface DebounceSelectProps extends Omit, "options" | "children"> { fetchOptions: (url: string, search: string) => Promise; // Function to fetch options debounceTimeout?: number; // Debounce timeout for search url: string; // API endpoint URL } // DebounceSelect component // A Select component with debounced search functionality function DebounceSelect< ValueType extends { label: Element; // Label for the option value: string | number; // Value for the option } = any, >({ fetchOptions, debounceTimeout = 800, // Default debounce timeout url, ...props }: DebounceSelectProps) { const [fetching, setFetching] = useState(false); // State to track fetching status const [options, setOptions] = useState([]); // State to store fetched options const fetchRef = useRef(0); // Reference to track fetch requests // Memoized function to debounce the fetchOptions call const debounceFetcher = useMemo(() => { const loadOptions = (url: string, value: string) => { fetchRef.current += 1; // Increment fetch reference const fetchId = fetchRef.current; // Store current fetch ID setOptions([]); // Clear options before fetching setFetching(true); // Set fetching state to true fetchOptions(url, value).then((newOptions) => { if (fetchId !== fetchRef.current) { // Ignore outdated fetch results return; } setOptions(newOptions); // Update options with fetched data setFetching(false); // Set fetching state to false }); }; return debounce(loadOptions, debounceTimeout); // Return debounced function }, [fetchOptions, debounceTimeout]); return (