UNPKG

@logicblocks/react-accordion

Version:

A headless, fully controlled, unstyled React accordion component with maximum flexibility.

100 lines (98 loc) 3.23 kB
"use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/Accordion.tsx var Accordion_exports = {}; __export(Accordion_exports, { Accordion: () => Accordion }); module.exports = __toCommonJS(Accordion_exports); var import_jsx_runtime = require("react/jsx-runtime"); var Accordion = ({ items, currentIndex, onToggle, multiple = false, collapseOthers = false, containerClassName, containerStyle, itemClassName, itemStyle, triggerClassName, triggerStyle, panelClassName, panelStyle }) => { const isOpen = (index) => { if (multiple && Array.isArray(currentIndex)) { return currentIndex.includes(index); } return currentIndex === index; }; const handleClick = (index) => { if (multiple) { const current = Array.isArray(currentIndex) ? currentIndex : []; const isCurrentlyOpen = current.includes(index); if (collapseOthers) { onToggle(isCurrentlyOpen ? [] : [index]); } else { const next = isCurrentlyOpen ? current.filter((i) => i !== index) : [...current, index]; onToggle(next); } } else { const isCurrentlyOpen = currentIndex === index; onToggle(isCurrentlyOpen ? -1 : index); } }; return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: containerClassName, style: containerStyle, children: items.map((item, index) => { const { Component } = item; const open = isOpen(index); const triggerId = `accordion-trigger-${index}`; const panelId = `accordion-panel-${index}`; return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: itemClassName, style: itemStyle, children: [ /* @__PURE__ */ (0, import_jsx_runtime.jsx)( "button", { role: "button", id: triggerId, "aria-controls": panelId, "aria-expanded": open, onClick: () => handleClick(index), className: triggerClassName, style: triggerStyle, children: item.title } ), open && /* @__PURE__ */ (0, import_jsx_runtime.jsx)( "div", { role: "region", id: panelId, "aria-labelledby": triggerId, className: panelClassName, style: panelStyle, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Component, {}) } ) ] }, index); }) }); }; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { Accordion });