UNPKG

@yandex/ui

Version:

Yandex UI components

46 lines (45 loc) 1.54 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useCollection = void 0; var tslib_1 = require("tslib"); var react_1 = require("react"); var isReactFragment_1 = require("../lib/isReactFragment"); function isCollectionElement(node) { if (react_1.isValidElement(node)) { var type = node.type; return typeof type === 'function' && typeof type.getCollectionNode === 'function'; } return false; } function createCollection(nodes) { var result = []; var context = { createCollection: createCollection }; react_1.Children.forEach(nodes, function (node) { if (isReactFragment_1.isReactFragment(node)) { result.push.apply(result, tslib_1.__spread(createCollection(node.props.children))); } else if (isCollectionElement(node)) { result.push(node.type.getCollectionNode(node.props, context)); } else if (node) { throw new Error('Unknown element of the children'); } }); return result; } /** * Реакт-хук для создания коллекций из `children` * с помощью виртуальных компонентов. * * @param props - свойства компонента * * @example * const collection = useCollection({ children }); */ function useCollection(props) { var children = props.children; return react_1.useMemo(function () { return createCollection(children); }, [children]); } exports.useCollection = useCollection;