@wordpress/block-library
Version:
Block library for the WordPress editor.
313 lines (312 loc) • 12 kB
JavaScript
import { __experimentalVStack } from "@wordpress/components";
import { SearchableChipSelectControl, VisuallyHidden } from "@wordpress/ui";
import { useSelect } from "@wordpress/data";
import { store } from "@wordpress/core-data";
import { Fragment, useEffect, useMemo, useState } from "@wordpress/element";
import { useDebounce } from "@wordpress/compose";
import { speak } from "@wordpress/a11y";
import { decodeEntities } from "@wordpress/html-entities";
import { __, _n, _x, sprintf } from "@wordpress/i18n";
import { useTaxonomies } from "../../utils.mjs";
import { jsx, jsxs } from "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 = SearchableChipSelectControl.useFilteredItems().length;
if (!count) return null;
return /* @__PURE__ */ jsx(VisuallyHidden, { children: sprintf(_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 sprintf(__("Showing the first %d. Search to find more."), shown);
return sprintf(_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: 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(decodeEntities(parent.name));
parent = termById.get(parent.parent);
}
items.set(term.id, {
value: String(term.id),
label: decodeEntities(term.name),
description: ancestors.length ? ancestors.reduce((path, ancestor) => sprintf(_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__ */ jsxs(SearchableChipSelectControl.ChipWithRemove, {
"aria-label": item.description ? sprintf(_x("%1$s (%2$s)", "term"), item.label, item.description) : void 0,
children: [item.label, item.description && /* @__PURE__ */ 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 = useTaxonomies(postType);
if (!taxonomies?.length) return null;
return /* @__PURE__ */ jsx(__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__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(TaxonomyItem, {
taxonomy,
termIds: includeTermIds,
oppositeTermIds: excludeTermIds,
onChange: (value) => onChangeTaxQuery(value, "include"),
label: taxonomy.name
}), /* @__PURE__ */ jsx(TaxonomyItem, {
taxonomy,
termIds: excludeTermIds,
oppositeTermIds: includeTermIds,
onChange: (value) => onChangeTaxQuery(value, "exclude"),
label: sprintf(__("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] = useState(false);
const [inputValue, setInputValue] = useState("");
const [search, setSearch] = useState("");
const [value, setValue] = useState(EMPTY_ARRAY);
const debouncedSearch = useDebounce(setSearch, 250);
const isHierarchical = !!taxonomy.hierarchical;
const needsTree = isHierarchical && (hasOpened || !!termIds?.length);
const { tree, treeHasResolved } = useSelect((select) => {
if (!needsTree) return {
tree: null,
treeHasResolved: false
};
const { getEntityRecords, hasFinishedResolution } = select(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 = useMemo(() => tree ? getTreeItems(tree) : EMPTY_MAP, [tree]);
const { listedTerms, listTotal, listHasResolved } = useSelect((select) => {
if (isHierarchical || !hasOpened) return {
listedTerms: EMPTY_ARRAY,
listTotal: null,
listHasResolved: false
};
const { getEntityRecords, getEntityRecordsTotalItems, hasFinishedResolution } = select(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] = useState(EMPTY_ARRAY);
useEffect(() => {
if (listHasResolved) setLastListedTerms(listedTerms);
}, [listHasResolved, listedTerms]);
const shownTerms = listHasResolved ? listedTerms : lastListedTerms;
const existingTerms = useSelect((select) => {
if (isHierarchical || !termIds?.length) return EMPTY_ARRAY;
const { getEntityRecords } = select(store);
return getEntityRecords("taxonomy", taxonomy.slug, {
...FLAT_QUERY,
include: termIds,
per_page: termIds.length
});
}, [
isHierarchical,
taxonomy.slug,
termIds
]);
const selectedItemById = useMemo(() => {
if (isHierarchical) return treeItemById;
return new Map((existingTerms || EMPTY_ARRAY).map((term) => [term.id, termToItem(term)]));
}, [
isHierarchical,
treeItemById,
existingTerms
]);
useEffect(() => {
if (!termIds?.length) setValue(EMPTY_ARRAY);
if (!selectedItemById.size) return;
setValue(termIds.map((id) => selectedItemById.get(id)).filter(Boolean));
}, [termIds, selectedItemById]);
const items = 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 ?? __("Term");
speak(newValue.length > value.length ? sprintf(_x("%s added", "term"), singularName) : sprintf(_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__ */ jsx(ListedTermCount, {});
if (isPending) statusContent = /* @__PURE__ */ jsx(SearchableChipSelectControl.LoadingIndicator, {});
else if (isLimited) statusContent = /* @__PURE__ */ jsx("div", {
className: "block-library-query-inspector__taxonomy-control-limited-count",
children: /* @__PURE__ */ jsx(LimitedTermCount, {
isSearch: !!search,
shown: items.length,
total: listTotal
})
});
return /* @__PURE__ */ 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__ */ jsx(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
})
});
}
export { TaxonomyControls };
//# sourceMappingURL=taxonomy-controls.mjs.map