UNPKG

@kit-data-manager/react-search-component

Version:

All-in-one component for rendering an elastic search UI for searching anything. Built-in support for visualizing related items in a graph and resolving unique identifiers.

57 lines 3.06 kB
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../../components/ui/select"; import { useCallback, useContext, useEffect, useMemo, useState } from "react"; import { SearchContext } from "@elastic/react-search-ui"; import { ArrowUpDown } from "lucide-react"; import { ReactSearchComponentContext } from "../../components/ReactSearchComponentContext"; export function DefaultSorting() { const [value, setValue] = useState(""); const search = useContext(SearchContext); const { config } = useContext(ReactSearchComponentContext); const handleChange = useCallback((value) => { setValue(value); if (value.startsWith("-")) { const field = value.replace("-", ""); search.driver.setSort([{ field, direction: "" }], ""); } else if (value.startsWith("asc-")) { const field = value.replace("asc-", ""); search.driver.setSort([{ field, direction: "asc" }], "asc"); } else { const field = value.replace("desc-", ""); search.driver.setSort([{ field, direction: "desc" }], "desc"); } }, [search]); const makeKey = useCallback((item) => { return `${item.direction}-${item.field}`; }, []); const defaultSortOption = useMemo(() => { return config.sortOptions?.find((elem) => elem.default); }, [config.sortOptions]); // Set default sorting on first load useEffect(() => { if (defaultSortOption && value === "") { const value = makeKey(defaultSortOption); setValue(value); // Call to setValue does not trigger onValueChange handleChange(value); } }, [defaultSortOption, handleChange, makeKey, value]); // Update sort dropdown if the sortList changed from the drivers side useEffect(() => { const handler = ({ sortList }) => { if (sortList && sortList.length === 1) { const sorting = sortList[0]; const sortingValue = makeKey(sorting); setValue(sortingValue); } }; search.driver.subscribeToStateChanges(handler); return () => search.driver.unsubscribeToStateChanges(handler); }, [makeKey, search.driver]); if (!config.sortOptions || config.sortOptions.length === 0) return null; return (_jsxs(Select, { value: value, onValueChange: handleChange, children: [_jsx(SelectTrigger, { className: "rfs-max-w-[400px]", children: _jsxs("div", { className: "rfs-flex rfs-items-center rfs-gap-2", children: [_jsx(ArrowUpDown, { className: "rfs-size-4" }), _jsx(SelectValue, {})] }) }), _jsx(SelectContent, { children: config.sortOptions.map((item) => (_jsx(SelectItem, { className: "rfs-flex rfs-items-center", value: makeKey(item), children: item.label ?? (item.field + " " + item.direction === "asc" ? " (ascending)" : " (descending)") }, makeKey(item)))) })] })); } //# sourceMappingURL=DefaultSorting.js.map