| 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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546 |
75x
74x
74x
8x
74x
3x
120x
120x
120x
601x
64x
120x
120x
120x
120x
120x
21x
21x
62x
120x
120x
287x
120x
120x
65x
9x
9x
9x
9x
8x
1x
1x
1x
1x
1x
8x
1x
1x
8x
3x
3x
1x
3x
1x
1x
8x
3x
2x
1x
1x
1x
1x
1x
1x
1x
4x
4x
2x
2x
1x
1x
1x
1x
4x
4x
4x
232x
232x
232x
232x
232x
232x
1x
4x
87x
5x
64x
1x
75x
75x
75x
75x
75x
4x
4x
12x
1x
11x
11x
31x
197x
8x
| import React from 'react';
import _ from 'lodash';
import { lucidClassNames } from '../../util/style-helpers';
import { createClass, getFirst, findTypes, rejectTypes, omitProps } from '../../util/component-types';
import { scrollParentTo } from '../../util/dom-helpers';
import * as KEYCODE from '../../constants/key-code';
import * as reducers from './DropMenu.reducers';
import ContextMenu from '../ContextMenu/ContextMenu';
function joinArray(array, getSeparator) {
return _.reduce(array, (newArray, element, index) => {
newArray.push(element);
if (index < _.size(array) - 1) {
newArray.push(getSeparator(element, index, array));
}
return newArray;
}, []);
}
function isOptionVisible(option) {
return !option.optionProps.isHidden;
}
const cx = lucidClassNames.bind('&-DropMenu');
const {
any,
arrayOf,
bool,
func,
node,
number,
object,
oneOf,
string,
} = React.PropTypes;
/**
*
* {"categories": ["helpers"], "madeFrom": ["ContextMenu"]}
*
* This is a helper component used to render a menu of options attached to any control. Supports option groups with and without labels as well as special options with a `null` index for unselect.
*/
const DropMenu = createClass({
displayName: 'DropMenu',
reducers,
components: {
/**
* An optional header to be displayed within the expanded Flyout, above all `Option`s.
*/
Header: createClass({
displayName: 'DropMenu.Header',
propName: 'Header',
}),
/**
* Renders a `<div>` that acts as the control target which the flyout menu is anchored to. Only one `Control` is used.
*/
Control: createClass({
displayName: 'DropMenu.Control',
propName: 'Control',
}),
/**
* A special kind of `Option` that is always rendered at the top of the menu and has an `optionIndex` of `null`. Useful for unselect.
*/
OptionGroup: createClass({
displayName: 'DropMenu.OptionGroup',
propName: 'OptionGroup',
propTypes: {
/**
* hides the `OptionGroup` from the list.
*/
isHidden: bool,
},
}),
/**
* Renders a `<div>` that acts as an option in the menu.
*/
Option: createClass({
displayName: 'DropMenu.Option',
propName: 'Option',
propTypes: {
/**
* disables selection of the `Option`.
*/
isDisabled: bool,
/**
* hides the `Option` from the list.
*/
isHidden: bool,
},
}),
/**
* A special kind of `Option` that is always rendered at the top of the menu and has an `optionIndex` of `null` used for deselecting.
*/
NullOption: createClass({
displayName: 'DropMenu.NullOption',
propName: 'NullOption',
}),
},
propTypes: {
/**
* Should be instances of {`DropMenu.Control`, `DropMenu.Option`, `DropMenu.OptionGroup`, `DropMenu.Nulloption`}. Other direct child elements will not render.
*/
children: node,
/**
* Appended to the component-specific class names set on the root elements. Applies to *both* the control and the flyout menu.
*/
className: string,
/**
* Styles that are passed through to root element.
*/
style: object,
/**
* Disables the DropMenu from being clicked or focused.
*/
isDisabled: bool,
/**
* Renders the flyout menu adjacent to the control.
*/
isExpanded: bool,
/**
* Sets the direction the flyout menu will render relative to the control.
*/
direction: oneOf(['down', 'up']),
/**
* An array of currently selected `DropMenu.Option` indices.
*/
selectedIndices: arrayOf(number),
/**
* The currently focused index of `DropMenu.Option`. Can also be `null`.
*/
focusedIndex: number,
/**
* The `id` of the flyout menu portal element that is appended to `document.body`. Defaults to a generated id.
*/
portalId: string,
/**
* Styles that are passed through to the ContextMenu FlyOut element.
*/
flyOutStyle: object,
/**
* Styles that are passed through to the option container element.
*/
optionContainerStyle: object,
/**
* Called when collapsed and the control is clicked, or when the control has focus and the Down Arrow is pressed.
* Has the signature `({ props, event }) => {}`
*/
onExpand: func,
/**
* Called when expanded and the user clicks the control or outside of the menu, or when the control has focus and the Escape key is pressed
* Has the signature `({ props, event }) => {}`
*/
onCollapse: func,
/**
* Called when an option is clicked, or when an option has focus and the Enter key is pressed.
* Has the signature `(optionIndex, {props, event}) => {}` where optionIndex can be a number or `null`.
*/
onSelect: func,
/**
* Called when expanded and the the Down Arrow key is pressed. Not called when focus is on the last option.
* Has the signature `({ props, event }) => {}`
*/
onFocusNext: func,
/**
* Called when expanded and the the Up Arrow key is pressed. Not called when focus is on the first option.
* Has the signature `({ props, event }) => {}`
*/
onFocusPrev: func,
/**
* Called when the mouse moves over an option.
* Has the signature `(optionIndex) => {}` where optionIndex can be a number or `null`.
*/
onFocusOption: func,
/**
* *Child Element* - The control target which the flyout menu is anchored to. Only one `Control` is used.
*/
Control: any,
/**
* *Child Element* - These are menu options. The `optionIndex` is in-order of rendering regardless of group nesting, starting with index `0`.
* Each `Option` may be passed a prop called `isDisabled` to disable selection of that `Option`.
* Any other props pass to Option will be available from the `onSelect` handler.
*/
Option: any,
/**
* *Child Element* - Used to group `Option`s within the menu. Any non-`Option`s passed in will be rendered as a label for the group.
*/
OptionGroup: any,
/**
* *Child Element* - A special kind of `Option` that is always rendered at the top of the menu and has an `optionIndex` of `null`. Useful for unselect.
*/
NullOption: any,
/**
* *Child Element* - An optional header to be displayed within the expanded Flyout, above all `Option`s.
*/
Header: any,
},
getDefaultProps() {
return {
isDisabled: false,
isExpanded: false,
direction: 'down',
selectedIndices: [],
focusedIndex: null,
flyOutStyle: { maxHeight: '18em' },
onExpand: _.noop,
onCollapse: _.noop,
onSelect: _.noop,
onFocusNext: _.noop,
onFocusPrev: _.noop,
onFocusOption: _.noop,
};
},
getInitialState() {
return {
isMouseTriggered: false,
optionGroups: [],
flattenedOptionsData: [],
ungroupedOptionData: [],
optionGroupDataLookup: {},
portalId: this.props.portalId || _.uniqueId('DropMenu-Portal-'),
}
},
statics: {
preprocessOptionData(props, ParentType=DropMenu) {
const {
OptionGroup,
Option,
NullOption,
} = ParentType;
const optionGroups = _.map(findTypes(props, OptionGroup), 'props'); // find all OptionGroup props
const ungroupedOptions = _.map(findTypes(props, Option), 'props') // find all ungrouped Option props
const nullOptions = NullOption ? _.map(findTypes(props, NullOption), 'props') : []; // find all NullOption props
// flatten grouped options into array of objects to associate { index, group index, and props } for each option
const groupedOptionData = _.reduce(optionGroups, (memo, optionGroupProps, optionGroupIndex) => {
const groupedOptions = _.map(findTypes(optionGroupProps, Option), 'props'); // find all Option props for current group
return memo.concat(_.map(groupedOptions, (optionProps, localOptionIndex) => {
return {
localOptionIndex,
optionIndex: _.size(memo) + localOptionIndex, // add current index to current array length to get final option index
optionGroupIndex, // store option group index to associate option back to group
optionProps,
};
}));
}, []);
// create lookup object for options by their group index
const optionGroupDataLookup = _.groupBy(groupedOptionData, 'optionGroupIndex');
// store ungrouped options into array of objects to associate { index, and props } for each option
const ungroupedOptionData = _.map(ungroupedOptions, (optionProps, localOptionIndex) => {
return {
localOptionIndex,
optionIndex: _.size(groupedOptionData) + localOptionIndex, // add current index to grouped options array length to get final option index (grouped options rendered first)
optionGroupIndex: null, // ungrouped options have no `optionGroupIndex`
optionProps,
};
});
// concatenate grouped options array with ungrouped options array to get flat list of all options
const flattenedOptionsData = groupedOptionData.concat(ungroupedOptionData);
return {
optionGroups,
optionGroupDataLookup,
ungroupedOptionData,
flattenedOptionsData,
nullOptions,
};
},
},
getPreprocessedOptionData(props) {
return DropMenu.preprocessOptionData(props, DropMenu);
},
handleKeydown(event) {
const {
props,
props: {
isExpanded,
focusedIndex,
onExpand,
onCollapse,
onSelect,
onFocusOption,
},
} = this;
const {
flattenedOptionsData,
nullOptions,
} = this.state;
this.setState({
isMouseTriggered: false,
});
if (isExpanded) {
if (event.keyCode === KEYCODE.Enter) {
event.preventDefault();
const focusedOptionData = _.get(flattenedOptionsData, focusedIndex, null);
const focusedOptionProps = _.get(focusedOptionData, 'optionProps', {});
Eif (focusedOptionData && !focusedOptionProps.isDisabled) {
onSelect(focusedIndex, {props: focusedOptionProps, event});
} else if (_.isNull(focusedIndex)) {
onSelect(null, {props: _.first(nullOptions), event});
}
}
if (event.keyCode === KEYCODE.Escape) {
event.preventDefault();
onCollapse({ props, event });
}
if (event.keyCode === KEYCODE.ArrowUp) {
Eif (_.isNumber(focusedIndex) || _.isNull(focusedIndex)) {
if (focusedIndex === 0) {
Iif (!_.isEmpty(nullOptions)) {
event.preventDefault();
onFocusOption(null, { props, event });
}
}
if (focusedIndex > 0) {
event.preventDefault();
onFocusOption(_.findLastIndex(flattenedOptionsData, isOptionVisible, focusedIndex - 1), { props, event });
}
} else {
event.preventDefault();
onFocusOption(_.findLastIndex(flattenedOptionsData, isOptionVisible, focusedIndex - 1), { props, event });
}
}
if (event.keyCode === KEYCODE.ArrowDown) {
if (_.isNumber(focusedIndex)) {
if (focusedIndex < _.size(flattenedOptionsData) - 1) {
event.preventDefault();
onFocusOption(_.findIndex(flattenedOptionsData, isOptionVisible, focusedIndex + 1), { props, event });
}
} else {
event.preventDefault();
onFocusOption(_.findIndex(flattenedOptionsData, isOptionVisible, focusedIndex), { props, event });
}
}
} else {
Eif (event.keyCode === KEYCODE.ArrowDown) {
event.preventDefault();
onExpand({ props, event });
}
}
},
handleClick(event) {
const {
props,
props: {
isExpanded,
onExpand,
onCollapse,
},
} = this;
if (isExpanded) {
onCollapse({ props, event });
} else {
onExpand({ props, event });
}
},
handleMouseFocusOption(optionIndex, optionProps, event) {
const {
focusedIndex,
onFocusOption,
} = this.props;
this.setState({
isMouseTriggered: true,
});
Eif (!optionProps.isDisabled && focusedIndex !== optionIndex) {
onFocusOption(optionIndex, { props: optionProps, event });
}
},
handleSelectOption(optionIndex, optionProps, event) {
const {
onSelect,
} = this.props;
Eif (!optionProps.isDisabled) {
onSelect(optionIndex, { props: optionProps, event });
}
},
renderOption(optionProps, optionIndex, isGrouped) {
const {
selectedIndices,
focusedIndex,
} = this.props;
const {
isMouseTriggered,
} = this.state;
const {
isDisabled,
isHidden,
} = optionProps;
const isFocused = optionIndex === focusedIndex;
const isSelected = _.includes(selectedIndices, optionIndex);
return (
!isHidden &&
<div
key={'DropMenuOption' + optionIndex}
onMouseMove={(event) => this.handleMouseFocusOption(optionIndex, optionProps, event)}
onClick={(event) => this.handleSelectOption(optionIndex, optionProps, event)}
{...omitProps(optionProps, DropMenu.Option)}
className={cx(
'&-Option', {
'&-Option-is-grouped': isGrouped,
'&-Option-is-focused': isFocused,
'&-Option-is-selected': isSelected,
'&-Option-is-disabled': isDisabled,
'&-Option-is-null': _.isNull(optionIndex),
}, optionProps.className)}
ref={(optionDOMNode)=> {
if (isFocused && !isMouseTriggered) {
scrollParentTo(optionDOMNode, this._header && this._header.offsetHeight);
}
}}
/>
);
},
componentWillMount() {
// preprocess the options data before rendering
this.setState(this.getPreprocessedOptionData(this.props));
},
componentWillReceiveProps(nextProps) {
// only preprocess options data when it changes (via new props) - better performance than doing this each render
this.setState(this.getPreprocessedOptionData(nextProps));
},
render() {
const {
className,
style,
isDisabled,
isExpanded,
direction,
onCollapse,
flyOutStyle,
optionContainerStyle,
} = this.props;
const {
optionGroups,
ungroupedOptionData,
optionGroupDataLookup,
nullOptions,
portalId,
} = this.state;
const controlProps = _.get(getFirst(this.props, DropMenu.Control), 'props', {});
const headerProps = _.get(getFirst(this.props, DropMenu.Header), 'props', {});
return (
<div className={cx('&', '&-base', {
'&-is-expanded': isExpanded,
'&-direction-down': isExpanded && direction === 'down',
'&-direction-up': isExpanded && direction === 'up',
}, className)} style={style}>
<ContextMenu
portalId={portalId}
isExpanded={isExpanded}
direction={direction}
onClickOut={onCollapse}
>
<ContextMenu.Target>
<div
{...(!isDisabled ? {
tabIndex: 0,
onClick: this.handleClick,
onKeyDown: this.handleKeydown,
} : null)}
{...controlProps}
className={cx('&-Control', _.get(controlProps, 'className'))}
/>
</ContextMenu.Target>
<ContextMenu.FlyOut className={cx('&', className)} style={flyOutStyle}>
{
!_.isEmpty(headerProps) &&
<div
{...headerProps}
className={cx('&-Header', headerProps.className)}
onKeyDown={this.handleKeydown}
ref={(header) => this._header = header}
/>
}
<div
className={cx('&-option-container')}
style={_.assign({}, flyOutStyle, optionContainerStyle)}
>
{
_.map(nullOptions, (optionProps) => this.renderOption(optionProps, null))
.concat(_.isEmpty(nullOptions) ? [] : [(<div key={'OptionGroup-divider-NullOption'} className={cx('&-OptionGroup-divider')} />)])
}
{
joinArray(
// for each option group,
_.map(optionGroups, (optionGroupProps, optionGroupIndex) => {
if (optionGroupProps.isHidden) {
return null;
}
const labelElements = rejectTypes(optionGroupProps.children, [DropMenu.Control, DropMenu.OptionGroup, DropMenu.Option, DropMenu.NullOption]);
// render label if there is one
return (_.isEmpty(labelElements) ? [] : [
<div {...optionGroupProps} className={cx('&-label', optionGroupProps.className)}>
{labelElements}
</div>,
// render the options in the group
]).concat(_.map(_.get(optionGroupDataLookup, optionGroupIndex), ({ optionProps, optionIndex }) => this.renderOption(optionProps, optionIndex, true)));
// append all ungrouped options as another unlabeled group
}).concat(_.isEmpty(ungroupedOptionData) ? [] : [_.map(ungroupedOptionData, ({ optionProps, optionIndex }) => this.renderOption(optionProps, optionIndex))]),
(element, index) => (element && <div key={`OptionGroup-divider-${index}`} className={cx('&-OptionGroup-divider')} />) // separate each group with divider
)
}
</div>
</ContextMenu.FlyOut>
</ContextMenu>
</div>
);
},
});
export default DropMenu;
|