/
expand.ts
297 lines (238 loc) · 7.49 KB
/
expand.ts
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
// @ts-ignore
import CustomEvent from 'custom-event';
import queryAll from './query-all';
import {
isOrContains,
updateAndDispatch,
generateCaughtError,
switchAElementToButton
} from './utils';
import { request } from 'https';
interface ExpandData {
controllerElements: Element[];
controlledElement: Element;
controlledID: string;
defaultState: boolean;
expanded: boolean;
clickOutside: string;
}
const expandObjects: ExpandData[] = [];
let resizeRequested = false;
const requestResize = () => {
if (!resizeRequested) {
resizeRequested = true;
if (window.requestAnimationFrame) {
window.requestAnimationFrame(() => {
window.dispatchEvent(new CustomEvent('resize'));
resizeRequested = false;
});
}
}
};
const setIsInitialState = (element: Element, initialState = false) => {
updateAndDispatch(
element,
'data-initial-state',
initialState ? 'true' : 'false'
);
};
const refreshState = (expandObj: ExpandData, initialState = false) => {
expandObj.controllerElements.forEach(controllerElement => {
updateAndDispatch(
controllerElement,
'aria-pressed',
expandObj.expanded ? 'true' : 'false'
);
setIsInitialState(controllerElement, initialState);
});
updateAndDispatch(
expandObj.controlledElement,
'aria-expanded',
expandObj.expanded ? 'true' : 'false'
);
if (expandObj.controlledElement.nodeName === 'DIALOG') {
updateAndDispatch(
expandObj.controlledElement,
'open',
expandObj.expanded ? 'true' : null
);
}
setIsInitialState(expandObj.controlledElement, initialState);
requestResize();
};
const preventScrollToAnchor = (expandObj: ExpandData) => {
const { controlledID } = expandObj;
if (expandObj.expanded === false) {
expandObj.controlledElement.setAttribute('id', '');
window.requestAnimationFrame(() => {
expandObj.controlledElement.setAttribute('id', controlledID);
});
}
};
const changeExpandedState = (expandObj: ExpandData) => {
expandObj.expanded = !expandObj.expanded;
refreshState(expandObj);
// preventScrollToAnchor(expandObj);
};
const deselect = (expandObj: ExpandData) => {
expandObj.expanded = false;
refreshState(expandObj);
// preventScrollToAnchor(expandObj);
};
const keypressEvent = (event: KeyboardEvent) => {
if (event.key === ' ' || event.key === 'Enter') {
sendEventUpward(event);
}
};
const addController = (expandObj: ExpandData, element: Element) => {
element = switchAElementToButton(element);
expandObj.controllerElements.push(element);
const previousAriaControls = element.getAttribute('aria-controls') ? `${element.getAttribute('aria-controls')} ` : '';
element.setAttribute('aria-controls', `${previousAriaControls}${expandObj.controlledID}`);
if (element.nodeName !== 'BUTTON') {
element.setAttribute('role', 'button');
element.setAttribute('tabindex', '0');
element.addEventListener('keypress', keypressEvent);
}
};
const expandIfAnchored = (expandObj: ExpandData) => {
try {
// Will not work on old IEs
if (
window.document.querySelector(':target') === expandObj.controlledElement
) {
changeExpandedState(expandObj);
}
} catch (error) {
// Todo
console.error(error);
}
};
const sendEventUpward = (event: Event) => {
const clickEvent = new MouseEvent('click', {
view: window,
bubbles: true,
cancelable: true
});
if (event.target === null) {
return generateCaughtError('event target is null', null);
}
event.target.dispatchEvent(clickEvent);
};
const createExpand = (controllerElement: Element, controlledID: string): ExpandData | null => {
const controlledElement = window.document.getElementById(controlledID);
if (controlledElement === null) {
return generateCaughtError(
`element with ID ${controlledID} cannot be found`,
null
);
}
const defaultState
= controllerElement.getAttribute('data-expand-default-state') === 'true';
const controlledRole = controlledElement.getAttribute('role');
const clickOutside
= controlledElement.getAttribute('data-click-outside') || '';
const expandObj: ExpandData = {
controllerElements: [],
controlledElement,
controlledID,
defaultState,
expanded: defaultState,
clickOutside
};
// const controllerElements = expandObj.controllerElements;
expandObj.controlledElement.setAttribute(
'role',
controlledRole ? controlledRole : 'region'
);
refreshState(expandObj, true);
addController(expandObj, controllerElement);
refreshState(expandObj, false);
expandIfAnchored(expandObj);
return expandObj;
};
window.document.documentElement.addEventListener('click', event => {
expandObjects.forEach(expandObj => {
const controllerElem = expandObj.controllerElements.reduce(
(prev, curr) =>
(isOrContains(curr, event.target as Element) ? curr : prev),
null
);
if (controllerElem) {
changeExpandedState(expandObj);
}
const isControlledElm = isOrContains(
expandObj.controlledElement,
event.target as Element
);
if (!controllerElem && !isControlledElm && expandObj.clickOutside === 'deselect') {
deselect(expandObj);
}
});
});
const getControlledIDS = (controllerElement: Element) => {
const IDString = controllerElement.getAttribute('data-controls');
if (IDString === null) {
console.log(controllerElement);
return generateCaughtError('no data-controls attribute', []);
}
const IDs = IDString.split(' ');
return IDs;
};
export const getExpandObj = (id: string, list: ExpandData[]) =>
list.reduce((acc, val) => {
if (acc) {
return acc;
}
if (val.controlledID === id) {
return val;
}
return null;
}, null);
export const removeExpandObject = (expandObject: ExpandData) => {
expandObject.controlledElement.removeAttribute('aria-expanded');
expandObjects.splice(expandObjects.indexOf(expandObject), 1);
};
export const addExpandObject = (newExpand: ExpandData) => {
expandObjects.push(newExpand);
};
export const removeExpandController = (controllerElement: Element) => {
const IDs = getControlledIDS(controllerElement);
IDs.forEach(ID => {
const expandObj = getExpandObj(ID, expandObjects);
if (expandObj) {
expandObj.controllerElements = expandObj.controllerElements.filter(curr => curr !== controllerElement);
controllerElement.removeEventListener('keypress', keypressEvent);
controllerElement.removeAttribute('aria-controls');
controllerElement.removeAttribute('aria-pressed');
if (controllerElement.getAttribute('role') === 'button') {
controllerElement.removeAttribute('role');
controllerElement.removeAttribute('tabindex');
}
if (expandObj.controllerElements.length === 0) {
removeExpandObject(expandObj);
}
}
});
};
export const removeExpand = (controlledElement: Element) => {
const expandObj = getExpandObj(controlledElement.id, expandObjects);
if (expandObj) {
[...expandObj.controllerElements].forEach(removeExpandController);
}
};
export const addExpand = (controllerElement: Element) => {
const IDs = getControlledIDS(controllerElement);
IDs.forEach(ID => {
const expandObj = getExpandObj(ID, expandObjects);
if (expandObj) {
addController(expandObj, controllerElement);
} else {
const newExpand = createExpand(controllerElement, ID);
if (newExpand) {
expandObjects.push(newExpand);
}
}
});
};
queryAll('[data-expand]').forEach(addExpand);