UNPKG

@wordpress/block-library

Version:
318 lines (317 loc) • 13.4 kB
"use strict"; Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } }); let _wordpress_components = require("@wordpress/components"); let _wordpress_ui = require("@wordpress/ui"); let _wordpress_data = require("@wordpress/data"); let _wordpress_core_data = require("@wordpress/core-data"); let _wordpress_element = require("@wordpress/element"); let _wordpress_compose = require("@wordpress/compose"); let _wordpress_a11y = require("@wordpress/a11y"); let _wordpress_html_entities = require("@wordpress/html-entities"); let _wordpress_i18n = require("@wordpress/i18n"); let ______utils_js = require("../../utils.cjs"); let react_jsx_runtime = require("react/jsx-runtime"); // packages/block-library/src/query/edit/inspector-controls/taxonomy-controls.jsx const EMPTY_ARRAY = []; const EMPTY_MAP = /* @__PURE__ */ new Map(); const BASE_QUERY = { order: "asc", orderby: "name", context: "view" }; const FLAT_QUERY = { ...BASE_QUERY, _fields: "id,name" }; const TREE_QUERY = { ...BASE_QUERY, _fields: "id,name,parent", per_page: -1 }; const MAX_TERMS_TO_LIST = 100; const MAX_SEARCH_RESULTS = 20; /** * Matches items by term id. * * @param {{value: string}} item An item from the list. * @param {{value: string}} selected A currently selected item. * @return {boolean} Whether both refer to the same term. */ const isItemEqualToValue = (item, selected) => item.value === selected.value; /** * Announces how many terms the list holds. * * @return {React.JSX.Element|null} The announcement, or nothing while the list is empty. */ function ListedTermCount() { const count = _wordpress_ui.SearchableChipSelectControl.useFilteredItems().length; if (!count) return null; return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_wordpress_ui.VisuallyHidden, { children: (0, _wordpress_i18n.sprintf)((0, _wordpress_i18n._n)("%d result found.", "%d results found.", count), count) }); } /** * Explains that the server returned only part of the matching terms, and how to find more. * * @param {Object} props * @param {boolean} props.isSearch Whether the terms are search results. * @param {number} props.shown The number of terms shown. * @param {number} props.total The number of matching terms. */ function LimitedTermCount({ isSearch, shown, total }) { if (!isSearch) return (0, _wordpress_i18n.sprintf)((0, _wordpress_i18n.__)("Showing the first %d. Search to find more."), shown); return (0, _wordpress_i18n.sprintf)((0, _wordpress_i18n._n)("Showing %1$d of %2$d result. Refine your search to see more.", "Showing %1$d of %2$d results. Refine your search to see more.", total), shown, total); } const termToItem = (term) => ({ value: String(term.id), label: (0, _wordpress_html_entities.decodeEntities)(term.name) }); /** * Turns the terms of a hierarchical taxonomy into items, keyed by term id. * A nested term carries the terms it sits under as its description. * * @param {Array<{id: number, name: string, parent: number}>} terms All the terms of the taxonomy. * @return {Map<number, {value: string, label: string, description?: string}>} The items, keyed by term id. */ function getTreeItems(terms) { const termById = new Map(terms.map((term) => [term.id, term])); const items = /* @__PURE__ */ new Map(); for (const term of terms) { const ancestors = []; const visited = /* @__PURE__ */ new Set([term.id]); let parent = termById.get(term.parent); while (parent && !visited.has(parent.id)) { visited.add(parent.id); ancestors.unshift((0, _wordpress_html_entities.decodeEntities)(parent.name)); parent = termById.get(parent.parent); } items.set(term.id, { value: String(term.id), label: (0, _wordpress_html_entities.decodeEntities)(term.name), description: ancestors.length ? ancestors.reduce((path, ancestor) => (0, _wordpress_i18n.sprintf)((0, _wordpress_i18n._x)("%1$s › %2$s", "term ancestors"), path, ancestor)) : void 0 }); } return items; } /** * Renders the selected terms of a hierarchical taxonomy as chips, showing the * terms a nested term sits under in a quieter style than its name. * * @param {Array<{value: string, label: string, description?: string}>} selected The selected items. * @return {React.JSX.Element[]} The chips. */ function renderTreeChips(selected) { return selected.map((item) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(_wordpress_ui.SearchableChipSelectControl.ChipWithRemove, { "aria-label": item.description ? (0, _wordpress_i18n.sprintf)((0, _wordpress_i18n._x)("%1$s (%2$s)", "term"), item.label, item.description) : void 0, children: [item.label, item.description && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: "block-library-query-inspector__taxonomy-control-path", children: item.description })] }, item.value)); } function TaxonomyControls({ onChange, query }) { const { postType, taxQuery } = query; const taxonomies = (0, ______utils_js.useTaxonomies)(postType); if (!taxonomies?.length) return null; return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_wordpress_components.__experimentalVStack, { spacing: 4, children: taxonomies.map((taxonomy) => { const includeTermIds = taxQuery?.include?.[taxonomy.slug] || EMPTY_ARRAY; const excludeTermIds = taxQuery?.exclude?.[taxonomy.slug] || EMPTY_ARRAY; const onChangeTaxQuery = (newTermIds, key) => { const newPartialTaxQuery = { ...taxQuery?.[key], [taxonomy.slug]: newTermIds }; if (!newTermIds.length) delete newPartialTaxQuery[taxonomy.slug]; const newTaxQuery = { ...taxQuery, [key]: !!Object.keys(newPartialTaxQuery).length ? newPartialTaxQuery : void 0 }; onChange({ taxQuery: Object.values(newTaxQuery).every((value) => !value) ? void 0 : newTaxQuery }); }; return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(_wordpress_element.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(TaxonomyItem, { taxonomy, termIds: includeTermIds, oppositeTermIds: excludeTermIds, onChange: (value) => onChangeTaxQuery(value, "include"), label: taxonomy.name }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(TaxonomyItem, { taxonomy, termIds: excludeTermIds, oppositeTermIds: includeTermIds, onChange: (value) => onChangeTaxQuery(value, "exclude"), label: (0, _wordpress_i18n.sprintf)((0, _wordpress_i18n.__)("Exclude: %s"), taxonomy.name) })] }, taxonomy.slug); }) }); } /** * Renders a `SearchableChipSelectControl` for a given taxonomy. * * The list of terms is browsable: opening the control lists the existing terms * without requiring the user to remember and type their names. Typing narrows * the list down, in the browser for a hierarchical taxonomy and through a * server side search for a flat one. * * @param {Object} props The props for the component. * @param {Object} props.taxonomy The taxonomy object. * @param {number[]} props.termIds An array with the block's term ids for the given taxonomy. * @param {number[]} props.oppositeTermIds An array with the opposite control's term ids (to exclude from suggestions). * @param {Function} props.onChange Callback `onChange` function. * @param {string} props.label Label of the control. * @return {React.JSX.Element} The rendered component. */ function TaxonomyItem({ taxonomy, termIds, oppositeTermIds, onChange, label }) { const [hasOpened, setHasOpened] = (0, _wordpress_element.useState)(false); const [inputValue, setInputValue] = (0, _wordpress_element.useState)(""); const [search, setSearch] = (0, _wordpress_element.useState)(""); const [value, setValue] = (0, _wordpress_element.useState)(EMPTY_ARRAY); const debouncedSearch = (0, _wordpress_compose.useDebounce)(setSearch, 250); const isHierarchical = !!taxonomy.hierarchical; const needsTree = isHierarchical && (hasOpened || !!termIds?.length); const { tree, treeHasResolved } = (0, _wordpress_data.useSelect)((select) => { if (!needsTree) return { tree: null, treeHasResolved: false }; const { getEntityRecords, hasFinishedResolution } = select(_wordpress_core_data.store); const selectorArgs = [ "taxonomy", taxonomy.slug, TREE_QUERY ]; const records = getEntityRecords(...selectorArgs); const hasResolved = hasFinishedResolution("getEntityRecords", selectorArgs); return { tree: hasResolved ? records : null, treeHasResolved: hasResolved }; }, [needsTree, taxonomy.slug]); const treeItemById = (0, _wordpress_element.useMemo)(() => tree ? getTreeItems(tree) : EMPTY_MAP, [tree]); const { listedTerms, listTotal, listHasResolved } = (0, _wordpress_data.useSelect)((select) => { if (isHierarchical || !hasOpened) return { listedTerms: EMPTY_ARRAY, listTotal: null, listHasResolved: false }; const { getEntityRecords, getEntityRecordsTotalItems, hasFinishedResolution } = select(_wordpress_core_data.store); const selectorArgs = [ "taxonomy", taxonomy.slug, { ...FLAT_QUERY, ...search && { search }, ...oppositeTermIds.length && { exclude: oppositeTermIds }, per_page: search ? MAX_SEARCH_RESULTS : MAX_TERMS_TO_LIST } ]; return { listedTerms: getEntityRecords(...selectorArgs) || EMPTY_ARRAY, listTotal: getEntityRecordsTotalItems(...selectorArgs), listHasResolved: hasFinishedResolution("getEntityRecords", selectorArgs) }; }, [ isHierarchical, hasOpened, search, taxonomy.slug, oppositeTermIds ]); const [lastListedTerms, setLastListedTerms] = (0, _wordpress_element.useState)(EMPTY_ARRAY); (0, _wordpress_element.useEffect)(() => { if (listHasResolved) setLastListedTerms(listedTerms); }, [listHasResolved, listedTerms]); const shownTerms = listHasResolved ? listedTerms : lastListedTerms; const existingTerms = (0, _wordpress_data.useSelect)((select) => { if (isHierarchical || !termIds?.length) return EMPTY_ARRAY; const { getEntityRecords } = select(_wordpress_core_data.store); return getEntityRecords("taxonomy", taxonomy.slug, { ...FLAT_QUERY, include: termIds, per_page: termIds.length }); }, [ isHierarchical, taxonomy.slug, termIds ]); const selectedItemById = (0, _wordpress_element.useMemo)(() => { if (isHierarchical) return treeItemById; return new Map((existingTerms || EMPTY_ARRAY).map((term) => [term.id, termToItem(term)])); }, [ isHierarchical, treeItemById, existingTerms ]); (0, _wordpress_element.useEffect)(() => { if (!termIds?.length) setValue(EMPTY_ARRAY); if (!selectedItemById.size) return; setValue(termIds.map((id) => selectedItemById.get(id)).filter(Boolean)); }, [termIds, selectedItemById]); const items = (0, _wordpress_element.useMemo)(() => { const excludedIds = new Set(oppositeTermIds.map(String)); return (isHierarchical ? Array.from(treeItemById.values()) : shownTerms.map(termToItem)).filter((item) => !excludedIds.has(item.value)); }, [ isHierarchical, treeItemById, shownTerms, oppositeTermIds ]); const onInputValueChange = (nextInputValue) => { setInputValue(nextInputValue); if (!isHierarchical) debouncedSearch(nextInputValue); }; const onTermsChange = (newValue) => { if (newValue.length !== value.length) { const singularName = taxonomy.labels?.singular_name ?? (0, _wordpress_i18n.__)("Term"); (0, _wordpress_a11y.speak)(newValue.length > value.length ? (0, _wordpress_i18n.sprintf)((0, _wordpress_i18n._x)("%s added", "term"), singularName) : (0, _wordpress_i18n.sprintf)((0, _wordpress_i18n._x)("%s removed", "term"), singularName), "assertive"); } debouncedSearch.cancel(); setInputValue(""); setSearch(""); setValue(newValue); onChange(newValue.map((item) => Number(item.value))); }; const isPending = isHierarchical ? !treeHasResolved : !isHierarchical && inputValue !== search || !listHasResolved; const isLimited = !isHierarchical && listTotal > shownTerms.length; let statusContent = /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ListedTermCount, {}); if (isPending) statusContent = /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_wordpress_ui.SearchableChipSelectControl.LoadingIndicator, {}); else if (isLimited) statusContent = /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: "block-library-query-inspector__taxonomy-control-limited-count", children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(LimitedTermCount, { isSearch: !!search, shown: items.length, total: listTotal }) }); return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { className: "block-library-query-inspector__taxonomy-control", onKeyDownCapture: (event) => { if (event.key === "Enter" && isPending && event.target.getAttribute("role") === "combobox" && !event.target.getAttribute("aria-activedescendant")) { event.preventDefault(); event.stopPropagation(); } }, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_wordpress_ui.SearchableChipSelectControl, { label, items, value, onValueChange: onTermsChange, inputValue, onInputValueChange, onOpenChange: (isOpen) => { if (isOpen) setHasOpened(true); }, filter: isHierarchical || isPending ? void 0 : null, autoHighlight: inputValue ? "always" : true, isItemEqualToValue, chipsContent: isHierarchical ? renderTreeChips : void 0, statusContent, emptyContent: isPending ? null : void 0 }) }); } exports.TaxonomyControls = TaxonomyControls; //# sourceMappingURL=taxonomy-controls.cjs.map