# all files / src/widgets/ MenuSelectWidget.js

40.82% Statements 60/147
25.6% Branches 32/125
30.77% Functions 4/13
40.82% Lines 60/147

    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

    1×

    5728×

    5728×

    5728×
    5728×

    5728×
    5728×
    5728×
    5728×
    5728×
    5728×
    5728×
    5728×
    5728×
    5728×

    5728×
    5728×
    5728×

    5728×
    5728×

    1×
    1×
    1×

    1×

    1×

    1×
    8008×

    8008×
    4×
    4×

    4×
    9×
    9×

    9×
    9×
    9×
    9×
    9×
    9×
    9×

    4×

    4×
    3×

    4×

    8008×

    1×

    1×

    1×

    1×

    1×

    1×

    4006×

    4006×

    4006×

    1×

    1×

    4002×

    4002×

    4002×

    1×

     /**
     * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
     * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
     * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget},
     * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
     * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
     * and customized to be opened, closed, and displayed as needed.
     *
     * By default, menus are clipped to the visible viewport and are not visible when a user presses the
     * mouse outside the menu.
     *
     * Menus also have support for keyboard interaction:
     *
     * - Enter/Return key: choose and select a menu option
     * - Up-arrow key: highlight the previous menu option
     * - Down-arrow key: highlight the next menu option
     * - Esc key: hide the menu
     *
     * Unlike most widgets, MenuSelectWidget is initially hidden and must be shown by calling #toggle.
     *
     * Please see the [OOUI documentation on MediaWiki][1] for more information.
     * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
     *
     * @class
     * @extends OO.ui.SelectWidget
     * @mixins OO.ui.mixin.ClippableElement
     * @mixins OO.ui.mixin.FloatableElement
     *
     * @constructor
     * @param {Object} [config] Configuration options
     * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
     *  the text the user types. This config is used by {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}
     *  and {@link OO.ui.mixin.LookupElement LookupElement}
     * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
     *  the text the user types. This config is used by {@link OO.ui.CapsuleMultiselectWidget CapsuleMultiselectWidget}
     * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
     *  anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
     *  that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
     *  that button, unless the button (or its parent widget) is passed in here.
     * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
     * @cfg {jQuery} [$autoCloseIgnore] If these elements are clicked, don't auto-hide the menu.
     * @cfg {boolean} [hideOnChoose=true] Hide the menu when the user chooses an option.
     * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
     * @cfg {boolean} [highlightOnFilter] Highlight the first result when filtering
     * @cfg {number} [width] Width of the menu
     */
    OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) {
    	// Configuration initialization
    	config = config || {};

    	// Parent constructor
    	OO.ui.MenuSelectWidget.parent.call( this, config );

    	// Mixin constructors
    	OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
    	OO.ui.mixin.FloatableElement.call( this, config );

    	// Properties
    	this.autoHide = config.autoHide === undefined || !!config.autoHide;
    	this.hideOnChoose = config.hideOnChoose === undefined || !!config.hideOnChoose;
    	this.filterFromInput = !!config.filterFromInput;
    	this.$input = config.$input ? config.$input : config.input ? config.input.$input : null;
    	this.$widget = config.widget ? config.widget.$element : null;
    	this.$autoCloseIgnore = config.$autoCloseIgnore || $( [] );
    	this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
    	this.onInputEditHandler = OO.ui.debounce( this.updateItemVisibility.bind( this ), 100 );
    	this.highlightOnFilter = !!config.highlightOnFilter;
    	this.width = config.width;

    	// Initialization
    	this.$element.addClass( 'oo-ui-menuSelectWidget' );
    	Eif ( config.widget ) {
    		this.setFocusOwner( config.widget.$tabIndexed );
    	}

    	// Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
    	// that reference properties not initialized at that time of parent class construction
    	// TODO: Find a better way to handle post-constructor setup
    	this.visible = false;
    	this.$element.addClass( 'oo-ui-element-hidden' );
    };

    /* Setup */

    OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget );
    OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.ClippableElement );
    OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.FloatableElement );

    /* Events */

    /**
     * @event ready
     *
     * The menu is ready: it is visible and has been positioned and clipped.
     */

    /* Methods */

    /**
     * Handles document mouse down events.
     *
     * @protected
     * @param {MouseEvent} e Mouse down event
     */
    OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) {
    	if (
    		this.isVisible() &&
    		!OO.ui.contains(
    			this.$element.add( this.$widget ).add( this.$autoCloseIgnore ).get(),
    			e.target,
    			true
    		)
    	) {
    		this.toggle( false );
    	}
    };

    /**
     * @inheritdoc
     */
    OO.ui.MenuSelectWidget.prototype.onKeyDown = function ( e ) {
    	var currentItem = this.findHighlightedItem() || this.findSelectedItem();

    	if ( !this.isDisabled() && this.isVisible() ) {
    		switch ( e.keyCode ) {
    			case OO.ui.Keys.LEFT:
    			case OO.ui.Keys.RIGHT:
    				// Do nothing if a text field is associated, arrow keys will be handled natively
    				if ( !this.$input ) {
    					OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e );
    				}
    				break;
    			case OO.ui.Keys.ESCAPE:
    			case OO.ui.Keys.TAB:
    				if ( currentItem ) {
    					currentItem.setHighlighted( false );
    				}
    				this.toggle( false );
    				// Don't prevent tabbing away, prevent defocusing
    				if ( e.keyCode === OO.ui.Keys.ESCAPE ) {
    					e.preventDefault();
    					e.stopPropagation();
    				}
    				break;
    			default:
    				OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e );
    				return;
    		}
    	}
    };

    /**
     * Update menu item visibility and clipping after input changes (if filterFromInput is enabled)
     * or after items were added/removed (always).
     *
     * @protected
     */
    OO.ui.MenuSelectWidget.prototype.updateItemVisibility = function () {
    	var i, item, visible, section, sectionEmpty, filter, exactFilter,
    		firstItemFound = false,
    		anyVisible = false,
    		len = this.items.length,
    		showAll = !this.isVisible(),
    		exactMatch = false;

    	if ( this.$input && this.filterFromInput ) {
    		filter = showAll ? null : this.getItemMatcher( this.$input.val() );
    		exactFilter = this.getItemMatcher( this.$input.val(), true );

    		// Hide non-matching options, and also hide section headers if all options
    		// in their section are hidden.
    		for ( i = 0; i < len; i++ ) {
    			item = this.items[ i ];
    			Iif ( item instanceof OO.ui.MenuSectionOptionWidget ) {
    				if ( section ) {
    					// If the previous section was empty, hide its header
    					section.toggle( showAll || !sectionEmpty );
    				}
    				section = item;
    				sectionEmpty = true;
    			} else Eif ( item instanceof OO.ui.OptionWidget ) {
    				visible = showAll || filter( item );
    				exactMatch = exactMatch || exactFilter( item );
    				anyVisible = anyVisible || visible;
    				sectionEmpty = sectionEmpty && !visible;
    				item.toggle( visible );
    				Iif ( this.highlightOnFilter && visible && !firstItemFound ) {
    					// Highlight the first item in the list
    					this.highlightItem( item );
    					firstItemFound = true;
    				}
    			}
    		}
    		// Process the final section
    		Iif ( section ) {
    			section.toggle( showAll || !sectionEmpty );
    		}

    		if ( anyVisible && this.items.length && !exactMatch ) {
    			this.scrollItemIntoView( this.items[ 0 ] );
    		}

    		this.$element.toggleClass( 'oo-ui-menuSelectWidget-invisible', !anyVisible );
    	}

    	// Reevaluate clipping
    	this.clip();
    };

    /**
     * @inheritdoc
     */
    OO.ui.MenuSelectWidget.prototype.bindKeyDownListener = function () {
    	if ( this.$input ) {
    		this.$input.on( 'keydown', this.onKeyDownHandler );
    	} else {
    		OO.ui.MenuSelectWidget.parent.prototype.bindKeyDownListener.call( this );
    	}
    };

    /**
     * @inheritdoc
     */
    OO.ui.MenuSelectWidget.prototype.unbindKeyDownListener = function () {
    	if ( this.$input ) {
    		this.$input.off( 'keydown', this.onKeyDownHandler );
    	} else {
    		OO.ui.MenuSelectWidget.parent.prototype.unbindKeyDownListener.call( this );
    	}
    };

    /**
     * @inheritdoc
     */
    OO.ui.MenuSelectWidget.prototype.bindKeyPressListener = function () {
    	if ( this.$input ) {
    		if ( this.filterFromInput ) {
    			this.$input.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
    			this.updateItemVisibility();
    		}
    	} else {
    		OO.ui.MenuSelectWidget.parent.prototype.bindKeyPressListener.call( this );
    	}
    };

    /**
     * @inheritdoc
     */
    OO.ui.MenuSelectWidget.prototype.unbindKeyPressListener = function () {
    	if ( this.$input ) {
    		if ( this.filterFromInput ) {
    			this.$input.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler );
    			this.updateItemVisibility();
    		}
    	} else {
    		OO.ui.MenuSelectWidget.parent.prototype.unbindKeyPressListener.call( this );
    	}
    };

    /**
     * Choose an item.
     *
     * When a user chooses an item, the menu is closed, unless the hideOnChoose config option is set to false.
     *
     * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
     * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
     *
     * @param {OO.ui.OptionWidget} item Item to choose
     * @chainable
     */
    OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) {
    	OO.ui.MenuSelectWidget.parent.prototype.chooseItem.call( this, item );
    	if ( this.hideOnChoose ) {
    		this.toggle( false );
    	}
    	return this;
    };

    /**
     * @inheritdoc
     */
    OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) {
    	// Parent method
    	OO.ui.MenuSelectWidget.parent.prototype.addItems.call( this, items, index );

    	this.updateItemVisibility();

    	return this;
    };

    /**
     * @inheritdoc
     */
    OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) {
    	// Parent method
    	OO.ui.MenuSelectWidget.parent.prototype.removeItems.call( this, items );

    	this.updateItemVisibility();

    	return this;
    };

    /**
     * @inheritdoc
     */
    OO.ui.MenuSelectWidget.prototype.clearItems = function () {
    	// Parent method
    	OO.ui.MenuSelectWidget.parent.prototype.clearItems.call( this );

    	this.updateItemVisibility();

    	return this;
    };

    /**
     * Toggle visibility of the menu. The menu is initially hidden and must be shown by calling
     * `.toggle( true )` after its #$element is attached to the DOM.
     *
     * Do not show the menu while it is not attached to the DOM. The calculations required to display
     * it in the right place and with the right dimensions only work correctly while it is attached.
     * Side-effects may include broken interface and exceptions being thrown. This wasn't always
     * strictly enforced, so currently it only generates a warning in the browser console.
     *
     * @fires ready
     * @inheritdoc
     */
    OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) {
    	var change, belowHeight, aboveHeight;

    	visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length;
    	change = visible !== this.isVisible();

    	if ( visible && !this.warnedUnattached && !this.isElementAttached() ) {
    		OO.ui.warnDeprecation( 'MenuSelectWidget#toggle: Before calling this method, the menu must be attached to the DOM.' );
    		this.warnedUnattached = true;
    	}

    	if ( change ) {
    		if ( visible && ( this.width || this.$floatableContainer ) ) {
    			this.setIdealSize( this.width || this.$floatableContainer.width() );
    		}
    		if ( visible ) {
    			// Reset position before showing the popup again. It's possible we no longer need to flip
    			// (e.g. if the user scrolled).
    			this.setVerticalPosition( 'below' );
    		}
    	}

    	// Parent method
    	OO.ui.MenuSelectWidget.parent.prototype.toggle.call( this, visible );

    	if ( change ) {
    		if ( visible ) {
    			this.bindKeyDownListener();
    			this.bindKeyPressListener();

    			this.togglePositioning( !!this.$floatableContainer );
    			this.toggleClipping( true );

    			if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
    				// If opening the menu downwards causes it to be clipped, flip it to open upwards instead
    				belowHeight = this.$element.height();
    				this.setVerticalPosition( 'above' );
    				if ( this.isClippedVertically() || this.isFloatableOutOfView() ) {
    					// If opening upwards also causes it to be clipped, flip it to open in whichever direction
    					// we have more space
    					aboveHeight = this.$element.height();
    					if ( aboveHeight < belowHeight ) {
    						this.setVerticalPosition( 'below' );
    					}
    				}
    			}
    			// Note that we do not flip the menu's opening direction if the clipping changes
    			// later (e.g. after the user scrolls), that seems like it would be annoying

    			this.$focusOwner.attr( 'aria-expanded', 'true' );

    			if ( this.findSelectedItem() ) {
    				this.$focusOwner.attr( 'aria-activedescendant', this.findSelectedItem().getElementId() );
    				this.findSelectedItem().scrollElementIntoView( { duration: 0 } );
    			}

    			// Auto-hide
    			if ( this.autoHide ) {
    				this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
    			}

    			this.emit( 'ready' );
    		} else {
    			this.$focusOwner.removeAttr( 'aria-activedescendant' );
    			this.unbindKeyDownListener();
    			this.unbindKeyPressListener();
    			this.$focusOwner.attr( 'aria-expanded', 'false' );
    			this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler, true );
    			this.togglePositioning( false );
    			this.toggleClipping( false );
    		}
    	}

    	return this;
    };