@neo4j-ndl/react
Version:
React implementation of Neo4j Design System
221 lines (220 loc) • 11.4 kB
JavaScript
/**
*
* 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/>.
*/
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { createContext, useCallback, useContext, useImperativeHandle, useRef, } from 'react';
import { classNames } from '../_common/defaultImports';
import { findUntil } from '../_common/utils';
import { Divider } from '../divider';
import { forwardRef } from '../helpers';
import { ChevronDownIconOutline } from '../icons';
import { Typography } from '../typography';
var AccordionSelector;
(function (AccordionSelector) {
AccordionSelector["Item"] = ".ndl-accordion-item";
AccordionSelector["ItemNotDisabled"] = ".ndl-accordion-item:not(.ndl-accordion-item-disabled)";
})(AccordionSelector || (AccordionSelector = {}));
const getAccordionItem = (accordionElement, selector, direction = 'next') => {
const itemParent = accordionElement.closest(AccordionSelector.Item);
if (!itemParent)
return null;
return findUntil(direction, itemParent, selector);
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const AccordionContext = createContext(null);
const useAccordionContext = () => {
const context = useContext(AccordionContext);
if (context === null) {
throw new Error('Accordion used without context');
}
return context;
};
const AccordionComponent = forwardRef(function AccordionComponent(_a, ref) {
var { children, as, isMultiple, onChange, className, style, htmlAttributes } = _a, restProps = __rest(_a, ["children", "as", "isMultiple", "onChange", "className", "style", "htmlAttributes"]);
const accordionRef = useRef(null);
const Component = as || 'div';
// The following function includes code needed to be
// able to navigate with the arrow keys (not tab).
const handleKeyDown = (event) => {
const accordionElement = accordionRef.current;
if (!accordionElement) {
return;
}
const activeElement = document.activeElement;
if (event.key === 'ArrowDown') {
event.preventDefault();
event.stopPropagation();
const newFocusedElement = getAccordionItem(activeElement, AccordionSelector.ItemNotDisabled, 'next');
const newHeader = newFocusedElement === null || newFocusedElement === void 0 ? void 0 : newFocusedElement.firstElementChild;
if (newHeader && newHeader instanceof HTMLElement) {
focusAccordionItem(newHeader);
}
}
else if (event.key === 'ArrowUp') {
event.preventDefault();
event.stopPropagation();
const newFocusedElement = getAccordionItem(activeElement, AccordionSelector.ItemNotDisabled, 'prev');
const newHeader = newFocusedElement === null || newFocusedElement === void 0 ? void 0 : newFocusedElement.firstElementChild;
if (newHeader && newHeader instanceof HTMLElement) {
focusAccordionItem(newHeader);
}
}
else if (event.key === ' ' || event.key === 'Enter') {
event.preventDefault();
event.stopPropagation();
activeElement.click();
}
};
const focusAccordionItem = (accordionHtmlElement) => {
const accordionButton = accordionHtmlElement
.getElementsByClassName('ndl-accordion-item-header-button')
.item(0);
if (accordionButton !== null && accordionButton instanceof HTMLElement) {
accordionButton.focus();
}
};
useImperativeHandle(ref, () => accordionRef.current);
const classes = classNames('ndl-accordion', className);
const { expandedItemIds } = restProps;
const { expandedItemId } = restProps;
const contextValue = isMultiple
? {
onChange,
isMultiple,
expandedItemIds,
}
: {
onChange,
isMultiple,
expandedItemId,
};
return (_jsx(Component, Object.assign({ className: classes, style: style, ref: accordionRef, onKeyDown: handleKeyDown, role: "presentation" }, htmlAttributes, { children: _jsx(AccordionContext.Provider, { value: contextValue, children: children }) })));
});
AccordionComponent.displayName = 'Accordion';
const createItemId = (type, id) => `ndl-accordionitem${type}id-${id}`;
const BaseAccordionItem = ({ itemId, children, title, className = '', arrowPosition = 'left', isDisabled = false, onExpandedChange, htmlAttributes, style, as, titleTypographyVariant = 'subheading-medium', hasDivider = true, rightContent, }) => {
const contentRef = useRef(null);
const innerContentRef = useRef(null);
const itemElementId = createItemId('item', itemId);
const headerElementId = createItemId('header', itemId);
const buttonElementId = createItemId('button', itemId);
const panelElementId = createItemId('panel', itemId);
const Component = as || 'div';
const context = useAccordionContext();
const { isMultiple } = context;
const isExpanded = isMultiple
? context.expandedItemIds.includes(itemId)
: context.expandedItemId === itemId;
const handleOnClick = useCallback(() => {
var _a, _b;
if (isDisabled)
return;
// Custom callback to call.
if (onExpandedChange !== undefined)
onExpandedChange(!isExpanded);
if (isMultiple) {
const { expandedItemIds, onChange } = context;
// Multiple expanded.
if (isExpanded) {
// Remove from list.
const newArray = expandedItemIds.filter((activeId) => activeId !== itemId);
onChange(newArray);
}
else if (!isExpanded) {
// Add to list.
const newArray = [...expandedItemIds];
newArray.push(itemId);
onChange(newArray);
}
}
else {
const { onChange } = context;
// Single expanded.
if (isExpanded) {
// Set null.
onChange(null);
}
else if (!isExpanded) {
// Set to id.
onChange(itemId);
}
}
// The W3 WAI-ARIA states that focus can only happen on the header not the header button.
(_b = (_a = document.activeElement) === null || _a === void 0 ? void 0 : _a.parentElement) === null || _b === void 0 ? void 0 : _b.focus();
}, [isExpanded, isMultiple, isDisabled, itemId, onExpandedChange, context]);
const classes = classNames('ndl-accordion-item', className, {
'ndl-accordion-item-disabled': isDisabled,
'ndl-accordion-item-expanded': isExpanded,
});
const headerClasses = classNames('ndl-accordion-item-header', {
'ndl-accordion-item-header-disabled': isDisabled,
});
const iconClasses = classNames('ndl-accordion-item-header-icon-wrapper', {
'ndl-accordion-item-header-icon-wrapper-left': arrowPosition === 'left',
});
const buttonClasses = classNames('ndl-accordion-item-header-button', {
'ndl-accordion-item-header-button-disabled': isDisabled,
});
const titleClasses = classNames('ndl-accordion-item-header-button-title', {
'ndl-accordion-item-header-button-title': isDisabled,
'ndl-accordion-item-header-button-title-left': arrowPosition === 'left',
});
const contentClasses = classNames('ndl-accordion-item-content', {
'ndl-accordion-item-content-expanded': isExpanded,
'ndl-accordion-item-content-left': arrowPosition === 'left',
});
return (_jsxs(Component, Object.assign({}, htmlAttributes, { className: classes, style: style, id: itemElementId, children: [_jsxs("div", { className: headerClasses, id: headerElementId, children: [_jsx("button", { id: buttonElementId, onClick: handleOnClick, className: buttonClasses, "aria-expanded": isExpanded, "aria-disabled": isDisabled, "aria-label": title, "aria-controls": panelElementId, disabled: isDisabled, children: _jsxs("span", { className: iconClasses, children: [_jsx(Typography, { variant: titleTypographyVariant, className: titleClasses, htmlAttributes: {
role: 'heading',
'aria-level': 2,
}, children: title }), _jsx(ChevronDownIconOutline, { className: classNames('ndl-accordion-item-header-icon', {
'-n-rotate-180': isExpanded,
}) })] }) }), rightContent && (_jsx(Typography, { as: "div", variant: "body-medium", children: rightContent }))] }), _jsx("div", { id: panelElementId, ref: contentRef, className: contentClasses, "aria-hidden": !isExpanded, "aria-labelledby": buttonElementId, role: "region", children: _jsx("div", { ref: innerContentRef, className: "ndl-accordion-item-content-inner", onKeyDown: (event) => event.stopPropagation(), children: _jsx(Typography, { variant: "body-medium", className: "n-text-palette-neutral-text-weak", as: "div", children: children }) }) }), hasDivider && _jsx(Divider, {})] })));
};
const AccordionItem = (_a) => {
var { className } = _a, restProps = __rest(_a, ["className"]);
const classes = classNames('ndl-accordion-item-classic', className);
return _jsx(BaseAccordionItem, Object.assign({}, restProps, { className: classes }));
};
AccordionItem.displayName = 'Accordion.Item';
const CleanItem = (_a) => {
var { className } = _a, restProps = __rest(_a, ["className"]);
const classes = classNames('ndl-accordion-item-clean', className);
return (_jsx(BaseAccordionItem, Object.assign({}, restProps, { className: classes, hasDivider: false })));
};
CleanItem.displayName = 'Accordion.CleanItem';
// Issue with TypeScript forwardRef and subcomponents: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/34757#issuecomment-894053907
// Fixes issue with: Accordion.Item = Item;
const Accordion = Object.assign(AccordionComponent, {
Item: AccordionItem,
CleanItem: CleanItem,
});
export { Accordion };
//# sourceMappingURL=Accordion.js.map