@wordpress/components
Version:
UI components for WordPress.
121 lines (117 loc) • 3.19 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.TreeSelect = TreeSelect;
exports.default = void 0;
var _element = require("@wordpress/element");
var _htmlEntities = require("@wordpress/html-entities");
var _selectControl = require("../select-control");
var _useDeprecatedProps = require("../utils/use-deprecated-props");
var _context = require("../context");
var _deprecated36pxSize = require("../utils/deprecated-36px-size");
var _jsxRuntime = require("react/jsx-runtime");
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const CONTEXT_VALUE = {
BaseControl: {
// Temporary during deprecation grace period: Overrides the underlying `__associatedWPComponentName`
// via the context system to override the value set by SelectControl.
_overrides: {
__associatedWPComponentName: 'TreeSelect'
}
}
};
function getSelectOptions(tree, level = 0) {
return tree.flatMap(treeNode => [{
value: treeNode.id,
label: '\u00A0'.repeat(level * 3) + (0, _htmlEntities.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
* __nextHasNoMarginBottom
* __next40pxDefaultSize
* 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 {
label,
noOptionLabel,
onChange,
selectedId,
tree = [],
...restProps
} = (0, _useDeprecatedProps.useDeprecated36pxDefaultSizeProp)(props);
const options = (0, _element.useMemo)(() => {
return [noOptionLabel && {
value: '',
label: noOptionLabel
}, ...getSelectOptions(tree)].filter(option => !!option);
}, [noOptionLabel, tree]);
(0, _deprecated36pxSize.maybeWarnDeprecated36pxSize)({
componentName: 'TreeSelect',
size: restProps.size,
__next40pxDefaultSize: restProps.__next40pxDefaultSize
});
return /*#__PURE__*/(0, _jsxRuntime.jsx)(_context.ContextSystemProvider, {
value: CONTEXT_VALUE,
children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_selectControl.SelectControl, {
__shouldNotWarnDeprecated36pxSize: true,
label,
options,
onChange,
value: selectedId,
...restProps
})
});
}
var _default = exports.default = TreeSelect;
//# sourceMappingURL=index.js.map