import "./style.pcss"; import type { FC, ReactElement } from "react"; import { createRef, useEffect, useImperativeHandle, useRef, useState, } from "react"; import type { ICheckerGroup, ICheckerGroupItemsGroup, ICheckerGroupRef, TCheckerGroupGetItem, TCheckerGroupGetItemArg, TCheckerGroupItem, TCheckerGroupItemsProp, TCheckerGroupOnChangeFn, } from "./config/types"; import { getCheckedItems } from "./utils/getCheckedItems"; import type { IComponentBaseProps } from "../../types/components/index"; import { useCN } from "../../utils/react/useCN"; import { Checker } from "../checker"; import type { IInputEventParams } from "../input/config/types"; /** * Группа чекеров * @returns {ReactElement} */ const CheckerGroup: FC = ({ baseClass = "checkerGroup", extraAttrs = {}, extraClasses = {}, children = null, items = [], form, type = "checkbox", onChange = null, getItem = null, emptyPlaceholder = "Нет элементов", ref, }): ReactElement => { const { getCN } = useCN(baseClass); const [ list, setList ] = useState(items); const listRef = useRef(null); const containerRef = useRef(null); const setScroll = (value = 0) => { if (listRef.current) { listRef.current.scrollTop = value; } }; useEffect(() => { setList(items); }, [ items ]); useEffect(() => { setScroll(); }, []); const onInputChange = (e: IInputEventParams) => { if (typeof onChange === "function") { onChange(e, setList); } else { const { name, value, checked } = e.event.target as HTMLInputElement; setList((checkers) => { return getCheckedItems(checkers, { type, name, value, checked, }); }); } }; const getList = (items: TCheckerGroupItemsProp = [], nestedKey = 0) => { if (!items.length) { return
  • {emptyPlaceholder}
  • ; } return items.map((item, index) => { const checker = ; const comp = typeof getItem === "function" ? getItem({ item, index, checker, getCN, }) : checker; const isInnerList = "items" in item && Array.isArray(item.items); const key = `${index}${nestedKey}${"name" in item ? item.name : ""}${"value" in item ? item.value : ""}${"isChecked" in item ? item.isChecked : false}`; return (
  • {!!item.label && isInnerList &&

    {item.label}

    } {isInnerList ?
      {getList(item.items, index)}
    : comp}
  • ); }); }; useImperativeHandle(ref, (): ICheckerGroupRef => ({ el: containerRef.current, ref: createRef(), stateActions: null, getData: () => null, utils: { setScroll, }, }), []); return (
    {children || (
      {getList(list)}
    )}
    ); }; export type { ICheckerGroup, ICheckerGroupItemsGroup, ICheckerGroupRef, TCheckerGroupGetItem, TCheckerGroupGetItemArg, TCheckerGroupItem, TCheckerGroupItemsProp, TCheckerGroupOnChangeFn, }; export { CheckerGroup, };