@bentoproject/accordion
Version:
Displays content sections that can be collapsed and expanded.
563 lines (553 loc) • 16.8 kB
JavaScript
// src/bento/components/bento-accordion/1.0/component.jss.js
var $sectionChild = "section-child-76fac82";
var $header = "header-76fac82";
var $contentHidden = "content-hidden-76fac82";
// src/core/data-structures/promise.js
var resolved;
function resolvedPromise() {
if (resolved) {
return resolved;
}
resolved = Promise.resolve(void 0);
return resolved;
}
// node_modules/obj-str/dist/obj-str.mjs
function obj_str_default(obj) {
var k, cls = "";
for (k in obj) {
if (obj[k]) {
cls && (cls += " ");
cls += k;
}
}
return cls;
}
// src/core/data-structures/id-generator.js
function sequentialIdGenerator() {
let counter = 0;
return () => String(++counter);
}
function randomIdGenerator(maxValue) {
return () => String(Math.floor(Math.random() * maxValue));
}
// src/core/types/object/index.js
var {
hasOwnProperty: hasOwn_,
toString: toString_
} = Object.prototype;
function map(opt_initial) {
const obj = Object.create(null);
if (opt_initial) {
Object.assign(obj, opt_initial);
}
return obj;
}
function omit(o, props) {
return Object.keys(o).reduce((acc, key) => {
if (!props.includes(key)) {
acc[key] = o[key];
}
return acc;
}, {});
}
// src/bento/components/bento-accordion/1.0/component.js
import {
createContext,
createElement
} from "@bentoproject/core/preact";
import { useCallback as useCallback2, useContext, useEffect, useImperativeHandle, useLayoutEffect as useLayoutEffect2, useMemo, useRef, useState } from "@bentoproject/core/preact";
import { forwardRef } from "@bentoproject/core/preact";
import { WithAmpContext } from "@bentoproject/core/preact";
// src/preact/utils.js
import { useCallback, useLayoutEffect } from "@bentoproject/core/preact";
import { useAmpContext } from "@bentoproject/core/preact";
function propName(name) {
return name;
}
function tabindexFromProps(props, fallback = 0) {
var _ref, _props$tabindex;
return (_ref = (_props$tabindex = props.tabindex) != null ? _props$tabindex : props.tabIndex) != null ? _ref : fallback;
}
// src/core/dom/style.js
var propertyNameCache;
var vendorPrefixes = ["Webkit", "webkit", "Moz", "moz", "ms", "O", "o"];
function camelCaseToTitleCase(camelCase) {
return camelCase.charAt(0).toUpperCase() + camelCase.slice(1);
}
function camelCaseToHyphenCase(camelCase) {
const hyphenated = camelCase.replace(/[A-Z]/g, (match) => "-" + match.toLowerCase());
if (vendorPrefixes.some((prefix) => hyphenated.startsWith(prefix + "-"))) {
return `-${hyphenated}`;
}
return hyphenated;
}
function getVendorJsPropertyName_(style, titleCase) {
for (let i = 0; i < vendorPrefixes.length; i++) {
const propertyName = vendorPrefixes[i] + titleCase;
if (style[propertyName] !== void 0) {
return propertyName;
}
}
return "";
}
function getVendorJsPropertyName(style, camelCase, opt_bypassCache) {
if (isVar(camelCase)) {
return camelCase;
}
if (!propertyNameCache) {
propertyNameCache = map();
}
let propertyName = propertyNameCache[camelCase];
if (!propertyName || opt_bypassCache) {
propertyName = camelCase;
if (style[camelCase] === void 0) {
const titleCase = camelCaseToTitleCase(camelCase);
const prefixedPropertyName = getVendorJsPropertyName_(style, titleCase);
if (style[prefixedPropertyName] !== void 0) {
propertyName = prefixedPropertyName;
}
}
if (!opt_bypassCache) {
propertyNameCache[camelCase] = propertyName;
}
}
return propertyName;
}
function setStyle(element, property, value, opt_units, opt_bypassCache) {
const propertyName = getVendorJsPropertyName(element.style, property, opt_bypassCache);
if (!propertyName) {
return;
}
const styleValue = opt_units ? value + opt_units : value;
element.style.setProperty(camelCaseToHyphenCase(propertyName), styleValue);
}
function getStyle(element, property, opt_bypassCache) {
const propertyName = getVendorJsPropertyName(element.style, property, opt_bypassCache);
if (!propertyName) {
return void 0;
}
if (isVar(propertyName)) {
return element.style.getPropertyValue(propertyName);
}
return element.style[propertyName];
}
function setStyles(element, styles) {
for (const k in styles) {
setStyle(element, k, styles[k]);
}
}
function isVar(property) {
return property.startsWith("--");
}
// src/bento/components/bento-accordion/1.0/animations.js
var MAX_TRANSITION_DURATION = 500;
var MIN_TRANSITION_DURATION = 200;
var EXPAND_CURVE = "cubic-bezier(0.47, 0, 0.745, 0.715)";
var COLLAPSE_CURVE = "cubic-bezier(0.39, 0.575, 0.565, 1)";
function animateExpand(content) {
return animate(content, () => {
const oldHeight = getStyle(content, "height");
const oldOpacity = getStyle(content, "opacity");
const oldOverflowY = getStyle(content, "overflowY");
setStyles(content, {
height: 0,
opacity: 0,
overflowY: "auto"
});
const targetHeight = content.scrollHeight;
setStyles(content, {
height: oldHeight,
opacity: oldOpacity,
overflowY: oldOverflowY
});
const duration = getTransitionDuration(targetHeight);
return content.animate([{
height: 0,
opacity: 0,
overflowY: "hidden"
}, {
height: targetHeight + "px",
opacity: 1,
overflowY: "hidden"
}], {
easing: EXPAND_CURVE,
duration
});
});
}
function animateCollapse(content) {
return animate(content, () => {
const startHeight = content.offsetHeight;
const duration = getTransitionDuration(startHeight);
return content.animate([{
height: startHeight + "px",
opacity: 1,
overflowY: "hidden"
}, {
height: "0",
opacity: 0,
overflowY: "hidden"
}], {
easing: COLLAPSE_CURVE,
duration
});
});
}
function animate(element, prepare, cleanup = void 0) {
element.classList.add("i-amphtml-animating");
let player = prepare();
player.onfinish = player.oncancel = () => {
player = null;
if (cleanup) {
cleanup();
}
element.classList.remove("i-amphtml-animating");
};
return () => {
if (player) {
player.cancel();
}
};
}
function getTransitionDuration(dy) {
const maxY = window.innerHeight;
const distanceAdjustedDuration = Math.abs(dy) / maxY * MAX_TRANSITION_DURATION;
return Math.min(Math.max(distanceAdjustedDuration, MIN_TRANSITION_DURATION), MAX_TRANSITION_DURATION);
}
// src/bento/components/bento-accordion/1.0/component.js
var _excluded = ["animate", "as", "children", "expandSingleSection", "id"];
var _excluded2 = ["animate", "as", "children", "expanded", "id", "onExpandStateChange"];
function _toPropertyKey(arg) {
var key = _toPrimitive(arg, "string");
return typeof key === "symbol" ? key : String(key);
}
function _toPrimitive(input, hint) {
if (typeof input !== "object" || input === null)
return input;
var prim = input[Symbol.toPrimitive];
if (prim !== void 0) {
var res = prim.call(input, hint || "default");
if (typeof res !== "object")
return res;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return (hint === "string" ? String : Number)(input);
}
function _extends() {
_extends = Object.assign || function(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null)
return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0)
continue;
target[key] = source[key];
}
return target;
}
var AccordionContext = createContext({});
var SectionContext = createContext({});
var EMPTY_EXPANDED_MAP = {};
var EMPTY_EVENT_MAP = {};
var generateSectionId = sequentialIdGenerator();
var generateRandomId = randomIdGenerator(1e5);
function BentoAccordionWithRef(_ref, ref) {
let {
animate: animate2 = false,
as: Comp = "section",
children,
expandSingleSection = false,
id
} = _ref, rest = _objectWithoutPropertiesLoose(_ref, _excluded);
const [expandedMap, setExpandedMap] = useState(EMPTY_EXPANDED_MAP);
const eventMapRef = useRef(EMPTY_EVENT_MAP);
const [randomPrefix] = useState(generateRandomId);
const prefix = id || `a${randomPrefix}`;
useEffect(() => {
if (!expandSingleSection) {
return;
}
setExpandedMap((expandedMap2) => {
const newExpandedMap = {};
let expanded = 0;
for (const k in expandedMap2) {
newExpandedMap[k] = expandedMap2[k] && expanded++ == 0;
}
return newExpandedMap;
});
}, [expandSingleSection]);
const registerSection = useCallback2((id2, defaultExpanded, {
current: onExpandStateChange
}) => {
setExpandedMap((expandedMap2) => {
return setExpanded(id2, defaultExpanded, expandedMap2, expandSingleSection);
});
eventMapRef.current = _extends({}, eventMapRef.current, {
[id2]: onExpandStateChange
});
return () => {
setExpandedMap((expandedMap2) => omit(expandedMap2, id2));
eventMapRef.current = omit(eventMapRef.current, id2);
};
}, [expandSingleSection]);
const toggleExpanded = useCallback2((id2, opt_expand) => {
setExpandedMap((expandedMap2) => {
const newExpanded = opt_expand != null ? opt_expand : !expandedMap2[id2];
const newExpandedMap = setExpanded(id2, newExpanded, expandedMap2, expandSingleSection);
resolvedPromise().then(() => {
for (const k in expandedMap2) {
const onExpandStateChange = eventMapRef.current[k];
if (onExpandStateChange && expandedMap2[k] != newExpandedMap[k]) {
onExpandStateChange(newExpandedMap[k]);
}
}
});
return newExpandedMap;
});
}, [expandSingleSection]);
const isExpanded = useCallback2((id2, defaultExpanded) => {
var _expandedMap$id;
return (_expandedMap$id = expandedMap[id2]) != null ? _expandedMap$id : defaultExpanded;
}, [expandedMap]);
const toggle = useCallback2((id2) => {
if (id2) {
if (id2 in expandedMap) {
toggleExpanded(id2);
}
} else {
if (!expandSingleSection) {
for (const k in expandedMap) {
toggleExpanded(k);
}
}
}
}, [expandedMap, toggleExpanded, expandSingleSection]);
const expand = useCallback2((id2) => {
if (id2) {
if (!isExpanded(id2, true)) {
toggleExpanded(id2);
}
} else {
if (!expandSingleSection) {
for (const k in expandedMap) {
if (!isExpanded(k, true)) {
toggleExpanded(k);
}
}
}
}
}, [expandedMap, toggleExpanded, isExpanded, expandSingleSection]);
const collapse = useCallback2((id2) => {
if (id2) {
if (isExpanded(id2, false)) {
toggleExpanded(id2);
}
} else {
for (const k in expandedMap) {
if (isExpanded(k, false)) {
toggleExpanded(k);
}
}
}
}, [expandedMap, toggleExpanded, isExpanded]);
useImperativeHandle(ref, () => ({
toggle,
expand,
collapse
}), [toggle, collapse, expand]);
const context = useMemo(() => ({
registerSection,
toggleExpanded,
isExpanded,
animate: animate2,
prefix
}), [registerSection, toggleExpanded, isExpanded, animate2, prefix]);
return createElement(Comp, _extends({
id
}, rest), createElement(AccordionContext.Provider, {
value: context
}, children));
}
var BentoAccordion = forwardRef(BentoAccordionWithRef);
BentoAccordion.displayName = "Accordion";
function setExpanded(id, value, expandedMap, expandSingleSection) {
let newExpandedMap;
if (expandSingleSection && value) {
newExpandedMap = {
[id]: value
};
for (const k in expandedMap) {
if (k != id) {
newExpandedMap[k] = false;
}
}
} else {
newExpandedMap = _extends({}, expandedMap, {
[id]: value
});
}
return newExpandedMap;
}
function BentoAccordionSection(_ref2) {
let {
animate: defaultAnimate = false,
as: Comp = "section",
children,
expanded: defaultExpanded = false,
id: propId,
onExpandStateChange
} = _ref2, rest = _objectWithoutPropertiesLoose(_ref2, _excluded2);
const [genId] = useState(generateSectionId);
const id = propId || genId;
const [suffix] = useState(generateRandomId);
const [expandedState, setExpandedState] = useState(defaultExpanded);
const [contentIdState, setContentIdState] = useState(null);
const [headerIdState, setHeaderIdState] = useState(null);
const {
animate: contextAnimate,
isExpanded,
prefix,
registerSection,
toggleExpanded
} = useContext(AccordionContext);
const expanded = isExpanded ? isExpanded(id, defaultExpanded) : expandedState;
const animate2 = contextAnimate != null ? contextAnimate : defaultAnimate;
const contentId = contentIdState || `${prefix || "a"}-content-${id}-${suffix}`;
const headerId = headerIdState || `${prefix || "a"}-header-${id}-${suffix}`;
const onExpandStateChangeRef = useRef(null);
onExpandStateChangeRef.current = onExpandStateChange;
useLayoutEffect2(() => {
if (registerSection) {
return registerSection(id, defaultExpanded, onExpandStateChangeRef);
}
}, [registerSection, id, defaultExpanded]);
const toggleHandler = useCallback2((opt_expand) => {
if (toggleExpanded) {
toggleExpanded(id, opt_expand);
} else {
setExpandedState((prev) => {
const newValue = opt_expand != null ? opt_expand : !prev;
resolvedPromise().then(() => {
const onExpandStateChange2 = onExpandStateChangeRef.current;
if (onExpandStateChange2) {
onExpandStateChange2(newValue);
}
});
return newValue;
});
}
}, [id, toggleExpanded]);
const context = useMemo(() => ({
animate: animate2,
contentId,
headerId,
expanded,
toggleHandler,
setContentId: setContentIdState,
setHeaderId: setHeaderIdState
}), [animate2, contentId, headerId, expanded, toggleHandler]);
return createElement(Comp, _extends({}, rest), createElement(SectionContext.Provider, {
value: context
}, children));
}
function BentoAccordionHeader(_ref3) {
let _propName = propName("class"), {
as: Comp = "div",
children,
id,
role = "button",
[_propName]: className = ""
} = _ref3, rest = _objectWithoutPropertiesLoose(_ref3, ["as", "children", "id", "role", _propName].map(_toPropertyKey));
const {
contentId,
expanded,
headerId,
setHeaderId,
toggleHandler
} = useContext(SectionContext);
useLayoutEffect2(() => {
if (setHeaderId) {
setHeaderId(id);
}
}, [setHeaderId, id]);
return createElement(Comp, _extends({}, rest, {
id: headerId,
role,
class: `${className} ${$sectionChild} ${$header}`,
tabindex: tabindexFromProps(rest),
"aria-controls": contentId,
onClick: () => toggleHandler(),
"aria-expanded": String(expanded)
}), children);
}
function BentoAccordionContent(_ref4) {
let _propName2 = propName("class"), {
as: Comp = "div",
children,
id,
role = "region",
[_propName2]: className = ""
} = _ref4, rest = _objectWithoutPropertiesLoose(_ref4, ["as", "children", "id", "role", _propName2].map(_toPropertyKey));
const ref = useRef(null);
const hasMountedRef = useRef(false);
const {
animate: animate2,
contentId,
expanded,
headerId,
setContentId
} = useContext(SectionContext);
useEffect(() => {
hasMountedRef.current = true;
return () => hasMountedRef.current = false;
}, []);
useLayoutEffect2(() => {
if (setContentId) {
setContentId(id);
}
}, [setContentId, id]);
useLayoutEffect2(() => {
const hasMounted = hasMountedRef.current;
const content = ref.current;
if (!animate2 || !hasMounted || !content || !content.animate) {
return;
}
return expanded ? animateExpand(content) : animateCollapse(content);
}, [expanded, animate2]);
return createElement(WithAmpContext, {
renderable: expanded
}, createElement(Comp, _extends({}, rest, {
ref,
class: obj_str_default({
[className]: true,
[$sectionChild]: true,
[$contentHidden]: !expanded
}),
id: contentId,
"aria-labelledby": headerId,
role
}), children));
}
export {
BentoAccordion,
BentoAccordionContent,
BentoAccordionHeader,
BentoAccordionSection
};
//# sourceMappingURL=component-preact.max.module.js.map