-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample.tsx
113 lines (93 loc) · 2.66 KB
/
example.tsx
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import AccordionPanel from './panel-example';
import AccordionHeader from './header-example';
interface AccordionItempProps {
title: string;
content: string;
disableCollapse?: boolean;
}
const DUMMY: AccordionItempProps[] = [
{ title: '제목 1', content: '내용 1' },
{ title: '제목 2', content: '내용 2', disableCollapse: true },
{ title: '제목 3', content: '내용 3' },
];
const Accordion: FC = () => {
const [activeIndex, setActiveIndex] = useState<number | null>(null);
const accordionHeadersRef = useRef<Array<HTMLButtonElement | null>>([]);
const toggleAccordion = (index: number) => {
setActiveIndex((prevIndex) => (prevIndex === index ? null : index));
};
const focusNextAccordion = (currentIndex: number): void => {
const nextIndex = currentIndex === null ? 0 : currentIndex + 1;
if (accordionHeadersRef.current[nextIndex]) {
accordionHeadersRef.current[nextIndex]?.focus();
}
};
const focusPreviousAccordion = (currentIndex: number): void => {
console.log('?');
const previousIndex = currentIndex === null ? 0 : currentIndex - 1;
console.log('?', currentIndex);
if (accordionHeadersRef.current[previousIndex]) {
accordionHeadersRef.current[previousIndex]?.focus();
}
};
const focusFirstAccordion = (): void => {
if (accordionHeadersRef.current[0]) {
accordionHeadersRef.current[0]?.focus();
}
};
const focusLastAccordion = (): void => {
const lastIndex = accordionHeadersRef.current.length - 1;
if (accordionHeadersRef.current[lastIndex]) {
accordionHeadersRef.current[lastIndex]?.focus();
}
};
// 키보드 이벤트 관련
const handleKeyDown = (
e: KeyboardEvent<HTMLButtonElement>,
index: number
) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
toggleAccordion(index);
}
if (e.key === 'ArrowDown') {
e.preventDefault();
focusNextAccordion(index);
}
if (e.key === 'ArrowUp') {
e.preventDefault();
focusPreviousAccordion(index);
}
if (e.key === 'Home') {
e.preventDefault();
focusFirstAccordion();
}
if (e.key === 'End') {
e.preventDefault();
focusLastAccordion();
}
};
return (
<div>
{DUMMY.map((item, index) => (
<div key={index}>
<AccordionHeader
index={index}
isExpanded={activeIndex === index}
disableCollapse={item.disableCollapse ?? false}
header={item.title}
onKeyDown={(e) => handleKeyDown(e, index)}
onAccordionHeaderClick={() => toggleAccordion(index)}
/>
<AccordionPanel
index={index}
isActive={index === activeIndex}
content={item.content}
isMoreThanSixNode={DUMMY.length >= 6}
/>
</div>
))}
</div>
);
};
export default Accordion;