-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAccordion.tsx
More file actions
80 lines (66 loc) · 2.95 KB
/
Accordion.tsx
File metadata and controls
80 lines (66 loc) · 2.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import React, { useContext, useEffect, useRef, useState } from 'react';
import Expander from '../Expander';
import { TranslatorContext } from '@ids-context/Translator';
import { createCssClassNames } from '@ibexa/ids-core/helpers/cssClassNames';
import { AccordionProps } from './Accordion.types';
const FAKE_TIMEOUT_RERENDER = 1;
const Accordion = ({ children, header, initiallyExpanded = false, onHandleExpand = () => null }: AccordionProps) => {
const Translator = useContext(TranslatorContext);
const accordionContentRef = useRef<HTMLDivElement>(null);
const [isExpanded, setIsExpanded] = useState<boolean>(initiallyExpanded);
const [isAnimating, setIsAnimating] = useState<boolean>(false);
const collapseLabel = Translator.trans(/*@Desc("Hide")*/ 'ibexa.expander.label.collapse');
const expandLabel = Translator.trans(/*@Desc("Show")*/ 'ibexa.expander.label.expand');
const changeExpanded = (nextIsExpanded: boolean): void => {
setIsExpanded(nextIsExpanded);
onHandleExpand(nextIsExpanded);
setIsAnimating(true);
if (accordionContentRef.current) {
const initialHeight = nextIsExpanded ? 0 : accordionContentRef.current.offsetHeight;
accordionContentRef.current.style.height = `${initialHeight.toString()}px`;
accordionContentRef.current.addEventListener(
'transitionend',
() => {
setIsAnimating(false);
if (accordionContentRef.current) {
accordionContentRef.current.style.removeProperty('height');
}
},
{ once: true },
);
}
setTimeout(() => {
if (accordionContentRef.current) {
const finalHeight = nextIsExpanded ? accordionContentRef.current.scrollHeight : 0;
accordionContentRef.current.style.height = `${finalHeight.toString()}px`;
}
}, FAKE_TIMEOUT_RERENDER);
};
const mainClassName = createCssClassNames({
'ids-accordion': true,
'ids-accordion--is-animating': isAnimating,
'ids-accordion--is-expanded': isExpanded,
});
useEffect(() => {
setIsExpanded(initiallyExpanded);
}, [initiallyExpanded]);
return (
<div className={mainClassName}>
<div className="ids-accordion__header">
<div className="ids-accordion__header-content">{header}</div>
<Expander
collapseLabel={collapseLabel}
expandLabel={expandLabel}
hasIcon={true}
isExpanded={isExpanded}
onClick={changeExpanded}
type="caret"
/>
</div>
<div className="ids-accordion__content" ref={accordionContentRef}>
{isExpanded || isAnimating ? children : null}
</div>
</div>
);
};
export default Accordion;