UNPKG

@wordpress/components

Version:
81 lines (76 loc) 2.65 kB
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _compose = require("@wordpress/compose"); var _element = require("@wordpress/element"); var _context = _interopRequireDefault(require("./context")); var _jsxRuntime = require("react/jsx-runtime"); /** * External dependencies */ /** * WordPress dependencies */ /** * Internal dependencies */ /** * Whether the argument is a function. * * @param maybeFunc The argument to check. * @return True if the argument is a function, false otherwise. */ function isFunction(maybeFunc) { return typeof maybeFunc === 'function'; } function addKeysToChildren(children) { return _element.Children.map(children, (child, childIndex) => { if (!child || typeof child === 'string') { return child; } let childKey = childIndex; if (typeof child === 'object' && 'key' in child && child?.key) { childKey = child.key; } return (0, _element.cloneElement)(child, { key: childKey }); }); } function Slot(props) { var _useObservableValue; const registry = (0, _element.useContext)(_context.default); const instanceRef = (0, _element.useRef)({}); const { name, children, fillProps = {} } = props; (0, _element.useLayoutEffect)(() => { const instance = instanceRef.current; registry.registerSlot(name, instance); return () => registry.unregisterSlot(name, instance); }, [registry, name]); let fills = (_useObservableValue = (0, _compose.useObservableValue)(registry.fills, name)) !== null && _useObservableValue !== void 0 ? _useObservableValue : []; const currentSlot = (0, _compose.useObservableValue)(registry.slots, name); // Fills should only be rendered in the currently registered instance of the slot. if (currentSlot !== instanceRef.current) { fills = []; } const renderedFills = fills.map(fill => { const fillChildren = isFunction(fill.children) ? fill.children(fillProps) : fill.children; return addKeysToChildren(fillChildren); }).filter( // In some cases fills are rendered only when some conditions apply. // This ensures that we only use non-empty fills when rendering, i.e., // it allows us to render wrappers only when the fills are actually present. element => !(0, _element.isEmptyElement)(element)); return /*#__PURE__*/(0, _jsxRuntime.jsx)(_jsxRuntime.Fragment, { children: isFunction(children) ? children(renderedFills) : renderedFills }); } var _default = exports.default = Slot; //# sourceMappingURL=slot.js.map