-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathaccordion.tsx
192 lines (172 loc) · 6.03 KB
/
accordion.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
import { $, component$, createContextId, Slot, sync$, useComputed$, useContext, useContextProvider, useId, useSignal, useStore, useStyles$, useTask$ } from "@builder.io/qwik";
import { isBrowser } from '@builder.io/qwik/build';
import { nextFocus, previousFocus } from "../utils";
import type { Signal, QRL } from '@builder.io/qwik';
import type { UlAttributes } from "../types";
import styles from './accordion.scss?inline';
const AccordionContext = createContextId<AccordionService>('AccordionContext');
const DetailsContext = createContextId<DetailsService>('DetailsContext');
interface AccordionState {
opened: string[];
multiple: boolean;
}
interface AccordionService {
state: AccordionState;
next: QRL<() => any>;
previous: QRL<() => any>;
openAll: QRL<() => void >;
closeAll: QRL<() => void >;
toggle: QRL<(id: string) => void >;
}
interface DetailsService {
id: string;
opened: Signal<boolean>;
}
const accordionFlip = $((ids: string[], root: HTMLUListElement) => {
const state = new Map<string, DOMRect>();
const list = root.querySelectorAll<HTMLElement>('.he-details');
const openingPanels: HTMLElement[] = [];
state.set('root', root.getBoundingClientRect());
for (const item of list) {
state.set(item.id, item.getBoundingClientRect());
// Opening
if (!item.classList.contains('open') && ids.includes(item.id)) {
const panel = document.getElementById(`panel-${item.id}`);
if (!panel) throw new Error(`No panel found for accordion details with id "${item.id}"`);
openingPanels.push(panel);
}
}
// update after getting the state
for (const item of list) {
ids.includes(item.id) ? item.classList.add('open') : item.classList.remove('open');
}
requestAnimationFrame(() => {
// Root: change height only when it gets smaller to avoir shrinking content
const { height } = root.getBoundingClientRect();
const oldHeight = state.get('root')!.height;
if (oldHeight > height) {
root.animate({ height: [`${oldHeight}px`, `${height}px`] }, {
duration: 200,
easing: 'cubic-bezier(0.4, 0, 0.2, 1)'
})
}
// Translate item
for (const item of list) {
const box = item.getBoundingClientRect();
const oldState = state.get(item.id)!;
if (oldState.top !== box.top) {
const delta = oldState.top - box.top;
item.animate({ transform: [`translateY(${delta}px)`, `none`] }, {
duration: 200,
easing: 'cubic-bezier(0.4, 0, 0.2, 1)'
});
}
}
// Scale then make visible
for (const panel of openingPanels) {
panel.animate({ transform: ['scaleY(0)', 'scaleY(1)'] }, {
duration: 200,
easing: 'cubic-bezier(0.4, 0, 0.2, 1)'
});
const content = panel.querySelector('.he-details-panel-content')!;
content.animate([
{ opacity: 0 },
{ opacity: 0, transform: 'scale(0.995)' },
{ opacity: 1 },
], {
duration: 400,
easing: 'cubic-bezier(0.4, 0, 0.2, 1)'
})
}
})
})
export interface AccordionProps extends UlAttributes {
multiple?: boolean;
}
export const Accordion = component$((props: AccordionProps) => {
useStyles$(styles);
const { multiple, ...ulProps } = props;
const ref = useSignal<HTMLUListElement>();
const state = useStore<AccordionState>({
opened: [],
multiple: multiple ?? false,
});
useTask$(({ track }) => {
track(() => state.opened);
if (isBrowser) accordionFlip(state.opened, ref.value!);
});
useContextProvider(AccordionContext, {
state,
next: $(() => nextFocus(ref.value?.querySelectorAll<HTMLElement>('.he-details-controller'))),
previous: $(() => previousFocus(ref.value?.querySelectorAll<HTMLElement>('.he-details-controller'))),
openAll: $(() => {
const list = ref.value!.querySelectorAll('li.details')!;
state.opened = Array.from(list).map(item => item.id);
}),
closeAll: $(() => {state.opened = []}),
toggle: $((id: string) => {
const isOpen = state.opened.includes(id);
if (state.multiple) {
if (isOpen) {
state.opened = state.opened.filter(panelId => panelId !== id);
} else {
state.opened = state.opened.concat(id);
}
} else {
state.opened = isOpen ? [] : [id];
}
})
});
// TODO: remove after useContext is fixed in v2.0
useContext(AccordionContext);
return <ul class="he-accordion" {...ulProps} ref={ref}>
<Slot/>
</ul>
});
export const Details = component$(() => {
const id = useId();
const { state } = useContext(AccordionContext);
const opened = useComputed$(() => state.opened.includes(id));
useContextProvider(DetailsContext, { id, opened });
// TODO: remove after useContext is fixed in v2.0
useContext(DetailsContext);
return <li id={id} class="he-details">
<Slot/>
</li>
});
export const Summary = component$(() => {
const { next, previous, toggle } = useContext(AccordionContext);
const { id, opened } = useContext(DetailsContext);
const ref = useSignal<HTMLElement>();
const panelId = `panel-${id}`;
const preventDefault = sync$((event: KeyboardEvent) => {
const keys = ['ArrowRight', 'ArrowDown', 'ArrowLeft', 'ArrowUp', 'Enter', ' '];
if (keys.includes(event.key)) event.preventDefault();
})
const onKeyDown$ = $((event: KeyboardEvent) => {
if (event.key === 'ArrowRight' || event.key === 'ArrowDown') next();
if (event.key === 'ArrowLeft' || event.key === 'ArrowUp') previous();
if (event.key === 'Enter' || event.key === ' ') toggle(id);
});
return <button
ref={ref}
type="button"
class="he-summary"
aria-expanded={opened.value}
aria-controls={panelId}
onClick$={() => toggle(id)}
onKeyDown$={[preventDefault, onKeyDown$]}
>
<Slot/>
</button>
});
export const DetailsPanel = component$(() => {
const ref = useSignal<HTMLElement>();
const { id } = useContext(DetailsContext);
const panelId = `panel-${id}`;
return <div ref={ref} id={panelId} role="region" class="he-details-panel">
<div class="he-details-panel-content">
<Slot/>
</div>
</div>
});