UNPKG

@wordpress/components

Version:
346 lines (345 loc) • 12.6 kB
import clsx from "clsx"; import { __, _n, sprintf } from "@wordpress/i18n"; import { Component, useEffect, useMemo, useRef, useState } from "@wordpress/element"; import { useInstanceId } from "@wordpress/compose"; import { speak } from "@wordpress/a11y"; import { closeSmall } from "@wordpress/icons"; import { withIgnoreIMEEvents } from "@wordpress/keycodes"; import TokenInput from "../form-token-field/token-input.mjs"; import SuggestionsList from "../form-token-field/suggestions-list.mjs"; import BaseControl from "../base-control/index.mjs"; import Button from "../button/index.mjs"; import { Flex, FlexBlock } from "../flex/index.mjs"; import withFocusOutside from "../higher-order/with-focus-outside/index.mjs"; import { useControlledValue } from "../utils/hooks/index.mjs"; import { normalizeTextString } from "../utils/strings.mjs"; import Spinner from "../spinner/index.mjs"; import { jsx, jsxs } from "react/jsx-runtime"; // packages/style-runtime/src/index.ts const STYLE_HASH_ATTRIBUTE = "data-wp-hash"; /** * Returns the shared style runtime registry. * * The registry is stored on `globalThis` so separately bundled copies of this * package can coordinate through the same document and style maps. * * @return The shared runtime registry. */ function getRuntime() { const globalScope = globalThis; if (globalScope.__wpStyleRuntime) return globalScope.__wpStyleRuntime; globalScope.__wpStyleRuntime = { documents: /* @__PURE__ */ new Map(), styles: /* @__PURE__ */ new Map(), injectedStyles: /* @__PURE__ */ new WeakMap() }; if (typeof document !== "undefined") registerDocument(document); return globalScope.__wpStyleRuntime; } /** * Checks whether a document already contains a style tag for a hash. * * @param targetDocument Document to inspect. * @param hash Stable hash for the transformed CSS. * * @return Whether the style hash already exists in the document. */ function documentContainsStyleHash(targetDocument, hash) { if (!targetDocument.head) return false; for (const style of targetDocument.head.querySelectorAll(`style[${STYLE_HASH_ATTRIBUTE}]`)) if (style.getAttribute(STYLE_HASH_ATTRIBUTE) === hash) return true; return false; } /** * Injects a registered style into a document, unless that document already * contains a style tag for the same hash. * * @param targetDocument Document to inject the style into. * @param hash Stable hash for the transformed CSS. * @param css CSS text to inject. */ function injectStyle(targetDocument, hash, css) { if (!targetDocument.head) return; const runtime = getRuntime(); let injectedStyles = runtime.injectedStyles.get(targetDocument); if (!injectedStyles) { injectedStyles = /* @__PURE__ */ new Set(); runtime.injectedStyles.set(targetDocument, injectedStyles); } if (injectedStyles.has(hash)) return; if (documentContainsStyleHash(targetDocument, hash)) { injectedStyles.add(hash); return; } const style = targetDocument.createElement("style"); style.setAttribute(STYLE_HASH_ATTRIBUTE, hash); style.appendChild(targetDocument.createTextNode(css)); targetDocument.head.appendChild(style); injectedStyles.add(hash); } /** * Registers a document as a style injection target. * * Existing registered styles are replayed into the document immediately. * Documents are reference-counted so multiple providers can safely register the * same document without one cleanup removing it while another registration is * still active. * * @param targetDocument Document to receive registered styles. * @return Cleanup function that unregisters this document registration. */ function registerDocument(targetDocument) { const runtime = getRuntime(); runtime.documents.set(targetDocument, (runtime.documents.get(targetDocument) ?? 0) + 1); for (const [hash, css] of runtime.styles) injectStyle(targetDocument, hash, css); return () => { const count = runtime.documents.get(targetDocument); if (count === void 0) return; if (count <= 1) { runtime.documents.delete(targetDocument); return; } runtime.documents.set(targetDocument, count - 1); }; } /** * Registers a style and injects it into all registered documents. * * The hash is used as the deduplication key, so calling this repeatedly with * the same hash will not add duplicate style tags to a document. * Registered styles are retained for the lifetime of the page so they can be * replayed into documents that are registered later. * * @param hash Stable hash for the transformed CSS. * @param css CSS text to inject. */ function registerStyle(hash, css) { const runtime = getRuntime(); runtime.styles.set(hash, css); for (const targetDocument of runtime.documents.keys()) injectStyle(targetDocument, hash, css); } // packages/components/src/combobox-control/style.module.scss if (typeof process === "undefined" || process.env.NODE_ENV !== "test") registerStyle("95fd09c5c0", ".f615c36ce62c2e41__input-wrapper{height:38px;padding-inline:8px}"); var style_module_default = { "input-wrapper": "f615c36ce62c2e41__input-wrapper" }; // packages/components/src/combobox-control/index.tsx const noop = () => {}; const DetectOutside = withFocusOutside(class DetectOutsideComponent extends Component { handleFocusOutside(event) { this.props.onFocusOutside(event); } render() { return this.props.children; } }); const getIndexOfMatchingSuggestion = (selectedSuggestion, matchingSuggestions) => selectedSuggestion === null ? -1 : matchingSuggestions.indexOf(selectedSuggestion); /** * `ComboboxControl` is an enhanced version of a [`SelectControl`](../select-control/README.md) with the addition of * being able to search for options using a search input. * * ```jsx * import { ComboboxControl } from '@wordpress/components'; * import { useState } from '@wordpress/element'; * * const options = [ * { * value: 'small', * label: 'Small', * }, * { * value: 'normal', * label: 'Normal', * disabled: true, * }, * { * value: 'large', * label: 'Large', * disabled: false, * }, * ]; * * function MyComboboxControl() { * const [ fontSize, setFontSize ] = useState(); * const [ filteredOptions, setFilteredOptions ] = useState( options ); * return ( * <ComboboxControl * label="Font Size" * value={ fontSize } * onChange={ setFontSize } * options={ filteredOptions } * onFilterValueChange={ ( inputValue ) => * setFilteredOptions( * options.filter( ( option ) => * option.label * .toLowerCase() * .startsWith( inputValue.toLowerCase() ) * ) * ) * } * /> * ); * } * ``` */ function ComboboxControl(props) { const { value: valueProp, label, options, onChange: onChangeProp, onFilterValueChange = noop, hideLabelFromVision, help, allowReset = true, className, isLoading = false, messages = { selected: __("Item selected.") }, __experimentalRenderItem, expandOnFocus = true, placeholder } = props; const [value, setValue] = useControlledValue({ value: valueProp, onChange: onChangeProp }); const currentOption = options.find((option) => option.value === value); const currentLabel = currentOption?.label ?? ""; const instanceId = useInstanceId(ComboboxControl, "combobox-control"); const [selectedSuggestion, setSelectedSuggestion] = useState(currentOption || null); const [isExpanded, setIsExpanded] = useState(false); const [inputHasFocus, setInputHasFocus] = useState(false); const [inputValue, setInputValue] = useState(""); const inputContainer = useRef(null); const matchingSuggestions = useMemo(() => { const startsWithMatch = []; const containsMatch = []; const match = normalizeTextString(inputValue); options.forEach((option) => { const index = normalizeTextString(option.label).indexOf(match); if (index === 0) startsWithMatch.push(option); else if (index > 0) containsMatch.push(option); }); return startsWithMatch.concat(containsMatch); }, [inputValue, options]); const onSuggestionSelected = (newSelectedSuggestion) => { if (newSelectedSuggestion.disabled) return; setValue(newSelectedSuggestion.value); speak(messages.selected, "assertive"); setSelectedSuggestion(newSelectedSuggestion); setInputValue(""); setIsExpanded(false); }; const handleArrowNavigation = (offset = 1) => { let nextIndex = getIndexOfMatchingSuggestion(selectedSuggestion, matchingSuggestions) + offset; if (nextIndex < 0) nextIndex = matchingSuggestions.length - 1; else if (nextIndex >= matchingSuggestions.length) nextIndex = 0; setSelectedSuggestion(matchingSuggestions[nextIndex]); setIsExpanded(true); }; const onKeyDown = withIgnoreIMEEvents((event) => { let preventDefault = false; if (event.defaultPrevented) return; switch (event.code) { case "Enter": if (selectedSuggestion) { onSuggestionSelected(selectedSuggestion); preventDefault = true; } break; case "ArrowUp": handleArrowNavigation(-1); preventDefault = true; break; case "ArrowDown": handleArrowNavigation(1); preventDefault = true; break; case "Escape": setIsExpanded(false); setSelectedSuggestion(null); preventDefault = true; } if (preventDefault) event.preventDefault(); }); const onBlur = () => { setInputHasFocus(false); }; const onFocus = () => { setInputHasFocus(true); if (expandOnFocus) setIsExpanded(true); onFilterValueChange(""); setInputValue(""); }; const onClick = () => { setIsExpanded(true); }; const onFocusOutside = () => { setIsExpanded(false); }; const onInputChange = (event) => { const text = event.value; setInputValue(text); onFilterValueChange(text); if (inputHasFocus) setIsExpanded(true); }; const handleOnReset = () => { setValue(null); inputContainer.current?.focus(); }; const handleResetStopPropagation = (event) => { event.stopPropagation(); }; useEffect(() => { const hasMatchingSuggestions = matchingSuggestions.length > 0; const hasSelectedMatchingSuggestions = getIndexOfMatchingSuggestion(selectedSuggestion, matchingSuggestions) > 0; if (hasMatchingSuggestions && !hasSelectedMatchingSuggestions) setSelectedSuggestion(matchingSuggestions[0]); }, [matchingSuggestions, selectedSuggestion]); useEffect(() => { const hasMatchingSuggestions = matchingSuggestions.length > 0; if (isExpanded) { const message = hasMatchingSuggestions ? sprintf(_n("%d result found, use up and down arrow keys to navigate.", "%d results found, use up and down arrow keys to navigate.", matchingSuggestions.length), matchingSuggestions.length) : __("No results."); speak(message, "polite"); } }, [matchingSuggestions, isExpanded]); const isSuggestionsListVisible = isExpanded && !isLoading; return /* @__PURE__ */ jsx(DetectOutside, { onFocusOutside, children: /* @__PURE__ */ jsx(BaseControl, { className: clsx(className, "components-combobox-control"), label, id: `components-form-token-input-${instanceId}`, hideLabelFromVision, help, children: /* @__PURE__ */ jsxs("div", { className: "components-combobox-control__suggestions-container", tabIndex: -1, onKeyDown, children: [/* @__PURE__ */ jsxs(Flex, { className: style_module_default["input-wrapper"], children: [ /* @__PURE__ */ jsx(FlexBlock, { children: /* @__PURE__ */ jsx(TokenInput, { className: "components-combobox-control__input", instanceId, ref: inputContainer, placeholder, value: isExpanded ? inputValue : currentLabel, onFocus, onBlur, onClick, isExpanded: isSuggestionsListVisible, selectedSuggestionIndex: getIndexOfMatchingSuggestion(selectedSuggestion, matchingSuggestions), onChange: onInputChange, "aria-describedby": help ? `components-form-token-input-${instanceId}__help` : void 0 }) }), isLoading && /* @__PURE__ */ jsx(Spinner, {}), allowReset && Boolean(value) && !isExpanded && /* @__PURE__ */ jsx(Button, { size: "small", icon: closeSmall, onClick: handleOnReset, onKeyDown: handleResetStopPropagation, label: __("Reset") }) ] }), isSuggestionsListVisible && /* @__PURE__ */ jsx(SuggestionsList, { instanceId, match: { label: inputValue, value: "" }, displayTransform: (suggestion) => suggestion.label, suggestions: matchingSuggestions, selectedIndex: getIndexOfMatchingSuggestion(selectedSuggestion, matchingSuggestions), onHover: setSelectedSuggestion, onSelect: onSuggestionSelected, scrollIntoView: true, __experimentalRenderItem })] }) }) }); } export { ComboboxControl as default }; //# sourceMappingURL=index.mjs.map