UNPKG

@yandex/ui

Version:

Yandex UI components

42 lines (41 loc) 1.38 kB
import { __read, __spread } from "tslib"; import { Children, isValidElement, useMemo } from 'react'; import { isReactFragment } from '../lib/isReactFragment'; function isCollectionElement(node) { if (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 }; Children.forEach(nodes, function (node) { if (isReactFragment(node)) { result.push.apply(result, __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 }); */ export function useCollection(props) { var children = props.children; return useMemo(function () { return createCollection(children); }, [children]); }