-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.tsx
469 lines (433 loc) · 15.6 KB
/
index.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
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
// The MIT License
//
// Copyright (c) 2018 Google, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import React from 'react';
import classnames from 'classnames';
import {MDCListFoundation} from '@material/list/foundation';
import {MDCListIndex} from '@material/list/types';
import {MDCListAdapter} from '@material/list/adapter';
// @ts-ignore @types cannot be used on dist files
import memoizeOne from 'memoize-one/dist/memoize-one.cjs.js';
import ListItem, {ListItemProps} from './ListItem'; // eslint-disable-line @typescript-eslint/no-unused-vars
import ListItemGraphic from './ListItemGraphic';
import ListItemText from './ListItemText';
import ListItemMeta from './ListItemMeta';
import ListDivider from './ListDivider';
import ListGroup from './ListGroup';
import ListGroupSubheader from './ListGroupSubheader';
const HORIZONTAL = 'horizontal';
export interface ListProps extends React.HTMLProps<HTMLElement> {
className?: string;
checkboxList?: boolean;
radioList?: boolean;
nonInteractive?: boolean;
dense?: boolean;
avatarList?: boolean;
twoLine?: boolean;
singleSelection?: boolean;
selectedIndex?: MDCListIndex;
handleSelect?: (activatedItemIndex: number, selected: MDCListIndex) => void;
wrapFocus?: boolean;
tag?: string;
ref?: React.Ref<any>;
orientation?: 'vertical' | 'horizontal';
}
interface ListState {
listItemClassNames: {[listItemIndex: number]: string[]};
}
export interface ListItemContextShape {
checkboxList?: boolean;
radioList?: boolean;
handleClick?: (e: React.MouseEvent<any>, index: number) => void;
handleKeyDown?: (e: React.KeyboardEvent<any>, index: number) => void;
handleBlur?: (e: React.FocusEvent<any>, index: number) => void;
handleFocus?: (e: React.FocusEvent<any>, index: number) => void;
onDestroy?: (index: number) => void;
getListItemInitialTabIndex?: (index: number) => number;
getClassNamesFromList?: () => ListState['listItemClassNames'];
tabIndex?: number;
}
function isSelectedIndexType(
selectedIndex: unknown
): selectedIndex is MDCListIndex {
return (
(typeof selectedIndex === 'number' && !isNaN(selectedIndex)) ||
Array.isArray(selectedIndex)
);
}
export const defaultListItemContext: ListItemContextShape = {
handleClick: () => {},
handleKeyDown: () => {},
handleBlur: () => {},
handleFocus: () => {},
onDestroy: () => {},
getListItemInitialTabIndex: () => -1,
getClassNamesFromList: () => ({}),
};
export const ListItemContext = React.createContext(defaultListItemContext);
export default class List extends React.Component<ListProps, ListState> {
foundation!: MDCListFoundation;
hasInitializedListItemTabIndex = false;
private listElement = React.createRef<HTMLElement>();
state: ListState = {
listItemClassNames: {},
};
static defaultProps: Partial<ListProps> = {
className: '',
checkboxList: false,
radioList: false,
nonInteractive: false,
dense: false,
avatarList: false,
twoLine: false,
singleSelection: false,
selectedIndex: -1,
handleSelect: () => {},
wrapFocus: true,
tag: 'ul',
};
componentDidMount() {
const {singleSelection, wrapFocus, selectedIndex} = this.props;
this.foundation = new MDCListFoundation(this.adapter);
this.foundation.init();
this.foundation.setSingleSelection(singleSelection!);
this.foundation.layout();
if (isSelectedIndexType(selectedIndex)) {
this.foundation.setSelectedIndex(selectedIndex);
}
this.foundation.setWrapFocus(wrapFocus!);
// Vertical is the default so true unless explicitly horizontal.
this.foundation.setVerticalOrientation(
this.props.orientation !== HORIZONTAL
);
this.initializeListType();
}
componentDidUpdate(prevProps: ListProps) {
const {singleSelection, wrapFocus, selectedIndex} = this.props;
const hasSelectedIndexUpdated = selectedIndex !== prevProps.selectedIndex;
if (singleSelection !== prevProps.singleSelection) {
this.foundation.setSingleSelection(singleSelection!);
}
if (hasSelectedIndexUpdated && isSelectedIndexType(selectedIndex)) {
this.foundation.setSelectedIndex(selectedIndex);
}
if (wrapFocus !== prevProps.wrapFocus) {
this.foundation.setWrapFocus(wrapFocus!);
}
if (this.props.orientation !== prevProps.orientation) {
this.foundation.setVerticalOrientation(
this.props.orientation !== HORIZONTAL
);
}
}
componentWillUnmount() {
this.foundation.destroy();
}
initializeListType = () => {
const {singleSelection} = this.props;
const {cssClasses, strings} = MDCListFoundation;
if (!this.listElement.current) return;
const checkboxListItems = this.listElement.current.querySelectorAll(
strings.ARIA_ROLE_CHECKBOX_SELECTOR
);
const radioSelectedListItem = this.listElement.current.querySelector(
strings.ARIA_CHECKED_RADIO_SELECTOR
);
if (checkboxListItems.length) {
const preselectedItems = this.listElement.current.querySelectorAll(
strings.ARIA_CHECKED_CHECKBOX_SELECTOR
);
const selectedIndex = [].map.call(preselectedItems, (listItem: Element) =>
this.listElements.indexOf(listItem)
) as number[];
this.foundation.setSelectedIndex(selectedIndex);
} else if (singleSelection) {
const isActivated = this.listElement.current.querySelector(
cssClasses.LIST_ITEM_ACTIVATED_CLASS
);
if (isActivated) {
this.foundation.setUseActivatedClass(true);
}
} else if (radioSelectedListItem) {
this.foundation.setSelectedIndex(
this.listElements.indexOf(radioSelectedListItem)
);
}
};
get listElements(): Element[] {
if (this.listElement.current) {
return [].slice.call(
this.listElement.current.querySelectorAll(
MDCListFoundation.strings.ENABLED_ITEMS_SELECTOR
)
);
}
return [];
}
get classes() {
const {className, nonInteractive, dense, avatarList, twoLine} = this.props;
return classnames('mdc-list', className, {
'mdc-list--non-interactive': nonInteractive,
'mdc-list--dense': dense,
'mdc-list--avatar-list': avatarList,
'mdc-list--two-line': twoLine,
});
}
get adapter(): MDCListAdapter {
return {
getListItemCount: () => this.listElements.length,
getFocusedElementIndex: () =>
this.listElements.indexOf(document.activeElement as HTMLLIElement),
getAttributeForElementIndex: (index, attr) => {
const listItem = this.listElements[index];
return listItem.getAttribute(attr);
},
setAttributeForElementIndex: (index, attr, value) => {
const listItem = this.listElements[index];
if (listItem) {
listItem.setAttribute(attr, value);
}
},
/**
* Pushes class name to state.listItemClassNames[listItemIndex] if it doesn't yet exist.
*/
addClassForElementIndex: (index, className) => {
const {listItemClassNames} = this.state;
if (
listItemClassNames[index] &&
listItemClassNames[index].indexOf(className) === -1
) {
listItemClassNames[index].push(className);
} else {
listItemClassNames[index] = [className];
}
this.setState({listItemClassNames});
},
/**
* Finds the className within state.listItemClassNames[listItemIndex], and removes it
* from the array.
*/
removeClassForElementIndex: (index, className) => {
const {listItemClassNames} = this.state;
if (listItemClassNames[index]) {
const removalIndex = listItemClassNames[index].indexOf(className);
if (removalIndex !== -1) {
listItemClassNames[index].splice(removalIndex, 1);
this.setState({listItemClassNames});
}
}
},
setTabIndexForListItemChildren: (listItemIndex, tabIndexValue) => {
const listItem = this.listElements[listItemIndex];
const selector =
MDCListFoundation.strings.CHILD_ELEMENTS_TO_TOGGLE_TABINDEX;
const listItemChildren: Element[] = [].slice.call(
listItem.querySelectorAll(selector)
);
listItemChildren.forEach((el) =>
el.setAttribute('tabindex', tabIndexValue)
);
},
focusItemAtIndex: (index) => {
const element = this.listElements[index] as HTMLElement | undefined;
if (element) {
element.focus();
}
},
setCheckedCheckboxOrRadioAtIndex: () => {
// TODO: implement when this issue is fixed:
// https://github.com/material-components/material-components-web-react/issues/438
// not implemented since MDC React Radio/Checkbox has events to
// handle toggling checkbox to correct state
},
hasCheckboxAtIndex: (index) => {
const listItem = this.listElements[index];
return !!listItem.querySelector(
MDCListFoundation.strings.CHECKBOX_SELECTOR
);
},
hasRadioAtIndex: (index) => {
const listItem = this.listElements[index];
return !!listItem.querySelector(
MDCListFoundation.strings.RADIO_SELECTOR
);
},
isCheckboxCheckedAtIndex: (index) => {
const listItem = this.listElements[index];
const selector = MDCListFoundation.strings.CHECKBOX_SELECTOR;
const toggleEl = listItem.querySelector<HTMLInputElement>(selector);
return toggleEl!.checked;
},
isFocusInsideList: () => {
if (!this.listElement.current) return false;
return this.listElement.current.contains(document.activeElement);
},
notifyAction: (index) => {
this.props.handleSelect!(index, this.foundation.getSelectedIndex());
},
};
}
get role() {
const {checkboxList, radioList, role} = this.props;
if (role) return role;
if (checkboxList) {
return 'group';
} else if (radioList) {
return 'radiogroup';
}
return null;
}
/**
* Called from ListItem.
* Initializes the tabIndex prop for the listItems. tabIndex is determined by:
* 1. if selectedIndex is an array, and the index === selectedIndex[0]
* 2. if selectedIndex is a number, and the the index === selectedIndex
* 3. if there is no selectedIndex
*/
getListItemInitialTabIndex = (index: number) => {
const {selectedIndex} = this.props;
let tabIndex = -1;
if (!this.hasInitializedListItemTabIndex) {
const isSelectedIndexArray =
Array.isArray(selectedIndex) &&
selectedIndex.length > 0 &&
index === selectedIndex[0];
const isSelected = selectedIndex === index;
if (isSelectedIndexArray || isSelected || selectedIndex === -1) {
tabIndex = 0;
this.hasInitializedListItemTabIndex = true;
}
}
return tabIndex;
};
/**
* Method checks if the list item at `index` contains classes. If true,
* method merges state.listItemClassNames[index] with listItem.props.className.
* The return value is used as the listItem's className.
*/
private getListItemClassNames = () => {
const {listItemClassNames} = this.state;
return listItemClassNames;
};
handleKeyDown = (e: React.KeyboardEvent<any>, index: number) => {
e.persist(); // Persist the synthetic event to access its `key`
this.foundation.handleKeydown(
e.nativeEvent,
true /* isRootListItem is true if index >= 0 */,
index
);
};
handleClick = (_e: React.MouseEvent<any>, index: number) => {
// TODO: fix https://github.com/material-components/material-components-web-react/issues/728
// Hardcoding toggleCheckbox to false for now since we want the checkbox to handle checkbox logic.
// The List Foundation tries to toggle the checkbox and radio, but its difficult to turn that off for checkbox
// or radio.
this.foundation.handleClick(index, false);
};
// Use onFocus as workaround because onFocusIn is not yet supported in React
// https://github.com/facebook/react/issues/6410
handleFocus = (e: React.FocusEvent, index: number) => {
this.foundation.handleFocusIn(e.nativeEvent, index);
};
// Use onBlur as workaround because onFocusOut is not yet supported in React
// https://github.com/facebook/react/issues/6410
handleBlur = (e: React.FocusEvent, index: number) => {
this.foundation.handleFocusOut(e.nativeEvent, index);
};
onDestroy = (index: number) => {
const {listItemClassNames} = this.state;
delete listItemClassNames[index];
this.setState({listItemClassNames});
};
private getListProps = (checkboxList?: boolean, radioList?: boolean) => ({
checkboxList: Boolean(checkboxList),
radioList: Boolean(radioList),
handleKeyDown: this.handleKeyDown,
handleClick: this.handleClick,
handleFocus: this.handleFocus,
handleBlur: this.handleBlur,
onDestroy: this.onDestroy,
getClassNamesFromList: this.getListItemClassNames,
getListItemInitialTabIndex: this.getListItemInitialTabIndex,
});
// decreases rerenders
// https://overreacted.io/writing-resilient-components/#dont-stop-the-data-flow-in-rendering
getListPropsMemoized = memoizeOne(this.getListProps);
render() {
const {
/* eslint-disable @typescript-eslint/no-unused-vars */
className,
checkboxList,
radioList,
nonInteractive,
dense,
avatarList,
twoLine,
singleSelection,
role,
selectedIndex,
handleSelect,
wrapFocus,
/* eslint-enable @typescript-eslint/no-unused-vars */
children,
tag: Tag,
orientation,
...otherProps
} = this.props;
return (
// https://github.com/Microsoft/TypeScript/issues/28892
// @ts-ignore
<Tag
className={this.classes}
ref={this.listElement}
role={this.role}
// Only specify aria-orientation if:
// - orientation is horizontal (vertical is implicit)
// - props.role is falsy (not overridden)
// - this.role is truthy (we are applying role for checkboxList/radiogroup that supports aria-orientation)
// https://github.com/material-components/material-components-web/tree/master/packages/mdc-list#accessibility
aria-orientation={
orientation === HORIZONTAL && !role && this.role
? HORIZONTAL
: undefined
}
{...otherProps}
>
<ListItemContext.Provider
value={this.getListPropsMemoized(checkboxList, radioList)}
>
{children}
</ListItemContext.Provider>
</Tag>
);
}
}
/* eslint-enable quote-props */
export {
ListItem,
ListItemGraphic,
ListItemText,
ListItemMeta,
ListDivider,
ListGroup,
ListGroupSubheader,
ListItemProps,
};