UNPKG

@neo4j-ndl/react

Version:

React implementation of Neo4j Design System

69 lines 2.95 kB
import { jsx as _jsx } from "react/jsx-runtime"; /** * * Copyright (c) "Neo4j" * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import React, { cloneElement, useCallback, useMemo, useRef, useState, } from 'react'; export const ButtonGroup = ({ children }) => { const [selectedIndex, setSelectedIndex] = useState(0); const parentRef = useRef(null); const focusElement = (index) => { var _a, _b; const child = (_b = (_a = parentRef.current) === null || _a === void 0 ? void 0 : _a.children[index]) === null || _b === void 0 ? void 0 : _b.children[0]; if (child instanceof HTMLElement) { child.focus(); } }; const childrenCount = useMemo(() => React.Children.count(children), [children]); const safeSetSelectedIndex = useCallback((index) => { if (index >= childrenCount) { setSelectedIndex(childrenCount - 1); } else { setSelectedIndex(Math.max(0, index)); } }, [childrenCount, setSelectedIndex]); const handleKeyDown = (event) => { let newIndx = selectedIndex; if (event.key === 'ArrowRight' || event.key === 'ArrowDown') { newIndx = (selectedIndex + 1) % React.Children.count(children); safeSetSelectedIndex(newIndx); } else if (event.key === 'ArrowLeft' || event.key === 'ArrowUp') { newIndx = (selectedIndex - 1 + React.Children.count(children)) % React.Children.count(children); safeSetSelectedIndex(newIndx); } // set focus to new button focusElement(newIndx); }; return ( // eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions _jsx("ul", { onKeyDown: (e) => handleKeyDown(e), ref: parentRef, style: { all: 'inherit', listStyleType: 'none' }, children: React.Children.map(children, (child, index) => { if (!React.isValidElement(child)) { return null; } const clonedElement = cloneElement(child, { tabIndex: selectedIndex === index ? 0 : -1, }); return _jsx("li", { children: clonedElement }, index); }) })); }; //# sourceMappingURL=button-group.js.map