UNPKG

@wordpress/components

Version:
45 lines (44 loc) • 1.81 kB
import { useObservableValue } from "@wordpress/compose"; import { Children, cloneElement, isEmptyElement, useContext, useLayoutEffect, useRef } from "@wordpress/element"; import SlotFillContext from "./context.mjs"; import { Fragment, jsx } from "react/jsx-runtime"; // packages/components/src/slot-fill/slot.tsx /** * 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 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 cloneElement(child, { key: childKey }); }); } function Slot(props) { const { name, children, fillProps = {} } = props; const registry = useContext(SlotFillContext); const instanceRef = useRef({}); useLayoutEffect(() => { const instance = instanceRef.current; registry.registerSlot(name, { type: "children", instance }); return () => registry.unregisterSlot(name, instance); }, [registry, name]); let fills = useObservableValue(registry.fills, name) ?? []; const currentSlot = useObservableValue(registry.slots, name); if (!currentSlot || currentSlot.instance !== instanceRef.current) fills = []; const renderedFills = fills.map((fill) => { return addKeysToChildren(isFunction(fill.children) ? fill.children(fillProps) : fill.children); }).filter((element) => !isEmptyElement(element)); return /* @__PURE__ */ jsx(Fragment, { children: isFunction(children) ? children(renderedFills) : renderedFills }); } export { Slot as default }; //# sourceMappingURL=slot.mjs.map