UNPKG

@wordpress/components

Version:
596 lines (595 loc) • 22.5 kB
import clsx from "clsx"; import { useEffect, useRef, useState } from "@wordpress/element"; import { __, _n, sprintf } from "@wordpress/i18n"; import { useDebounce, useInstanceId, usePrevious } from "@wordpress/compose"; import { speak } from "@wordpress/a11y"; import { isShallowEqual } from "@wordpress/is-shallow-equal"; import deprecated from "@wordpress/deprecated"; import { withIgnoreIMEEvents } from "@wordpress/keycodes"; import Token from "./token.mjs"; import TokenInput from "./token-input.mjs"; import SuggestionsList from "./suggestions-list.mjs"; import { Flex, FlexItem } from "../flex/index.mjs"; import { StyledHelp, StyledLabel } from "../base-control/styles/base-control-styles.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/form-token-field/style.module.scss if (typeof process === "undefined" || process.env.NODE_ENV !== "test") registerStyle("d027d15409", "._8aacd159e9111ea9__tokens-and-input{box-sizing:border-box;padding:7px}._8aacd159e9111ea9__tokens-and-input *,._8aacd159e9111ea9__tokens-and-input :after,._8aacd159e9111ea9__tokens-and-input :before{box-sizing:inherit}"); var style_module_default = { "tokens-and-input": "_8aacd159e9111ea9__tokens-and-input" }; // packages/components/src/form-token-field/index.tsx const identity = (value) => value; /** * A `FormTokenField` is a field similar to the tags and categories fields in the interim editor chrome, * or the "to" field in Mail on OS X. Tokens can be entered by typing them or selecting them from a list of suggested tokens. * * Up to one hundred suggestions that match what the user has typed so far will be shown from which the user can pick from (auto-complete). * Tokens are separated by the "," character. Suggestions can be selected with the up or down arrows and added with the tab or enter key. * * The `value` property is handled in a manner similar to controlled form components. * See [Forms](https://react.dev/reference/react-dom/components#form-components) in the React Documentation for more information. */ function FormTokenField(props) { const { autoCapitalize, autoComplete, maxLength, placeholder, label = __("Add item"), className, suggestions = [], maxSuggestions = 100, value = [], displayTransform = identity, saveTransform = (token) => token.trim(), onChange = () => {}, onInputChange = () => {}, onFocus = void 0, isBorderless = false, disabled = false, tokenizeOnSpace = false, messages = { added: __("Item added."), removed: __("Item removed."), remove: __("Remove item"), __experimentalInvalid: __("Invalid item") }, __experimentalRenderItem, __experimentalExpandOnFocus = false, __experimentalValidateInput = () => true, __experimentalShowHowTo, __experimentalAutoSelectFirstMatch = false, tokenizeOnBlur = false, help } = props; const defaultHelp = tokenizeOnSpace ? __("Separate with commas, spaces, or the Enter key.") : __("Separate with commas or the Enter key."); let computedHelp = help !== void 0 ? help : defaultHelp; if (typeof __experimentalShowHowTo === "boolean") { deprecated("`__experimentalShowHowTo` prop in wp.components.FormTokenField", { since: "7.1", alternative: "`help` prop", hint: "The `help` prop now defaults to the previous how-to text. Pass an empty string to hide it." }); if (__experimentalShowHowTo === false && help === void 0) computedHelp = ""; } const instanceId = useInstanceId(FormTokenField); const [incompleteTokenValue, setIncompleteTokenValue] = useState(""); const [inputOffsetFromEnd, setInputOffsetFromEnd] = useState(0); const [isActive, setIsActive] = useState(false); const [isExpanded, setIsExpanded] = useState(false); const [selectedSuggestionIndex, setSelectedSuggestionIndex] = useState(-1); const [selectedSuggestionScroll, setSelectedSuggestionScroll] = useState(false); const prevSuggestions = usePrevious(suggestions); const prevValue = usePrevious(value); const input = useRef(null); const tokensAndInput = useRef(null); const debouncedSpeak = useDebounce(speak, 500); useEffect(() => { if (isActive && !hasFocus()) focus(); }, [isActive]); useEffect(() => { const suggestionsDidUpdate = !isShallowEqual(suggestions, prevSuggestions || []); if (suggestionsDidUpdate || value !== prevValue) updateSuggestions(suggestionsDidUpdate); }, [ suggestions, prevSuggestions, value, prevValue ]); useEffect(() => { updateSuggestions(); }, [incompleteTokenValue]); useEffect(() => { updateSuggestions(); }, [__experimentalAutoSelectFirstMatch]); if (disabled && isActive) { setIsActive(false); setIncompleteTokenValue(""); } function focus() { input.current?.focus(); } function hasFocus() { return input.current === input.current?.ownerDocument.activeElement; } function onFocusHandler(event) { if (hasFocus() || event.target === tokensAndInput.current) { setIsActive(true); setIsExpanded(__experimentalExpandOnFocus || isExpanded); } else setIsActive(false); if ("function" === typeof onFocus) onFocus(event); } function onBlur(event) { if (inputHasValidValue() && __experimentalValidateInput(incompleteTokenValue)) { setIsActive(false); if (tokenizeOnBlur && inputHasValidValue()) addNewToken(incompleteTokenValue); } else { setIncompleteTokenValue(""); setInputOffsetFromEnd(0); setIsActive(false); if (__experimentalExpandOnFocus) { const hasFocusWithin = event.relatedTarget === tokensAndInput.current; setIsExpanded(hasFocusWithin); } else setIsExpanded(false); setSelectedSuggestionIndex(-1); setSelectedSuggestionScroll(false); } } function onKeyDown(event) { let preventDefault = false; if (event.defaultPrevented) return; switch (event.key) { case "Backspace": preventDefault = handleDeleteKey(deleteTokenBeforeInput); break; case "Enter": preventDefault = addCurrentToken(); break; case "ArrowLeft": preventDefault = handleLeftArrowKey(); break; case "ArrowUp": preventDefault = handleUpArrowKey(); break; case "ArrowRight": preventDefault = handleRightArrowKey(); break; case "ArrowDown": preventDefault = handleDownArrowKey(); break; case "Delete": preventDefault = handleDeleteKey(deleteTokenAfterInput); break; case "Space": if (tokenizeOnSpace) preventDefault = addCurrentToken({ preventDefaultOnFailedValidation: false }); break; case "Escape": preventDefault = handleEscapeKey(event); break; case "Tab": preventDefault = handleTabKey(event); } if (preventDefault) event.preventDefault(); } function onKeyPress(event) { let preventDefault = false; switch (event.key) { case ",": preventDefault = handleCommaKey(); } if (preventDefault) event.preventDefault(); } function onContainerTouched(event) { if (event.target === tokensAndInput.current && isActive) event.preventDefault(); } function onTokenClickRemove(event) { deleteToken(event.value); focus(); } function onSuggestionHovered(suggestion) { const index = getMatchingSuggestions().indexOf(suggestion); if (index >= 0) { setSelectedSuggestionIndex(index); setSelectedSuggestionScroll(false); } } function onSuggestionSelected(suggestion) { addNewToken(suggestion); } function onInputChangeHandler(event) { const text = event.value; const separator = tokenizeOnSpace ? /[ ,\t]+/ : /[,\t]+/; const items = text.split(separator); const tokenValue = items[items.length - 1] || ""; if (items.length > 1) { const tokensToProcess = items.slice(0, -1); const willFailValidation = (segment) => { const transformed = saveTransform(segment); return !!transformed && !valueContainsToken(transformed) && !__experimentalValidateInput(transformed); }; const hasFailures = tokensToProcess.some(willFailValidation); const addedTokens = addNewTokens(hasFailures ? items : tokensToProcess); if (hasFailures) { const rejected = items.filter((token) => { const transformed = saveTransform(token); if (!transformed) return false; if (addedTokens.has(transformed)) return false; if (valueContainsToken(transformed)) return false; return !__experimentalValidateInput(transformed); }); const usedSeparators = text.match(/[ ,\t]/g); const separatorChar = usedSeparators?.[usedSeparators.length - 1] ?? (tokenizeOnSpace ? " " : ","); const trailing = tokenValue === "" ? separatorChar : ""; const remaining = rejected.join(separatorChar) + trailing; setIncompleteTokenValue(remaining); onInputChange(remaining); return; } } setIncompleteTokenValue(tokenValue); onInputChange(tokenValue); } function handleDeleteKey(_deleteToken) { let preventDefault = false; if (hasFocus() && isInputEmpty()) { _deleteToken(); preventDefault = true; } return preventDefault; } function handleLeftArrowKey() { let preventDefault = false; if (isInputEmpty()) { moveInputBeforePreviousToken(); preventDefault = true; } return preventDefault; } function handleRightArrowKey() { let preventDefault = false; if (isInputEmpty()) { moveInputAfterNextToken(); preventDefault = true; } return preventDefault; } function handleUpArrowKey() { setSelectedSuggestionIndex((index) => { return (index <= 0 ? getMatchingSuggestions(incompleteTokenValue, suggestions, value, maxSuggestions, saveTransform).length : index) - 1; }); setSelectedSuggestionScroll(true); return true; } function handleDownArrowKey() { setSelectedSuggestionIndex((index) => { return (index + 1) % getMatchingSuggestions(incompleteTokenValue, suggestions, value, maxSuggestions, saveTransform).length; }); setSelectedSuggestionScroll(true); return true; } function collapseSuggestionsList(event) { if (event.target instanceof HTMLInputElement) { setIncompleteTokenValue(event.target.value); setIsExpanded(false); setSelectedSuggestionIndex(-1); setSelectedSuggestionScroll(false); } } function handleEscapeKey(event) { collapseSuggestionsList(event); return true; } function handleTabKey(event) { collapseSuggestionsList(event); return false; } function handleCommaKey() { if (inputHasValidValue()) addNewToken(incompleteTokenValue); return true; } function moveInputToIndex(index) { setInputOffsetFromEnd(value.length - Math.max(index, -1) - 1); } function moveInputBeforePreviousToken() { setInputOffsetFromEnd((prevInputOffsetFromEnd) => { return Math.min(prevInputOffsetFromEnd + 1, value.length); }); } function moveInputAfterNextToken() { setInputOffsetFromEnd((prevInputOffsetFromEnd) => { return Math.max(prevInputOffsetFromEnd - 1, 0); }); } function deleteTokenBeforeInput() { const index = getIndexOfInput() - 1; if (index > -1) deleteToken(value[index]); } function deleteTokenAfterInput() { const index = getIndexOfInput(); if (index < value.length) { deleteToken(value[index]); moveInputToIndex(index); } } function addCurrentToken({ preventDefaultOnFailedValidation = true } = {}) { let preventDefault = false; const selectedSuggestion = getSelectedSuggestion(); if (selectedSuggestion) { addNewToken(selectedSuggestion); preventDefault = true; } else if (inputHasValidValue()) preventDefault = addNewToken(incompleteTokenValue) || preventDefaultOnFailedValidation; return preventDefault; } function addNewTokens(tokens) { const tokensToAdd = [...new Set(tokens.map(saveTransform).filter(Boolean).filter((token) => !valueContainsToken(token)).filter((token) => __experimentalValidateInput(token)))]; if (tokensToAdd.length > 0) { const newValue = [...value]; newValue.splice(getIndexOfInput(), 0, ...tokensToAdd); onChange(newValue); } return new Set(tokensToAdd); } /** * Validates and adds `token`. Returns `true` if validation passed, * `false` if it was rejected by `__experimentalValidateInput`. A `true` * return does not guarantee the token was added: `addNewTokens` may * still drop it as a duplicate or after `saveTransform` returns empty. */ function addNewToken(token) { if (!__experimentalValidateInput(token)) { speak(messages.__experimentalInvalid, "assertive"); return false; } addNewTokens([token]); speak(messages.added, "assertive"); setIncompleteTokenValue(""); setSelectedSuggestionIndex(-1); setSelectedSuggestionScroll(false); setIsExpanded(!__experimentalExpandOnFocus); if (isActive && !tokenizeOnBlur) focus(); return true; } function deleteToken(token) { const newTokens = value.filter((item) => { return getTokenValue(item) !== getTokenValue(token); }); onChange(newTokens); speak(messages.removed, "assertive"); } function getTokenValue(token) { if ("object" === typeof token) return token.value; return token; } function getMatchingSuggestions(searchValue = incompleteTokenValue, _suggestions = suggestions, _value = value, _maxSuggestions = maxSuggestions, _saveTransform = saveTransform) { let match = _saveTransform(searchValue); const startsWithMatch = []; const containsMatch = []; const normalizedValue = _value.map((item) => { if (typeof item === "string") return item; return item.value; }); if (match.length === 0) _suggestions = _suggestions.filter((suggestion) => !normalizedValue.includes(suggestion)); else { match = match.normalize("NFKC").toLocaleLowerCase(); _suggestions.forEach((suggestion) => { const index = suggestion.normalize("NFKC").toLocaleLowerCase().indexOf(match); if (normalizedValue.indexOf(suggestion) === -1) { if (index === 0) startsWithMatch.push(suggestion); else if (index > 0) containsMatch.push(suggestion); } }); _suggestions = startsWithMatch.concat(containsMatch); } return _suggestions.slice(0, _maxSuggestions); } function getSelectedSuggestion() { if (selectedSuggestionIndex !== -1) return getMatchingSuggestions()[selectedSuggestionIndex]; } function valueContainsToken(token) { return value.some((item) => { return getTokenValue(token) === getTokenValue(item); }); } function getIndexOfInput() { return value.length - inputOffsetFromEnd; } function isInputEmpty() { return incompleteTokenValue.length === 0; } function inputHasValidValue() { return saveTransform(incompleteTokenValue).length > 0; } function updateSuggestions(resetSelectedSuggestion = true) { const inputHasMinimumChars = incompleteTokenValue.trim().length > 1; const matchingSuggestions = getMatchingSuggestions(incompleteTokenValue); const hasMatchingSuggestions = matchingSuggestions.length > 0; const shouldExpandIfFocuses = hasFocus() && __experimentalExpandOnFocus; setIsExpanded(shouldExpandIfFocuses || inputHasMinimumChars && hasMatchingSuggestions); if (resetSelectedSuggestion) { if (__experimentalAutoSelectFirstMatch && inputHasMinimumChars && hasMatchingSuggestions) { setSelectedSuggestionIndex(0); setSelectedSuggestionScroll(true); } else { setSelectedSuggestionIndex(-1); setSelectedSuggestionScroll(false); } } if (inputHasMinimumChars) { 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."); debouncedSpeak(message, "assertive"); } } function renderTokensAndInput() { const components = value.map(renderToken); components.splice(getIndexOfInput(), 0, renderInput()); return components; } function renderToken(token, index, tokens) { const _value = getTokenValue(token); const status = typeof token !== "string" ? token.status : void 0; const termPosition = index + 1; const termsCount = tokens.length; return /* @__PURE__ */ jsx(FlexItem, { children: /* @__PURE__ */ jsx(Token, { value: _value, status, title: typeof token !== "string" ? token.title : void 0, displayTransform, onClickRemove: onTokenClickRemove, isBorderless: typeof token !== "string" && token.isBorderless || isBorderless, onMouseEnter: typeof token !== "string" ? token.onMouseEnter : void 0, onMouseLeave: typeof token !== "string" ? token.onMouseLeave : void 0, disabled: "error" !== status && disabled, messages, termsCount, termPosition }) }, "token-" + _value); } function renderInput() { const describedById = computedHelp ? `components-form-token-input-${instanceId}__help` : void 0; const inputProps = { instanceId, autoCapitalize, autoComplete, placeholder: value.length === 0 ? placeholder : "", disabled, value: incompleteTokenValue, onBlur, isExpanded, selectedSuggestionIndex, "aria-describedby": describedById }; return /* @__PURE__ */ jsx(TokenInput, { ...inputProps, onChange: !(maxLength && value.length >= maxLength) ? onInputChangeHandler : void 0, ref: input }, "input"); } const classes = clsx(className, "components-form-token-field__input-container", { "is-active": isActive, "is-disabled": disabled }); let tokenFieldProps = { className: "components-form-token-field", tabIndex: -1 }; const matchingSuggestions = getMatchingSuggestions(); if (!disabled) tokenFieldProps = Object.assign({}, tokenFieldProps, { onKeyDown: withIgnoreIMEEvents(onKeyDown), onKeyPress, onFocus: onFocusHandler }); return /* @__PURE__ */ jsxs("div", { ...tokenFieldProps, children: [ label && /* @__PURE__ */ jsx(StyledLabel, { htmlFor: `components-form-token-input-${instanceId}`, className: "components-form-token-field__label", children: label }), /* @__PURE__ */ jsxs("div", { ref: tokensAndInput, className: classes, tabIndex: -1, onMouseDown: onContainerTouched, onTouchStart: onContainerTouched, children: [/* @__PURE__ */ jsx(Flex, { className: style_module_default["tokens-and-input"], justify: "flex-start", align: "center", gap: 1, wrap: true, children: renderTokensAndInput() }), isExpanded && /* @__PURE__ */ jsx(SuggestionsList, { instanceId, match: saveTransform(incompleteTokenValue), displayTransform, suggestions: matchingSuggestions, selectedIndex: selectedSuggestionIndex, scrollIntoView: selectedSuggestionScroll, onHover: onSuggestionHovered, onSelect: onSuggestionSelected, __experimentalRenderItem })] }), computedHelp && /* @__PURE__ */ jsx(StyledHelp, { id: `components-form-token-input-${instanceId}__help`, className: "components-form-token-field__help", children: computedHelp }) ] }); } export { FormTokenField, FormTokenField as default }; //# sourceMappingURL=index.mjs.map