@brizy/ui
Version:
React elements in Brizy style
30 lines (29 loc) • 2.7 kB
JavaScript
import { classNames } from "../../classNamesFn";
import FuzzySearch from "fuzzy-search";
import React, { useCallback, useMemo, } from "react";
import { Popper } from "react-popper";
import { LegacyScrollBar } from "../../LegacyScrollbar";
import { Portal } from "../../Portal";
import { getDropdownHeight } from "../utils";
import { DropdownItem } from "./DropdownItem";
import { BRZ_PREFIX } from "../../constants";
import { useTranslation } from "../../utils/localization/useTranslation";
export const Dropdown = ({ className: _className, options: _options, value, isMultiple, isFixed, itemHeight = 30, minItems = 1, maxItems = 5, isOpen, inputValue, highlightedIndex, selectedItem, getItemProps, getMenuProps, selectRef, }) => {
const { t } = useTranslation();
const container = selectRef.current;
const menuWidth = container === null || container === void 0 ? void 0 : container.getBoundingClientRect().width;
const node = container === null || container === void 0 ? void 0 : container.ownerDocument.body;
const strategy = isFixed ? "fixed" : "absolute";
const className = classNames(_className)("select2-portal");
const options = useMemo(() => Array.isArray(value) && isMultiple
? _options.filter(option => value.every(tagValue => tagValue !== option.value))
: _options, [_options, value, isMultiple]);
const searcher = useMemo(() => new FuzzySearch(options, ["value"]), [options]);
const getItemStyles = useCallback((style) => (Object.assign(Object.assign({}, style), { width: menuWidth })), [menuWidth]);
const items = searcher.search(inputValue).map((item, index) => (React.createElement(DropdownItem, Object.assign({ key: item.value, value: item.value, isSelected: selectedItem === item.value || highlightedIndex === index }, getItemProps({ index, item })))));
const scrollbarHeight = useMemo(() => getDropdownHeight(items.length, itemHeight, minItems, maxItems), [items.length, itemHeight, minItems, maxItems]);
return node && isOpen ? (React.createElement(Portal, { node: node, className: className },
React.createElement(Popper, { placement: "bottom", strategy: strategy }, ({ ref, style, placement }) => (React.createElement("div", { ref: ref, style: getItemStyles(style), className: `${BRZ_PREFIX}-control__select2-menu`, "data-placement": placement },
React.createElement(LegacyScrollBar, { autoHeightMax: scrollbarHeight, theme: "dark" },
React.createElement("ul", Object.assign({ className: `${BRZ_PREFIX}-ul` }, getMenuProps()), items.length > 0 ? (items) : (React.createElement("li", { className: `${BRZ_PREFIX}-control__select2-option` }, t("Nothing found")))))))))) : null;
};