@adaptabletools/adaptable
Version:
Powerful AG Grid extension which provides advanced, cutting-edge functionality to meet all DataGrid requirements
59 lines (58 loc) • 2.6 kB
JavaScript
import { jsx as _jsx } from "react/jsx-runtime";
import * as React from 'react';
import { Flex } from '../Flex';
import { useRef } from 'react';
import contains from '../utils/contains';
import { cn } from '../../lib/utils';
export const ToggleGroupContext = React.createContext({
toggleButtons: [],
activeIndex: -1,
});
export const ToggleGroup = (props) => {
const ref = useRef(null);
const [context, setContext] = React.useState({
toggleButtons: [],
activeIndex: 0,
});
const setActiveIndex = React.useCallback((index) => {
setContext((prev) => ({
...prev,
activeIndex: index,
}));
}, []);
return (_jsx(ToggleGroupContext.Provider, { value: context, children: _jsx(Flex, { ref: ref, tabIndex: 0, className: cn('ab-Toggle-Group twa:shadow-sm', 'twa:bg-primary twa:text-primary-foreground', 'twa:rounded-standard twa:overflow-hidden', 'twa:inline-flex twa:w-fit', 'twa:focus:outline-0', 'twa:not-focus-within:[--ab-focus-light__box-shadow:none]', 'twa:not-focus-within:[--ab-focus__box-shadow:none]'), onMouseDown: (event) => {
const index = context.toggleButtons.findIndex((btn) => contains(btn.node, event.target));
if (index !== -1) {
setActiveIndex(index);
}
}, onKeyDown: (event) => {
const { toggleButtons, activeIndex } = context;
if (event.key === ' ') {
event.preventDefault();
event.stopPropagation();
const activeButton = toggleButtons[activeIndex];
if (!activeButton) {
return;
}
activeButton.toggle();
return;
}
if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') {
event.preventDefault();
event.stopPropagation();
const node = ref.current;
if (!node) {
return;
}
const dir = event.key === 'ArrowLeft' ? -1 : 1;
let nextIndex = activeIndex + dir;
if (nextIndex < 0) {
nextIndex = toggleButtons.length - 1;
}
else if (nextIndex > toggleButtons.length - 1) {
nextIndex = 0;
}
setActiveIndex(nextIndex);
}
}, children: props.children }) }));
};