@wordpress/components
Version:
UI components for WordPress.
77 lines (76 loc) • 2.01 kB
JavaScript
import { useMemo } from "@wordpress/element";
import { decodeEntities } from "@wordpress/html-entities";
import { SelectControl } from "../select-control/index.mjs";
import { jsx } from "react/jsx-runtime";
// packages/components/src/tree-select/index.tsx
function getSelectOptions(tree, level = 0) {
return tree.flatMap((treeNode) => [{
value: treeNode.id,
label: "\xA0".repeat(level * 3) + decodeEntities(treeNode.name)
}, ...getSelectOptions(treeNode.children || [], level + 1)]);
}
/**
* Generates a hierarchical select input.
*
* ```jsx
* import { useState } from 'react';
* import { TreeSelect } from '@wordpress/components';
*
* const MyTreeSelect = () => {
* const [ page, setPage ] = useState( 'p21' );
*
* return (
* <TreeSelect
* label="Parent page"
* noOptionLabel="No parent page"
* onChange={ ( newPage ) => setPage( newPage ) }
* selectedId={ page }
* tree={ [
* {
* name: 'Page 1',
* id: 'p1',
* children: [
* { name: 'Descend 1 of page 1', id: 'p11' },
* { name: 'Descend 2 of page 1', id: 'p12' },
* ],
* },
* {
* name: 'Page 2',
* id: 'p2',
* children: [
* {
* name: 'Descend 1 of page 2',
* id: 'p21',
* children: [
* {
* name: 'Descend 1 of Descend 1 of page 2',
* id: 'p211',
* },
* ],
* },
* ],
* },
* ] }
* />
* );
* }
* ```
*/
function TreeSelect(props) {
const { __nextHasNoMarginBottom: _, __next40pxDefaultSize: _next40pxDefaultSize, label, noOptionLabel, onChange, selectedId, tree = [], ...restProps } = props;
const options = useMemo(() => {
return [noOptionLabel && {
value: "",
label: noOptionLabel
}, ...getSelectOptions(tree)].filter((option) => !!option);
}, [noOptionLabel, tree]);
return /* @__PURE__ */ jsx(SelectControl, {
label,
options,
onChange,
value: selectedId,
...restProps
});
}
export { TreeSelect, TreeSelect as default };
//# sourceMappingURL=index.mjs.map