import React, { useRef } from "react"; import { HTMLInputProps as BlueprintHTMLInputProps } from "@blueprintjs/core"; import { ItemRendererProps as BlueprintItemRendererProps, MultiSelect as BlueprintMultiSelect, MultiSelectProps as BlueprintMultiSelectProps, } from "@blueprintjs/select"; import classNames from "classnames"; import { IntentBlueprint } from "../../common/Intent"; import { removeExtraSpaces } from "../../common/utils/stringUtils"; import { CLASSPREFIX as eccgui } from "../../configuration/constants"; import { TestableComponent } from "../interfaces"; import { ContextOverlayProps, Highlighter, highlighterUtils, IconButton, MenuItem, OverflowText, Spinner, } from "./../../index"; export interface MultiSuggestFieldSelectionProps { newlySelected?: T; newlyRemoved?: T; selectedItems: T[]; createdItems: Partial[]; } export interface MultiSuggestFieldCommonProps extends TestableComponent, Pick< BlueprintMultiSelectProps, "items" | "placeholder" | "openOnKeyDown" | "noResults" | "createNewItemRenderer" >, Partial, "itemRenderer">> { /** * Additional class name, space separated. */ className?: string; /** * Returns the unique ID of an item. This will be used for equality of items. */ itemId: (item: T) => string; /** * Returns the label of an item. * this would be used in the item selection list as well as the multi-select input */ itemLabel: (item: T) => string; /** * function handler that would be called anytime an item is selected/deselected or an item is created/removed */ onSelection?: (params: MultiSuggestFieldSelectionProps) => void; /** * Props to spread to `ContextOverlay`. Note that `content` cannot be changed. */ contextOverlayProps?: Partial>; /** * Props to spread to `TagInput`. Use `query` and `onQueryChange` to control the input. */ tagInputProps?: BlueprintMultiSelectProps["tagInputProps"]; /** Additional properties for the (query) input field of the multi-selection. */ inputProps?: BlueprintHTMLInputProps; /** * prop to listen for query changes, when text is entered in the multi-select input */ runOnQueryChange?: (query: string) => Promise | (T[] | undefined); /** * Whether the component should take up the full width of its container. * This overrides `tagInputProps.fill`. */ fullWidth?: boolean; /** * text content to render when filtering items returns zero results. * If omitted, "No results." will be rendered in this case. */ noResultText?: string; /** * text content to render when a new item non-existing in filtered items is about to be created . * If omitted, "No results." will be rendered in this case. */ newItemCreationText?: string; /** * Allows to create new item from a given query. If this is not provided then no new items can be created. */ createNewItemFromQuery?: (query: string) => T; /** Validates if a new item can be created from the current query string. */ isValidNewOption?: (query: string) => boolean; /** * Items that were newly created and not taken from the list will be post-fixed with this string. */ newItemPostfix?: string; /** * Intent state of the multi select. */ intent?: IntentBlueprint | "accent"; /** * Disables the input element */ disabled?: boolean; /** * Delay in ms how long the request for the given query should be delayed. */ requestDelay?: number; /** * Clear query when an option is selected or unselected. * The query is empty then and the user need to enter a new query. */ clearQueryOnSelection?: boolean; /** * If set then a `div` element is used as wrapper. * It uses the attributes given via this property. */ wrapperProps?: React.HTMLAttributes; /** * Function that allows us to filter values from the option list. * * @deprecated (v27) use `searchListPredicate` instead. */ searchPredicate?: (item: T, query: string) => boolean; /** * Returns the filtered the search option list. * By default, a case-insensitive multi-word filtering is applied. * * @param items The options. * @param query The search query. */ searchListPredicate?: (items: T[], query: string) => T[]; /** * Limits the height of the input target plus its dropdown menu when it is opened. * Need to be a `number not greater than 100` (as `vh`, a unit describing a length relative to the viewport height) or `true` (equals 100). * If not set than the dropdown menu cannot be larger that appr. the half of the available viewport hight. */ limitHeightOpened?: boolean | number; } export type MultiSuggestFieldProps = MultiSuggestFieldCommonProps & ( | { /** * Predefined selected values. * `prePopulateWithItems` cannot be used then. */ selectedItems?: T[]; prePopulateWithItems?: never; } | { selectedItems?: never; /** * When set to `true` will set the multi-select value with all the items provided. * `selectedItems` cannot be used then. */ prePopulateWithItems?: boolean; } ); /** * Element behaves very similar to `SuggestField` but allows multiple selections. * Its value does not represent a string but a stack of objects. * * Example usage: input field for user created tags. * * Attention: there may be another `MultiSelect` component in future but this will be a re-implemented `Select` like element allowing multiple selections. */ export function MultiSuggestField({ items, selectedItems: externalSelectedItems, prePopulateWithItems, itemId, itemLabel, onSelection, contextOverlayProps, tagInputProps, inputProps, runOnQueryChange, fullWidth = true, noResultText = "No results.", newItemCreationText = "Add new item", newItemPostfix = " (new item)", disabled, createNewItemFromQuery, isValidNewOption, requestDelay = 0, clearQueryOnSelection = false, className, "data-test-id": dataTestId, "data-testid": dataTestid, wrapperProps, searchPredicate, searchListPredicate, limitHeightOpened, intent, ...otherMultiSelectProps }: MultiSuggestFieldProps) { type SelectionChange = { type: "selected"; item: T } | { type: "removed"; item: T } | { type: "none" }; // Options created by a user const createdItems = useRef([]); // Options passed outside (f.e. from the backend) const [externalItems, setExternalItems] = React.useState([...items]); // All options (created and passed) that match the query const [filteredItems, setFilteredItems] = React.useState([]); // All options (created and passed) selected by a user const [selectedItems, setSelectedItems] = React.useState(() => prePopulateWithItems ? [...items] : externalSelectedItems ? [...externalSelectedItems] : [], ); // Max height of the menu const [calculatedMaxHeight, setCalculatedMaxHeight] = React.useState(null); // The active popover item is only needed for keyboard interaction and should not trigger rerenders. const focusedItemRef = React.useRef(null); const [showSpinner, setShowSpinner] = React.useState(false); const inputRef = React.useRef(null); const requestState = useRef<{ query?: string; timeoutId?: number; }>({}); const selectionChange = useRef({ type: "none" }); /** Update external items when they change * e.g for auto-complete when query change */ React.useEffect(() => { setExternalItems(items); setFilteredItems([...items, ...createdItems.current]); }, [items.map((item) => itemId(item)).join("|")]); React.useEffect(() => { const selectionParams: MultiSuggestFieldSelectionProps = { createdItems: createdItems.current, selectedItems, }; if (selectionChange.current.type === "selected") { selectionParams.newlySelected = selectionChange.current.item; } if (selectionChange.current.type === "removed") { selectionParams.newlyRemoved = selectionChange.current.item; } onSelection?.(selectionParams); selectionChange.current = { type: "none" }; }, [ onSelection, selectedItems.map((item) => itemId(item)).join("|"), createdItems.current.map((item) => itemId(item)).join("|"), ]); /** * Update selected items if we get new selected items from outside */ React.useEffect(() => { if (!externalSelectedItems) { return; } selectionChange.current = { type: "none" }; setSelectedItems(externalSelectedItems); }, [externalSelectedItems?.map((item) => itemId(item)).join("|")]); React.useEffect(() => { const calculateMaxHeight = () => { if (inputRef.current) { // Get the height of the input target const inputTargetHeight = inputRef.current.getBoundingClientRect().height; // Calculate the menu dropdown by using the limited height reduced by the target height setCalculatedMaxHeight(`calc(${maxHeightToProcess}vh - ${inputTargetHeight}px)`); } }; const removeListener = () => { window.removeEventListener("resize", calculateMaxHeight); }; if (!limitHeightOpened || (typeof limitHeightOpened === "number" && limitHeightOpened > 100)) return removeListener; const maxHeightToProcess = typeof limitHeightOpened === "number" ? limitHeightOpened : 100; calculateMaxHeight(); window.addEventListener("resize", calculateMaxHeight); return removeListener; }, [limitHeightOpened, selectedItems]); /** * using the equality prop specified checks if an item has already been selected * @param matcher * @returns */ const itemHasBeenSelectedAlready = (matcher: string) => { return !!selectedItems.find((item) => itemId(item) === matcher); }; /** * removes already selected item from the selectedItems * @param matcher */ const removeItemSelection = (matcher: string) => { setSelectedItems((items) => { const removedItem = items.find((item) => itemId(item) === matcher); selectionChange.current = removedItem ? { type: "removed", item: removedItem } : { type: "none" }; return items.filter((item) => itemId(item) !== matcher); }); }; /** Does a case-insensitive multi-word search in the item label. */ const defaultSearchListPredicate = (items: T[], query: string): T[] => { const searchWords = highlighterUtils.extractSearchWords(query, true); return items.filter((item) => { const searchIn = itemLabel(item).toLowerCase(); return highlighterUtils.matchesAllWords(searchIn, searchWords); }); }; /** * selects and deselects an item from selection list * if the item exists it removes it instead * @param item */ const onItemSelect = (item: T) => { if (itemHasBeenSelectedAlready(itemId(item))) { removeItemSelection(itemId(item)); } else { selectionChange.current = { type: "selected", item }; setSelectedItems((items) => [...items, item]); } if (clearQueryOnSelection) { requestState.current.query = ""; inputRef.current?.focus(); } else { inputRef.current?.select(); } }; /** * search through item list using "label prop" and update the items popover * @param query */ const onQueryChange = (query: string) => { if (query.length && query !== requestState.current.query) { requestState.current.query = query; if (requestState.current.timeoutId) { clearTimeout(requestState.current.timeoutId); } setShowSpinner(true); setFilteredItems([]); const fn = async () => { const resultFromQuery = runOnQueryChange && (await runOnQueryChange(removeExtraSpaces(query))); if (requestState.current.query === query) { // Only use most recent request const outsideOptions = [...(resultFromQuery ?? externalItems)]; let itemFilter = defaultSearchListPredicate; if (searchListPredicate) { itemFilter = searchListPredicate; } else if (searchPredicate) { itemFilter = (items, query) => { return items.filter((item) => searchPredicate(item, query)); }; } setFilteredItems(itemFilter([...outsideOptions, ...createdItems.current], query)); setShowSpinner(false); } }; requestState.current.timeoutId = window.setTimeout(fn, requestDelay && requestDelay > 0 ? requestDelay : 0); } else if (!query.length) { // if the query is empty we need to show all options and reset current query requestState.current.query = ""; setFilteredItems(() => [...externalItems, ...createdItems.current]); } }; // Renders the entries of the (search) options list const optionRenderer = (label: string) => { return ; }; /** * defines how an item in the item list is displayed */ const onItemRenderer = (item: T, { handleClick, modifiers }: BlueprintItemRendererProps) => { if (!modifiers.matchesPredicate) { return null; } let label = itemLabel(item); if (createdItems.current.find((created) => itemId(created) === itemId(item))) { label += newItemPostfix; } return ( ); }; /** * clear all selected items in the multi-select input */ const handleClear = () => { requestState.current.query = ""; selectionChange.current = { type: "none" }; setSelectedItems([]); setFilteredItems([...externalItems, ...createdItems.current]); }; /** * remove a specific item from the multi-select input * @param label * @param index */ const removeTagFromSelectionViaIndex = (_label: React.ReactNode, index: number) => { setSelectedItems((items) => { const removedItem = items[index]; selectionChange.current = removedItem ? { type: "removed", item: removedItem } : { type: "none" }; return [...items.slice(0, index), ...items.slice(index + 1)]; }); }; /** * Utility function to create a new Item. createNewItemFromQuery is assumed to be defined! */ const createNewItem = (query: string): T => { const newItem = createNewItemFromQuery!(query); //set new items createdItems.current = [...createdItems.current, newItem]; setFilteredItems((items) => [...items, newItem]); requestState.current.query = ""; return newItem; }; /** * added functionality to create new item when there are no matching items on enter keypress * @param event */ const handleOnKeyUp = (event: React.KeyboardEvent) => { if (event.key === "Enter" && !filteredItems.length && !!requestState.current.query && createNewItemFromQuery) { if (!isValidNewOption || isValidNewOption(requestState.current.query)) { createNewItem(requestState.current.query); } } inputRef.current?.focus(); }; /** * added functionality to either create new item * when there are no matching items or select an item on tab keypress * @param event */ const handleOnKeyDown = (event: React.KeyboardEvent) => { if (event.key === "Tab" && !!requestState.current.query) { event.preventDefault(); if (focusedItemRef.current) { onItemSelect(focusedItemRef.current); } else { if (!isValidNewOption || isValidNewOption(requestState.current.query)) { onItemSelect(createNewItem(requestState.current.query)); } else { return; } } requestState.current.query = ""; setTimeout(() => inputRef.current?.focus()); } }; /** * create new item handler, displays the new item selector and creates a new item when selected * @param label ' * @param active * @param handleClick * @returns */ const newItemRenderer = (label: string, active: boolean, handleClick: React.MouseEventHandler) => { if (!createNewItemFromQuery || (isValidNewOption && !isValidNewOption(label))) return undefined; const clickHandler = (e: React.MouseEvent) => { createNewItem(label); handleClick(e); }; return ( {`${newItemCreationText} '${label}'`}} /> ); }; // Clear button and spinner are both shown as "right element" const clearButton = selectedItems.length > 0 ? ( ) : undefined; const spinnerProps = showSpinner ? { rightElement: , } : {}; const contentMultiSelect = ( placeholder={ !otherMultiSelectProps.placeholder && createNewItemFromQuery ? "Search for item, or enter term to create new one..." : undefined } query={requestState.current.query} onQueryChange={onQueryChange} items={filteredItems} onItemSelect={onItemSelect} itemRenderer={onItemRenderer} itemsEqual={(a: T, b: T) => itemId(a) === itemId(b)} selectedItems={selectedItems} noResults={} tagRenderer={(item) => itemLabel(item)} createNewItemRenderer={newItemRenderer} onActiveItemChange={(activeItem) => { focusedItemRef.current = activeItem; }} fill={fullWidth} createNewItemFromQuery={createNewItemFromQuery} disabled={disabled} tagInputProps={{ inputProps: { id: "item", autoComplete: "off", "data-test-id": dataTestId ? dataTestId + "_searchinput" : undefined, "data-testid": dataTestid ? dataTestid + "_searchinput" : undefined, ...inputProps, } as React.InputHTMLAttributes, className: classNames(`${eccgui}-multisuggestfield`, `${eccgui}-multiselect`, className, { [`${eccgui}-intent--${intent}`]: intent === "accent", }), fill: fullWidth, inputRef: inputRef, intent: intent && intent !== "accent" ? intent : undefined, addOnBlur: true, onKeyDown: handleOnKeyDown, onKeyUp: handleOnKeyUp, onRemove: removeTagFromSelectionViaIndex, rightElement: ( <> {clearButton ?? null} {otherMultiSelectProps.openOnKeyDown !== true && ( )} ), tagProps: { minimal: true }, disabled, ...tagInputProps, ...spinnerProps, }} popoverTargetProps={{ className: `${eccgui}-multiselect__target`, }} popoverProps={{ minimal: true, placement: "bottom-start", matchTargetWidth: fullWidth, ...contextOverlayProps, }} popoverContentProps={ { "data-test-id": dataTestId ? dataTestId + "_drowpdown" : undefined, "data-testid": dataTestid ? dataTestid + "_dropdown" : undefined, style: calculatedMaxHeight ? ({ "--eccgui-multisuggestfield-max-height": `${calculatedMaxHeight}`, } as React.CSSProperties) : undefined, } as BlueprintMultiSelectProps["popoverContentProps"] } {...otherMultiSelectProps} /> ); return wrapperProps || dataTestId || dataTestid ? (
{contentMultiSelect}
) : ( <>{contentMultiSelect} ); }