-
Notifications
You must be signed in to change notification settings - Fork 70
/
Autowhatever.js
355 lines (308 loc) · 11.2 KB
/
Autowhatever.js
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
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import createSectionIterator from 'section-iterator';
import themeable from 'react-themeable';
import SectionTitle from './SectionTitle';
import ItemsList from './ItemsList';
const emptyObject = {};
const defaultRenderInputComponent = props => <input {...props} />;
const defaultRenderItemsContainer =
({ containerProps, children }) => <div {...containerProps}>{children}</div>;
const defaultTheme = {
container: 'react-autowhatever__container',
containerOpen: 'react-autowhatever__container--open',
input: 'react-autowhatever__input',
inputOpen: 'react-autowhatever__input--open',
inputFocused: 'react-autowhatever__input--focused',
itemsContainer: 'react-autowhatever__items-container',
itemsContainerOpen: 'react-autowhatever__items-container--open',
itemsList: 'react-autowhatever__items-list',
item: 'react-autowhatever__item',
itemFirst: 'react-autowhatever__item--first',
itemHighlighted: 'react-autowhatever__item--highlighted',
sectionContainer: 'react-autowhatever__section-container',
sectionContainerFirst: 'react-autowhatever__section-container--first',
sectionTitle: 'react-autowhatever__section-title'
};
export default class Autowhatever extends Component {
static propTypes = {
id: PropTypes.string, // Used in aria-* attributes. If multiple Autowhatever's are rendered on a page, they must have unique ids.
multiSection: PropTypes.bool, // Indicates whether a multi section layout should be rendered.
renderInputComponent: PropTypes.func, // When specified, it is used to render the input element.
renderItemsContainer: PropTypes.func, // Renders the items container.
items: PropTypes.array.isRequired, // Array of items or sections to render.
renderItem: PropTypes.func, // This function renders a single item.
renderItemData: PropTypes.object, // Arbitrary data that will be passed to renderItem()
renderSectionTitle: PropTypes.func, // This function gets a section and renders its title.
getSectionItems: PropTypes.func, // This function gets a section and returns its items, which will be passed into `renderItem` for rendering.
inputProps: PropTypes.object, // Arbitrary input props
itemProps: PropTypes.oneOfType([ // Arbitrary item props
PropTypes.object,
PropTypes.func
]),
highlightedSectionIndex: PropTypes.number, // Section index of the highlighted item
highlightedItemIndex: PropTypes.number, // Highlighted item index (within a section)
theme: PropTypes.oneOfType([ // Styles. See: https://github.com/markdalgleish/react-themeable
PropTypes.object,
PropTypes.array
])
};
static defaultProps = {
id: '1',
multiSection: false,
renderInputComponent: defaultRenderInputComponent,
renderItemsContainer: defaultRenderItemsContainer,
renderItem: () => {
throw new Error('`renderItem` must be provided');
},
renderItemData: emptyObject,
renderSectionTitle: () => {
throw new Error('`renderSectionTitle` must be provided');
},
getSectionItems: () => {
throw new Error('`getSectionItems` must be provided');
},
inputProps: emptyObject,
itemProps: emptyObject,
highlightedSectionIndex: null,
highlightedItemIndex: null,
theme: defaultTheme
};
constructor(props) {
super(props);
this.highlightedItem = null;
this.state = {
isInputFocused: false
};
this.setSectionsItems(props);
this.setSectionIterator(props);
this.setTheme(props);
}
componentDidMount() {
this.ensureHighlightedItemIsVisible();
}
componentWillReceiveProps(nextProps) {
if (nextProps.items !== this.props.items) {
this.setSectionsItems(nextProps);
}
if (nextProps.items !== this.props.items || nextProps.multiSection !== this.props.multiSection) {
this.setSectionIterator(nextProps);
}
if (nextProps.theme !== this.props.theme) {
this.setTheme(nextProps);
}
}
componentDidUpdate() {
this.ensureHighlightedItemIsVisible();
}
setSectionsItems(props) {
if (props.multiSection) {
this.sectionsItems = props.items.map(section => props.getSectionItems(section));
this.sectionsLengths = this.sectionsItems.map(items => items.length);
this.allSectionsAreEmpty = this.sectionsLengths.every(itemsCount => itemsCount === 0);
}
}
setSectionIterator(props) {
this.sectionIterator = createSectionIterator({
multiSection: props.multiSection,
data: props.multiSection ? this.sectionsLengths : props.items.length
});
}
setTheme(props) {
this.theme = themeable(props.theme);
}
storeInputReference = input => {
if (input !== null) {
this.input = input;
}
};
storeItemsContainerReference = itemsContainer => {
if (itemsContainer !== null) {
this.itemsContainer = itemsContainer;
}
};
onHighlightedItemChange = highlightedItem => {
this.highlightedItem = highlightedItem;
};
getItemId = (sectionIndex, itemIndex) => {
if (itemIndex === null) {
return null;
}
const { id } = this.props;
const section = (sectionIndex === null ? '' : `section-${sectionIndex}`);
return `react-autowhatever-${id}-${section}-item-${itemIndex}`;
};
renderSections() {
if (this.allSectionsAreEmpty) {
return null;
}
const { theme } = this;
const {
id, items, renderItem, renderItemData, renderSectionTitle,
highlightedSectionIndex, highlightedItemIndex, itemProps
} = this.props;
return items.map((section, sectionIndex) => {
const keyPrefix = `react-autowhatever-${id}-`;
const sectionKeyPrefix = `${keyPrefix}section-${sectionIndex}-`;
const isFirstSection = (sectionIndex === 0);
// `key` is provided by theme()
/* eslint-disable react/jsx-key */
return (
<div {...theme(`${sectionKeyPrefix}container`, 'sectionContainer', isFirstSection && 'sectionContainerFirst')}>
<SectionTitle
section={section}
renderSectionTitle={renderSectionTitle}
theme={theme}
sectionKeyPrefix={sectionKeyPrefix}
/>
<ItemsList
items={this.sectionsItems[sectionIndex]}
itemProps={itemProps}
renderItem={renderItem}
renderItemData={renderItemData}
sectionIndex={sectionIndex}
highlightedItemIndex={highlightedSectionIndex === sectionIndex ? highlightedItemIndex : null}
onHighlightedItemChange={this.onHighlightedItemChange}
getItemId={this.getItemId}
theme={theme}
keyPrefix={keyPrefix}
ref={this.storeItemsListReference}
/>
</div>
);
/* eslint-enable react/jsx-key */
});
}
renderItems() {
const { items } = this.props;
if (items.length === 0) {
return null;
}
const { theme } = this;
const {
id, renderItem, renderItemData, highlightedSectionIndex,
highlightedItemIndex, itemProps
} = this.props;
return (
<ItemsList
items={items}
itemProps={itemProps}
renderItem={renderItem}
renderItemData={renderItemData}
highlightedItemIndex={highlightedSectionIndex === null ? highlightedItemIndex : null}
onHighlightedItemChange={this.onHighlightedItemChange}
getItemId={this.getItemId}
theme={theme}
keyPrefix={`react-autowhatever-${id}-`}
/>
);
}
onFocus = event => {
const { inputProps } = this.props;
this.setState({
isInputFocused: true
});
inputProps.onFocus && inputProps.onFocus(event);
};
onBlur = event => {
const { inputProps } = this.props;
this.setState({
isInputFocused: false
});
inputProps.onBlur && inputProps.onBlur(event);
};
onKeyDown = event => {
const { inputProps, highlightedSectionIndex, highlightedItemIndex } = this.props;
switch (event.key) {
case 'ArrowDown':
case 'ArrowUp': {
const nextPrev = (event.key === 'ArrowDown' ? 'next' : 'prev');
const [newHighlightedSectionIndex, newHighlightedItemIndex] =
this.sectionIterator[nextPrev]([highlightedSectionIndex, highlightedItemIndex]);
inputProps.onKeyDown(event, { newHighlightedSectionIndex, newHighlightedItemIndex });
break;
}
default:
inputProps.onKeyDown(event, { highlightedSectionIndex, highlightedItemIndex });
}
};
ensureHighlightedItemIsVisible() {
const { highlightedItem } = this;
if (!highlightedItem) {
return;
}
const { itemsContainer } = this;
const itemOffsetRelativeToContainer =
highlightedItem.offsetParent === itemsContainer
? highlightedItem.offsetTop
: highlightedItem.offsetTop - itemsContainer.offsetTop;
let { scrollTop } = itemsContainer; // Top of the visible area
if (itemOffsetRelativeToContainer < scrollTop) {
// Item is off the top of the visible area
scrollTop = itemOffsetRelativeToContainer;
} else if (itemOffsetRelativeToContainer + highlightedItem.offsetHeight > scrollTop + itemsContainer.offsetHeight) {
// Item is off the bottom of the visible area
scrollTop = itemOffsetRelativeToContainer + highlightedItem.offsetHeight - itemsContainer.offsetHeight;
}
if (scrollTop !== itemsContainer.scrollTop) {
itemsContainer.scrollTop = scrollTop;
}
}
render() {
const { theme } = this;
const {
id, multiSection, renderInputComponent, renderItemsContainer,
highlightedSectionIndex, highlightedItemIndex
} = this.props;
const { isInputFocused } = this.state;
const renderedItems = multiSection ? this.renderSections() : this.renderItems();
const isOpen = (renderedItems !== null);
const ariaActivedescendant = this.getItemId(highlightedSectionIndex, highlightedItemIndex);
const containerProps = theme(
`react-autowhatever-${id}-container`,
'container',
isOpen && 'containerOpen'
);
const itemsContainerId = `react-autowhatever-${id}`;
const inputComponent = renderInputComponent({
type: 'text',
value: '',
autoComplete: 'off',
role: 'combobox',
'aria-autocomplete': 'list',
'aria-owns': itemsContainerId,
'aria-expanded': isOpen,
'aria-haspopup': isOpen,
'aria-activedescendant': ariaActivedescendant,
...theme(
`react-autowhatever-${id}-input`,
'input',
isOpen && 'inputOpen',
isInputFocused && 'inputFocused'
),
...this.props.inputProps,
onFocus: this.onFocus,
onBlur: this.onBlur,
onKeyDown: this.props.inputProps.onKeyDown && this.onKeyDown,
ref: this.storeInputReference
});
const itemsContainer = renderItemsContainer({
containerProps: {
id: itemsContainerId,
...theme(
`react-autowhatever-${id}-items-container`,
'itemsContainer',
isOpen && 'itemsContainerOpen'
),
ref: this.storeItemsContainerReference
},
children: renderedItems
});
return (
<div {...containerProps}>
{inputComponent}
{itemsContainer}
</div>
);
}
}