Merge "RCFilters: define consistent interface in ChangesListFilterGroup"
[lhc/web/wiklou.git] / resources / lib / oojs-ui / oojs-ui-widgets.js
1 /*!
2 * OOjs UI v0.24.0
3 * https://www.mediawiki.org/wiki/OOjs_UI
4 *
5 * Copyright 2011–2017 OOjs UI Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
8 *
9 * Date: 2017-10-17T23:18:51Z
10 */
11 ( function ( OO ) {
12
13 'use strict';
14
15 /**
16 * DraggableElement is a mixin class used to create elements that can be clicked
17 * and dragged by a mouse to a new position within a group. This class must be used
18 * in conjunction with OO.ui.mixin.DraggableGroupElement, which provides a container for
19 * the draggable elements.
20 *
21 * @abstract
22 * @class
23 *
24 * @constructor
25 * @param {Object} [config] Configuration options
26 * @cfg {jQuery} [$handle] The part of the element which can be used for dragging, defaults to the whole element
27 * @cfg {boolean} [draggable] The items are draggable. This can change with #toggleDraggable
28 * but the draggable state should be called from the DraggableGroupElement, which updates
29 * the whole group
30 */
31 OO.ui.mixin.DraggableElement = function OoUiMixinDraggableElement( config ) {
32 config = config || {};
33
34 // Properties
35 this.index = null;
36 this.$handle = config.$handle || this.$element;
37 this.wasHandleUsed = null;
38
39 // Initialize and events
40 this.$element
41 .addClass( 'oo-ui-draggableElement' )
42 .on( {
43 mousedown: this.onDragMouseDown.bind( this ),
44 dragstart: this.onDragStart.bind( this ),
45 dragover: this.onDragOver.bind( this ),
46 dragend: this.onDragEnd.bind( this ),
47 drop: this.onDrop.bind( this )
48 } );
49 this.$handle.addClass( 'oo-ui-draggableElement-handle' );
50 this.toggleDraggable( config.draggable === undefined ? true : !!config.draggable );
51 };
52
53 OO.initClass( OO.ui.mixin.DraggableElement );
54
55 /* Events */
56
57 /**
58 * @event dragstart
59 *
60 * A dragstart event is emitted when the user clicks and begins dragging an item.
61 * @param {OO.ui.mixin.DraggableElement} item The item the user has clicked and is dragging with the mouse.
62 */
63
64 /**
65 * @event dragend
66 * A dragend event is emitted when the user drags an item and releases the mouse,
67 * thus terminating the drag operation.
68 */
69
70 /**
71 * @event drop
72 * A drop event is emitted when the user drags an item and then releases the mouse button
73 * over a valid target.
74 */
75
76 /* Static Properties */
77
78 /**
79 * @inheritdoc OO.ui.mixin.ButtonElement
80 */
81 OO.ui.mixin.DraggableElement.static.cancelButtonMouseDownEvents = false;
82
83 /* Methods */
84
85 /**
86 * Change the draggable state of this widget.
87 * This allows users to temporarily halt the dragging operations.
88 *
89 * @param {boolean} isDraggable Widget supports draggable operations
90 * @fires draggable
91 */
92 OO.ui.mixin.DraggableElement.prototype.toggleDraggable = function ( isDraggable ) {
93 isDraggable = isDraggable !== undefined ? !!isDraggable : !this.draggable;
94
95 if ( this.draggable !== isDraggable ) {
96 this.draggable = isDraggable;
97
98 this.$handle.toggleClass( 'oo-ui-draggableElement-undraggable', !this.draggable );
99
100 // We make the entire element draggable, not just the handle, so that
101 // the whole element appears to move. wasHandleUsed prevents drags from
102 // starting outside the handle
103 this.$element.prop( 'draggable', this.draggable );
104 }
105 };
106
107 /**
108 * Check the draggable state of this widget
109 *
110 * @return {boolean} Widget supports draggable operations
111 */
112 OO.ui.mixin.DraggableElement.prototype.isDraggable = function () {
113 return this.draggable;
114 };
115
116 /**
117 * Respond to mousedown event.
118 *
119 * @private
120 * @param {jQuery.Event} e Drag event
121 */
122 OO.ui.mixin.DraggableElement.prototype.onDragMouseDown = function ( e ) {
123 if ( !this.isDraggable() ) {
124 return;
125 }
126
127 this.wasHandleUsed =
128 // Optimization: if the handle is the whole element this is always true
129 this.$handle[ 0 ] === this.$element[ 0 ] ||
130 // Check the mousedown occurred inside the handle
131 OO.ui.contains( this.$handle[ 0 ], e.target, true );
132 };
133
134 /**
135 * Respond to dragstart event.
136 *
137 * @private
138 * @param {jQuery.Event} e Drag event
139 * @return {boolean} False if the event is cancelled
140 * @fires dragstart
141 */
142 OO.ui.mixin.DraggableElement.prototype.onDragStart = function ( e ) {
143 var element = this,
144 dataTransfer = e.originalEvent.dataTransfer;
145
146 if ( !this.wasHandleUsed || !this.isDraggable() ) {
147 return false;
148 }
149
150 // Define drop effect
151 dataTransfer.dropEffect = 'none';
152 dataTransfer.effectAllowed = 'move';
153 // Support: Firefox
154 // We must set up a dataTransfer data property or Firefox seems to
155 // ignore the fact the element is draggable.
156 try {
157 dataTransfer.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
158 } catch ( err ) {
159 // The above is only for Firefox. Move on if it fails.
160 }
161 // Briefly add a 'clone' class to style the browser's native drag image
162 this.$element.addClass( 'oo-ui-draggableElement-clone' );
163 // Add placeholder class after the browser has rendered the clone
164 setTimeout( function () {
165 element.$element
166 .removeClass( 'oo-ui-draggableElement-clone' )
167 .addClass( 'oo-ui-draggableElement-placeholder' );
168 } );
169 // Emit event
170 this.emit( 'dragstart', this );
171 return true;
172 };
173
174 /**
175 * Respond to dragend event.
176 *
177 * @private
178 * @fires dragend
179 */
180 OO.ui.mixin.DraggableElement.prototype.onDragEnd = function () {
181 this.$element.removeClass( 'oo-ui-draggableElement-placeholder' );
182 this.emit( 'dragend' );
183 };
184
185 /**
186 * Handle drop event.
187 *
188 * @private
189 * @param {jQuery.Event} e Drop event
190 * @fires drop
191 */
192 OO.ui.mixin.DraggableElement.prototype.onDrop = function ( e ) {
193 e.preventDefault();
194 this.emit( 'drop', e );
195 };
196
197 /**
198 * In order for drag/drop to work, the dragover event must
199 * return false and stop propogation.
200 *
201 * @param {jQuery.Event} e Drag event
202 * @private
203 */
204 OO.ui.mixin.DraggableElement.prototype.onDragOver = function ( e ) {
205 e.preventDefault();
206 };
207
208 /**
209 * Set item index.
210 * Store it in the DOM so we can access from the widget drag event
211 *
212 * @private
213 * @param {number} index Item index
214 */
215 OO.ui.mixin.DraggableElement.prototype.setIndex = function ( index ) {
216 if ( this.index !== index ) {
217 this.index = index;
218 this.$element.data( 'index', index );
219 }
220 };
221
222 /**
223 * Get item index
224 *
225 * @private
226 * @return {number} Item index
227 */
228 OO.ui.mixin.DraggableElement.prototype.getIndex = function () {
229 return this.index;
230 };
231
232 /**
233 * DraggableGroupElement is a mixin class used to create a group element to
234 * contain draggable elements, which are items that can be clicked and dragged by a mouse.
235 * The class is used with OO.ui.mixin.DraggableElement.
236 *
237 * @abstract
238 * @class
239 * @mixins OO.ui.mixin.GroupElement
240 *
241 * @constructor
242 * @param {Object} [config] Configuration options
243 * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation
244 * should match the layout of the items. Items displayed in a single row
245 * or in several rows should use horizontal orientation. The vertical orientation should only be
246 * used when the items are displayed in a single column. Defaults to 'vertical'
247 * @cfg {boolean} [draggable] The items are draggable. This can change with #toggleDraggable
248 */
249 OO.ui.mixin.DraggableGroupElement = function OoUiMixinDraggableGroupElement( config ) {
250 // Configuration initialization
251 config = config || {};
252
253 // Parent constructor
254 OO.ui.mixin.GroupElement.call( this, config );
255
256 // Properties
257 this.orientation = config.orientation || 'vertical';
258 this.dragItem = null;
259 this.itemKeys = {};
260 this.dir = null;
261 this.itemsOrder = null;
262 this.draggable = config.draggable === undefined ? true : !!config.draggable;
263
264 // Events
265 this.aggregate( {
266 dragstart: 'itemDragStart',
267 dragend: 'itemDragEnd',
268 drop: 'itemDrop'
269 } );
270 this.connect( this, {
271 itemDragStart: 'onItemDragStart',
272 itemDrop: 'onItemDropOrDragEnd',
273 itemDragEnd: 'onItemDropOrDragEnd'
274 } );
275
276 // Initialize
277 if ( Array.isArray( config.items ) ) {
278 this.addItems( config.items );
279 }
280 this.$element
281 .addClass( 'oo-ui-draggableGroupElement' )
282 .append( this.$status )
283 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation === 'horizontal' );
284 };
285
286 /* Setup */
287 OO.mixinClass( OO.ui.mixin.DraggableGroupElement, OO.ui.mixin.GroupElement );
288
289 /* Events */
290
291 /**
292 * An item has been dragged to a new position, but not yet dropped.
293 *
294 * @event drag
295 * @param {OO.ui.mixin.DraggableElement} item Dragged item
296 * @param {number} [newIndex] New index for the item
297 */
298
299 /**
300 * An item has been dropped at a new position.
301 *
302 * @event reorder
303 * @param {OO.ui.mixin.DraggableElement} item Reordered item
304 * @param {number} [newIndex] New index for the item
305 */
306
307 /**
308 * Draggable state of this widget has changed.
309 *
310 * @event draggable
311 * @param {boolean} [draggable] Widget is draggable
312 */
313
314 /* Methods */
315
316 /**
317 * Change the draggable state of this widget.
318 * This allows users to temporarily halt the dragging operations.
319 *
320 * @param {boolean} isDraggable Widget supports draggable operations
321 * @fires draggable
322 */
323 OO.ui.mixin.DraggableGroupElement.prototype.toggleDraggable = function ( isDraggable ) {
324 isDraggable = isDraggable !== undefined ? !!isDraggable : !this.draggable;
325
326 if ( this.draggable !== isDraggable ) {
327 this.draggable = isDraggable;
328
329 // Tell the items their draggable state changed
330 this.getItems().forEach( function ( item ) {
331 item.toggleDraggable( this.draggable );
332 }.bind( this ) );
333
334 // Emit event
335 this.emit( 'draggable', this.draggable );
336 }
337 };
338
339 /**
340 * Check the draggable state of this widget
341 *
342 * @return {boolean} Widget supports draggable operations
343 */
344 OO.ui.mixin.DraggableGroupElement.prototype.isDraggable = function () {
345 return this.draggable;
346 };
347
348 /**
349 * Respond to item drag start event
350 *
351 * @private
352 * @param {OO.ui.mixin.DraggableElement} item Dragged item
353 */
354 OO.ui.mixin.DraggableGroupElement.prototype.onItemDragStart = function ( item ) {
355 if ( !this.isDraggable() ) {
356 return;
357 }
358 // Make a shallow copy of this.items so we can re-order it during previews
359 // without affecting the original array.
360 this.itemsOrder = this.items.slice();
361 this.updateIndexes();
362 if ( this.orientation === 'horizontal' ) {
363 // Calculate and cache directionality on drag start - it's a little
364 // expensive and it shouldn't change while dragging.
365 this.dir = this.$element.css( 'direction' );
366 }
367 this.setDragItem( item );
368 };
369
370 /**
371 * Update the index properties of the items
372 */
373 OO.ui.mixin.DraggableGroupElement.prototype.updateIndexes = function () {
374 var i, len;
375
376 // Map the index of each object
377 for ( i = 0, len = this.itemsOrder.length; i < len; i++ ) {
378 this.itemsOrder[ i ].setIndex( i );
379 }
380 };
381
382 /**
383 * Handle drop or dragend event and switch the order of the items accordingly
384 *
385 * @private
386 * @param {OO.ui.mixin.DraggableElement} item Dropped item
387 */
388 OO.ui.mixin.DraggableGroupElement.prototype.onItemDropOrDragEnd = function () {
389 var targetIndex, originalIndex,
390 item = this.getDragItem();
391
392 // TODO: Figure out a way to configure a list of legally droppable
393 // elements even if they are not yet in the list
394 if ( item ) {
395 originalIndex = this.items.indexOf( item );
396 // If the item has moved forward, add one to the index to account for the left shift
397 targetIndex = item.getIndex() + ( item.getIndex() > originalIndex ? 1 : 0 );
398 if ( targetIndex !== originalIndex ) {
399 this.reorder( this.getDragItem(), targetIndex );
400 this.emit( 'reorder', this.getDragItem(), targetIndex );
401 }
402 this.updateIndexes();
403 }
404 this.unsetDragItem();
405 // Return false to prevent propogation
406 return false;
407 };
408
409 /**
410 * Respond to dragover event
411 *
412 * @private
413 * @param {jQuery.Event} e Dragover event
414 * @fires reorder
415 */
416 OO.ui.mixin.DraggableGroupElement.prototype.onDragOver = function ( e ) {
417 var overIndex, targetIndex,
418 item = this.getDragItem(),
419 dragItemIndex = item.getIndex();
420
421 // Get the OptionWidget item we are dragging over
422 overIndex = $( e.target ).closest( '.oo-ui-draggableElement' ).data( 'index' );
423
424 if ( overIndex !== undefined && overIndex !== dragItemIndex ) {
425 targetIndex = overIndex + ( overIndex > dragItemIndex ? 1 : 0 );
426
427 if ( targetIndex > 0 ) {
428 this.$group.children().eq( targetIndex - 1 ).after( item.$element );
429 } else {
430 this.$group.prepend( item.$element );
431 }
432 // Move item in itemsOrder array
433 this.itemsOrder.splice( overIndex, 0,
434 this.itemsOrder.splice( dragItemIndex, 1 )[ 0 ]
435 );
436 this.updateIndexes();
437 this.emit( 'drag', item, targetIndex );
438 }
439 // Prevent default
440 e.preventDefault();
441 };
442
443 /**
444 * Reorder the items in the group
445 *
446 * @param {OO.ui.mixin.DraggableElement} item Reordered item
447 * @param {number} newIndex New index
448 */
449 OO.ui.mixin.DraggableGroupElement.prototype.reorder = function ( item, newIndex ) {
450 this.addItems( [ item ], newIndex );
451 };
452
453 /**
454 * Set a dragged item
455 *
456 * @param {OO.ui.mixin.DraggableElement} item Dragged item
457 */
458 OO.ui.mixin.DraggableGroupElement.prototype.setDragItem = function ( item ) {
459 if ( this.dragItem !== item ) {
460 this.dragItem = item;
461 this.$element.on( 'dragover', this.onDragOver.bind( this ) );
462 this.$element.addClass( 'oo-ui-draggableGroupElement-dragging' );
463 }
464 };
465
466 /**
467 * Unset the current dragged item
468 */
469 OO.ui.mixin.DraggableGroupElement.prototype.unsetDragItem = function () {
470 if ( this.dragItem ) {
471 this.dragItem = null;
472 this.$element.off( 'dragover' );
473 this.$element.removeClass( 'oo-ui-draggableGroupElement-dragging' );
474 }
475 };
476
477 /**
478 * Get the item that is currently being dragged.
479 *
480 * @return {OO.ui.mixin.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged
481 */
482 OO.ui.mixin.DraggableGroupElement.prototype.getDragItem = function () {
483 return this.dragItem;
484 };
485
486 /**
487 * RequestManager is a mixin that manages the lifecycle of a promise-backed request for a widget, such as
488 * the {@link OO.ui.mixin.LookupElement}.
489 *
490 * @class
491 * @abstract
492 *
493 * @constructor
494 */
495 OO.ui.mixin.RequestManager = function OoUiMixinRequestManager() {
496 this.requestCache = {};
497 this.requestQuery = null;
498 this.requestRequest = null;
499 };
500
501 /* Setup */
502
503 OO.initClass( OO.ui.mixin.RequestManager );
504
505 /**
506 * Get request results for the current query.
507 *
508 * @return {jQuery.Promise} Promise object which will be passed response data as the first argument of
509 * the done event. If the request was aborted to make way for a subsequent request, this promise
510 * may not be rejected, depending on what jQuery feels like doing.
511 */
512 OO.ui.mixin.RequestManager.prototype.getRequestData = function () {
513 var widget = this,
514 value = this.getRequestQuery(),
515 deferred = $.Deferred(),
516 ourRequest;
517
518 this.abortRequest();
519 if ( Object.prototype.hasOwnProperty.call( this.requestCache, value ) ) {
520 deferred.resolve( this.requestCache[ value ] );
521 } else {
522 if ( this.pushPending ) {
523 this.pushPending();
524 }
525 this.requestQuery = value;
526 ourRequest = this.requestRequest = this.getRequest();
527 ourRequest
528 .always( function () {
529 // We need to pop pending even if this is an old request, otherwise
530 // the widget will remain pending forever.
531 // TODO: this assumes that an aborted request will fail or succeed soon after
532 // being aborted, or at least eventually. It would be nice if we could popPending()
533 // at abort time, but only if we knew that we hadn't already called popPending()
534 // for that request.
535 if ( widget.popPending ) {
536 widget.popPending();
537 }
538 } )
539 .done( function ( response ) {
540 // If this is an old request (and aborting it somehow caused it to still succeed),
541 // ignore its success completely
542 if ( ourRequest === widget.requestRequest ) {
543 widget.requestQuery = null;
544 widget.requestRequest = null;
545 widget.requestCache[ value ] = widget.getRequestCacheDataFromResponse( response );
546 deferred.resolve( widget.requestCache[ value ] );
547 }
548 } )
549 .fail( function () {
550 // If this is an old request (or a request failing because it's being aborted),
551 // ignore its failure completely
552 if ( ourRequest === widget.requestRequest ) {
553 widget.requestQuery = null;
554 widget.requestRequest = null;
555 deferred.reject();
556 }
557 } );
558 }
559 return deferred.promise();
560 };
561
562 /**
563 * Abort the currently pending request, if any.
564 *
565 * @private
566 */
567 OO.ui.mixin.RequestManager.prototype.abortRequest = function () {
568 var oldRequest = this.requestRequest;
569 if ( oldRequest ) {
570 // First unset this.requestRequest to the fail handler will notice
571 // that the request is no longer current
572 this.requestRequest = null;
573 this.requestQuery = null;
574 oldRequest.abort();
575 }
576 };
577
578 /**
579 * Get the query to be made.
580 *
581 * @protected
582 * @method
583 * @abstract
584 * @return {string} query to be used
585 */
586 OO.ui.mixin.RequestManager.prototype.getRequestQuery = null;
587
588 /**
589 * Get a new request object of the current query value.
590 *
591 * @protected
592 * @method
593 * @abstract
594 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
595 */
596 OO.ui.mixin.RequestManager.prototype.getRequest = null;
597
598 /**
599 * Pre-process data returned by the request from #getRequest.
600 *
601 * The return value of this function will be cached, and any further queries for the given value
602 * will use the cache rather than doing API requests.
603 *
604 * @protected
605 * @method
606 * @abstract
607 * @param {Mixed} response Response from server
608 * @return {Mixed} Cached result data
609 */
610 OO.ui.mixin.RequestManager.prototype.getRequestCacheDataFromResponse = null;
611
612 /**
613 * LookupElement is a mixin that creates a {@link OO.ui.MenuSelectWidget menu} of suggested values for
614 * a {@link OO.ui.TextInputWidget text input widget}. Suggested values are based on the characters the user types
615 * into the text input field and, in general, the menu is only displayed when the user types. If a suggested value is chosen
616 * from the lookup menu, that value becomes the value of the input field.
617 *
618 * Note that a new menu of suggested items is displayed when a value is chosen from the lookup menu. If this is
619 * not the desired behavior, disable lookup menus with the #setLookupsDisabled method, then set the value, then
620 * re-enable lookups.
621 *
622 * See the [OOjs UI demos][1] for an example.
623 *
624 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/index.html#widgets-apex-vector-ltr
625 *
626 * @class
627 * @abstract
628 * @mixins OO.ui.mixin.RequestManager
629 *
630 * @constructor
631 * @param {Object} [config] Configuration options
632 * @cfg {jQuery} [$overlay] Overlay for the lookup menu; defaults to relative positioning.
633 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
634 * @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element.
635 * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty.
636 * By default, the lookup menu is not generated and displayed until the user begins to type.
637 * @cfg {boolean} [highlightFirst=true] Whether the first lookup result should be highlighted (so, that the user can
638 * take it over into the input with simply pressing return) automatically or not.
639 */
640 OO.ui.mixin.LookupElement = function OoUiMixinLookupElement( config ) {
641 // Configuration initialization
642 config = $.extend( { highlightFirst: true }, config );
643
644 // Mixin constructors
645 OO.ui.mixin.RequestManager.call( this, config );
646
647 // Properties
648 this.$overlay = config.$overlay || this.$element;
649 this.lookupMenu = new OO.ui.MenuSelectWidget( {
650 widget: this,
651 input: this,
652 $floatableContainer: config.$container || this.$element
653 } );
654
655 this.allowSuggestionsWhenEmpty = config.allowSuggestionsWhenEmpty || false;
656
657 this.lookupsDisabled = false;
658 this.lookupInputFocused = false;
659 this.lookupHighlightFirstItem = config.highlightFirst;
660
661 // Events
662 this.$input.on( {
663 focus: this.onLookupInputFocus.bind( this ),
664 blur: this.onLookupInputBlur.bind( this ),
665 mousedown: this.onLookupInputMouseDown.bind( this )
666 } );
667 this.connect( this, { change: 'onLookupInputChange' } );
668 this.lookupMenu.connect( this, {
669 toggle: 'onLookupMenuToggle',
670 choose: 'onLookupMenuItemChoose'
671 } );
672
673 // Initialization
674 this.$input.attr( {
675 role: 'combobox',
676 'aria-owns': this.lookupMenu.getElementId(),
677 'aria-autocomplete': 'list'
678 } );
679 this.$element.addClass( 'oo-ui-lookupElement' );
680 this.lookupMenu.$element.addClass( 'oo-ui-lookupElement-menu' );
681 this.$overlay.append( this.lookupMenu.$element );
682 };
683
684 /* Setup */
685
686 OO.mixinClass( OO.ui.mixin.LookupElement, OO.ui.mixin.RequestManager );
687
688 /* Methods */
689
690 /**
691 * Handle input focus event.
692 *
693 * @protected
694 * @param {jQuery.Event} e Input focus event
695 */
696 OO.ui.mixin.LookupElement.prototype.onLookupInputFocus = function () {
697 this.lookupInputFocused = true;
698 this.populateLookupMenu();
699 };
700
701 /**
702 * Handle input blur event.
703 *
704 * @protected
705 * @param {jQuery.Event} e Input blur event
706 */
707 OO.ui.mixin.LookupElement.prototype.onLookupInputBlur = function () {
708 this.closeLookupMenu();
709 this.lookupInputFocused = false;
710 };
711
712 /**
713 * Handle input mouse down event.
714 *
715 * @protected
716 * @param {jQuery.Event} e Input mouse down event
717 */
718 OO.ui.mixin.LookupElement.prototype.onLookupInputMouseDown = function () {
719 // Only open the menu if the input was already focused.
720 // This way we allow the user to open the menu again after closing it with Esc
721 // by clicking in the input. Opening (and populating) the menu when initially
722 // clicking into the input is handled by the focus handler.
723 if ( this.lookupInputFocused && !this.lookupMenu.isVisible() ) {
724 this.populateLookupMenu();
725 }
726 };
727
728 /**
729 * Handle input change event.
730 *
731 * @protected
732 * @param {string} value New input value
733 */
734 OO.ui.mixin.LookupElement.prototype.onLookupInputChange = function () {
735 if ( this.lookupInputFocused ) {
736 this.populateLookupMenu();
737 }
738 };
739
740 /**
741 * Handle the lookup menu being shown/hidden.
742 *
743 * @protected
744 * @param {boolean} visible Whether the lookup menu is now visible.
745 */
746 OO.ui.mixin.LookupElement.prototype.onLookupMenuToggle = function ( visible ) {
747 if ( !visible ) {
748 // When the menu is hidden, abort any active request and clear the menu.
749 // This has to be done here in addition to closeLookupMenu(), because
750 // MenuSelectWidget will close itself when the user presses Esc.
751 this.abortLookupRequest();
752 this.lookupMenu.clearItems();
753 }
754 };
755
756 /**
757 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
758 *
759 * @protected
760 * @param {OO.ui.MenuOptionWidget} item Selected item
761 */
762 OO.ui.mixin.LookupElement.prototype.onLookupMenuItemChoose = function ( item ) {
763 this.setValue( item.getData() );
764 };
765
766 /**
767 * Get lookup menu.
768 *
769 * @private
770 * @return {OO.ui.MenuSelectWidget}
771 */
772 OO.ui.mixin.LookupElement.prototype.getLookupMenu = function () {
773 return this.lookupMenu;
774 };
775
776 /**
777 * Disable or re-enable lookups.
778 *
779 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
780 *
781 * @param {boolean} disabled Disable lookups
782 */
783 OO.ui.mixin.LookupElement.prototype.setLookupsDisabled = function ( disabled ) {
784 this.lookupsDisabled = !!disabled;
785 };
786
787 /**
788 * Open the menu. If there are no entries in the menu, this does nothing.
789 *
790 * @private
791 * @chainable
792 */
793 OO.ui.mixin.LookupElement.prototype.openLookupMenu = function () {
794 if ( !this.lookupMenu.isEmpty() ) {
795 this.lookupMenu.toggle( true );
796 }
797 return this;
798 };
799
800 /**
801 * Close the menu, empty it, and abort any pending request.
802 *
803 * @private
804 * @chainable
805 */
806 OO.ui.mixin.LookupElement.prototype.closeLookupMenu = function () {
807 this.lookupMenu.toggle( false );
808 this.abortLookupRequest();
809 this.lookupMenu.clearItems();
810 return this;
811 };
812
813 /**
814 * Request menu items based on the input's current value, and when they arrive,
815 * populate the menu with these items and show the menu.
816 *
817 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
818 *
819 * @private
820 * @chainable
821 */
822 OO.ui.mixin.LookupElement.prototype.populateLookupMenu = function () {
823 var widget = this,
824 value = this.getValue();
825
826 if ( this.lookupsDisabled || this.isReadOnly() ) {
827 return;
828 }
829
830 // If the input is empty, clear the menu, unless suggestions when empty are allowed.
831 if ( !this.allowSuggestionsWhenEmpty && value === '' ) {
832 this.closeLookupMenu();
833 // Skip population if there is already a request pending for the current value
834 } else if ( value !== this.lookupQuery ) {
835 this.getLookupMenuItems()
836 .done( function ( items ) {
837 widget.lookupMenu.clearItems();
838 if ( items.length ) {
839 widget.lookupMenu
840 .addItems( items )
841 .toggle( true );
842 widget.initializeLookupMenuSelection();
843 } else {
844 widget.lookupMenu.toggle( false );
845 }
846 } )
847 .fail( function () {
848 widget.lookupMenu.clearItems();
849 } );
850 }
851
852 return this;
853 };
854
855 /**
856 * Highlight the first selectable item in the menu, if configured.
857 *
858 * @private
859 * @chainable
860 */
861 OO.ui.mixin.LookupElement.prototype.initializeLookupMenuSelection = function () {
862 if ( this.lookupHighlightFirstItem && !this.lookupMenu.getSelectedItem() ) {
863 this.lookupMenu.highlightItem( this.lookupMenu.findFirstSelectableItem() );
864 }
865 };
866
867 /**
868 * Get lookup menu items for the current query.
869 *
870 * @private
871 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
872 * the done event. If the request was aborted to make way for a subsequent request, this promise
873 * will not be rejected: it will remain pending forever.
874 */
875 OO.ui.mixin.LookupElement.prototype.getLookupMenuItems = function () {
876 return this.getRequestData().then( function ( data ) {
877 return this.getLookupMenuOptionsFromData( data );
878 }.bind( this ) );
879 };
880
881 /**
882 * Abort the currently pending lookup request, if any.
883 *
884 * @private
885 */
886 OO.ui.mixin.LookupElement.prototype.abortLookupRequest = function () {
887 this.abortRequest();
888 };
889
890 /**
891 * Get a new request object of the current lookup query value.
892 *
893 * @protected
894 * @method
895 * @abstract
896 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
897 */
898 OO.ui.mixin.LookupElement.prototype.getLookupRequest = null;
899
900 /**
901 * Pre-process data returned by the request from #getLookupRequest.
902 *
903 * The return value of this function will be cached, and any further queries for the given value
904 * will use the cache rather than doing API requests.
905 *
906 * @protected
907 * @method
908 * @abstract
909 * @param {Mixed} response Response from server
910 * @return {Mixed} Cached result data
911 */
912 OO.ui.mixin.LookupElement.prototype.getLookupCacheDataFromResponse = null;
913
914 /**
915 * Get a list of menu option widgets from the (possibly cached) data returned by
916 * #getLookupCacheDataFromResponse.
917 *
918 * @protected
919 * @method
920 * @abstract
921 * @param {Mixed} data Cached result data, usually an array
922 * @return {OO.ui.MenuOptionWidget[]} Menu items
923 */
924 OO.ui.mixin.LookupElement.prototype.getLookupMenuOptionsFromData = null;
925
926 /**
927 * Set the read-only state of the widget.
928 *
929 * This will also disable/enable the lookups functionality.
930 *
931 * @param {boolean} readOnly Make input read-only
932 * @chainable
933 */
934 OO.ui.mixin.LookupElement.prototype.setReadOnly = function ( readOnly ) {
935 // Parent method
936 // Note: Calling #setReadOnly this way assumes this is mixed into an OO.ui.TextInputWidget
937 OO.ui.TextInputWidget.prototype.setReadOnly.call( this, readOnly );
938
939 // During construction, #setReadOnly is called before the OO.ui.mixin.LookupElement constructor
940 if ( this.isReadOnly() && this.lookupMenu ) {
941 this.closeLookupMenu();
942 }
943
944 return this;
945 };
946
947 /**
948 * @inheritdoc OO.ui.mixin.RequestManager
949 */
950 OO.ui.mixin.LookupElement.prototype.getRequestQuery = function () {
951 return this.getValue();
952 };
953
954 /**
955 * @inheritdoc OO.ui.mixin.RequestManager
956 */
957 OO.ui.mixin.LookupElement.prototype.getRequest = function () {
958 return this.getLookupRequest();
959 };
960
961 /**
962 * @inheritdoc OO.ui.mixin.RequestManager
963 */
964 OO.ui.mixin.LookupElement.prototype.getRequestCacheDataFromResponse = function ( response ) {
965 return this.getLookupCacheDataFromResponse( response );
966 };
967
968 /**
969 * TabPanelLayouts are used within {@link OO.ui.IndexLayout index layouts} to create tab panels that
970 * users can select and display from the index's optional {@link OO.ui.TabSelectWidget tab}
971 * navigation. TabPanels are usually not instantiated directly, rather extended to include the
972 * required content and functionality.
973 *
974 * Each tab panel must have a unique symbolic name, which is passed to the constructor. In addition,
975 * the tab panel's tab item is customized (with a label) using the #setupTabItem method. See
976 * {@link OO.ui.IndexLayout IndexLayout} for an example.
977 *
978 * @class
979 * @extends OO.ui.PanelLayout
980 *
981 * @constructor
982 * @param {string} name Unique symbolic name of tab panel
983 * @param {Object} [config] Configuration options
984 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] Label for tab panel's tab
985 */
986 OO.ui.TabPanelLayout = function OoUiTabPanelLayout( name, config ) {
987 // Allow passing positional parameters inside the config object
988 if ( OO.isPlainObject( name ) && config === undefined ) {
989 config = name;
990 name = config.name;
991 }
992
993 // Configuration initialization
994 config = $.extend( { scrollable: true }, config );
995
996 // Parent constructor
997 OO.ui.TabPanelLayout.parent.call( this, config );
998
999 // Properties
1000 this.name = name;
1001 this.label = config.label;
1002 this.tabItem = null;
1003 this.active = false;
1004
1005 // Initialization
1006 this.$element.addClass( 'oo-ui-tabPanelLayout' );
1007 };
1008
1009 /* Setup */
1010
1011 OO.inheritClass( OO.ui.TabPanelLayout, OO.ui.PanelLayout );
1012
1013 /* Events */
1014
1015 /**
1016 * An 'active' event is emitted when the tab panel becomes active. Tab panels become active when they are
1017 * shown in a index layout that is configured to display only one tab panel at a time.
1018 *
1019 * @event active
1020 * @param {boolean} active Tab panel is active
1021 */
1022
1023 /* Methods */
1024
1025 /**
1026 * Get the symbolic name of the tab panel.
1027 *
1028 * @return {string} Symbolic name of tab panel
1029 */
1030 OO.ui.TabPanelLayout.prototype.getName = function () {
1031 return this.name;
1032 };
1033
1034 /**
1035 * Check if tab panel is active.
1036 *
1037 * Tab panels become active when they are shown in a {@link OO.ui.IndexLayout index layout} that is configured to
1038 * display only one tab panel at a time. Additional CSS is applied to the tab panel's tab item to reflect the
1039 * active state.
1040 *
1041 * @return {boolean} Tab panel is active
1042 */
1043 OO.ui.TabPanelLayout.prototype.isActive = function () {
1044 return this.active;
1045 };
1046
1047 /**
1048 * Get tab item.
1049 *
1050 * The tab item allows users to access the tab panel from the index's tab
1051 * navigation. The tab item itself can be customized (with a label, level, etc.) using the #setupTabItem method.
1052 *
1053 * @return {OO.ui.TabOptionWidget|null} Tab option widget
1054 */
1055 OO.ui.TabPanelLayout.prototype.getTabItem = function () {
1056 return this.tabItem;
1057 };
1058
1059 /**
1060 * Set or unset the tab item.
1061 *
1062 * Specify a {@link OO.ui.TabOptionWidget tab option} to set it,
1063 * or `null` to clear the tab item. To customize the tab item itself (e.g., to set a label or tab
1064 * level), use #setupTabItem instead of this method.
1065 *
1066 * @param {OO.ui.TabOptionWidget|null} tabItem Tab option widget, null to clear
1067 * @chainable
1068 */
1069 OO.ui.TabPanelLayout.prototype.setTabItem = function ( tabItem ) {
1070 this.tabItem = tabItem || null;
1071 if ( tabItem ) {
1072 this.setupTabItem();
1073 }
1074 return this;
1075 };
1076
1077 /**
1078 * Set up the tab item.
1079 *
1080 * Use this method to customize the tab item (e.g., to add a label or tab level). To set or unset
1081 * the tab item itself (with a {@link OO.ui.TabOptionWidget tab option} or `null`), use
1082 * the #setTabItem method instead.
1083 *
1084 * @param {OO.ui.TabOptionWidget} tabItem Tab option widget to set up
1085 * @chainable
1086 */
1087 OO.ui.TabPanelLayout.prototype.setupTabItem = function () {
1088 if ( this.label ) {
1089 this.tabItem.setLabel( this.label );
1090 }
1091 return this;
1092 };
1093
1094 /**
1095 * Set the tab panel to its 'active' state.
1096 *
1097 * Tab panels become active when they are shown in a index layout that is configured to display only
1098 * one tab panel at a time. Additional CSS is applied to the tab item to reflect the tab panel's
1099 * active state. Outside of the index context, setting the active state on a tab panel does nothing.
1100 *
1101 * @param {boolean} active Tab panel is active
1102 * @fires active
1103 */
1104 OO.ui.TabPanelLayout.prototype.setActive = function ( active ) {
1105 active = !!active;
1106
1107 if ( active !== this.active ) {
1108 this.active = active;
1109 this.$element.toggleClass( 'oo-ui-tabPanelLayout-active', this.active );
1110 this.emit( 'active', this.active );
1111 }
1112 };
1113
1114 /**
1115 * PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display
1116 * from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly,
1117 * rather extended to include the required content and functionality.
1118 *
1119 * Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline
1120 * item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See
1121 * {@link OO.ui.BookletLayout BookletLayout} for an example.
1122 *
1123 * @class
1124 * @extends OO.ui.PanelLayout
1125 *
1126 * @constructor
1127 * @param {string} name Unique symbolic name of page
1128 * @param {Object} [config] Configuration options
1129 */
1130 OO.ui.PageLayout = function OoUiPageLayout( name, config ) {
1131 // Allow passing positional parameters inside the config object
1132 if ( OO.isPlainObject( name ) && config === undefined ) {
1133 config = name;
1134 name = config.name;
1135 }
1136
1137 // Configuration initialization
1138 config = $.extend( { scrollable: true }, config );
1139
1140 // Parent constructor
1141 OO.ui.PageLayout.parent.call( this, config );
1142
1143 // Properties
1144 this.name = name;
1145 this.outlineItem = null;
1146 this.active = false;
1147
1148 // Initialization
1149 this.$element.addClass( 'oo-ui-pageLayout' );
1150 };
1151
1152 /* Setup */
1153
1154 OO.inheritClass( OO.ui.PageLayout, OO.ui.PanelLayout );
1155
1156 /* Events */
1157
1158 /**
1159 * An 'active' event is emitted when the page becomes active. Pages become active when they are
1160 * shown in a booklet layout that is configured to display only one page at a time.
1161 *
1162 * @event active
1163 * @param {boolean} active Page is active
1164 */
1165
1166 /* Methods */
1167
1168 /**
1169 * Get the symbolic name of the page.
1170 *
1171 * @return {string} Symbolic name of page
1172 */
1173 OO.ui.PageLayout.prototype.getName = function () {
1174 return this.name;
1175 };
1176
1177 /**
1178 * Check if page is active.
1179 *
1180 * Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display
1181 * only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state.
1182 *
1183 * @return {boolean} Page is active
1184 */
1185 OO.ui.PageLayout.prototype.isActive = function () {
1186 return this.active;
1187 };
1188
1189 /**
1190 * Get outline item.
1191 *
1192 * The outline item allows users to access the page from the booklet's outline
1193 * navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method.
1194 *
1195 * @return {OO.ui.OutlineOptionWidget|null} Outline option widget
1196 */
1197 OO.ui.PageLayout.prototype.getOutlineItem = function () {
1198 return this.outlineItem;
1199 };
1200
1201 /**
1202 * Set or unset the outline item.
1203 *
1204 * Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it,
1205 * or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline
1206 * level), use #setupOutlineItem instead of this method.
1207 *
1208 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear
1209 * @chainable
1210 */
1211 OO.ui.PageLayout.prototype.setOutlineItem = function ( outlineItem ) {
1212 this.outlineItem = outlineItem || null;
1213 if ( outlineItem ) {
1214 this.setupOutlineItem();
1215 }
1216 return this;
1217 };
1218
1219 /**
1220 * Set up the outline item.
1221 *
1222 * Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset
1223 * the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use
1224 * the #setOutlineItem method instead.
1225 *
1226 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up
1227 * @chainable
1228 */
1229 OO.ui.PageLayout.prototype.setupOutlineItem = function () {
1230 return this;
1231 };
1232
1233 /**
1234 * Set the page to its 'active' state.
1235 *
1236 * Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional
1237 * CSS is applied to the outline item to reflect the page's active state. Outside of the booklet
1238 * context, setting the active state on a page does nothing.
1239 *
1240 * @param {boolean} active Page is active
1241 * @fires active
1242 */
1243 OO.ui.PageLayout.prototype.setActive = function ( active ) {
1244 active = !!active;
1245
1246 if ( active !== this.active ) {
1247 this.active = active;
1248 this.$element.toggleClass( 'oo-ui-pageLayout-active', active );
1249 this.emit( 'active', this.active );
1250 }
1251 };
1252
1253 /**
1254 * StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed
1255 * at a time, though the stack layout can also be configured to show all contained panels, one after another,
1256 * by setting the #continuous option to 'true'.
1257 *
1258 * @example
1259 * // A stack layout with two panels, configured to be displayed continously
1260 * var myStack = new OO.ui.StackLayout( {
1261 * items: [
1262 * new OO.ui.PanelLayout( {
1263 * $content: $( '<p>Panel One</p>' ),
1264 * padded: true,
1265 * framed: true
1266 * } ),
1267 * new OO.ui.PanelLayout( {
1268 * $content: $( '<p>Panel Two</p>' ),
1269 * padded: true,
1270 * framed: true
1271 * } )
1272 * ],
1273 * continuous: true
1274 * } );
1275 * $( 'body' ).append( myStack.$element );
1276 *
1277 * @class
1278 * @extends OO.ui.PanelLayout
1279 * @mixins OO.ui.mixin.GroupElement
1280 *
1281 * @constructor
1282 * @param {Object} [config] Configuration options
1283 * @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time.
1284 * @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout.
1285 */
1286 OO.ui.StackLayout = function OoUiStackLayout( config ) {
1287 // Configuration initialization
1288 config = $.extend( { scrollable: true }, config );
1289
1290 // Parent constructor
1291 OO.ui.StackLayout.parent.call( this, config );
1292
1293 // Mixin constructors
1294 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
1295
1296 // Properties
1297 this.currentItem = null;
1298 this.continuous = !!config.continuous;
1299
1300 // Initialization
1301 this.$element.addClass( 'oo-ui-stackLayout' );
1302 if ( this.continuous ) {
1303 this.$element.addClass( 'oo-ui-stackLayout-continuous' );
1304 this.$element.on( 'scroll', OO.ui.debounce( this.onScroll.bind( this ), 250 ) );
1305 }
1306 if ( Array.isArray( config.items ) ) {
1307 this.addItems( config.items );
1308 }
1309 };
1310
1311 /* Setup */
1312
1313 OO.inheritClass( OO.ui.StackLayout, OO.ui.PanelLayout );
1314 OO.mixinClass( OO.ui.StackLayout, OO.ui.mixin.GroupElement );
1315
1316 /* Events */
1317
1318 /**
1319 * A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed},
1320 * {@link #clearItems cleared} or {@link #setItem displayed}.
1321 *
1322 * @event set
1323 * @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown
1324 */
1325
1326 /**
1327 * When used in continuous mode, this event is emitted when the user scrolls down
1328 * far enough such that currentItem is no longer visible.
1329 *
1330 * @event visibleItemChange
1331 * @param {OO.ui.PanelLayout} panel The next visible item in the layout
1332 */
1333
1334 /* Methods */
1335
1336 /**
1337 * Handle scroll events from the layout element
1338 *
1339 * @param {jQuery.Event} e
1340 * @fires visibleItemChange
1341 */
1342 OO.ui.StackLayout.prototype.onScroll = function () {
1343 var currentRect,
1344 len = this.items.length,
1345 currentIndex = this.items.indexOf( this.currentItem ),
1346 newIndex = currentIndex,
1347 containerRect = this.$element[ 0 ].getBoundingClientRect();
1348
1349 if ( !containerRect || ( !containerRect.top && !containerRect.bottom ) ) {
1350 // Can't get bounding rect, possibly not attached.
1351 return;
1352 }
1353
1354 function getRect( item ) {
1355 return item.$element[ 0 ].getBoundingClientRect();
1356 }
1357
1358 function isVisible( item ) {
1359 var rect = getRect( item );
1360 return rect.bottom > containerRect.top && rect.top < containerRect.bottom;
1361 }
1362
1363 currentRect = getRect( this.currentItem );
1364
1365 if ( currentRect.bottom < containerRect.top ) {
1366 // Scrolled down past current item
1367 while ( ++newIndex < len ) {
1368 if ( isVisible( this.items[ newIndex ] ) ) {
1369 break;
1370 }
1371 }
1372 } else if ( currentRect.top > containerRect.bottom ) {
1373 // Scrolled up past current item
1374 while ( --newIndex >= 0 ) {
1375 if ( isVisible( this.items[ newIndex ] ) ) {
1376 break;
1377 }
1378 }
1379 }
1380
1381 if ( newIndex !== currentIndex ) {
1382 this.emit( 'visibleItemChange', this.items[ newIndex ] );
1383 }
1384 };
1385
1386 /**
1387 * Get the current panel.
1388 *
1389 * @return {OO.ui.Layout|null}
1390 */
1391 OO.ui.StackLayout.prototype.getCurrentItem = function () {
1392 return this.currentItem;
1393 };
1394
1395 /**
1396 * Unset the current item.
1397 *
1398 * @private
1399 * @param {OO.ui.StackLayout} layout
1400 * @fires set
1401 */
1402 OO.ui.StackLayout.prototype.unsetCurrentItem = function () {
1403 var prevItem = this.currentItem;
1404 if ( prevItem === null ) {
1405 return;
1406 }
1407
1408 this.currentItem = null;
1409 this.emit( 'set', null );
1410 };
1411
1412 /**
1413 * Add panel layouts to the stack layout.
1414 *
1415 * Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different
1416 * insertion point. Adding a panel that is already in the stack will move it to the end of the array or the point specified
1417 * by the index.
1418 *
1419 * @param {OO.ui.Layout[]} items Panels to add
1420 * @param {number} [index] Index of the insertion point
1421 * @chainable
1422 */
1423 OO.ui.StackLayout.prototype.addItems = function ( items, index ) {
1424 // Update the visibility
1425 this.updateHiddenState( items, this.currentItem );
1426
1427 // Mixin method
1428 OO.ui.mixin.GroupElement.prototype.addItems.call( this, items, index );
1429
1430 if ( !this.currentItem && items.length ) {
1431 this.setItem( items[ 0 ] );
1432 }
1433
1434 return this;
1435 };
1436
1437 /**
1438 * Remove the specified panels from the stack layout.
1439 *
1440 * Removed panels are detached from the DOM, not removed, so that they may be reused. To remove all panels,
1441 * you may wish to use the #clearItems method instead.
1442 *
1443 * @param {OO.ui.Layout[]} items Panels to remove
1444 * @chainable
1445 * @fires set
1446 */
1447 OO.ui.StackLayout.prototype.removeItems = function ( items ) {
1448 // Mixin method
1449 OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items );
1450
1451 if ( items.indexOf( this.currentItem ) !== -1 ) {
1452 if ( this.items.length ) {
1453 this.setItem( this.items[ 0 ] );
1454 } else {
1455 this.unsetCurrentItem();
1456 }
1457 }
1458
1459 return this;
1460 };
1461
1462 /**
1463 * Clear all panels from the stack layout.
1464 *
1465 * Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only
1466 * a subset of panels, use the #removeItems method.
1467 *
1468 * @chainable
1469 * @fires set
1470 */
1471 OO.ui.StackLayout.prototype.clearItems = function () {
1472 this.unsetCurrentItem();
1473 OO.ui.mixin.GroupElement.prototype.clearItems.call( this );
1474
1475 return this;
1476 };
1477
1478 /**
1479 * Show the specified panel.
1480 *
1481 * If another panel is currently displayed, it will be hidden.
1482 *
1483 * @param {OO.ui.Layout} item Panel to show
1484 * @chainable
1485 * @fires set
1486 */
1487 OO.ui.StackLayout.prototype.setItem = function ( item ) {
1488 if ( item !== this.currentItem ) {
1489 this.updateHiddenState( this.items, item );
1490
1491 if ( this.items.indexOf( item ) !== -1 ) {
1492 this.currentItem = item;
1493 this.emit( 'set', item );
1494 } else {
1495 this.unsetCurrentItem();
1496 }
1497 }
1498
1499 return this;
1500 };
1501
1502 /**
1503 * Update the visibility of all items in case of non-continuous view.
1504 *
1505 * Ensure all items are hidden except for the selected one.
1506 * This method does nothing when the stack is continuous.
1507 *
1508 * @private
1509 * @param {OO.ui.Layout[]} items Item list iterate over
1510 * @param {OO.ui.Layout} [selectedItem] Selected item to show
1511 */
1512 OO.ui.StackLayout.prototype.updateHiddenState = function ( items, selectedItem ) {
1513 var i, len;
1514
1515 if ( !this.continuous ) {
1516 for ( i = 0, len = items.length; i < len; i++ ) {
1517 if ( !selectedItem || selectedItem !== items[ i ] ) {
1518 items[ i ].$element.addClass( 'oo-ui-element-hidden' );
1519 items[ i ].$element.attr( 'aria-hidden', 'true' );
1520 }
1521 }
1522 if ( selectedItem ) {
1523 selectedItem.$element.removeClass( 'oo-ui-element-hidden' );
1524 selectedItem.$element.removeAttr( 'aria-hidden' );
1525 }
1526 }
1527 };
1528
1529 /**
1530 * MenuLayouts combine a menu and a content {@link OO.ui.PanelLayout panel}. The menu is positioned relative to the content (after, before, top, or bottom)
1531 * and its size is customized with the #menuSize config. The content area will fill all remaining space.
1532 *
1533 * @example
1534 * var menuLayout = new OO.ui.MenuLayout( {
1535 * position: 'top'
1536 * } ),
1537 * menuPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
1538 * contentPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
1539 * select = new OO.ui.SelectWidget( {
1540 * items: [
1541 * new OO.ui.OptionWidget( {
1542 * data: 'before',
1543 * label: 'Before',
1544 * } ),
1545 * new OO.ui.OptionWidget( {
1546 * data: 'after',
1547 * label: 'After',
1548 * } ),
1549 * new OO.ui.OptionWidget( {
1550 * data: 'top',
1551 * label: 'Top',
1552 * } ),
1553 * new OO.ui.OptionWidget( {
1554 * data: 'bottom',
1555 * label: 'Bottom',
1556 * } )
1557 * ]
1558 * } ).on( 'select', function ( item ) {
1559 * menuLayout.setMenuPosition( item.getData() );
1560 * } );
1561 *
1562 * menuLayout.$menu.append(
1563 * menuPanel.$element.append( '<b>Menu panel</b>', select.$element )
1564 * );
1565 * menuLayout.$content.append(
1566 * contentPanel.$element.append( '<b>Content panel</b>', '<p>Note that the menu is positioned relative to the content panel: top, bottom, after, before.</p>')
1567 * );
1568 * $( 'body' ).append( menuLayout.$element );
1569 *
1570 * If menu size needs to be overridden, it can be accomplished using CSS similar to the snippet
1571 * below. MenuLayout's CSS will override the appropriate values with 'auto' or '0' to display the
1572 * menu correctly. If `menuPosition` is known beforehand, CSS rules corresponding to other positions
1573 * may be omitted.
1574 *
1575 * .oo-ui-menuLayout-menu {
1576 * height: 200px;
1577 * width: 200px;
1578 * }
1579 * .oo-ui-menuLayout-content {
1580 * top: 200px;
1581 * left: 200px;
1582 * right: 200px;
1583 * bottom: 200px;
1584 * }
1585 *
1586 * @class
1587 * @extends OO.ui.Layout
1588 *
1589 * @constructor
1590 * @param {Object} [config] Configuration options
1591 * @cfg {boolean} [expanded=true] Expand the layout to fill the entire parent element.
1592 * @cfg {boolean} [showMenu=true] Show menu
1593 * @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before`
1594 */
1595 OO.ui.MenuLayout = function OoUiMenuLayout( config ) {
1596 // Configuration initialization
1597 config = $.extend( {
1598 expanded: true,
1599 showMenu: true,
1600 menuPosition: 'before'
1601 }, config );
1602
1603 // Parent constructor
1604 OO.ui.MenuLayout.parent.call( this, config );
1605
1606 this.expanded = !!config.expanded;
1607 /**
1608 * Menu DOM node
1609 *
1610 * @property {jQuery}
1611 */
1612 this.$menu = $( '<div>' );
1613 /**
1614 * Content DOM node
1615 *
1616 * @property {jQuery}
1617 */
1618 this.$content = $( '<div>' );
1619
1620 // Initialization
1621 this.$menu
1622 .addClass( 'oo-ui-menuLayout-menu' );
1623 this.$content.addClass( 'oo-ui-menuLayout-content' );
1624 this.$element
1625 .addClass( 'oo-ui-menuLayout' );
1626 if ( config.expanded ) {
1627 this.$element.addClass( 'oo-ui-menuLayout-expanded' );
1628 } else {
1629 this.$element.addClass( 'oo-ui-menuLayout-static' );
1630 }
1631 this.setMenuPosition( config.menuPosition );
1632 this.toggleMenu( config.showMenu );
1633 };
1634
1635 /* Setup */
1636
1637 OO.inheritClass( OO.ui.MenuLayout, OO.ui.Layout );
1638
1639 /* Methods */
1640
1641 /**
1642 * Toggle menu.
1643 *
1644 * @param {boolean} showMenu Show menu, omit to toggle
1645 * @chainable
1646 */
1647 OO.ui.MenuLayout.prototype.toggleMenu = function ( showMenu ) {
1648 showMenu = showMenu === undefined ? !this.showMenu : !!showMenu;
1649
1650 if ( this.showMenu !== showMenu ) {
1651 this.showMenu = showMenu;
1652 this.$element
1653 .toggleClass( 'oo-ui-menuLayout-showMenu', this.showMenu )
1654 .toggleClass( 'oo-ui-menuLayout-hideMenu', !this.showMenu );
1655 this.$menu.attr( 'aria-hidden', this.showMenu ? 'false' : 'true' );
1656 }
1657
1658 return this;
1659 };
1660
1661 /**
1662 * Check if menu is visible
1663 *
1664 * @return {boolean} Menu is visible
1665 */
1666 OO.ui.MenuLayout.prototype.isMenuVisible = function () {
1667 return this.showMenu;
1668 };
1669
1670 /**
1671 * Set menu position.
1672 *
1673 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
1674 * @throws {Error} If position value is not supported
1675 * @chainable
1676 */
1677 OO.ui.MenuLayout.prototype.setMenuPosition = function ( position ) {
1678 this.$element.removeClass( 'oo-ui-menuLayout-' + this.menuPosition );
1679 this.menuPosition = position;
1680 if ( this.menuPosition === 'top' || this.menuPosition === 'before' ) {
1681 this.$element.append( this.$menu, this.$content );
1682 } else {
1683 this.$element.append( this.$content, this.$menu );
1684 }
1685 this.$element.addClass( 'oo-ui-menuLayout-' + position );
1686
1687 return this;
1688 };
1689
1690 /**
1691 * Get menu position.
1692 *
1693 * @return {string} Menu position
1694 */
1695 OO.ui.MenuLayout.prototype.getMenuPosition = function () {
1696 return this.menuPosition;
1697 };
1698
1699 /**
1700 * BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as
1701 * an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate
1702 * through the pages and select which one to display. By default, only one page is
1703 * displayed at a time and the outline is hidden. When a user navigates to a new page,
1704 * the booklet layout automatically focuses on the first focusable element, unless the
1705 * default setting is changed. Optionally, booklets can be configured to show
1706 * {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items.
1707 *
1708 * @example
1709 * // Example of a BookletLayout that contains two PageLayouts.
1710 *
1711 * function PageOneLayout( name, config ) {
1712 * PageOneLayout.parent.call( this, name, config );
1713 * this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' );
1714 * }
1715 * OO.inheritClass( PageOneLayout, OO.ui.PageLayout );
1716 * PageOneLayout.prototype.setupOutlineItem = function () {
1717 * this.outlineItem.setLabel( 'Page One' );
1718 * };
1719 *
1720 * function PageTwoLayout( name, config ) {
1721 * PageTwoLayout.parent.call( this, name, config );
1722 * this.$element.append( '<p>Second page</p>' );
1723 * }
1724 * OO.inheritClass( PageTwoLayout, OO.ui.PageLayout );
1725 * PageTwoLayout.prototype.setupOutlineItem = function () {
1726 * this.outlineItem.setLabel( 'Page Two' );
1727 * };
1728 *
1729 * var page1 = new PageOneLayout( 'one' ),
1730 * page2 = new PageTwoLayout( 'two' );
1731 *
1732 * var booklet = new OO.ui.BookletLayout( {
1733 * outlined: true
1734 * } );
1735 *
1736 * booklet.addPages ( [ page1, page2 ] );
1737 * $( 'body' ).append( booklet.$element );
1738 *
1739 * @class
1740 * @extends OO.ui.MenuLayout
1741 *
1742 * @constructor
1743 * @param {Object} [config] Configuration options
1744 * @cfg {boolean} [continuous=false] Show all pages, one after another
1745 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed. Disabled on mobile.
1746 * @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet.
1747 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
1748 */
1749 OO.ui.BookletLayout = function OoUiBookletLayout( config ) {
1750 // Configuration initialization
1751 config = config || {};
1752
1753 // Parent constructor
1754 OO.ui.BookletLayout.parent.call( this, config );
1755
1756 // Properties
1757 this.currentPageName = null;
1758 this.pages = {};
1759 this.ignoreFocus = false;
1760 this.stackLayout = new OO.ui.StackLayout( {
1761 continuous: !!config.continuous,
1762 expanded: this.expanded
1763 } );
1764 this.$content.append( this.stackLayout.$element );
1765 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
1766 this.outlineVisible = false;
1767 this.outlined = !!config.outlined;
1768 if ( this.outlined ) {
1769 this.editable = !!config.editable;
1770 this.outlineControlsWidget = null;
1771 this.outlineSelectWidget = new OO.ui.OutlineSelectWidget();
1772 this.outlinePanel = new OO.ui.PanelLayout( {
1773 expanded: this.expanded,
1774 scrollable: true
1775 } );
1776 this.$menu.append( this.outlinePanel.$element );
1777 this.outlineVisible = true;
1778 if ( this.editable ) {
1779 this.outlineControlsWidget = new OO.ui.OutlineControlsWidget(
1780 this.outlineSelectWidget
1781 );
1782 }
1783 }
1784 this.toggleMenu( this.outlined );
1785
1786 // Events
1787 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
1788 if ( this.outlined ) {
1789 this.outlineSelectWidget.connect( this, { select: 'onOutlineSelectWidgetSelect' } );
1790 this.scrolling = false;
1791 this.stackLayout.connect( this, { visibleItemChange: 'onStackLayoutVisibleItemChange' } );
1792 }
1793 if ( this.autoFocus ) {
1794 // Event 'focus' does not bubble, but 'focusin' does
1795 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
1796 }
1797
1798 // Initialization
1799 this.$element.addClass( 'oo-ui-bookletLayout' );
1800 this.stackLayout.$element.addClass( 'oo-ui-bookletLayout-stackLayout' );
1801 if ( this.outlined ) {
1802 this.outlinePanel.$element
1803 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
1804 .append( this.outlineSelectWidget.$element );
1805 if ( this.editable ) {
1806 this.outlinePanel.$element
1807 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
1808 .append( this.outlineControlsWidget.$element );
1809 }
1810 }
1811 };
1812
1813 /* Setup */
1814
1815 OO.inheritClass( OO.ui.BookletLayout, OO.ui.MenuLayout );
1816
1817 /* Events */
1818
1819 /**
1820 * A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout.
1821 * @event set
1822 * @param {OO.ui.PageLayout} page Current page
1823 */
1824
1825 /**
1826 * An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout.
1827 *
1828 * @event add
1829 * @param {OO.ui.PageLayout[]} page Added pages
1830 * @param {number} index Index pages were added at
1831 */
1832
1833 /**
1834 * A 'remove' event is emitted when pages are {@link #clearPages cleared} or
1835 * {@link #removePages removed} from the booklet.
1836 *
1837 * @event remove
1838 * @param {OO.ui.PageLayout[]} pages Removed pages
1839 */
1840
1841 /* Methods */
1842
1843 /**
1844 * Handle stack layout focus.
1845 *
1846 * @private
1847 * @param {jQuery.Event} e Focusin event
1848 */
1849 OO.ui.BookletLayout.prototype.onStackLayoutFocus = function ( e ) {
1850 var name, $target;
1851
1852 // Find the page that an element was focused within
1853 $target = $( e.target ).closest( '.oo-ui-pageLayout' );
1854 for ( name in this.pages ) {
1855 // Check for page match, exclude current page to find only page changes
1856 if ( this.pages[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentPageName ) {
1857 this.setPage( name );
1858 break;
1859 }
1860 }
1861 };
1862
1863 /**
1864 * Handle visibleItemChange events from the stackLayout
1865 *
1866 * The next visible page is set as the current page by selecting it
1867 * in the outline
1868 *
1869 * @param {OO.ui.PageLayout} page The next visible page in the layout
1870 */
1871 OO.ui.BookletLayout.prototype.onStackLayoutVisibleItemChange = function ( page ) {
1872 // Set a flag to so that the resulting call to #onStackLayoutSet doesn't
1873 // try and scroll the item into view again.
1874 this.scrolling = true;
1875 this.outlineSelectWidget.selectItemByData( page.getName() );
1876 this.scrolling = false;
1877 };
1878
1879 /**
1880 * Handle stack layout set events.
1881 *
1882 * @private
1883 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
1884 */
1885 OO.ui.BookletLayout.prototype.onStackLayoutSet = function ( page ) {
1886 var promise, layout = this;
1887 // If everything is unselected, do nothing
1888 if ( !page ) {
1889 return;
1890 }
1891 // For continuous BookletLayouts, scroll the selected page into view first
1892 if ( this.stackLayout.continuous && !this.scrolling ) {
1893 promise = page.scrollElementIntoView();
1894 } else {
1895 promise = $.Deferred().resolve();
1896 }
1897 // Focus the first element on the newly selected panel
1898 if ( this.autoFocus && !OO.ui.isMobile() ) {
1899 promise.done( function () {
1900 layout.focus();
1901 } );
1902 }
1903 };
1904
1905 /**
1906 * Focus the first input in the current page.
1907 *
1908 * If no page is selected, the first selectable page will be selected.
1909 * If the focus is already in an element on the current page, nothing will happen.
1910 *
1911 * @param {number} [itemIndex] A specific item to focus on
1912 */
1913 OO.ui.BookletLayout.prototype.focus = function ( itemIndex ) {
1914 var page,
1915 items = this.stackLayout.getItems();
1916
1917 if ( itemIndex !== undefined && items[ itemIndex ] ) {
1918 page = items[ itemIndex ];
1919 } else {
1920 page = this.stackLayout.getCurrentItem();
1921 }
1922
1923 if ( !page && this.outlined ) {
1924 this.selectFirstSelectablePage();
1925 page = this.stackLayout.getCurrentItem();
1926 }
1927 if ( !page ) {
1928 return;
1929 }
1930 // Only change the focus if is not already in the current page
1931 if ( !OO.ui.contains( page.$element[ 0 ], this.getElementDocument().activeElement, true ) ) {
1932 page.focus();
1933 }
1934 };
1935
1936 /**
1937 * Find the first focusable input in the booklet layout and focus
1938 * on it.
1939 */
1940 OO.ui.BookletLayout.prototype.focusFirstFocusable = function () {
1941 OO.ui.findFocusable( this.stackLayout.$element ).focus();
1942 };
1943
1944 /**
1945 * Handle outline widget select events.
1946 *
1947 * @private
1948 * @param {OO.ui.OptionWidget|null} item Selected item
1949 */
1950 OO.ui.BookletLayout.prototype.onOutlineSelectWidgetSelect = function ( item ) {
1951 if ( item ) {
1952 this.setPage( item.getData() );
1953 }
1954 };
1955
1956 /**
1957 * Check if booklet has an outline.
1958 *
1959 * @return {boolean} Booklet has an outline
1960 */
1961 OO.ui.BookletLayout.prototype.isOutlined = function () {
1962 return this.outlined;
1963 };
1964
1965 /**
1966 * Check if booklet has editing controls.
1967 *
1968 * @return {boolean} Booklet is editable
1969 */
1970 OO.ui.BookletLayout.prototype.isEditable = function () {
1971 return this.editable;
1972 };
1973
1974 /**
1975 * Check if booklet has a visible outline.
1976 *
1977 * @return {boolean} Outline is visible
1978 */
1979 OO.ui.BookletLayout.prototype.isOutlineVisible = function () {
1980 return this.outlined && this.outlineVisible;
1981 };
1982
1983 /**
1984 * Hide or show the outline.
1985 *
1986 * @param {boolean} [show] Show outline, omit to invert current state
1987 * @chainable
1988 */
1989 OO.ui.BookletLayout.prototype.toggleOutline = function ( show ) {
1990 var booklet = this;
1991
1992 if ( this.outlined ) {
1993 show = show === undefined ? !this.outlineVisible : !!show;
1994 this.outlineVisible = show;
1995 this.toggleMenu( show );
1996 if ( show && this.editable ) {
1997 // HACK: Kill dumb scrollbars when the sidebar stops animating, see T161798. Only necessary when
1998 // outline controls are present, delay matches transition on `.oo-ui-menuLayout-menu`.
1999 setTimeout( function () {
2000 OO.ui.Element.static.reconsiderScrollbars( booklet.outlinePanel.$element[ 0 ] );
2001 }, 200 );
2002 }
2003 }
2004
2005 return this;
2006 };
2007
2008 /**
2009 * Find the page closest to the specified page.
2010 *
2011 * @param {OO.ui.PageLayout} page Page to use as a reference point
2012 * @return {OO.ui.PageLayout|null} Page closest to the specified page
2013 */
2014 OO.ui.BookletLayout.prototype.findClosestPage = function ( page ) {
2015 var next, prev, level,
2016 pages = this.stackLayout.getItems(),
2017 index = pages.indexOf( page );
2018
2019 if ( index !== -1 ) {
2020 next = pages[ index + 1 ];
2021 prev = pages[ index - 1 ];
2022 // Prefer adjacent pages at the same level
2023 if ( this.outlined ) {
2024 level = this.outlineSelectWidget.getItemFromData( page.getName() ).getLevel();
2025 if (
2026 prev &&
2027 level === this.outlineSelectWidget.getItemFromData( prev.getName() ).getLevel()
2028 ) {
2029 return prev;
2030 }
2031 if (
2032 next &&
2033 level === this.outlineSelectWidget.getItemFromData( next.getName() ).getLevel()
2034 ) {
2035 return next;
2036 }
2037 }
2038 }
2039 return prev || next || null;
2040 };
2041
2042 /**
2043 * Get the page closest to the specified page.
2044 *
2045 * @deprecated 0.23.0 Use {@link OO.ui.BookletLayout#findClosestPage} instead.
2046 * @param {OO.ui.PageLayout} page Page to use as a reference point
2047 * @return {OO.ui.PageLayout|null} Page closest to the specified page
2048 */
2049 OO.ui.BookletLayout.prototype.getClosestPage = function ( page ) {
2050 OO.ui.warnDeprecation( 'BookletLayout#getClosestPage: Deprecated function. Use findClosestPage instead. See T76630.' );
2051 return this.findClosestPage( page );
2052 };
2053
2054 /**
2055 * Get the outline widget.
2056 *
2057 * If the booklet is not outlined, the method will return `null`.
2058 *
2059 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
2060 */
2061 OO.ui.BookletLayout.prototype.getOutline = function () {
2062 return this.outlineSelectWidget;
2063 };
2064
2065 /**
2066 * Get the outline controls widget.
2067 *
2068 * If the outline is not editable, the method will return `null`.
2069 *
2070 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
2071 */
2072 OO.ui.BookletLayout.prototype.getOutlineControls = function () {
2073 return this.outlineControlsWidget;
2074 };
2075
2076 /**
2077 * Get a page by its symbolic name.
2078 *
2079 * @param {string} name Symbolic name of page
2080 * @return {OO.ui.PageLayout|undefined} Page, if found
2081 */
2082 OO.ui.BookletLayout.prototype.getPage = function ( name ) {
2083 return this.pages[ name ];
2084 };
2085
2086 /**
2087 * Get the current page.
2088 *
2089 * @return {OO.ui.PageLayout|undefined} Current page, if found
2090 */
2091 OO.ui.BookletLayout.prototype.getCurrentPage = function () {
2092 var name = this.getCurrentPageName();
2093 return name ? this.getPage( name ) : undefined;
2094 };
2095
2096 /**
2097 * Get the symbolic name of the current page.
2098 *
2099 * @return {string|null} Symbolic name of the current page
2100 */
2101 OO.ui.BookletLayout.prototype.getCurrentPageName = function () {
2102 return this.currentPageName;
2103 };
2104
2105 /**
2106 * Add pages to the booklet layout
2107 *
2108 * When pages are added with the same names as existing pages, the existing pages will be
2109 * automatically removed before the new pages are added.
2110 *
2111 * @param {OO.ui.PageLayout[]} pages Pages to add
2112 * @param {number} index Index of the insertion point
2113 * @fires add
2114 * @chainable
2115 */
2116 OO.ui.BookletLayout.prototype.addPages = function ( pages, index ) {
2117 var i, len, name, page, item, currentIndex,
2118 stackLayoutPages = this.stackLayout.getItems(),
2119 remove = [],
2120 items = [];
2121
2122 // Remove pages with same names
2123 for ( i = 0, len = pages.length; i < len; i++ ) {
2124 page = pages[ i ];
2125 name = page.getName();
2126
2127 if ( Object.prototype.hasOwnProperty.call( this.pages, name ) ) {
2128 // Correct the insertion index
2129 currentIndex = stackLayoutPages.indexOf( this.pages[ name ] );
2130 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
2131 index--;
2132 }
2133 remove.push( this.pages[ name ] );
2134 }
2135 }
2136 if ( remove.length ) {
2137 this.removePages( remove );
2138 }
2139
2140 // Add new pages
2141 for ( i = 0, len = pages.length; i < len; i++ ) {
2142 page = pages[ i ];
2143 name = page.getName();
2144 this.pages[ page.getName() ] = page;
2145 if ( this.outlined ) {
2146 item = new OO.ui.OutlineOptionWidget( { data: name } );
2147 page.setOutlineItem( item );
2148 items.push( item );
2149 }
2150 }
2151
2152 if ( this.outlined && items.length ) {
2153 this.outlineSelectWidget.addItems( items, index );
2154 this.selectFirstSelectablePage();
2155 }
2156 this.stackLayout.addItems( pages, index );
2157 this.emit( 'add', pages, index );
2158
2159 return this;
2160 };
2161
2162 /**
2163 * Remove the specified pages from the booklet layout.
2164 *
2165 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
2166 *
2167 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
2168 * @fires remove
2169 * @chainable
2170 */
2171 OO.ui.BookletLayout.prototype.removePages = function ( pages ) {
2172 var i, len, name, page,
2173 items = [];
2174
2175 for ( i = 0, len = pages.length; i < len; i++ ) {
2176 page = pages[ i ];
2177 name = page.getName();
2178 delete this.pages[ name ];
2179 if ( this.outlined ) {
2180 items.push( this.outlineSelectWidget.getItemFromData( name ) );
2181 page.setOutlineItem( null );
2182 }
2183 }
2184 if ( this.outlined && items.length ) {
2185 this.outlineSelectWidget.removeItems( items );
2186 this.selectFirstSelectablePage();
2187 }
2188 this.stackLayout.removeItems( pages );
2189 this.emit( 'remove', pages );
2190
2191 return this;
2192 };
2193
2194 /**
2195 * Clear all pages from the booklet layout.
2196 *
2197 * To remove only a subset of pages from the booklet, use the #removePages method.
2198 *
2199 * @fires remove
2200 * @chainable
2201 */
2202 OO.ui.BookletLayout.prototype.clearPages = function () {
2203 var i, len,
2204 pages = this.stackLayout.getItems();
2205
2206 this.pages = {};
2207 this.currentPageName = null;
2208 if ( this.outlined ) {
2209 this.outlineSelectWidget.clearItems();
2210 for ( i = 0, len = pages.length; i < len; i++ ) {
2211 pages[ i ].setOutlineItem( null );
2212 }
2213 }
2214 this.stackLayout.clearItems();
2215
2216 this.emit( 'remove', pages );
2217
2218 return this;
2219 };
2220
2221 /**
2222 * Set the current page by symbolic name.
2223 *
2224 * @fires set
2225 * @param {string} name Symbolic name of page
2226 */
2227 OO.ui.BookletLayout.prototype.setPage = function ( name ) {
2228 var selectedItem,
2229 $focused,
2230 page = this.pages[ name ],
2231 previousPage = this.currentPageName && this.pages[ this.currentPageName ];
2232
2233 if ( name !== this.currentPageName ) {
2234 if ( this.outlined ) {
2235 selectedItem = this.outlineSelectWidget.getSelectedItem();
2236 if ( selectedItem && selectedItem.getData() !== name ) {
2237 this.outlineSelectWidget.selectItemByData( name );
2238 }
2239 }
2240 if ( page ) {
2241 if ( previousPage ) {
2242 previousPage.setActive( false );
2243 // Blur anything focused if the next page doesn't have anything focusable.
2244 // This is not needed if the next page has something focusable (because once it is focused
2245 // this blur happens automatically). If the layout is non-continuous, this check is
2246 // meaningless because the next page is not visible yet and thus can't hold focus.
2247 if (
2248 this.autoFocus &&
2249 !OO.ui.isMobile() &&
2250 this.stackLayout.continuous &&
2251 OO.ui.findFocusable( page.$element ).length !== 0
2252 ) {
2253 $focused = previousPage.$element.find( ':focus' );
2254 if ( $focused.length ) {
2255 $focused[ 0 ].blur();
2256 }
2257 }
2258 }
2259 this.currentPageName = name;
2260 page.setActive( true );
2261 this.stackLayout.setItem( page );
2262 if ( !this.stackLayout.continuous && previousPage ) {
2263 // This should not be necessary, since any inputs on the previous page should have been
2264 // blurred when it was hidden, but browsers are not very consistent about this.
2265 $focused = previousPage.$element.find( ':focus' );
2266 if ( $focused.length ) {
2267 $focused[ 0 ].blur();
2268 }
2269 }
2270 this.emit( 'set', page );
2271 }
2272 }
2273 };
2274
2275 /**
2276 * Select the first selectable page.
2277 *
2278 * @chainable
2279 */
2280 OO.ui.BookletLayout.prototype.selectFirstSelectablePage = function () {
2281 if ( !this.outlineSelectWidget.getSelectedItem() ) {
2282 this.outlineSelectWidget.selectItem( this.outlineSelectWidget.findFirstSelectableItem() );
2283 }
2284
2285 return this;
2286 };
2287
2288 /**
2289 * IndexLayouts contain {@link OO.ui.TabPanelLayout tab panel layouts} as well as
2290 * {@link OO.ui.TabSelectWidget tabs} that allow users to easily navigate through the tab panels and
2291 * select which one to display. By default, only one tab panel is displayed at a time. When a user
2292 * navigates to a new tab panel, the index layout automatically focuses on the first focusable element,
2293 * unless the default setting is changed.
2294 *
2295 * TODO: This class is similar to BookletLayout, we may want to refactor to reduce duplication
2296 *
2297 * @example
2298 * // Example of a IndexLayout that contains two TabPanelLayouts.
2299 *
2300 * function TabPanelOneLayout( name, config ) {
2301 * TabPanelOneLayout.parent.call( this, name, config );
2302 * this.$element.append( '<p>First tab panel</p>' );
2303 * }
2304 * OO.inheritClass( TabPanelOneLayout, OO.ui.TabPanelLayout );
2305 * TabPanelOneLayout.prototype.setupTabItem = function () {
2306 * this.tabItem.setLabel( 'Tab panel one' );
2307 * };
2308 *
2309 * var tabPanel1 = new TabPanelOneLayout( 'one' ),
2310 * tabPanel2 = new OO.ui.TabPanelLayout( 'two', { label: 'Tab panel two' } );
2311 *
2312 * tabPanel2.$element.append( '<p>Second tab panel</p>' );
2313 *
2314 * var index = new OO.ui.IndexLayout();
2315 *
2316 * index.addTabPanels ( [ tabPanel1, tabPanel2 ] );
2317 * $( 'body' ).append( index.$element );
2318 *
2319 * @class
2320 * @extends OO.ui.MenuLayout
2321 *
2322 * @constructor
2323 * @param {Object} [config] Configuration options
2324 * @cfg {boolean} [continuous=false] Show all tab panels, one after another
2325 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new tab panel is displayed. Disabled on mobile.
2326 */
2327 OO.ui.IndexLayout = function OoUiIndexLayout( config ) {
2328 // Configuration initialization
2329 config = $.extend( {}, config, { menuPosition: 'top' } );
2330
2331 // Parent constructor
2332 OO.ui.IndexLayout.parent.call( this, config );
2333
2334 // Properties
2335 this.currentTabPanelName = null;
2336 this.tabPanels = {};
2337
2338 this.ignoreFocus = false;
2339 this.stackLayout = new OO.ui.StackLayout( {
2340 continuous: !!config.continuous,
2341 expanded: this.expanded
2342 } );
2343 this.$content.append( this.stackLayout.$element );
2344 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
2345
2346 this.tabSelectWidget = new OO.ui.TabSelectWidget();
2347 this.tabPanel = new OO.ui.PanelLayout( {
2348 expanded: this.expanded
2349 } );
2350 this.$menu.append( this.tabPanel.$element );
2351
2352 this.toggleMenu( true );
2353
2354 // Events
2355 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
2356 this.tabSelectWidget.connect( this, { select: 'onTabSelectWidgetSelect' } );
2357 if ( this.autoFocus ) {
2358 // Event 'focus' does not bubble, but 'focusin' does
2359 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
2360 }
2361
2362 // Initialization
2363 this.$element.addClass( 'oo-ui-indexLayout' );
2364 this.stackLayout.$element.addClass( 'oo-ui-indexLayout-stackLayout' );
2365 this.tabPanel.$element
2366 .addClass( 'oo-ui-indexLayout-tabPanel' )
2367 .append( this.tabSelectWidget.$element );
2368 };
2369
2370 /* Setup */
2371
2372 OO.inheritClass( OO.ui.IndexLayout, OO.ui.MenuLayout );
2373
2374 /* Events */
2375
2376 /**
2377 * A 'set' event is emitted when a tab panel is {@link #setTabPanel set} to be displayed by the index layout.
2378 * @event set
2379 * @param {OO.ui.TabPanelLayout} tabPanel Current tab panel
2380 */
2381
2382 /**
2383 * An 'add' event is emitted when tab panels are {@link #addTabPanels added} to the index layout.
2384 *
2385 * @event add
2386 * @param {OO.ui.TabPanelLayout[]} tabPanel Added tab panels
2387 * @param {number} index Index tab panels were added at
2388 */
2389
2390 /**
2391 * A 'remove' event is emitted when tab panels are {@link #clearTabPanels cleared} or
2392 * {@link #removeTabPanels removed} from the index.
2393 *
2394 * @event remove
2395 * @param {OO.ui.TabPanelLayout[]} tabPanel Removed tab panels
2396 */
2397
2398 /* Methods */
2399
2400 /**
2401 * Handle stack layout focus.
2402 *
2403 * @private
2404 * @param {jQuery.Event} e Focusing event
2405 */
2406 OO.ui.IndexLayout.prototype.onStackLayoutFocus = function ( e ) {
2407 var name, $target;
2408
2409 // Find the tab panel that an element was focused within
2410 $target = $( e.target ).closest( '.oo-ui-tabPanelLayout' );
2411 for ( name in this.tabPanels ) {
2412 // Check for tab panel match, exclude current tab panel to find only tab panel changes
2413 if ( this.tabPanels[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentTabPanelName ) {
2414 this.setTabPanel( name );
2415 break;
2416 }
2417 }
2418 };
2419
2420 /**
2421 * Handle stack layout set events.
2422 *
2423 * @private
2424 * @param {OO.ui.PanelLayout|null} tabPanel The tab panel that is now the current panel
2425 */
2426 OO.ui.IndexLayout.prototype.onStackLayoutSet = function ( tabPanel ) {
2427 // If everything is unselected, do nothing
2428 if ( !tabPanel ) {
2429 return;
2430 }
2431 // Focus the first element on the newly selected panel
2432 if ( this.autoFocus && !OO.ui.isMobile() ) {
2433 this.focus();
2434 }
2435 };
2436
2437 /**
2438 * Focus the first input in the current tab panel.
2439 *
2440 * If no tab panel is selected, the first selectable tab panel will be selected.
2441 * If the focus is already in an element on the current tab panel, nothing will happen.
2442 *
2443 * @param {number} [itemIndex] A specific item to focus on
2444 */
2445 OO.ui.IndexLayout.prototype.focus = function ( itemIndex ) {
2446 var tabPanel,
2447 items = this.stackLayout.getItems();
2448
2449 if ( itemIndex !== undefined && items[ itemIndex ] ) {
2450 tabPanel = items[ itemIndex ];
2451 } else {
2452 tabPanel = this.stackLayout.getCurrentItem();
2453 }
2454
2455 if ( !tabPanel ) {
2456 this.selectFirstSelectableTabPanel();
2457 tabPanel = this.stackLayout.getCurrentItem();
2458 }
2459 if ( !tabPanel ) {
2460 return;
2461 }
2462 // Only change the focus if is not already in the current page
2463 if ( !OO.ui.contains( tabPanel.$element[ 0 ], this.getElementDocument().activeElement, true ) ) {
2464 tabPanel.focus();
2465 }
2466 };
2467
2468 /**
2469 * Find the first focusable input in the index layout and focus
2470 * on it.
2471 */
2472 OO.ui.IndexLayout.prototype.focusFirstFocusable = function () {
2473 OO.ui.findFocusable( this.stackLayout.$element ).focus();
2474 };
2475
2476 /**
2477 * Handle tab widget select events.
2478 *
2479 * @private
2480 * @param {OO.ui.OptionWidget|null} item Selected item
2481 */
2482 OO.ui.IndexLayout.prototype.onTabSelectWidgetSelect = function ( item ) {
2483 if ( item ) {
2484 this.setTabPanel( item.getData() );
2485 }
2486 };
2487
2488 /**
2489 * Get the tab panel closest to the specified tab panel.
2490 *
2491 * @param {OO.ui.TabPanelLayout} tabPanel Tab panel to use as a reference point
2492 * @return {OO.ui.TabPanelLayout|null} Tab panel closest to the specified
2493 */
2494 OO.ui.IndexLayout.prototype.getClosestTabPanel = function ( tabPanel ) {
2495 var next, prev, level,
2496 tabPanels = this.stackLayout.getItems(),
2497 index = tabPanels.indexOf( tabPanel );
2498
2499 if ( index !== -1 ) {
2500 next = tabPanels[ index + 1 ];
2501 prev = tabPanels[ index - 1 ];
2502 // Prefer adjacent tab panels at the same level
2503 level = this.tabSelectWidget.getItemFromData( tabPanel.getName() ).getLevel();
2504 if (
2505 prev &&
2506 level === this.tabSelectWidget.getItemFromData( prev.getName() ).getLevel()
2507 ) {
2508 return prev;
2509 }
2510 if (
2511 next &&
2512 level === this.tabSelectWidget.getItemFromData( next.getName() ).getLevel()
2513 ) {
2514 return next;
2515 }
2516 }
2517 return prev || next || null;
2518 };
2519
2520 /**
2521 * Get the tabs widget.
2522 *
2523 * @return {OO.ui.TabSelectWidget} Tabs widget
2524 */
2525 OO.ui.IndexLayout.prototype.getTabs = function () {
2526 return this.tabSelectWidget;
2527 };
2528
2529 /**
2530 * Get a tab panel by its symbolic name.
2531 *
2532 * @param {string} name Symbolic name of tab panel
2533 * @return {OO.ui.TabPanelLayout|undefined} Tab panel, if found
2534 */
2535 OO.ui.IndexLayout.prototype.getTabPanel = function ( name ) {
2536 return this.tabPanels[ name ];
2537 };
2538
2539 /**
2540 * Get the current tab panel.
2541 *
2542 * @return {OO.ui.TabPanelLayout|undefined} Current tab panel, if found
2543 */
2544 OO.ui.IndexLayout.prototype.getCurrentTabPanel = function () {
2545 var name = this.getCurrentTabPanelName();
2546 return name ? this.getTabPanel( name ) : undefined;
2547 };
2548
2549 /**
2550 * Get the symbolic name of the current tab panel.
2551 *
2552 * @return {string|null} Symbolic name of the current tab panel
2553 */
2554 OO.ui.IndexLayout.prototype.getCurrentTabPanelName = function () {
2555 return this.currentTabPanelName;
2556 };
2557
2558 /**
2559 * Add tab panels to the index layout
2560 *
2561 * When tab panels are added with the same names as existing tab panels, the existing tab panels
2562 * will be automatically removed before the new tab panels are added.
2563 *
2564 * @param {OO.ui.TabPanelLayout[]} tabPanels Tab panels to add
2565 * @param {number} index Index of the insertion point
2566 * @fires add
2567 * @chainable
2568 */
2569 OO.ui.IndexLayout.prototype.addTabPanels = function ( tabPanels, index ) {
2570 var i, len, name, tabPanel, item, currentIndex,
2571 stackLayoutTabPanels = this.stackLayout.getItems(),
2572 remove = [],
2573 items = [];
2574
2575 // Remove tab panels with same names
2576 for ( i = 0, len = tabPanels.length; i < len; i++ ) {
2577 tabPanel = tabPanels[ i ];
2578 name = tabPanel.getName();
2579
2580 if ( Object.prototype.hasOwnProperty.call( this.tabPanels, name ) ) {
2581 // Correct the insertion index
2582 currentIndex = stackLayoutTabPanels.indexOf( this.tabPanels[ name ] );
2583 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
2584 index--;
2585 }
2586 remove.push( this.tabPanels[ name ] );
2587 }
2588 }
2589 if ( remove.length ) {
2590 this.removeTabPanels( remove );
2591 }
2592
2593 // Add new tab panels
2594 for ( i = 0, len = tabPanels.length; i < len; i++ ) {
2595 tabPanel = tabPanels[ i ];
2596 name = tabPanel.getName();
2597 this.tabPanels[ tabPanel.getName() ] = tabPanel;
2598 item = new OO.ui.TabOptionWidget( { data: name } );
2599 tabPanel.setTabItem( item );
2600 items.push( item );
2601 }
2602
2603 if ( items.length ) {
2604 this.tabSelectWidget.addItems( items, index );
2605 this.selectFirstSelectableTabPanel();
2606 }
2607 this.stackLayout.addItems( tabPanels, index );
2608 this.emit( 'add', tabPanels, index );
2609
2610 return this;
2611 };
2612
2613 /**
2614 * Remove the specified tab panels from the index layout.
2615 *
2616 * To remove all tab panels from the index, you may wish to use the #clearTabPanels method instead.
2617 *
2618 * @param {OO.ui.TabPanelLayout[]} tabPanels An array of tab panels to remove
2619 * @fires remove
2620 * @chainable
2621 */
2622 OO.ui.IndexLayout.prototype.removeTabPanels = function ( tabPanels ) {
2623 var i, len, name, tabPanel,
2624 items = [];
2625
2626 for ( i = 0, len = tabPanels.length; i < len; i++ ) {
2627 tabPanel = tabPanels[ i ];
2628 name = tabPanel.getName();
2629 delete this.tabPanels[ name ];
2630 items.push( this.tabSelectWidget.getItemFromData( name ) );
2631 tabPanel.setTabItem( null );
2632 }
2633 if ( items.length ) {
2634 this.tabSelectWidget.removeItems( items );
2635 this.selectFirstSelectableTabPanel();
2636 }
2637 this.stackLayout.removeItems( tabPanels );
2638 this.emit( 'remove', tabPanels );
2639
2640 return this;
2641 };
2642
2643 /**
2644 * Clear all tab panels from the index layout.
2645 *
2646 * To remove only a subset of tab panels from the index, use the #removeTabPanels method.
2647 *
2648 * @fires remove
2649 * @chainable
2650 */
2651 OO.ui.IndexLayout.prototype.clearTabPanels = function () {
2652 var i, len,
2653 tabPanels = this.stackLayout.getItems();
2654
2655 this.tabPanels = {};
2656 this.currentTabPanelName = null;
2657 this.tabSelectWidget.clearItems();
2658 for ( i = 0, len = tabPanels.length; i < len; i++ ) {
2659 tabPanels[ i ].setTabItem( null );
2660 }
2661 this.stackLayout.clearItems();
2662
2663 this.emit( 'remove', tabPanels );
2664
2665 return this;
2666 };
2667
2668 /**
2669 * Set the current tab panel by symbolic name.
2670 *
2671 * @fires set
2672 * @param {string} name Symbolic name of tab panel
2673 */
2674 OO.ui.IndexLayout.prototype.setTabPanel = function ( name ) {
2675 var selectedItem,
2676 $focused,
2677 tabPanel = this.tabPanels[ name ],
2678 previousTabPanel = this.currentTabPanelName && this.tabPanels[ this.currentTabPanelName ];
2679
2680 if ( name !== this.currentTabPanelName ) {
2681 selectedItem = this.tabSelectWidget.getSelectedItem();
2682 if ( selectedItem && selectedItem.getData() !== name ) {
2683 this.tabSelectWidget.selectItemByData( name );
2684 }
2685 if ( tabPanel ) {
2686 if ( previousTabPanel ) {
2687 previousTabPanel.setActive( false );
2688 // Blur anything focused if the next tab panel doesn't have anything focusable.
2689 // This is not needed if the next tab panel has something focusable (because once it is focused
2690 // this blur happens automatically). If the layout is non-continuous, this check is
2691 // meaningless because the next tab panel is not visible yet and thus can't hold focus.
2692 if (
2693 this.autoFocus &&
2694 !OO.ui.isMobile() &&
2695 this.stackLayout.continuous &&
2696 OO.ui.findFocusable( tabPanel.$element ).length !== 0
2697 ) {
2698 $focused = previousTabPanel.$element.find( ':focus' );
2699 if ( $focused.length ) {
2700 $focused[ 0 ].blur();
2701 }
2702 }
2703 }
2704 this.currentTabPanelName = name;
2705 tabPanel.setActive( true );
2706 this.stackLayout.setItem( tabPanel );
2707 if ( !this.stackLayout.continuous && previousTabPanel ) {
2708 // This should not be necessary, since any inputs on the previous tab panel should have been
2709 // blurred when it was hidden, but browsers are not very consistent about this.
2710 $focused = previousTabPanel.$element.find( ':focus' );
2711 if ( $focused.length ) {
2712 $focused[ 0 ].blur();
2713 }
2714 }
2715 this.emit( 'set', tabPanel );
2716 }
2717 }
2718 };
2719
2720 /**
2721 * Select the first selectable tab panel.
2722 *
2723 * @chainable
2724 */
2725 OO.ui.IndexLayout.prototype.selectFirstSelectableTabPanel = function () {
2726 if ( !this.tabSelectWidget.getSelectedItem() ) {
2727 this.tabSelectWidget.selectItem( this.tabSelectWidget.findFirstSelectableItem() );
2728 }
2729
2730 return this;
2731 };
2732
2733 /**
2734 * ToggleWidget implements basic behavior of widgets with an on/off state.
2735 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
2736 *
2737 * @abstract
2738 * @class
2739 * @extends OO.ui.Widget
2740 *
2741 * @constructor
2742 * @param {Object} [config] Configuration options
2743 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
2744 * By default, the toggle is in the 'off' state.
2745 */
2746 OO.ui.ToggleWidget = function OoUiToggleWidget( config ) {
2747 // Configuration initialization
2748 config = config || {};
2749
2750 // Parent constructor
2751 OO.ui.ToggleWidget.parent.call( this, config );
2752
2753 // Properties
2754 this.value = null;
2755
2756 // Initialization
2757 this.$element.addClass( 'oo-ui-toggleWidget' );
2758 this.setValue( !!config.value );
2759 };
2760
2761 /* Setup */
2762
2763 OO.inheritClass( OO.ui.ToggleWidget, OO.ui.Widget );
2764
2765 /* Events */
2766
2767 /**
2768 * @event change
2769 *
2770 * A change event is emitted when the on/off state of the toggle changes.
2771 *
2772 * @param {boolean} value Value representing the new state of the toggle
2773 */
2774
2775 /* Methods */
2776
2777 /**
2778 * Get the value representing the toggle’s state.
2779 *
2780 * @return {boolean} The on/off state of the toggle
2781 */
2782 OO.ui.ToggleWidget.prototype.getValue = function () {
2783 return this.value;
2784 };
2785
2786 /**
2787 * Set the state of the toggle: `true` for 'on', `false` for 'off'.
2788 *
2789 * @param {boolean} value The state of the toggle
2790 * @fires change
2791 * @chainable
2792 */
2793 OO.ui.ToggleWidget.prototype.setValue = function ( value ) {
2794 value = !!value;
2795 if ( this.value !== value ) {
2796 this.value = value;
2797 this.emit( 'change', value );
2798 this.$element.toggleClass( 'oo-ui-toggleWidget-on', value );
2799 this.$element.toggleClass( 'oo-ui-toggleWidget-off', !value );
2800 }
2801 return this;
2802 };
2803
2804 /**
2805 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
2806 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
2807 * configured with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators},
2808 * {@link OO.ui.mixin.TitledElement titles}, {@link OO.ui.mixin.FlaggedElement styling flags},
2809 * and {@link OO.ui.mixin.LabelElement labels}. Please see
2810 * the [OOjs UI documentation][1] on MediaWiki for more information.
2811 *
2812 * @example
2813 * // Toggle buttons in the 'off' and 'on' state.
2814 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
2815 * label: 'Toggle Button off'
2816 * } );
2817 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
2818 * label: 'Toggle Button on',
2819 * value: true
2820 * } );
2821 * // Append the buttons to the DOM.
2822 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
2823 *
2824 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
2825 *
2826 * @class
2827 * @extends OO.ui.ToggleWidget
2828 * @mixins OO.ui.mixin.ButtonElement
2829 * @mixins OO.ui.mixin.IconElement
2830 * @mixins OO.ui.mixin.IndicatorElement
2831 * @mixins OO.ui.mixin.LabelElement
2832 * @mixins OO.ui.mixin.TitledElement
2833 * @mixins OO.ui.mixin.FlaggedElement
2834 * @mixins OO.ui.mixin.TabIndexedElement
2835 *
2836 * @constructor
2837 * @param {Object} [config] Configuration options
2838 * @cfg {boolean} [value=false] The toggle button’s initial on/off
2839 * state. By default, the button is in the 'off' state.
2840 */
2841 OO.ui.ToggleButtonWidget = function OoUiToggleButtonWidget( config ) {
2842 // Configuration initialization
2843 config = config || {};
2844
2845 // Parent constructor
2846 OO.ui.ToggleButtonWidget.parent.call( this, config );
2847
2848 // Mixin constructors
2849 OO.ui.mixin.ButtonElement.call( this, $.extend( {}, config, { active: this.active } ) );
2850 OO.ui.mixin.IconElement.call( this, config );
2851 OO.ui.mixin.IndicatorElement.call( this, config );
2852 OO.ui.mixin.LabelElement.call( this, config );
2853 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
2854 OO.ui.mixin.FlaggedElement.call( this, config );
2855 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
2856
2857 // Events
2858 this.connect( this, { click: 'onAction' } );
2859
2860 // Initialization
2861 this.$button.append( this.$icon, this.$label, this.$indicator );
2862 this.$element
2863 .addClass( 'oo-ui-toggleButtonWidget' )
2864 .append( this.$button );
2865 };
2866
2867 /* Setup */
2868
2869 OO.inheritClass( OO.ui.ToggleButtonWidget, OO.ui.ToggleWidget );
2870 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.ButtonElement );
2871 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IconElement );
2872 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IndicatorElement );
2873 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.LabelElement );
2874 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TitledElement );
2875 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.FlaggedElement );
2876 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TabIndexedElement );
2877
2878 /* Static Properties */
2879
2880 /**
2881 * @static
2882 * @inheritdoc
2883 */
2884 OO.ui.ToggleButtonWidget.static.tagName = 'span';
2885
2886 /* Methods */
2887
2888 /**
2889 * Handle the button action being triggered.
2890 *
2891 * @private
2892 */
2893 OO.ui.ToggleButtonWidget.prototype.onAction = function () {
2894 this.setValue( !this.value );
2895 };
2896
2897 /**
2898 * @inheritdoc
2899 */
2900 OO.ui.ToggleButtonWidget.prototype.setValue = function ( value ) {
2901 value = !!value;
2902 if ( value !== this.value ) {
2903 // Might be called from parent constructor before ButtonElement constructor
2904 if ( this.$button ) {
2905 this.$button.attr( 'aria-pressed', value.toString() );
2906 }
2907 this.setActive( value );
2908 }
2909
2910 // Parent method
2911 OO.ui.ToggleButtonWidget.parent.prototype.setValue.call( this, value );
2912
2913 return this;
2914 };
2915
2916 /**
2917 * @inheritdoc
2918 */
2919 OO.ui.ToggleButtonWidget.prototype.setButtonElement = function ( $button ) {
2920 if ( this.$button ) {
2921 this.$button.removeAttr( 'aria-pressed' );
2922 }
2923 OO.ui.mixin.ButtonElement.prototype.setButtonElement.call( this, $button );
2924 this.$button.attr( 'aria-pressed', this.value.toString() );
2925 };
2926
2927 /**
2928 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
2929 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
2930 * visually by a slider in the leftmost position.
2931 *
2932 * @example
2933 * // Toggle switches in the 'off' and 'on' position.
2934 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
2935 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
2936 * value: true
2937 * } );
2938 *
2939 * // Create a FieldsetLayout to layout and label switches
2940 * var fieldset = new OO.ui.FieldsetLayout( {
2941 * label: 'Toggle switches'
2942 * } );
2943 * fieldset.addItems( [
2944 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
2945 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
2946 * ] );
2947 * $( 'body' ).append( fieldset.$element );
2948 *
2949 * @class
2950 * @extends OO.ui.ToggleWidget
2951 * @mixins OO.ui.mixin.TabIndexedElement
2952 *
2953 * @constructor
2954 * @param {Object} [config] Configuration options
2955 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
2956 * By default, the toggle switch is in the 'off' position.
2957 */
2958 OO.ui.ToggleSwitchWidget = function OoUiToggleSwitchWidget( config ) {
2959 // Parent constructor
2960 OO.ui.ToggleSwitchWidget.parent.call( this, config );
2961
2962 // Mixin constructors
2963 OO.ui.mixin.TabIndexedElement.call( this, config );
2964
2965 // Properties
2966 this.dragging = false;
2967 this.dragStart = null;
2968 this.sliding = false;
2969 this.$glow = $( '<span>' );
2970 this.$grip = $( '<span>' );
2971
2972 // Events
2973 this.$element.on( {
2974 click: this.onClick.bind( this ),
2975 keypress: this.onKeyPress.bind( this )
2976 } );
2977
2978 // Initialization
2979 this.$glow.addClass( 'oo-ui-toggleSwitchWidget-glow' );
2980 this.$grip.addClass( 'oo-ui-toggleSwitchWidget-grip' );
2981 this.$element
2982 .addClass( 'oo-ui-toggleSwitchWidget' )
2983 .attr( 'role', 'checkbox' )
2984 .append( this.$glow, this.$grip );
2985 };
2986
2987 /* Setup */
2988
2989 OO.inheritClass( OO.ui.ToggleSwitchWidget, OO.ui.ToggleWidget );
2990 OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.mixin.TabIndexedElement );
2991
2992 /* Methods */
2993
2994 /**
2995 * Handle mouse click events.
2996 *
2997 * @private
2998 * @param {jQuery.Event} e Mouse click event
2999 */
3000 OO.ui.ToggleSwitchWidget.prototype.onClick = function ( e ) {
3001 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
3002 this.setValue( !this.value );
3003 }
3004 return false;
3005 };
3006
3007 /**
3008 * Handle key press events.
3009 *
3010 * @private
3011 * @param {jQuery.Event} e Key press event
3012 */
3013 OO.ui.ToggleSwitchWidget.prototype.onKeyPress = function ( e ) {
3014 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
3015 this.setValue( !this.value );
3016 return false;
3017 }
3018 };
3019
3020 /**
3021 * @inheritdoc
3022 */
3023 OO.ui.ToggleSwitchWidget.prototype.setValue = function ( value ) {
3024 OO.ui.ToggleSwitchWidget.parent.prototype.setValue.call( this, value );
3025 this.$element.attr( 'aria-checked', this.value.toString() );
3026 return this;
3027 };
3028
3029 /**
3030 * @inheritdoc
3031 */
3032 OO.ui.ToggleSwitchWidget.prototype.simulateLabelClick = function () {
3033 if ( !this.isDisabled() ) {
3034 this.setValue( !this.value );
3035 }
3036 this.focus();
3037 };
3038
3039 /**
3040 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
3041 * Controls include moving items up and down, removing items, and adding different kinds of items.
3042 *
3043 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
3044 *
3045 * @class
3046 * @extends OO.ui.Widget
3047 * @mixins OO.ui.mixin.GroupElement
3048 * @mixins OO.ui.mixin.IconElement
3049 *
3050 * @constructor
3051 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
3052 * @param {Object} [config] Configuration options
3053 * @cfg {Object} [abilities] List of abilties
3054 * @cfg {boolean} [abilities.move=true] Allow moving movable items
3055 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
3056 */
3057 OO.ui.OutlineControlsWidget = function OoUiOutlineControlsWidget( outline, config ) {
3058 // Allow passing positional parameters inside the config object
3059 if ( OO.isPlainObject( outline ) && config === undefined ) {
3060 config = outline;
3061 outline = config.outline;
3062 }
3063
3064 // Configuration initialization
3065 config = $.extend( { icon: 'add' }, config );
3066
3067 // Parent constructor
3068 OO.ui.OutlineControlsWidget.parent.call( this, config );
3069
3070 // Mixin constructors
3071 OO.ui.mixin.GroupElement.call( this, config );
3072 OO.ui.mixin.IconElement.call( this, config );
3073
3074 // Properties
3075 this.outline = outline;
3076 this.$movers = $( '<div>' );
3077 this.upButton = new OO.ui.ButtonWidget( {
3078 framed: false,
3079 icon: 'collapse',
3080 title: OO.ui.msg( 'ooui-outline-control-move-up' )
3081 } );
3082 this.downButton = new OO.ui.ButtonWidget( {
3083 framed: false,
3084 icon: 'expand',
3085 title: OO.ui.msg( 'ooui-outline-control-move-down' )
3086 } );
3087 this.removeButton = new OO.ui.ButtonWidget( {
3088 framed: false,
3089 icon: 'trash',
3090 title: OO.ui.msg( 'ooui-outline-control-remove' )
3091 } );
3092 this.abilities = { move: true, remove: true };
3093
3094 // Events
3095 outline.connect( this, {
3096 select: 'onOutlineChange',
3097 add: 'onOutlineChange',
3098 remove: 'onOutlineChange'
3099 } );
3100 this.upButton.connect( this, { click: [ 'emit', 'move', -1 ] } );
3101 this.downButton.connect( this, { click: [ 'emit', 'move', 1 ] } );
3102 this.removeButton.connect( this, { click: [ 'emit', 'remove' ] } );
3103
3104 // Initialization
3105 this.$element.addClass( 'oo-ui-outlineControlsWidget' );
3106 this.$group.addClass( 'oo-ui-outlineControlsWidget-items' );
3107 this.$movers
3108 .addClass( 'oo-ui-outlineControlsWidget-movers' )
3109 .append( this.removeButton.$element, this.upButton.$element, this.downButton.$element );
3110 this.$element.append( this.$icon, this.$group, this.$movers );
3111 this.setAbilities( config.abilities || {} );
3112 };
3113
3114 /* Setup */
3115
3116 OO.inheritClass( OO.ui.OutlineControlsWidget, OO.ui.Widget );
3117 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.GroupElement );
3118 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.IconElement );
3119
3120 /* Events */
3121
3122 /**
3123 * @event move
3124 * @param {number} places Number of places to move
3125 */
3126
3127 /**
3128 * @event remove
3129 */
3130
3131 /* Methods */
3132
3133 /**
3134 * Set abilities.
3135 *
3136 * @param {Object} abilities List of abilties
3137 * @param {boolean} [abilities.move] Allow moving movable items
3138 * @param {boolean} [abilities.remove] Allow removing removable items
3139 */
3140 OO.ui.OutlineControlsWidget.prototype.setAbilities = function ( abilities ) {
3141 var ability;
3142
3143 for ( ability in this.abilities ) {
3144 if ( abilities[ ability ] !== undefined ) {
3145 this.abilities[ ability ] = !!abilities[ ability ];
3146 }
3147 }
3148
3149 this.onOutlineChange();
3150 };
3151
3152 /**
3153 * Handle outline change events.
3154 *
3155 * @private
3156 */
3157 OO.ui.OutlineControlsWidget.prototype.onOutlineChange = function () {
3158 var i, len, firstMovable, lastMovable,
3159 items = this.outline.getItems(),
3160 selectedItem = this.outline.getSelectedItem(),
3161 movable = this.abilities.move && selectedItem && selectedItem.isMovable(),
3162 removable = this.abilities.remove && selectedItem && selectedItem.isRemovable();
3163
3164 if ( movable ) {
3165 i = -1;
3166 len = items.length;
3167 while ( ++i < len ) {
3168 if ( items[ i ].isMovable() ) {
3169 firstMovable = items[ i ];
3170 break;
3171 }
3172 }
3173 i = len;
3174 while ( i-- ) {
3175 if ( items[ i ].isMovable() ) {
3176 lastMovable = items[ i ];
3177 break;
3178 }
3179 }
3180 }
3181 this.upButton.setDisabled( !movable || selectedItem === firstMovable );
3182 this.downButton.setDisabled( !movable || selectedItem === lastMovable );
3183 this.removeButton.setDisabled( !removable );
3184 };
3185
3186 /**
3187 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
3188 *
3189 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
3190 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
3191 * for an example.
3192 *
3193 * @class
3194 * @extends OO.ui.DecoratedOptionWidget
3195 *
3196 * @constructor
3197 * @param {Object} [config] Configuration options
3198 * @cfg {number} [level] Indentation level
3199 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
3200 */
3201 OO.ui.OutlineOptionWidget = function OoUiOutlineOptionWidget( config ) {
3202 // Configuration initialization
3203 config = config || {};
3204
3205 // Parent constructor
3206 OO.ui.OutlineOptionWidget.parent.call( this, config );
3207
3208 // Properties
3209 this.level = 0;
3210 this.movable = !!config.movable;
3211 this.removable = !!config.removable;
3212
3213 // Initialization
3214 this.$element.addClass( 'oo-ui-outlineOptionWidget' );
3215 this.setLevel( config.level );
3216 };
3217
3218 /* Setup */
3219
3220 OO.inheritClass( OO.ui.OutlineOptionWidget, OO.ui.DecoratedOptionWidget );
3221
3222 /* Static Properties */
3223
3224 /**
3225 * @static
3226 * @inheritdoc
3227 */
3228 OO.ui.OutlineOptionWidget.static.highlightable = true;
3229
3230 /**
3231 * @static
3232 * @inheritdoc
3233 */
3234 OO.ui.OutlineOptionWidget.static.scrollIntoViewOnSelect = true;
3235
3236 /**
3237 * @static
3238 * @inheritable
3239 * @property {string}
3240 */
3241 OO.ui.OutlineOptionWidget.static.levelClass = 'oo-ui-outlineOptionWidget-level-';
3242
3243 /**
3244 * @static
3245 * @inheritable
3246 * @property {number}
3247 */
3248 OO.ui.OutlineOptionWidget.static.levels = 3;
3249
3250 /* Methods */
3251
3252 /**
3253 * Check if item is movable.
3254 *
3255 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
3256 *
3257 * @return {boolean} Item is movable
3258 */
3259 OO.ui.OutlineOptionWidget.prototype.isMovable = function () {
3260 return this.movable;
3261 };
3262
3263 /**
3264 * Check if item is removable.
3265 *
3266 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
3267 *
3268 * @return {boolean} Item is removable
3269 */
3270 OO.ui.OutlineOptionWidget.prototype.isRemovable = function () {
3271 return this.removable;
3272 };
3273
3274 /**
3275 * Get indentation level.
3276 *
3277 * @return {number} Indentation level
3278 */
3279 OO.ui.OutlineOptionWidget.prototype.getLevel = function () {
3280 return this.level;
3281 };
3282
3283 /**
3284 * @inheritdoc
3285 */
3286 OO.ui.OutlineOptionWidget.prototype.setPressed = function ( state ) {
3287 OO.ui.OutlineOptionWidget.parent.prototype.setPressed.call( this, state );
3288 if ( this.pressed ) {
3289 this.setFlags( { progressive: true } );
3290 } else if ( !this.selected ) {
3291 this.setFlags( { progressive: false } );
3292 }
3293 return this;
3294 };
3295
3296 /**
3297 * Set movability.
3298 *
3299 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
3300 *
3301 * @param {boolean} movable Item is movable
3302 * @chainable
3303 */
3304 OO.ui.OutlineOptionWidget.prototype.setMovable = function ( movable ) {
3305 this.movable = !!movable;
3306 this.updateThemeClasses();
3307 return this;
3308 };
3309
3310 /**
3311 * Set removability.
3312 *
3313 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
3314 *
3315 * @param {boolean} removable Item is removable
3316 * @chainable
3317 */
3318 OO.ui.OutlineOptionWidget.prototype.setRemovable = function ( removable ) {
3319 this.removable = !!removable;
3320 this.updateThemeClasses();
3321 return this;
3322 };
3323
3324 /**
3325 * @inheritdoc
3326 */
3327 OO.ui.OutlineOptionWidget.prototype.setSelected = function ( state ) {
3328 OO.ui.OutlineOptionWidget.parent.prototype.setSelected.call( this, state );
3329 if ( this.selected ) {
3330 this.setFlags( { progressive: true } );
3331 } else {
3332 this.setFlags( { progressive: false } );
3333 }
3334 return this;
3335 };
3336
3337 /**
3338 * Set indentation level.
3339 *
3340 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
3341 * @chainable
3342 */
3343 OO.ui.OutlineOptionWidget.prototype.setLevel = function ( level ) {
3344 var levels = this.constructor.static.levels,
3345 levelClass = this.constructor.static.levelClass,
3346 i = levels;
3347
3348 this.level = level ? Math.max( 0, Math.min( levels - 1, level ) ) : 0;
3349 while ( i-- ) {
3350 if ( this.level === i ) {
3351 this.$element.addClass( levelClass + i );
3352 } else {
3353 this.$element.removeClass( levelClass + i );
3354 }
3355 }
3356 this.updateThemeClasses();
3357
3358 return this;
3359 };
3360
3361 /**
3362 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
3363 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
3364 *
3365 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
3366 *
3367 * @class
3368 * @extends OO.ui.SelectWidget
3369 * @mixins OO.ui.mixin.TabIndexedElement
3370 *
3371 * @constructor
3372 * @param {Object} [config] Configuration options
3373 */
3374 OO.ui.OutlineSelectWidget = function OoUiOutlineSelectWidget( config ) {
3375 // Parent constructor
3376 OO.ui.OutlineSelectWidget.parent.call( this, config );
3377
3378 // Mixin constructors
3379 OO.ui.mixin.TabIndexedElement.call( this, config );
3380
3381 // Events
3382 this.$element.on( {
3383 focus: this.bindKeyDownListener.bind( this ),
3384 blur: this.unbindKeyDownListener.bind( this )
3385 } );
3386
3387 // Initialization
3388 this.$element.addClass( 'oo-ui-outlineSelectWidget' );
3389 };
3390
3391 /* Setup */
3392
3393 OO.inheritClass( OO.ui.OutlineSelectWidget, OO.ui.SelectWidget );
3394 OO.mixinClass( OO.ui.OutlineSelectWidget, OO.ui.mixin.TabIndexedElement );
3395
3396 /**
3397 * ButtonOptionWidget is a special type of {@link OO.ui.mixin.ButtonElement button element} that
3398 * can be selected and configured with data. The class is
3399 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
3400 * [OOjs UI documentation on MediaWiki] [1] for more information.
3401 *
3402 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
3403 *
3404 * @class
3405 * @extends OO.ui.OptionWidget
3406 * @mixins OO.ui.mixin.ButtonElement
3407 * @mixins OO.ui.mixin.IconElement
3408 * @mixins OO.ui.mixin.IndicatorElement
3409 * @mixins OO.ui.mixin.TitledElement
3410 *
3411 * @constructor
3412 * @param {Object} [config] Configuration options
3413 */
3414 OO.ui.ButtonOptionWidget = function OoUiButtonOptionWidget( config ) {
3415 // Configuration initialization
3416 config = config || {};
3417
3418 // Parent constructor
3419 OO.ui.ButtonOptionWidget.parent.call( this, config );
3420
3421 // Mixin constructors
3422 OO.ui.mixin.ButtonElement.call( this, config );
3423 OO.ui.mixin.IconElement.call( this, config );
3424 OO.ui.mixin.IndicatorElement.call( this, config );
3425 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
3426
3427 // Initialization
3428 this.$element.addClass( 'oo-ui-buttonOptionWidget' );
3429 this.$button.append( this.$icon, this.$label, this.$indicator );
3430 this.$element.append( this.$button );
3431 };
3432
3433 /* Setup */
3434
3435 OO.inheritClass( OO.ui.ButtonOptionWidget, OO.ui.OptionWidget );
3436 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.ButtonElement );
3437 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.IconElement );
3438 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.IndicatorElement );
3439 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.TitledElement );
3440
3441 /* Static Properties */
3442
3443 /**
3444 * Allow button mouse down events to pass through so they can be handled by the parent select widget
3445 *
3446 * @static
3447 * @inheritdoc
3448 */
3449 OO.ui.ButtonOptionWidget.static.cancelButtonMouseDownEvents = false;
3450
3451 /**
3452 * @static
3453 * @inheritdoc
3454 */
3455 OO.ui.ButtonOptionWidget.static.highlightable = false;
3456
3457 /* Methods */
3458
3459 /**
3460 * @inheritdoc
3461 */
3462 OO.ui.ButtonOptionWidget.prototype.setSelected = function ( state ) {
3463 OO.ui.ButtonOptionWidget.parent.prototype.setSelected.call( this, state );
3464
3465 if ( this.constructor.static.selectable ) {
3466 this.setActive( state );
3467 }
3468
3469 return this;
3470 };
3471
3472 /**
3473 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
3474 * button options and is used together with
3475 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
3476 * highlighting, choosing, and selecting mutually exclusive options. Please see
3477 * the [OOjs UI documentation on MediaWiki] [1] for more information.
3478 *
3479 * @example
3480 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
3481 * var option1 = new OO.ui.ButtonOptionWidget( {
3482 * data: 1,
3483 * label: 'Option 1',
3484 * title: 'Button option 1'
3485 * } );
3486 *
3487 * var option2 = new OO.ui.ButtonOptionWidget( {
3488 * data: 2,
3489 * label: 'Option 2',
3490 * title: 'Button option 2'
3491 * } );
3492 *
3493 * var option3 = new OO.ui.ButtonOptionWidget( {
3494 * data: 3,
3495 * label: 'Option 3',
3496 * title: 'Button option 3'
3497 * } );
3498 *
3499 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
3500 * items: [ option1, option2, option3 ]
3501 * } );
3502 * $( 'body' ).append( buttonSelect.$element );
3503 *
3504 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
3505 *
3506 * @class
3507 * @extends OO.ui.SelectWidget
3508 * @mixins OO.ui.mixin.TabIndexedElement
3509 *
3510 * @constructor
3511 * @param {Object} [config] Configuration options
3512 */
3513 OO.ui.ButtonSelectWidget = function OoUiButtonSelectWidget( config ) {
3514 // Parent constructor
3515 OO.ui.ButtonSelectWidget.parent.call( this, config );
3516
3517 // Mixin constructors
3518 OO.ui.mixin.TabIndexedElement.call( this, config );
3519
3520 // Events
3521 this.$element.on( {
3522 focus: this.bindKeyDownListener.bind( this ),
3523 blur: this.unbindKeyDownListener.bind( this )
3524 } );
3525
3526 // Initialization
3527 this.$element.addClass( 'oo-ui-buttonSelectWidget' );
3528 };
3529
3530 /* Setup */
3531
3532 OO.inheritClass( OO.ui.ButtonSelectWidget, OO.ui.SelectWidget );
3533 OO.mixinClass( OO.ui.ButtonSelectWidget, OO.ui.mixin.TabIndexedElement );
3534
3535 /**
3536 * TabOptionWidget is an item in a {@link OO.ui.TabSelectWidget TabSelectWidget}.
3537 *
3538 * Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}, which contain
3539 * {@link OO.ui.TabPanelLayout tab panel layouts}. See {@link OO.ui.IndexLayout IndexLayout}
3540 * for an example.
3541 *
3542 * @class
3543 * @extends OO.ui.OptionWidget
3544 *
3545 * @constructor
3546 * @param {Object} [config] Configuration options
3547 */
3548 OO.ui.TabOptionWidget = function OoUiTabOptionWidget( config ) {
3549 // Configuration initialization
3550 config = config || {};
3551
3552 // Parent constructor
3553 OO.ui.TabOptionWidget.parent.call( this, config );
3554
3555 // Initialization
3556 this.$element.addClass( 'oo-ui-tabOptionWidget' );
3557 };
3558
3559 /* Setup */
3560
3561 OO.inheritClass( OO.ui.TabOptionWidget, OO.ui.OptionWidget );
3562
3563 /* Static Properties */
3564
3565 /**
3566 * @static
3567 * @inheritdoc
3568 */
3569 OO.ui.TabOptionWidget.static.highlightable = false;
3570
3571 /**
3572 * TabSelectWidget is a list that contains {@link OO.ui.TabOptionWidget tab options}
3573 *
3574 * **Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}.**
3575 *
3576 * @class
3577 * @extends OO.ui.SelectWidget
3578 * @mixins OO.ui.mixin.TabIndexedElement
3579 *
3580 * @constructor
3581 * @param {Object} [config] Configuration options
3582 */
3583 OO.ui.TabSelectWidget = function OoUiTabSelectWidget( config ) {
3584 // Parent constructor
3585 OO.ui.TabSelectWidget.parent.call( this, config );
3586
3587 // Mixin constructors
3588 OO.ui.mixin.TabIndexedElement.call( this, config );
3589
3590 // Events
3591 this.$element.on( {
3592 focus: this.bindKeyDownListener.bind( this ),
3593 blur: this.unbindKeyDownListener.bind( this )
3594 } );
3595
3596 // Initialization
3597 this.$element.addClass( 'oo-ui-tabSelectWidget' );
3598 };
3599
3600 /* Setup */
3601
3602 OO.inheritClass( OO.ui.TabSelectWidget, OO.ui.SelectWidget );
3603 OO.mixinClass( OO.ui.TabSelectWidget, OO.ui.mixin.TabIndexedElement );
3604
3605 /**
3606 * CapsuleItemWidgets are used within a {@link OO.ui.CapsuleMultiselectWidget
3607 * CapsuleMultiselectWidget} to display the selected items.
3608 *
3609 * @class
3610 * @extends OO.ui.Widget
3611 * @mixins OO.ui.mixin.ItemWidget
3612 * @mixins OO.ui.mixin.LabelElement
3613 * @mixins OO.ui.mixin.FlaggedElement
3614 * @mixins OO.ui.mixin.TabIndexedElement
3615 *
3616 * @constructor
3617 * @param {Object} [config] Configuration options
3618 */
3619 OO.ui.CapsuleItemWidget = function OoUiCapsuleItemWidget( config ) {
3620 // Configuration initialization
3621 config = config || {};
3622
3623 // Parent constructor
3624 OO.ui.CapsuleItemWidget.parent.call( this, config );
3625
3626 // Mixin constructors
3627 OO.ui.mixin.ItemWidget.call( this );
3628 OO.ui.mixin.LabelElement.call( this, config );
3629 OO.ui.mixin.FlaggedElement.call( this, config );
3630 OO.ui.mixin.TabIndexedElement.call( this, config );
3631
3632 // Events
3633 this.closeButton = new OO.ui.ButtonWidget( {
3634 framed: false,
3635 icon: 'close',
3636 tabIndex: -1,
3637 title: OO.ui.msg( 'ooui-item-remove' )
3638 } ).on( 'click', this.onCloseClick.bind( this ) );
3639
3640 this.on( 'disable', function ( disabled ) {
3641 this.closeButton.setDisabled( disabled );
3642 }.bind( this ) );
3643
3644 // Initialization
3645 this.$element
3646 .on( {
3647 click: this.onClick.bind( this ),
3648 keydown: this.onKeyDown.bind( this )
3649 } )
3650 .addClass( 'oo-ui-capsuleItemWidget' )
3651 .append( this.$label, this.closeButton.$element );
3652 };
3653
3654 /* Setup */
3655
3656 OO.inheritClass( OO.ui.CapsuleItemWidget, OO.ui.Widget );
3657 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.ItemWidget );
3658 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.LabelElement );
3659 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.FlaggedElement );
3660 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.TabIndexedElement );
3661
3662 /* Methods */
3663
3664 /**
3665 * Handle close icon clicks
3666 */
3667 OO.ui.CapsuleItemWidget.prototype.onCloseClick = function () {
3668 var element = this.getElementGroup();
3669
3670 if ( element && $.isFunction( element.removeItems ) ) {
3671 element.removeItems( [ this ] );
3672 element.focus();
3673 }
3674 };
3675
3676 /**
3677 * Handle click event for the entire capsule
3678 */
3679 OO.ui.CapsuleItemWidget.prototype.onClick = function () {
3680 var element = this.getElementGroup();
3681
3682 if ( !this.isDisabled() && element && $.isFunction( element.editItem ) ) {
3683 element.editItem( this );
3684 }
3685 };
3686
3687 /**
3688 * Handle keyDown event for the entire capsule
3689 *
3690 * @param {jQuery.Event} e Key down event
3691 */
3692 OO.ui.CapsuleItemWidget.prototype.onKeyDown = function ( e ) {
3693 var element = this.getElementGroup();
3694
3695 if ( e.keyCode === OO.ui.Keys.BACKSPACE || e.keyCode === OO.ui.Keys.DELETE ) {
3696 element.removeItems( [ this ] );
3697 element.focus();
3698 return false;
3699 } else if ( e.keyCode === OO.ui.Keys.ENTER ) {
3700 element.editItem( this );
3701 return false;
3702 } else if ( e.keyCode === OO.ui.Keys.LEFT ) {
3703 element.getPreviousItem( this ).focus();
3704 } else if ( e.keyCode === OO.ui.Keys.RIGHT ) {
3705 element.getNextItem( this ).focus();
3706 }
3707 };
3708
3709 /**
3710 * CapsuleMultiselectWidgets are something like a {@link OO.ui.ComboBoxInputWidget combo box widget}
3711 * that allows for selecting multiple values.
3712 *
3713 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
3714 *
3715 * @example
3716 * // Example: A CapsuleMultiselectWidget.
3717 * var capsule = new OO.ui.CapsuleMultiselectWidget( {
3718 * label: 'CapsuleMultiselectWidget',
3719 * selected: [ 'Option 1', 'Option 3' ],
3720 * menu: {
3721 * items: [
3722 * new OO.ui.MenuOptionWidget( {
3723 * data: 'Option 1',
3724 * label: 'Option One'
3725 * } ),
3726 * new OO.ui.MenuOptionWidget( {
3727 * data: 'Option 2',
3728 * label: 'Option Two'
3729 * } ),
3730 * new OO.ui.MenuOptionWidget( {
3731 * data: 'Option 3',
3732 * label: 'Option Three'
3733 * } ),
3734 * new OO.ui.MenuOptionWidget( {
3735 * data: 'Option 4',
3736 * label: 'Option Four'
3737 * } ),
3738 * new OO.ui.MenuOptionWidget( {
3739 * data: 'Option 5',
3740 * label: 'Option Five'
3741 * } )
3742 * ]
3743 * }
3744 * } );
3745 * $( 'body' ).append( capsule.$element );
3746 *
3747 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
3748 *
3749 * @class
3750 * @extends OO.ui.Widget
3751 * @mixins OO.ui.mixin.GroupElement
3752 * @mixins OO.ui.mixin.PopupElement
3753 * @mixins OO.ui.mixin.TabIndexedElement
3754 * @mixins OO.ui.mixin.IndicatorElement
3755 * @mixins OO.ui.mixin.IconElement
3756 * @uses OO.ui.CapsuleItemWidget
3757 * @uses OO.ui.MenuSelectWidget
3758 *
3759 * @constructor
3760 * @param {Object} [config] Configuration options
3761 * @cfg {string} [placeholder] Placeholder text
3762 * @cfg {boolean} [allowArbitrary=false] Allow data items to be added even if not present in the menu.
3763 * @cfg {boolean} [allowDuplicates=false] Allow duplicate items to be added.
3764 * @cfg {Object} [menu] (required) Configuration options to pass to the
3765 * {@link OO.ui.MenuSelectWidget menu select widget}.
3766 * @cfg {Object} [popup] Configuration options to pass to the {@link OO.ui.PopupWidget popup widget}.
3767 * If specified, this popup will be shown instead of the menu (but the menu
3768 * will still be used for item labels and allowArbitrary=false). The widgets
3769 * in the popup should use {@link #addItemsFromData} or {@link #addItems} as necessary.
3770 * @cfg {jQuery} [$overlay=this.$element] Render the menu or popup into a separate layer.
3771 * This configuration is useful in cases where the expanded menu is larger than
3772 * its containing `<div>`. The specified overlay layer is usually on top of
3773 * the containing `<div>` and has a larger area. By default, the menu uses
3774 * relative positioning.
3775 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
3776 */
3777 OO.ui.CapsuleMultiselectWidget = function OoUiCapsuleMultiselectWidget( config ) {
3778 var $tabFocus;
3779
3780 // Parent constructor
3781 OO.ui.CapsuleMultiselectWidget.parent.call( this, config );
3782
3783 // Configuration initialization
3784 config = $.extend( {
3785 allowArbitrary: false,
3786 allowDuplicates: false,
3787 $overlay: this.$element
3788 }, config );
3789
3790 // Properties (must be set before mixin constructor calls)
3791 this.$handle = $( '<div>' );
3792 this.$input = config.popup ? null : $( '<input>' );
3793 if ( config.placeholder !== undefined && config.placeholder !== '' ) {
3794 this.$input.attr( 'placeholder', config.placeholder );
3795 }
3796
3797 // Mixin constructors
3798 OO.ui.mixin.GroupElement.call( this, config );
3799 if ( config.popup ) {
3800 config.popup = $.extend( {}, config.popup, {
3801 align: 'forwards',
3802 anchor: false
3803 } );
3804 OO.ui.mixin.PopupElement.call( this, config );
3805 $tabFocus = $( '<span>' );
3806 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: $tabFocus } ) );
3807 } else {
3808 this.popup = null;
3809 $tabFocus = null;
3810 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
3811 }
3812 OO.ui.mixin.IndicatorElement.call( this, config );
3813 OO.ui.mixin.IconElement.call( this, config );
3814
3815 // Properties
3816 this.$content = $( '<div>' );
3817 this.allowArbitrary = config.allowArbitrary;
3818 this.allowDuplicates = config.allowDuplicates;
3819 this.$overlay = config.$overlay;
3820 this.menu = new OO.ui.MenuSelectWidget( $.extend(
3821 {
3822 widget: this,
3823 $input: this.$input,
3824 $floatableContainer: this.$element,
3825 filterFromInput: true,
3826 disabled: this.isDisabled()
3827 },
3828 config.menu
3829 ) );
3830
3831 // Events
3832 if ( this.popup ) {
3833 $tabFocus.on( {
3834 focus: this.focus.bind( this )
3835 } );
3836 this.popup.$element.on( 'focusout', this.onPopupFocusOut.bind( this ) );
3837 if ( this.popup.$autoCloseIgnore ) {
3838 this.popup.$autoCloseIgnore.on( 'focusout', this.onPopupFocusOut.bind( this ) );
3839 }
3840 this.popup.connect( this, {
3841 toggle: function ( visible ) {
3842 $tabFocus.toggle( !visible );
3843 }
3844 } );
3845 } else {
3846 this.$input.on( {
3847 focus: this.onInputFocus.bind( this ),
3848 blur: this.onInputBlur.bind( this ),
3849 'propertychange change click mouseup keydown keyup input cut paste select focus':
3850 OO.ui.debounce( this.updateInputSize.bind( this ) ),
3851 keydown: this.onKeyDown.bind( this ),
3852 keypress: this.onKeyPress.bind( this )
3853 } );
3854 }
3855 this.menu.connect( this, {
3856 choose: 'onMenuChoose',
3857 toggle: 'onMenuToggle',
3858 add: 'onMenuItemsChange',
3859 remove: 'onMenuItemsChange'
3860 } );
3861 this.$handle.on( {
3862 mousedown: this.onMouseDown.bind( this )
3863 } );
3864
3865 // Initialization
3866 if ( this.$input ) {
3867 this.$input.prop( 'disabled', this.isDisabled() );
3868 this.$input.attr( {
3869 role: 'combobox',
3870 'aria-owns': this.menu.getElementId(),
3871 'aria-autocomplete': 'list'
3872 } );
3873 }
3874 if ( config.data ) {
3875 this.setItemsFromData( config.data );
3876 }
3877 this.$content.addClass( 'oo-ui-capsuleMultiselectWidget-content' )
3878 .append( this.$group );
3879 this.$group.addClass( 'oo-ui-capsuleMultiselectWidget-group' );
3880 this.$handle.addClass( 'oo-ui-capsuleMultiselectWidget-handle' )
3881 .append( this.$indicator, this.$icon, this.$content );
3882 this.$element.addClass( 'oo-ui-capsuleMultiselectWidget' )
3883 .append( this.$handle );
3884 if ( this.popup ) {
3885 this.popup.$element.addClass( 'oo-ui-capsuleMultiselectWidget-popup' );
3886 this.$content.append( $tabFocus );
3887 this.$overlay.append( this.popup.$element );
3888 } else {
3889 this.$content.append( this.$input );
3890 this.$overlay.append( this.menu.$element );
3891 }
3892 if ( $tabFocus ) {
3893 $tabFocus.addClass( 'oo-ui-capsuleMultiselectWidget-focusTrap' );
3894 }
3895
3896 // Input size needs to be calculated after everything else is rendered
3897 setTimeout( function () {
3898 if ( this.$input ) {
3899 this.updateInputSize();
3900 }
3901 }.bind( this ) );
3902
3903 this.onMenuItemsChange();
3904 };
3905
3906 /* Setup */
3907
3908 OO.inheritClass( OO.ui.CapsuleMultiselectWidget, OO.ui.Widget );
3909 OO.mixinClass( OO.ui.CapsuleMultiselectWidget, OO.ui.mixin.GroupElement );
3910 OO.mixinClass( OO.ui.CapsuleMultiselectWidget, OO.ui.mixin.PopupElement );
3911 OO.mixinClass( OO.ui.CapsuleMultiselectWidget, OO.ui.mixin.TabIndexedElement );
3912 OO.mixinClass( OO.ui.CapsuleMultiselectWidget, OO.ui.mixin.IndicatorElement );
3913 OO.mixinClass( OO.ui.CapsuleMultiselectWidget, OO.ui.mixin.IconElement );
3914
3915 /* Events */
3916
3917 /**
3918 * @event change
3919 *
3920 * A change event is emitted when the set of selected items changes.
3921 *
3922 * @param {Mixed[]} datas Data of the now-selected items
3923 */
3924
3925 /**
3926 * @event resize
3927 *
3928 * A resize event is emitted when the widget's dimensions change to accomodate newly added items or
3929 * current user input.
3930 */
3931
3932 /* Methods */
3933
3934 /**
3935 * Construct a OO.ui.CapsuleItemWidget (or a subclass thereof) from given label and data.
3936 * May return `null` if the given label and data are not valid.
3937 *
3938 * @protected
3939 * @param {Mixed} data Custom data of any type.
3940 * @param {string} label The label text.
3941 * @return {OO.ui.CapsuleItemWidget|null}
3942 */
3943 OO.ui.CapsuleMultiselectWidget.prototype.createItemWidget = function ( data, label ) {
3944 if ( label === '' ) {
3945 return null;
3946 }
3947 return new OO.ui.CapsuleItemWidget( { data: data, label: label } );
3948 };
3949
3950 /**
3951 * @inheritdoc
3952 */
3953 OO.ui.CapsuleMultiselectWidget.prototype.getInputId = function () {
3954 if ( !this.$input ) {
3955 return null;
3956 }
3957 return OO.ui.mixin.TabIndexedElement.prototype.getInputId.call( this );
3958 };
3959
3960 /**
3961 * Get the data of the items in the capsule
3962 *
3963 * @return {Mixed[]}
3964 */
3965 OO.ui.CapsuleMultiselectWidget.prototype.getItemsData = function () {
3966 return this.getItems().map( function ( item ) {
3967 return item.data;
3968 } );
3969 };
3970
3971 /**
3972 * Set the items in the capsule by providing data
3973 *
3974 * @chainable
3975 * @param {Mixed[]} datas
3976 * @return {OO.ui.CapsuleMultiselectWidget}
3977 */
3978 OO.ui.CapsuleMultiselectWidget.prototype.setItemsFromData = function ( datas ) {
3979 var widget = this,
3980 menu = this.menu,
3981 items = this.getItems();
3982
3983 $.each( datas, function ( i, data ) {
3984 var j, label,
3985 item = menu.getItemFromData( data );
3986
3987 if ( item ) {
3988 label = item.label;
3989 } else if ( widget.allowArbitrary ) {
3990 label = String( data );
3991 } else {
3992 return;
3993 }
3994
3995 item = null;
3996 for ( j = 0; j < items.length; j++ ) {
3997 if ( items[ j ].data === data && items[ j ].label === label ) {
3998 item = items[ j ];
3999 items.splice( j, 1 );
4000 break;
4001 }
4002 }
4003 if ( !item ) {
4004 item = widget.createItemWidget( data, label );
4005 }
4006 if ( item ) {
4007 widget.addItems( [ item ], i );
4008 }
4009 } );
4010
4011 if ( items.length ) {
4012 widget.removeItems( items );
4013 }
4014
4015 return this;
4016 };
4017
4018 /**
4019 * Add items to the capsule by providing their data
4020 *
4021 * @chainable
4022 * @param {Mixed[]} datas
4023 * @return {OO.ui.CapsuleMultiselectWidget}
4024 */
4025 OO.ui.CapsuleMultiselectWidget.prototype.addItemsFromData = function ( datas ) {
4026 var widget = this,
4027 menu = this.menu,
4028 items = [];
4029
4030 $.each( datas, function ( i, data ) {
4031 var item;
4032
4033 if ( !widget.getItemFromData( data ) || widget.allowDuplicates ) {
4034 item = menu.getItemFromData( data );
4035 if ( item ) {
4036 item = widget.createItemWidget( data, item.label );
4037 } else if ( widget.allowArbitrary ) {
4038 item = widget.createItemWidget( data, String( data ) );
4039 }
4040 if ( item ) {
4041 items.push( item );
4042 }
4043 }
4044 } );
4045
4046 if ( items.length ) {
4047 this.addItems( items );
4048 }
4049
4050 return this;
4051 };
4052
4053 /**
4054 * Add items to the capsule by providing a label
4055 *
4056 * @param {string} label
4057 * @return {boolean} Whether the item was added or not
4058 */
4059 OO.ui.CapsuleMultiselectWidget.prototype.addItemFromLabel = function ( label ) {
4060 var item, items;
4061 item = this.menu.getItemFromLabel( label, true );
4062 if ( item ) {
4063 this.addItemsFromData( [ item.data ] );
4064 return true;
4065 } else if ( this.allowArbitrary ) {
4066 items = this.getItems();
4067 this.addItemsFromData( [ label ] );
4068 return !OO.compare( this.getItems(), items );
4069 }
4070 return false;
4071 };
4072
4073 /**
4074 * Remove items by data
4075 *
4076 * @chainable
4077 * @param {Mixed[]} datas
4078 * @return {OO.ui.CapsuleMultiselectWidget}
4079 */
4080 OO.ui.CapsuleMultiselectWidget.prototype.removeItemsFromData = function ( datas ) {
4081 var widget = this,
4082 items = [];
4083
4084 $.each( datas, function ( i, data ) {
4085 var item = widget.getItemFromData( data );
4086 if ( item ) {
4087 items.push( item );
4088 }
4089 } );
4090
4091 if ( items.length ) {
4092 this.removeItems( items );
4093 }
4094
4095 return this;
4096 };
4097
4098 /**
4099 * @inheritdoc
4100 */
4101 OO.ui.CapsuleMultiselectWidget.prototype.addItems = function ( items ) {
4102 var same, i, l,
4103 oldItems = this.items.slice();
4104
4105 OO.ui.mixin.GroupElement.prototype.addItems.call( this, items );
4106
4107 if ( this.items.length !== oldItems.length ) {
4108 same = false;
4109 } else {
4110 same = true;
4111 for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
4112 same = same && this.items[ i ] === oldItems[ i ];
4113 }
4114 }
4115 if ( !same ) {
4116 this.emit( 'change', this.getItemsData() );
4117 this.updateInputSize();
4118 }
4119
4120 return this;
4121 };
4122
4123 /**
4124 * Removes the item from the list and copies its label to `this.$input`.
4125 *
4126 * @param {Object} item
4127 */
4128 OO.ui.CapsuleMultiselectWidget.prototype.editItem = function ( item ) {
4129 this.addItemFromLabel( this.$input.val() );
4130 this.clearInput();
4131 this.$input.val( item.label );
4132 this.updateInputSize();
4133 this.focus();
4134 this.menu.updateItemVisibility(); // Hack, we shouldn't be calling this method directly
4135 this.removeItems( [ item ] );
4136 };
4137
4138 /**
4139 * @inheritdoc
4140 */
4141 OO.ui.CapsuleMultiselectWidget.prototype.removeItems = function ( items ) {
4142 var same, i, l,
4143 oldItems = this.items.slice();
4144
4145 OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items );
4146
4147 if ( this.items.length !== oldItems.length ) {
4148 same = false;
4149 } else {
4150 same = true;
4151 for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
4152 same = same && this.items[ i ] === oldItems[ i ];
4153 }
4154 }
4155 if ( !same ) {
4156 this.emit( 'change', this.getItemsData() );
4157 this.updateInputSize();
4158 }
4159
4160 return this;
4161 };
4162
4163 /**
4164 * @inheritdoc
4165 */
4166 OO.ui.CapsuleMultiselectWidget.prototype.clearItems = function () {
4167 if ( this.items.length ) {
4168 OO.ui.mixin.GroupElement.prototype.clearItems.call( this );
4169 this.emit( 'change', this.getItemsData() );
4170 this.updateInputSize();
4171 }
4172 return this;
4173 };
4174
4175 /**
4176 * Given an item, returns the item after it. If its the last item,
4177 * returns `this.$input`. If no item is passed, returns the very first
4178 * item.
4179 *
4180 * @param {OO.ui.CapsuleItemWidget} [item]
4181 * @return {OO.ui.CapsuleItemWidget|jQuery|boolean}
4182 */
4183 OO.ui.CapsuleMultiselectWidget.prototype.getNextItem = function ( item ) {
4184 var itemIndex;
4185
4186 if ( item === undefined ) {
4187 return this.items[ 0 ];
4188 }
4189
4190 itemIndex = this.items.indexOf( item );
4191 if ( itemIndex < 0 ) { // Item not in list
4192 return false;
4193 } else if ( itemIndex === this.items.length - 1 ) { // Last item
4194 return this.$input;
4195 } else {
4196 return this.items[ itemIndex + 1 ];
4197 }
4198 };
4199
4200 /**
4201 * Given an item, returns the item before it. If its the first item,
4202 * returns `this.$input`. If no item is passed, returns the very last
4203 * item.
4204 *
4205 * @param {OO.ui.CapsuleItemWidget} [item]
4206 * @return {OO.ui.CapsuleItemWidget|jQuery|boolean}
4207 */
4208 OO.ui.CapsuleMultiselectWidget.prototype.getPreviousItem = function ( item ) {
4209 var itemIndex;
4210
4211 if ( item === undefined ) {
4212 return this.items[ this.items.length - 1 ];
4213 }
4214
4215 itemIndex = this.items.indexOf( item );
4216 if ( itemIndex < 0 ) { // Item not in list
4217 return false;
4218 } else if ( itemIndex === 0 ) { // First item
4219 return this.$input;
4220 } else {
4221 return this.items[ itemIndex - 1 ];
4222 }
4223 };
4224
4225 /**
4226 * Get the capsule widget's menu.
4227 *
4228 * @return {OO.ui.MenuSelectWidget} Menu widget
4229 */
4230 OO.ui.CapsuleMultiselectWidget.prototype.getMenu = function () {
4231 return this.menu;
4232 };
4233
4234 /**
4235 * Handle focus events
4236 *
4237 * @private
4238 * @param {jQuery.Event} event
4239 */
4240 OO.ui.CapsuleMultiselectWidget.prototype.onInputFocus = function () {
4241 if ( !this.isDisabled() ) {
4242 this.updateInputSize();
4243 this.menu.toggle( true );
4244 }
4245 };
4246
4247 /**
4248 * Handle blur events
4249 *
4250 * @private
4251 * @param {jQuery.Event} event
4252 */
4253 OO.ui.CapsuleMultiselectWidget.prototype.onInputBlur = function () {
4254 this.addItemFromLabel( this.$input.val() );
4255 this.clearInput();
4256 };
4257
4258 /**
4259 * Handles popup focus out events.
4260 *
4261 * @private
4262 * @param {jQuery.Event} e Focus out event
4263 */
4264 OO.ui.CapsuleMultiselectWidget.prototype.onPopupFocusOut = function () {
4265 var widget = this.popup;
4266
4267 setTimeout( function () {
4268 if (
4269 widget.isVisible() &&
4270 !OO.ui.contains( widget.$element.add( widget.$autoCloseIgnore ).get(), document.activeElement, true )
4271 ) {
4272 widget.toggle( false );
4273 }
4274 } );
4275 };
4276
4277 /**
4278 * Handle mouse down events.
4279 *
4280 * @private
4281 * @param {jQuery.Event} e Mouse down event
4282 */
4283 OO.ui.CapsuleMultiselectWidget.prototype.onMouseDown = function ( e ) {
4284 if ( e.which === OO.ui.MouseButtons.LEFT ) {
4285 this.focus();
4286 return false;
4287 } else {
4288 this.updateInputSize();
4289 }
4290 };
4291
4292 /**
4293 * Handle key press events.
4294 *
4295 * @private
4296 * @param {jQuery.Event} e Key press event
4297 */
4298 OO.ui.CapsuleMultiselectWidget.prototype.onKeyPress = function ( e ) {
4299 if ( !this.isDisabled() ) {
4300 if ( e.which === OO.ui.Keys.ESCAPE ) {
4301 this.clearInput();
4302 return false;
4303 }
4304
4305 if ( !this.popup ) {
4306 this.menu.toggle( true );
4307 if ( e.which === OO.ui.Keys.ENTER ) {
4308 if ( this.addItemFromLabel( this.$input.val() ) ) {
4309 this.clearInput();
4310 }
4311 return false;
4312 }
4313
4314 // Make sure the input gets resized.
4315 setTimeout( this.updateInputSize.bind( this ), 0 );
4316 }
4317 }
4318 };
4319
4320 /**
4321 * Handle key down events.
4322 *
4323 * @private
4324 * @param {jQuery.Event} e Key down event
4325 */
4326 OO.ui.CapsuleMultiselectWidget.prototype.onKeyDown = function ( e ) {
4327 if (
4328 !this.isDisabled() &&
4329 this.$input.val() === '' &&
4330 this.items.length
4331 ) {
4332 // 'keypress' event is not triggered for Backspace
4333 if ( e.keyCode === OO.ui.Keys.BACKSPACE ) {
4334 if ( e.metaKey || e.ctrlKey ) {
4335 this.removeItems( this.items.slice( -1 ) );
4336 } else {
4337 this.editItem( this.items[ this.items.length - 1 ] );
4338 }
4339 return false;
4340 } else if ( e.keyCode === OO.ui.Keys.LEFT ) {
4341 this.getPreviousItem().focus();
4342 } else if ( e.keyCode === OO.ui.Keys.RIGHT ) {
4343 this.getNextItem().focus();
4344 }
4345 }
4346 };
4347
4348 /**
4349 * Update the dimensions of the text input field to encompass all available area.
4350 *
4351 * @private
4352 * @param {jQuery.Event} e Event of some sort
4353 */
4354 OO.ui.CapsuleMultiselectWidget.prototype.updateInputSize = function () {
4355 var $lastItem, direction, contentWidth, currentWidth, bestWidth;
4356 if ( this.$input && !this.isDisabled() ) {
4357 this.$input.css( 'width', '1em' );
4358 $lastItem = this.$group.children().last();
4359 direction = OO.ui.Element.static.getDir( this.$handle );
4360
4361 // Get the width of the input with the placeholder text as
4362 // the value and save it so that we don't keep recalculating
4363 if (
4364 this.contentWidthWithPlaceholder === undefined &&
4365 this.$input.val() === '' &&
4366 this.$input.attr( 'placeholder' ) !== undefined
4367 ) {
4368 this.$input.val( this.$input.attr( 'placeholder' ) );
4369 this.contentWidthWithPlaceholder = this.$input[ 0 ].scrollWidth;
4370 this.$input.val( '' );
4371
4372 }
4373
4374 // Always keep the input wide enough for the placeholder text
4375 contentWidth = Math.max(
4376 this.$input[ 0 ].scrollWidth,
4377 // undefined arguments in Math.max lead to NaN
4378 ( this.contentWidthWithPlaceholder === undefined ) ?
4379 0 : this.contentWidthWithPlaceholder
4380 );
4381 currentWidth = this.$input.width();
4382
4383 if ( contentWidth < currentWidth ) {
4384 this.updateIfHeightChanged();
4385 // All is fine, don't perform expensive calculations
4386 return;
4387 }
4388
4389 if ( $lastItem.length === 0 ) {
4390 bestWidth = this.$content.innerWidth();
4391 } else {
4392 bestWidth = direction === 'ltr' ?
4393 this.$content.innerWidth() - $lastItem.position().left - $lastItem.outerWidth() :
4394 $lastItem.position().left;
4395 }
4396
4397 // Some safety margin for sanity, because I *really* don't feel like finding out where the few
4398 // pixels this is off by are coming from.
4399 bestWidth -= 10;
4400 if ( contentWidth > bestWidth ) {
4401 // This will result in the input getting shifted to the next line
4402 bestWidth = this.$content.innerWidth() - 10;
4403 }
4404 this.$input.width( Math.floor( bestWidth ) );
4405 this.updateIfHeightChanged();
4406 } else {
4407 this.updateIfHeightChanged();
4408 }
4409 };
4410
4411 /**
4412 * Determine if widget height changed, and if so, update menu position and emit 'resize' event.
4413 *
4414 * @private
4415 */
4416 OO.ui.CapsuleMultiselectWidget.prototype.updateIfHeightChanged = function () {
4417 var height = this.$element.height();
4418 if ( height !== this.height ) {
4419 this.height = height;
4420 this.menu.position();
4421 if ( this.popup ) {
4422 this.popup.updateDimensions();
4423 }
4424 this.emit( 'resize' );
4425 }
4426 };
4427
4428 /**
4429 * Handle menu choose events.
4430 *
4431 * @private
4432 * @param {OO.ui.OptionWidget} item Chosen item
4433 */
4434 OO.ui.CapsuleMultiselectWidget.prototype.onMenuChoose = function ( item ) {
4435 if ( item && item.isVisible() ) {
4436 this.addItemsFromData( [ item.getData() ] );
4437 this.clearInput();
4438 }
4439 };
4440
4441 /**
4442 * Handle menu toggle events.
4443 *
4444 * @private
4445 * @param {boolean} isVisible Menu toggle event
4446 */
4447 OO.ui.CapsuleMultiselectWidget.prototype.onMenuToggle = function ( isVisible ) {
4448 this.$element.toggleClass( 'oo-ui-capsuleMultiselectWidget-open', isVisible );
4449 };
4450
4451 /**
4452 * Handle menu item change events.
4453 *
4454 * @private
4455 */
4456 OO.ui.CapsuleMultiselectWidget.prototype.onMenuItemsChange = function () {
4457 this.setItemsFromData( this.getItemsData() );
4458 this.$element.toggleClass( 'oo-ui-capsuleMultiselectWidget-empty', this.menu.isEmpty() );
4459 };
4460
4461 /**
4462 * Clear the input field
4463 *
4464 * @private
4465 */
4466 OO.ui.CapsuleMultiselectWidget.prototype.clearInput = function () {
4467 if ( this.$input ) {
4468 this.$input.val( '' );
4469 this.updateInputSize();
4470 }
4471 if ( this.popup ) {
4472 this.popup.toggle( false );
4473 }
4474 this.menu.toggle( false );
4475 this.menu.selectItem();
4476 this.menu.highlightItem();
4477 };
4478
4479 /**
4480 * @inheritdoc
4481 */
4482 OO.ui.CapsuleMultiselectWidget.prototype.setDisabled = function ( disabled ) {
4483 var i, len;
4484
4485 // Parent method
4486 OO.ui.CapsuleMultiselectWidget.parent.prototype.setDisabled.call( this, disabled );
4487
4488 if ( this.$input ) {
4489 this.$input.prop( 'disabled', this.isDisabled() );
4490 }
4491 if ( this.menu ) {
4492 this.menu.setDisabled( this.isDisabled() );
4493 }
4494 if ( this.popup ) {
4495 this.popup.setDisabled( this.isDisabled() );
4496 }
4497
4498 if ( this.items ) {
4499 for ( i = 0, len = this.items.length; i < len; i++ ) {
4500 this.items[ i ].updateDisabled();
4501 }
4502 }
4503
4504 return this;
4505 };
4506
4507 /**
4508 * Focus the widget
4509 *
4510 * @chainable
4511 */
4512 OO.ui.CapsuleMultiselectWidget.prototype.focus = function () {
4513 if ( !this.isDisabled() ) {
4514 if ( this.popup ) {
4515 this.popup.setSize( this.$handle.outerWidth() );
4516 this.popup.toggle( true );
4517 OO.ui.findFocusable( this.popup.$element ).focus();
4518 } else {
4519 OO.ui.mixin.TabIndexedElement.prototype.focus.call( this );
4520 }
4521 }
4522 return this;
4523 };
4524
4525 /**
4526 * TagItemWidgets are used within a {@link OO.ui.TagMultiselectWidget
4527 * TagMultiselectWidget} to display the selected items.
4528 *
4529 * @class
4530 * @extends OO.ui.Widget
4531 * @mixins OO.ui.mixin.ItemWidget
4532 * @mixins OO.ui.mixin.LabelElement
4533 * @mixins OO.ui.mixin.FlaggedElement
4534 * @mixins OO.ui.mixin.TabIndexedElement
4535 * @mixins OO.ui.mixin.DraggableElement
4536 *
4537 * @constructor
4538 * @param {Object} [config] Configuration object
4539 * @cfg {boolean} [valid=true] Item is valid
4540 */
4541 OO.ui.TagItemWidget = function OoUiTagItemWidget( config ) {
4542 config = config || {};
4543
4544 // Parent constructor
4545 OO.ui.TagItemWidget.parent.call( this, config );
4546
4547 // Mixin constructors
4548 OO.ui.mixin.ItemWidget.call( this );
4549 OO.ui.mixin.LabelElement.call( this, config );
4550 OO.ui.mixin.FlaggedElement.call( this, config );
4551 OO.ui.mixin.TabIndexedElement.call( this, config );
4552 OO.ui.mixin.DraggableElement.call( this, config );
4553
4554 this.valid = config.valid === undefined ? true : !!config.valid;
4555
4556 this.closeButton = new OO.ui.ButtonWidget( {
4557 framed: false,
4558 icon: 'close',
4559 tabIndex: -1,
4560 title: OO.ui.msg( 'ooui-item-remove' )
4561 } );
4562 this.closeButton.setDisabled( this.isDisabled() );
4563
4564 // Events
4565 this.closeButton
4566 .connect( this, { click: 'remove' } );
4567 this.$element
4568 .on( 'click', this.select.bind( this ) )
4569 .on( 'keydown', this.onKeyDown.bind( this ) )
4570 // Prevent propagation of mousedown; the tag item "lives" in the
4571 // clickable area of the TagMultiselectWidget, which listens to
4572 // mousedown to open the menu or popup. We want to prevent that
4573 // for clicks specifically on the tag itself, so the actions taken
4574 // are more deliberate. When the tag is clicked, it will emit the
4575 // selection event (similar to how #OO.ui.MultioptionWidget emits 'change')
4576 // and can be handled separately.
4577 .on( 'mousedown', function ( e ) { e.stopPropagation(); } );
4578
4579 // Initialization
4580 this.$element
4581 .addClass( 'oo-ui-tagItemWidget' )
4582 .append( this.$label, this.closeButton.$element );
4583 };
4584
4585 /* Initialization */
4586
4587 OO.inheritClass( OO.ui.TagItemWidget, OO.ui.Widget );
4588 OO.mixinClass( OO.ui.TagItemWidget, OO.ui.mixin.ItemWidget );
4589 OO.mixinClass( OO.ui.TagItemWidget, OO.ui.mixin.LabelElement );
4590 OO.mixinClass( OO.ui.TagItemWidget, OO.ui.mixin.FlaggedElement );
4591 OO.mixinClass( OO.ui.TagItemWidget, OO.ui.mixin.TabIndexedElement );
4592 OO.mixinClass( OO.ui.TagItemWidget, OO.ui.mixin.DraggableElement );
4593
4594 /* Events */
4595
4596 /**
4597 * @event remove
4598 *
4599 * A remove action was performed on the item
4600 */
4601
4602 /**
4603 * @event navigate
4604 * @param {string} direction Direction of the movement, forward or backwards
4605 *
4606 * A navigate action was performed on the item
4607 */
4608
4609 /**
4610 * @event select
4611 *
4612 * The tag widget was selected. This can occur when the widget
4613 * is either clicked or enter was pressed on it.
4614 */
4615
4616 /**
4617 * @event valid
4618 * @param {boolean} isValid Item is valid
4619 *
4620 * Item validity has changed
4621 */
4622
4623 /* Methods */
4624
4625 /**
4626 * @inheritdoc
4627 */
4628 OO.ui.TagItemWidget.prototype.setDisabled = function ( state ) {
4629 // Parent method
4630 OO.ui.TagItemWidget.parent.prototype.setDisabled.call( this, state );
4631
4632 if ( this.closeButton ) {
4633 this.closeButton.setDisabled( state );
4634 }
4635 return this;
4636 };
4637
4638 /**
4639 * Handle removal of the item
4640 *
4641 * This is mainly for extensibility concerns, so other children
4642 * of this class can change the behavior if they need to. This
4643 * is called by both clicking the 'remove' button but also
4644 * on keypress, which is harder to override if needed.
4645 *
4646 * @fires remove
4647 */
4648 OO.ui.TagItemWidget.prototype.remove = function () {
4649 if ( !this.isDisabled() ) {
4650 this.emit( 'remove' );
4651 }
4652 };
4653
4654 /**
4655 * Handle a keydown event on the widget
4656 *
4657 * @fires navigate
4658 * @fires remove
4659 * @param {jQuery.Event} e Key down event
4660 * @return {boolean|undefined} false to stop the operation
4661 */
4662 OO.ui.TagItemWidget.prototype.onKeyDown = function ( e ) {
4663 var movement;
4664
4665 if ( e.keyCode === OO.ui.Keys.BACKSPACE || e.keyCode === OO.ui.Keys.DELETE ) {
4666 this.remove();
4667 return false;
4668 } else if ( e.keyCode === OO.ui.Keys.ENTER ) {
4669 this.select();
4670 return false;
4671 } else if (
4672 e.keyCode === OO.ui.Keys.LEFT ||
4673 e.keyCode === OO.ui.Keys.RIGHT
4674 ) {
4675 if ( OO.ui.Element.static.getDir( this.$element ) === 'rtl' ) {
4676 movement = {
4677 left: 'forwards',
4678 right: 'backwards'
4679 };
4680 } else {
4681 movement = {
4682 left: 'backwards',
4683 right: 'forwards'
4684 };
4685 }
4686
4687 this.emit(
4688 'navigate',
4689 e.keyCode === OO.ui.Keys.LEFT ?
4690 movement.left : movement.right
4691 );
4692 }
4693 };
4694
4695 /**
4696 * Select this item
4697 *
4698 * @fires select
4699 */
4700 OO.ui.TagItemWidget.prototype.select = function () {
4701 if ( !this.isDisabled() ) {
4702 this.emit( 'select' );
4703 }
4704 };
4705
4706 /**
4707 * Set the valid state of this item
4708 *
4709 * @param {boolean} [valid] Item is valid
4710 * @fires valid
4711 */
4712 OO.ui.TagItemWidget.prototype.toggleValid = function ( valid ) {
4713 valid = valid === undefined ? !this.valid : !!valid;
4714
4715 if ( this.valid !== valid ) {
4716 this.valid = valid;
4717
4718 this.setFlags( { invalid: !this.valid } );
4719
4720 this.emit( 'valid', this.valid );
4721 }
4722 };
4723
4724 /**
4725 * Check whether the item is valid
4726 *
4727 * @return {boolean} Item is valid
4728 */
4729 OO.ui.TagItemWidget.prototype.isValid = function () {
4730 return this.valid;
4731 };
4732
4733 /**
4734 * A basic tag multiselect widget, similar in concept to {@link OO.ui.ComboBoxInputWidget combo box widget}
4735 * that allows the user to add multiple values that are displayed in a tag area.
4736 *
4737 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
4738 *
4739 * This widget is a base widget; see {@link OO.ui.MenuTagMultiselectWidget MenuTagMultiselectWidget} and
4740 * {@link OO.ui.PopupTagMultiselectWidget PopupTagMultiselectWidget} for the implementations that use
4741 * a menu and a popup respectively.
4742 *
4743 * @example
4744 * // Example: A basic TagMultiselectWidget.
4745 * var widget = new OO.ui.TagMultiselectWidget( {
4746 * inputPosition: 'outline',
4747 * allowedValues: [ 'Option 1', 'Option 2', 'Option 3' ],
4748 * selected: [ 'Option 1' ]
4749 * } );
4750 * $( 'body' ).append( widget.$element );
4751 *
4752 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
4753 *
4754 * @class
4755 * @extends OO.ui.Widget
4756 * @mixins OO.ui.mixin.GroupWidget
4757 * @mixins OO.ui.mixin.DraggableGroupElement
4758 * @mixins OO.ui.mixin.IndicatorElement
4759 * @mixins OO.ui.mixin.IconElement
4760 * @mixins OO.ui.mixin.TabIndexedElement
4761 * @mixins OO.ui.mixin.FlaggedElement
4762 *
4763 * @constructor
4764 * @param {Object} config Configuration object
4765 * @cfg {Object} [input] Configuration options for the input widget
4766 * @cfg {OO.ui.InputWidget} [inputWidget] An optional input widget. If given, it will
4767 * replace the input widget used in the TagMultiselectWidget. If not given,
4768 * TagMultiselectWidget creates its own.
4769 * @cfg {boolean} [inputPosition='inline'] Position of the input. Options are:
4770 * - inline: The input is invisible, but exists inside the tag list, so
4771 * the user types into the tag groups to add tags.
4772 * - outline: The input is underneath the tag area.
4773 * - none: No input supplied
4774 * @cfg {boolean} [allowEditTags=true] Allow editing of the tags by clicking them
4775 * @cfg {boolean} [allowArbitrary=false] Allow data items to be added even if
4776 * not present in the menu.
4777 * @cfg {Object[]} [allowedValues] An array representing the allowed items
4778 * by their datas.
4779 * @cfg {boolean} [allowDuplicates=false] Allow duplicate items to be added
4780 * @cfg {boolean} [allowDisplayInvalidTags=false] Allow the display of
4781 * invalid tags. These tags will display with an invalid state, and
4782 * the widget as a whole will have an invalid state if any invalid tags
4783 * are present.
4784 * @cfg {boolean} [allowReordering=true] Allow reordering of the items
4785 * @cfg {Object[]|String[]} [selected] A set of selected tags. If given,
4786 * these will appear in the tag list on initialization, as long as they
4787 * pass the validity tests.
4788 */
4789 OO.ui.TagMultiselectWidget = function OoUiTagMultiselectWidget( config ) {
4790 var inputEvents,
4791 rAF = window.requestAnimationFrame || setTimeout,
4792 widget = this,
4793 $tabFocus = $( '<span>' )
4794 .addClass( 'oo-ui-tagMultiselectWidget-focusTrap' );
4795
4796 config = config || {};
4797
4798 // Parent constructor
4799 OO.ui.TagMultiselectWidget.parent.call( this, config );
4800
4801 // Mixin constructors
4802 OO.ui.mixin.GroupWidget.call( this, config );
4803 OO.ui.mixin.IndicatorElement.call( this, config );
4804 OO.ui.mixin.IconElement.call( this, config );
4805 OO.ui.mixin.TabIndexedElement.call( this, config );
4806 OO.ui.mixin.FlaggedElement.call( this, config );
4807 OO.ui.mixin.DraggableGroupElement.call( this, config );
4808
4809 this.toggleDraggable(
4810 config.allowReordering === undefined ?
4811 true : !!config.allowReordering
4812 );
4813
4814 this.inputPosition =
4815 this.constructor.static.allowedInputPositions.indexOf( config.inputPosition ) > -1 ?
4816 config.inputPosition : 'inline';
4817 this.allowEditTags = config.allowEditTags === undefined ? true : !!config.allowEditTags;
4818 this.allowArbitrary = !!config.allowArbitrary;
4819 this.allowDuplicates = !!config.allowDuplicates;
4820 this.allowedValues = config.allowedValues || [];
4821 this.allowDisplayInvalidTags = config.allowDisplayInvalidTags;
4822 this.hasInput = this.inputPosition !== 'none';
4823 this.height = null;
4824 this.valid = true;
4825
4826 this.$content = $( '<div>' )
4827 .addClass( 'oo-ui-tagMultiselectWidget-content' );
4828 this.$handle = $( '<div>' )
4829 .addClass( 'oo-ui-tagMultiselectWidget-handle' )
4830 .append(
4831 this.$indicator,
4832 this.$icon,
4833 this.$content
4834 .append(
4835 this.$group
4836 .addClass( 'oo-ui-tagMultiselectWidget-group' )
4837 )
4838 );
4839
4840 // Events
4841 this.aggregate( {
4842 remove: 'itemRemove',
4843 navigate: 'itemNavigate',
4844 select: 'itemSelect'
4845 } );
4846 this.connect( this, {
4847 itemRemove: 'onTagRemove',
4848 itemSelect: 'onTagSelect',
4849 itemNavigate: 'onTagNavigate',
4850 change: 'onChangeTags'
4851 } );
4852 this.$handle.on( {
4853 mousedown: this.onMouseDown.bind( this )
4854 } );
4855
4856 // Initialize
4857 this.$element
4858 .addClass( 'oo-ui-tagMultiselectWidget' )
4859 .append( this.$handle );
4860
4861 if ( this.hasInput ) {
4862 if ( config.inputWidget ) {
4863 this.input = config.inputWidget;
4864 } else {
4865 this.input = new OO.ui.TextInputWidget( $.extend( {
4866 placeholder: config.placeholder,
4867 classes: [ 'oo-ui-tagMultiselectWidget-input' ]
4868 }, config.input ) );
4869 }
4870 this.input.setDisabled( this.isDisabled() );
4871
4872 inputEvents = {
4873 focus: this.onInputFocus.bind( this ),
4874 blur: this.onInputBlur.bind( this ),
4875 'propertychange change click mouseup keydown keyup input cut paste select focus':
4876 OO.ui.debounce( this.updateInputSize.bind( this ) ),
4877 keydown: this.onInputKeyDown.bind( this ),
4878 keypress: this.onInputKeyPress.bind( this )
4879 };
4880
4881 this.input.$input.on( inputEvents );
4882
4883 if ( this.inputPosition === 'outline' ) {
4884 // Override max-height for the input widget
4885 // in the case the widget is outline so it can
4886 // stretch all the way if the widet is wide
4887 this.input.$element.css( 'max-width', 'inherit' );
4888 this.$element
4889 .addClass( 'oo-ui-tagMultiselectWidget-outlined' )
4890 .append( this.input.$element );
4891 } else {
4892 this.$element.addClass( 'oo-ui-tagMultiselectWidget-inlined' );
4893 // HACK: When the widget is using 'inline' input, the
4894 // behavior needs to only use the $input itself
4895 // so we style and size it accordingly (otherwise
4896 // the styling and sizing can get very convoluted
4897 // when the wrapping divs and other elements)
4898 // We are taking advantage of still being able to
4899 // call the widget itself for operations like
4900 // .getValue() and setDisabled() and .focus() but
4901 // having only the $input attached to the DOM
4902 this.$content.append( this.input.$input );
4903 }
4904 } else {
4905 this.$content.append( $tabFocus );
4906 }
4907
4908 this.setTabIndexedElement(
4909 this.hasInput ?
4910 this.input.$input :
4911 $tabFocus
4912 );
4913
4914 if ( config.selected ) {
4915 this.setValue( config.selected );
4916 }
4917
4918 // HACK: Input size needs to be calculated after everything
4919 // else is rendered
4920 rAF( function () {
4921 if ( widget.hasInput ) {
4922 widget.updateInputSize();
4923 }
4924 } );
4925 };
4926
4927 /* Initialization */
4928
4929 OO.inheritClass( OO.ui.TagMultiselectWidget, OO.ui.Widget );
4930 OO.mixinClass( OO.ui.TagMultiselectWidget, OO.ui.mixin.GroupWidget );
4931 OO.mixinClass( OO.ui.TagMultiselectWidget, OO.ui.mixin.DraggableGroupElement );
4932 OO.mixinClass( OO.ui.TagMultiselectWidget, OO.ui.mixin.IndicatorElement );
4933 OO.mixinClass( OO.ui.TagMultiselectWidget, OO.ui.mixin.IconElement );
4934 OO.mixinClass( OO.ui.TagMultiselectWidget, OO.ui.mixin.TabIndexedElement );
4935 OO.mixinClass( OO.ui.TagMultiselectWidget, OO.ui.mixin.FlaggedElement );
4936
4937 /* Static properties */
4938
4939 /**
4940 * Allowed input positions.
4941 * - inline: The input is inside the tag list
4942 * - outline: The input is under the tag list
4943 * - none: There is no input
4944 *
4945 * @property {Array}
4946 */
4947 OO.ui.TagMultiselectWidget.static.allowedInputPositions = [ 'inline', 'outline', 'none' ];
4948
4949 /* Methods */
4950
4951 /**
4952 * Handle mouse down events.
4953 *
4954 * @private
4955 * @param {jQuery.Event} e Mouse down event
4956 * @return {boolean} False to prevent defaults
4957 */
4958 OO.ui.TagMultiselectWidget.prototype.onMouseDown = function ( e ) {
4959 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
4960 this.focus();
4961 return false;
4962 }
4963 };
4964
4965 /**
4966 * Handle key press events.
4967 *
4968 * @private
4969 * @param {jQuery.Event} e Key press event
4970 * @return {boolean} Whether to prevent defaults
4971 */
4972 OO.ui.TagMultiselectWidget.prototype.onInputKeyPress = function ( e ) {
4973 var stopOrContinue,
4974 withMetaKey = e.metaKey || e.ctrlKey;
4975
4976 if ( !this.isDisabled() ) {
4977 if ( e.which === OO.ui.Keys.ENTER ) {
4978 stopOrContinue = this.doInputEnter( e, withMetaKey );
4979 }
4980
4981 // Make sure the input gets resized.
4982 setTimeout( this.updateInputSize.bind( this ), 0 );
4983 return stopOrContinue;
4984 }
4985 };
4986
4987 /**
4988 * Handle key down events.
4989 *
4990 * @private
4991 * @param {jQuery.Event} e Key down event
4992 * @return {boolean}
4993 */
4994 OO.ui.TagMultiselectWidget.prototype.onInputKeyDown = function ( e ) {
4995 var movement, direction,
4996 withMetaKey = e.metaKey || e.ctrlKey;
4997
4998 if ( !this.isDisabled() ) {
4999 // 'keypress' event is not triggered for Backspace
5000 if ( e.keyCode === OO.ui.Keys.BACKSPACE ) {
5001 return this.doInputBackspace( e, withMetaKey );
5002 } else if ( e.keyCode === OO.ui.Keys.ESCAPE ) {
5003 return this.doInputEscape( e );
5004 } else if (
5005 e.keyCode === OO.ui.Keys.LEFT ||
5006 e.keyCode === OO.ui.Keys.RIGHT
5007 ) {
5008 if ( OO.ui.Element.static.getDir( this.$element ) === 'rtl' ) {
5009 movement = {
5010 left: 'forwards',
5011 right: 'backwards'
5012 };
5013 } else {
5014 movement = {
5015 left: 'backwards',
5016 right: 'forwards'
5017 };
5018 }
5019 direction = e.keyCode === OO.ui.Keys.LEFT ?
5020 movement.left : movement.right;
5021
5022 return this.doInputArrow( e, direction, withMetaKey );
5023 }
5024 }
5025 };
5026
5027 /**
5028 * Respond to input focus event
5029 */
5030 OO.ui.TagMultiselectWidget.prototype.onInputFocus = function () {
5031 this.$element.addClass( 'oo-ui-tagMultiselectWidget-focus' );
5032 };
5033
5034 /**
5035 * Respond to input blur event
5036 */
5037 OO.ui.TagMultiselectWidget.prototype.onInputBlur = function () {
5038 this.$element.removeClass( 'oo-ui-tagMultiselectWidget-focus' );
5039 };
5040
5041 /**
5042 * Perform an action after the enter key on the input
5043 *
5044 * @param {jQuery.Event} e Event data
5045 * @param {boolean} [withMetaKey] Whether this key was pressed with
5046 * a meta key like 'ctrl'
5047 * @return {boolean} Whether to prevent defaults
5048 */
5049 OO.ui.TagMultiselectWidget.prototype.doInputEnter = function () {
5050 this.addTagFromInput();
5051 return false;
5052 };
5053
5054 /**
5055 * Perform an action responding to the enter key on the input
5056 *
5057 * @param {jQuery.Event} e Event data
5058 * @param {boolean} [withMetaKey] Whether this key was pressed with
5059 * a meta key like 'ctrl'
5060 * @return {boolean} Whether to prevent defaults
5061 */
5062 OO.ui.TagMultiselectWidget.prototype.doInputBackspace = function ( e, withMetaKey ) {
5063 var items, item;
5064
5065 if (
5066 this.inputPosition === 'inline' &&
5067 this.input.getValue() === '' &&
5068 !this.isEmpty()
5069 ) {
5070 // Delete the last item
5071 items = this.getItems();
5072 item = items[ items.length - 1 ];
5073 this.removeItems( [ item ] );
5074 // If Ctrl/Cmd was pressed, delete item entirely.
5075 // Otherwise put it into the text field for editing.
5076 if ( !withMetaKey ) {
5077 this.input.setValue( item.getData() );
5078 }
5079
5080 return false;
5081 }
5082 };
5083
5084 /**
5085 * Perform an action after the escape key on the input
5086 *
5087 * @param {jQuery.Event} e Event data
5088 */
5089 OO.ui.TagMultiselectWidget.prototype.doInputEscape = function () {
5090 this.clearInput();
5091 };
5092
5093 /**
5094 * Perform an action after the arrow key on the input, select the previous
5095 * or next item from the input.
5096 * See #getPreviousItem and #getNextItem
5097 *
5098 * @param {jQuery.Event} e Event data
5099 * @param {string} direction Direction of the movement; forwards or backwards
5100 * @param {boolean} [withMetaKey] Whether this key was pressed with
5101 * a meta key like 'ctrl'
5102 */
5103 OO.ui.TagMultiselectWidget.prototype.doInputArrow = function ( e, direction ) {
5104 if (
5105 this.inputPosition === 'inline' &&
5106 !this.isEmpty()
5107 ) {
5108 if ( direction === 'backwards' ) {
5109 // Get previous item
5110 this.getPreviousItem().focus();
5111 } else {
5112 // Get next item
5113 this.getNextItem().focus();
5114 }
5115 }
5116 };
5117
5118 /**
5119 * Respond to item select event
5120 *
5121 * @param {OO.ui.TagItemWidget} item Selected item
5122 */
5123 OO.ui.TagMultiselectWidget.prototype.onTagSelect = function ( item ) {
5124 if ( this.hasInput && this.allowEditTags ) {
5125 if ( this.input.getValue() ) {
5126 this.addTagFromInput();
5127 }
5128 // 1. Get the label of the tag into the input
5129 this.input.setValue( item.getData() );
5130 // 2. Remove the tag
5131 this.removeItems( [ item ] );
5132 // 3. Focus the input
5133 this.focus();
5134 }
5135 };
5136
5137 /**
5138 * Respond to change event, where items were added, removed, or cleared.
5139 */
5140 OO.ui.TagMultiselectWidget.prototype.onChangeTags = function () {
5141 this.toggleValid( this.checkValidity() );
5142 if ( this.hasInput ) {
5143 this.updateInputSize();
5144 }
5145 this.updateIfHeightChanged();
5146 };
5147
5148 /**
5149 * @inheritdoc
5150 */
5151 OO.ui.TagMultiselectWidget.prototype.setDisabled = function ( isDisabled ) {
5152 // Parent method
5153 OO.ui.TagMultiselectWidget.parent.prototype.setDisabled.call( this, isDisabled );
5154
5155 if ( this.hasInput && this.input ) {
5156 this.input.setDisabled( !!isDisabled );
5157 }
5158
5159 if ( this.items ) {
5160 this.getItems().forEach( function ( item ) {
5161 item.setDisabled( !!isDisabled );
5162 } );
5163 }
5164 };
5165
5166 /**
5167 * Respond to tag remove event
5168 * @param {OO.ui.TagItemWidget} item Removed tag
5169 */
5170 OO.ui.TagMultiselectWidget.prototype.onTagRemove = function ( item ) {
5171 this.removeTagByData( item.getData() );
5172 };
5173
5174 /**
5175 * Respond to navigate event on the tag
5176 *
5177 * @param {OO.ui.TagItemWidget} item Removed tag
5178 * @param {string} direction Direction of movement; 'forwards' or 'backwards'
5179 */
5180 OO.ui.TagMultiselectWidget.prototype.onTagNavigate = function ( item, direction ) {
5181 if ( direction === 'forwards' ) {
5182 this.getNextItem( item ).focus();
5183 } else {
5184 this.getPreviousItem( item ).focus();
5185 }
5186 };
5187
5188 /**
5189 * Add tag from input value
5190 */
5191 OO.ui.TagMultiselectWidget.prototype.addTagFromInput = function () {
5192 var val = this.input.getValue(),
5193 isValid = this.isAllowedData( val );
5194
5195 if ( !val ) {
5196 return;
5197 }
5198
5199 if ( isValid || this.allowDisplayInvalidTags ) {
5200 this.addTag( val );
5201 this.clearInput();
5202 this.focus();
5203 }
5204 };
5205
5206 /**
5207 * Clear the input
5208 */
5209 OO.ui.TagMultiselectWidget.prototype.clearInput = function () {
5210 this.input.setValue( '' );
5211 };
5212
5213 /**
5214 * Check whether the given value is a duplicate of an existing
5215 * tag already in the list.
5216 *
5217 * @param {string|Object} data Requested value
5218 * @return {boolean} Value is duplicate
5219 */
5220 OO.ui.TagMultiselectWidget.prototype.isDuplicateData = function ( data ) {
5221 return !!this.getItemFromData( data );
5222 };
5223
5224 /**
5225 * Check whether a given value is allowed to be added
5226 *
5227 * @param {string|Object} data Requested value
5228 * @return {boolean} Value is allowed
5229 */
5230 OO.ui.TagMultiselectWidget.prototype.isAllowedData = function ( data ) {
5231 if (
5232 !this.allowDuplicates &&
5233 this.isDuplicateData( data )
5234 ) {
5235 return false;
5236 }
5237
5238 if ( this.allowArbitrary ) {
5239 return true;
5240 }
5241
5242 // Check with allowed values
5243 if (
5244 this.getAllowedValues().some( function ( value ) {
5245 return data === value;
5246 } )
5247 ) {
5248 return true;
5249 }
5250
5251 return false;
5252 };
5253
5254 /**
5255 * Get the allowed values list
5256 *
5257 * @return {string[]} Allowed data values
5258 */
5259 OO.ui.TagMultiselectWidget.prototype.getAllowedValues = function () {
5260 return this.allowedValues;
5261 };
5262
5263 /**
5264 * Add a value to the allowed values list
5265 *
5266 * @param {string} value Allowed data value
5267 */
5268 OO.ui.TagMultiselectWidget.prototype.addAllowedValue = function ( value ) {
5269 if ( this.allowedValues.indexOf( value ) === -1 ) {
5270 this.allowedValues.push( value );
5271 }
5272 };
5273
5274 /**
5275 * Get the datas of the currently selected items
5276 *
5277 * @return {string[]|Object[]} Datas of currently selected items
5278 */
5279 OO.ui.TagMultiselectWidget.prototype.getValue = function () {
5280 return this.getItems()
5281 .filter( function ( item ) {
5282 return item.isValid();
5283 } )
5284 .map( function ( item ) {
5285 return item.getData();
5286 } );
5287 };
5288
5289 /**
5290 * Set the value of this widget by datas.
5291 *
5292 * @param {string|string[]|Object|Object[]} valueObject An object representing the data
5293 * and label of the value. If the widget allows arbitrary values,
5294 * the items will be added as-is. Otherwise, the data value will
5295 * be checked against allowedValues.
5296 * This object must contain at least a data key. Example:
5297 * { data: 'foo', label: 'Foo item' }
5298 * For multiple items, use an array of objects. For example:
5299 * [
5300 * { data: 'foo', label: 'Foo item' },
5301 * { data: 'bar', label: 'Bar item' }
5302 * ]
5303 * Value can also be added with plaintext array, for example:
5304 * [ 'foo', 'bar', 'bla' ] or a single string, like 'foo'
5305 */
5306 OO.ui.TagMultiselectWidget.prototype.setValue = function ( valueObject ) {
5307 valueObject = Array.isArray( valueObject ) ? valueObject : [ valueObject ];
5308
5309 this.clearItems();
5310 valueObject.forEach( function ( obj ) {
5311 if ( typeof obj === 'string' ) {
5312 this.addTag( obj );
5313 } else {
5314 this.addTag( obj.data, obj.label );
5315 }
5316 }.bind( this ) );
5317 };
5318
5319 /**
5320 * Add tag to the display area
5321 *
5322 * @param {string|Object} data Tag data
5323 * @param {string} [label] Tag label. If no label is provided, the
5324 * stringified version of the data will be used instead.
5325 * @return {boolean} Item was added successfully
5326 */
5327 OO.ui.TagMultiselectWidget.prototype.addTag = function ( data, label ) {
5328 var newItemWidget,
5329 isValid = this.isAllowedData( data );
5330
5331 if ( isValid || this.allowDisplayInvalidTags ) {
5332 newItemWidget = this.createTagItemWidget( data, label );
5333 newItemWidget.toggleValid( isValid );
5334 this.addItems( [ newItemWidget ] );
5335 return true;
5336 }
5337 return false;
5338 };
5339
5340 /**
5341 * Remove tag by its data property.
5342 *
5343 * @param {string|Object} data Tag data
5344 */
5345 OO.ui.TagMultiselectWidget.prototype.removeTagByData = function ( data ) {
5346 var item = this.getItemFromData( data );
5347
5348 this.removeItems( [ item ] );
5349 };
5350
5351 /**
5352 * Construct a OO.ui.TagItemWidget (or a subclass thereof) from given label and data.
5353 *
5354 * @protected
5355 * @param {string} data Item data
5356 * @param {string} label The label text.
5357 * @return {OO.ui.TagItemWidget}
5358 */
5359 OO.ui.TagMultiselectWidget.prototype.createTagItemWidget = function ( data, label ) {
5360 label = label || data;
5361
5362 return new OO.ui.TagItemWidget( { data: data, label: label } );
5363 };
5364
5365 /**
5366 * Given an item, returns the item after it. If the item is already the
5367 * last item, return `this.input`. If no item is passed, returns the
5368 * very first item.
5369 *
5370 * @protected
5371 * @param {OO.ui.TagItemWidget} [item] Tag item
5372 * @return {OO.ui.Widget} The next widget available.
5373 */
5374 OO.ui.TagMultiselectWidget.prototype.getNextItem = function ( item ) {
5375 var itemIndex = this.items.indexOf( item );
5376
5377 if ( item === undefined || itemIndex === -1 ) {
5378 return this.items[ 0 ];
5379 }
5380
5381 if ( itemIndex === this.items.length - 1 ) { // Last item
5382 if ( this.hasInput ) {
5383 return this.input;
5384 } else {
5385 // Return first item
5386 return this.items[ 0 ];
5387 }
5388 } else {
5389 return this.items[ itemIndex + 1 ];
5390 }
5391 };
5392
5393 /**
5394 * Given an item, returns the item before it. If the item is already the
5395 * first item, return `this.input`. If no item is passed, returns the
5396 * very last item.
5397 *
5398 * @protected
5399 * @param {OO.ui.TagItemWidget} [item] Tag item
5400 * @return {OO.ui.Widget} The previous widget available.
5401 */
5402 OO.ui.TagMultiselectWidget.prototype.getPreviousItem = function ( item ) {
5403 var itemIndex = this.items.indexOf( item );
5404
5405 if ( item === undefined || itemIndex === -1 ) {
5406 return this.items[ this.items.length - 1 ];
5407 }
5408
5409 if ( itemIndex === 0 ) {
5410 if ( this.hasInput ) {
5411 return this.input;
5412 } else {
5413 // Return the last item
5414 return this.items[ this.items.length - 1 ];
5415 }
5416 } else {
5417 return this.items[ itemIndex - 1 ];
5418 }
5419 };
5420
5421 /**
5422 * Update the dimensions of the text input field to encompass all available area.
5423 * This is especially relevant for when the input is at the edge of a line
5424 * and should get smaller. The usual operation (as an inline-block with min-width)
5425 * does not work in that case, pushing the input downwards to the next line.
5426 *
5427 * @private
5428 */
5429 OO.ui.TagMultiselectWidget.prototype.updateInputSize = function () {
5430 var $lastItem, direction, contentWidth, currentWidth, bestWidth;
5431 if ( this.inputPosition === 'inline' && !this.isDisabled() ) {
5432 if ( this.input.$input[ 0 ].scrollWidth === 0 ) {
5433 // Input appears to be attached but not visible.
5434 // Don't attempt to adjust its size, because our measurements
5435 // are going to fail anyway.
5436 return;
5437 }
5438 this.input.$input.css( 'width', '1em' );
5439 $lastItem = this.$group.children().last();
5440 direction = OO.ui.Element.static.getDir( this.$handle );
5441
5442 // Get the width of the input with the placeholder text as
5443 // the value and save it so that we don't keep recalculating
5444 if (
5445 this.contentWidthWithPlaceholder === undefined &&
5446 this.input.getValue() === '' &&
5447 this.input.$input.attr( 'placeholder' ) !== undefined
5448 ) {
5449 this.input.setValue( this.input.$input.attr( 'placeholder' ) );
5450 this.contentWidthWithPlaceholder = this.input.$input[ 0 ].scrollWidth;
5451 this.input.setValue( '' );
5452
5453 }
5454
5455 // Always keep the input wide enough for the placeholder text
5456 contentWidth = Math.max(
5457 this.input.$input[ 0 ].scrollWidth,
5458 // undefined arguments in Math.max lead to NaN
5459 ( this.contentWidthWithPlaceholder === undefined ) ?
5460 0 : this.contentWidthWithPlaceholder
5461 );
5462 currentWidth = this.input.$input.width();
5463
5464 if ( contentWidth < currentWidth ) {
5465 this.updateIfHeightChanged();
5466 // All is fine, don't perform expensive calculations
5467 return;
5468 }
5469
5470 if ( $lastItem.length === 0 ) {
5471 bestWidth = this.$content.innerWidth();
5472 } else {
5473 bestWidth = direction === 'ltr' ?
5474 this.$content.innerWidth() - $lastItem.position().left - $lastItem.outerWidth() :
5475 $lastItem.position().left;
5476 }
5477
5478 // Some safety margin for sanity, because I *really* don't feel like finding out where the few
5479 // pixels this is off by are coming from.
5480 bestWidth -= 10;
5481 if ( contentWidth > bestWidth ) {
5482 // This will result in the input getting shifted to the next line
5483 bestWidth = this.$content.innerWidth() - 10;
5484 }
5485 this.input.$input.width( Math.floor( bestWidth ) );
5486 this.updateIfHeightChanged();
5487 } else {
5488 this.updateIfHeightChanged();
5489 }
5490 };
5491
5492 /**
5493 * Determine if widget height changed, and if so,
5494 * emit the resize event. This is useful for when there are either
5495 * menus or popups attached to the bottom of the widget, to allow
5496 * them to change their positioning in case the widget moved down
5497 * or up.
5498 *
5499 * @private
5500 */
5501 OO.ui.TagMultiselectWidget.prototype.updateIfHeightChanged = function () {
5502 var height = this.$element.height();
5503 if ( height !== this.height ) {
5504 this.height = height;
5505 this.emit( 'resize' );
5506 }
5507 };
5508
5509 /**
5510 * Check whether all items in the widget are valid
5511 *
5512 * @return {boolean} Widget is valid
5513 */
5514 OO.ui.TagMultiselectWidget.prototype.checkValidity = function () {
5515 return this.getItems().every( function ( item ) {
5516 return item.isValid();
5517 } );
5518 };
5519
5520 /**
5521 * Set the valid state of this item
5522 *
5523 * @param {boolean} [valid] Item is valid
5524 * @fires valid
5525 */
5526 OO.ui.TagMultiselectWidget.prototype.toggleValid = function ( valid ) {
5527 valid = valid === undefined ? !this.valid : !!valid;
5528
5529 if ( this.valid !== valid ) {
5530 this.valid = valid;
5531
5532 this.setFlags( { invalid: !this.valid } );
5533
5534 this.emit( 'valid', this.valid );
5535 }
5536 };
5537
5538 /**
5539 * Get the current valid state of the widget
5540 *
5541 * @return {boolean} Widget is valid
5542 */
5543 OO.ui.TagMultiselectWidget.prototype.isValid = function () {
5544 return this.valid;
5545 };
5546
5547 /**
5548 * PopupTagMultiselectWidget is a {@link OO.ui.TagMultiselectWidget OO.ui.TagMultiselectWidget} intended
5549 * to use a popup. The popup can be configured to have a default input to insert values into the widget.
5550 *
5551 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
5552 *
5553 * @example
5554 * // Example: A basic PopupTagMultiselectWidget.
5555 * var widget = new OO.ui.PopupTagMultiselectWidget();
5556 * $( 'body' ).append( widget.$element );
5557 *
5558 * // Example: A PopupTagMultiselectWidget with an external popup.
5559 * var popupInput = new OO.ui.TextInputWidget(),
5560 * widget = new OO.ui.PopupTagMultiselectWidget( {
5561 * popupInput: popupInput,
5562 * popup: {
5563 * $content: popupInput.$element
5564 * }
5565 * } );
5566 * $( 'body' ).append( widget.$element );
5567 *
5568 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
5569 *
5570 * @class
5571 * @extends OO.ui.TagMultiselectWidget
5572 * @mixins OO.ui.mixin.PopupElement
5573 *
5574 * @param {Object} config Configuration object
5575 * @cfg {jQuery} [$overlay] An overlay for the popup.
5576 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
5577 * @cfg {Object} [popup] Configuration options for the popup
5578 * @cfg {OO.ui.InputWidget} [popupInput] An input widget inside the popup that will be
5579 * focused when the popup is opened and will be used as replacement for the
5580 * general input in the widget.
5581 */
5582 OO.ui.PopupTagMultiselectWidget = function OoUiPopupTagMultiselectWidget( config ) {
5583 var defaultInput,
5584 defaultConfig = { popup: {} };
5585
5586 config = config || {};
5587
5588 // Parent constructor
5589 OO.ui.PopupTagMultiselectWidget.parent.call( this, $.extend( { inputPosition: 'none' }, config ) );
5590
5591 this.$overlay = config.$overlay || this.$element;
5592
5593 if ( !config.popup ) {
5594 // For the default base implementation, we give a popup
5595 // with an input widget inside it. For any other use cases
5596 // the popup needs to be populated externally and the
5597 // event handled to add tags separately and manually
5598 defaultInput = new OO.ui.TextInputWidget();
5599
5600 defaultConfig.popupInput = defaultInput;
5601 defaultConfig.popup.$content = defaultInput.$element;
5602
5603 this.$element.addClass( 'oo-ui-popupTagMultiselectWidget-defaultPopup' );
5604 }
5605
5606 // Add overlay, and add that to the autoCloseIgnore
5607 defaultConfig.popup.$overlay = this.$overlay;
5608 defaultConfig.popup.$autoCloseIgnore = this.hasInput ?
5609 this.input.$element.add( this.$overlay ) : this.$overlay;
5610
5611 // Allow extending any of the above
5612 config = $.extend( defaultConfig, config );
5613
5614 // Mixin constructors
5615 OO.ui.mixin.PopupElement.call( this, config );
5616
5617 if ( this.hasInput ) {
5618 this.input.$input.on( 'focus', this.popup.toggle.bind( this.popup, true ) );
5619 }
5620
5621 // Configuration options
5622 this.popupInput = config.popupInput;
5623 if ( this.popupInput ) {
5624 this.popupInput.connect( this, {
5625 enter: 'onPopupInputEnter'
5626 } );
5627 }
5628
5629 // Events
5630 this.on( 'resize', this.popup.updateDimensions.bind( this.popup ) );
5631 this.popup.connect( this, { toggle: 'onPopupToggle' } );
5632 this.$tabIndexed
5633 .on( 'focus', this.onFocus.bind( this ) );
5634
5635 // Initialize
5636 this.$element
5637 .append( this.popup.$element )
5638 .addClass( 'oo-ui-popupTagMultiselectWidget' );
5639 };
5640
5641 /* Initialization */
5642
5643 OO.inheritClass( OO.ui.PopupTagMultiselectWidget, OO.ui.TagMultiselectWidget );
5644 OO.mixinClass( OO.ui.PopupTagMultiselectWidget, OO.ui.mixin.PopupElement );
5645
5646 /* Methods */
5647
5648 /**
5649 * Focus event handler.
5650 *
5651 * @private
5652 */
5653 OO.ui.PopupTagMultiselectWidget.prototype.onFocus = function () {
5654 this.popup.toggle( true );
5655 };
5656
5657 /**
5658 * Respond to popup toggle event
5659 *
5660 * @param {boolean} isVisible Popup is visible
5661 */
5662 OO.ui.PopupTagMultiselectWidget.prototype.onPopupToggle = function ( isVisible ) {
5663 if ( isVisible && this.popupInput ) {
5664 this.popupInput.focus();
5665 }
5666 };
5667
5668 /**
5669 * Respond to popup input enter event
5670 */
5671 OO.ui.PopupTagMultiselectWidget.prototype.onPopupInputEnter = function () {
5672 if ( this.popupInput ) {
5673 this.addTagByPopupValue( this.popupInput.getValue() );
5674 this.popupInput.setValue( '' );
5675 }
5676 };
5677
5678 /**
5679 * @inheritdoc
5680 */
5681 OO.ui.PopupTagMultiselectWidget.prototype.onTagSelect = function ( item ) {
5682 if ( this.popupInput && this.allowEditTags ) {
5683 this.popupInput.setValue( item.getData() );
5684 this.removeItems( [ item ] );
5685
5686 this.popup.toggle( true );
5687 this.popupInput.focus();
5688 } else {
5689 // Parent
5690 OO.ui.PopupTagMultiselectWidget.parent.prototype.onTagSelect.call( this, item );
5691 }
5692 };
5693
5694 /**
5695 * Add a tag by the popup value.
5696 * Whatever is responsible for setting the value in the popup should call
5697 * this method to add a tag, or use the regular methods like #addTag or
5698 * #setValue directly.
5699 *
5700 * @param {string} data The value of item
5701 * @param {string} [label] The label of the tag. If not given, the data is used.
5702 */
5703 OO.ui.PopupTagMultiselectWidget.prototype.addTagByPopupValue = function ( data, label ) {
5704 this.addTag( data, label );
5705 };
5706
5707 /**
5708 * MenuTagMultiselectWidget is a {@link OO.ui.TagMultiselectWidget OO.ui.TagMultiselectWidget} intended
5709 * to use a menu of selectable options.
5710 *
5711 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
5712 *
5713 * @example
5714 * // Example: A basic MenuTagMultiselectWidget.
5715 * var widget = new OO.ui.MenuTagMultiselectWidget( {
5716 * inputPosition: 'outline',
5717 * options: [
5718 * { data: 'option1', label: 'Option 1' },
5719 * { data: 'option2', label: 'Option 2' },
5720 * { data: 'option3', label: 'Option 3' },
5721 * ],
5722 * selected: [ 'option1', 'option2' ]
5723 * } );
5724 * $( 'body' ).append( widget.$element );
5725 *
5726 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
5727 *
5728 * @class
5729 * @extends OO.ui.TagMultiselectWidget
5730 *
5731 * @constructor
5732 * @param {Object} [config] Configuration object
5733 * @cfg {Object} [menu] Configuration object for the menu widget
5734 * @cfg {jQuery} [$overlay] An overlay for the menu.
5735 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
5736 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
5737 */
5738 OO.ui.MenuTagMultiselectWidget = function OoUiMenuTagMultiselectWidget( config ) {
5739 config = config || {};
5740
5741 // Parent constructor
5742 OO.ui.MenuTagMultiselectWidget.parent.call( this, config );
5743
5744 this.$overlay = config.$overlay || this.$element;
5745
5746 this.menu = this.createMenuWidget( $.extend( {
5747 widget: this,
5748 input: this.hasInput ? this.input : null,
5749 $input: this.hasInput ? this.input.$input : null,
5750 filterFromInput: !!this.hasInput,
5751 $autoCloseIgnore: this.hasInput ?
5752 this.input.$element.add( this.$overlay ) : this.$overlay,
5753 $floatableContainer: this.hasInput && this.inputPosition === 'outline' ?
5754 this.input.$element : this.$element,
5755 $overlay: this.$overlay,
5756 disabled: this.isDisabled()
5757 }, config.menu ) );
5758 this.addOptions( config.options || [] );
5759
5760 // Events
5761 this.menu.connect( this, {
5762 choose: 'onMenuChoose',
5763 toggle: 'onMenuToggle'
5764 } );
5765 if ( this.hasInput ) {
5766 this.input.connect( this, { change: 'onInputChange' } );
5767 }
5768 this.connect( this, { resize: 'onResize' } );
5769
5770 // Initialization
5771 this.$overlay
5772 .append( this.menu.$element );
5773 this.$element
5774 .addClass( 'oo-ui-menuTagMultiselectWidget' );
5775 // TagMultiselectWidget already does this, but it doesn't work right because this.menu is not yet
5776 // set up while the parent constructor runs, and #getAllowedValues rejects everything.
5777 if ( config.selected ) {
5778 this.setValue( config.selected );
5779 }
5780 };
5781
5782 /* Initialization */
5783
5784 OO.inheritClass( OO.ui.MenuTagMultiselectWidget, OO.ui.TagMultiselectWidget );
5785
5786 /* Methods */
5787
5788 /**
5789 * Respond to resize event
5790 */
5791 OO.ui.MenuTagMultiselectWidget.prototype.onResize = function () {
5792 // Reposition the menu
5793 this.menu.position();
5794 };
5795
5796 /**
5797 * @inheritdoc
5798 */
5799 OO.ui.MenuTagMultiselectWidget.prototype.onInputFocus = function () {
5800 // Parent method
5801 OO.ui.MenuTagMultiselectWidget.parent.prototype.onInputFocus.call( this );
5802
5803 this.menu.toggle( true );
5804 };
5805
5806 /**
5807 * Respond to input change event
5808 */
5809 OO.ui.MenuTagMultiselectWidget.prototype.onInputChange = function () {
5810 this.menu.toggle( true );
5811 };
5812
5813 /**
5814 * Respond to menu choose event
5815 *
5816 * @param {OO.ui.OptionWidget} menuItem Chosen menu item
5817 */
5818 OO.ui.MenuTagMultiselectWidget.prototype.onMenuChoose = function ( menuItem ) {
5819 // Add tag
5820 this.addTag( menuItem.getData(), menuItem.getLabel() );
5821 };
5822
5823 /**
5824 * Respond to menu toggle event. Reset item highlights on hide.
5825 *
5826 * @param {boolean} isVisible The menu is visible
5827 */
5828 OO.ui.MenuTagMultiselectWidget.prototype.onMenuToggle = function ( isVisible ) {
5829 if ( !isVisible ) {
5830 this.menu.selectItem( null );
5831 this.menu.highlightItem( null );
5832 }
5833 };
5834
5835 /**
5836 * @inheritdoc
5837 */
5838 OO.ui.MenuTagMultiselectWidget.prototype.onTagSelect = function ( tagItem ) {
5839 var menuItem = this.menu.getItemFromData( tagItem.getData() );
5840 // Override the base behavior from TagMultiselectWidget; the base behavior
5841 // in TagMultiselectWidget is to remove the tag to edit it in the input,
5842 // but in our case, we want to utilize the menu selection behavior, and
5843 // definitely not remove the item.
5844
5845 // Select the menu item
5846 this.menu.selectItem( menuItem );
5847
5848 this.focus();
5849 };
5850
5851 /**
5852 * @inheritdoc
5853 */
5854 OO.ui.MenuTagMultiselectWidget.prototype.addTagFromInput = function () {
5855 var inputValue = this.input.getValue(),
5856 validated = false,
5857 highlightedItem = this.menu.findHighlightedItem(),
5858 item = this.menu.getItemFromData( inputValue );
5859
5860 // Override the parent method so we add from the menu
5861 // rather than directly from the input
5862
5863 // Look for a highlighted item first
5864 if ( highlightedItem ) {
5865 validated = this.addTag( highlightedItem.getData(), highlightedItem.getLabel() );
5866 } else if ( item ) {
5867 // Look for the element that fits the data
5868 validated = this.addTag( item.getData(), item.getLabel() );
5869 } else {
5870 // Otherwise, add the tag - the method will only add if the
5871 // tag is valid or if invalid tags are allowed
5872 validated = this.addTag( inputValue );
5873 }
5874
5875 if ( validated ) {
5876 this.clearInput();
5877 this.focus();
5878 }
5879 };
5880
5881 /**
5882 * Return the visible items in the menu. This is mainly used for when
5883 * the menu is filtering results.
5884 *
5885 * @return {OO.ui.MenuOptionWidget[]} Visible results
5886 */
5887 OO.ui.MenuTagMultiselectWidget.prototype.getMenuVisibleItems = function () {
5888 return this.menu.getItems().filter( function ( menuItem ) {
5889 return menuItem.isVisible();
5890 } );
5891 };
5892
5893 /**
5894 * Create the menu for this widget. This is in a separate method so that
5895 * child classes can override this without polluting the constructor with
5896 * unnecessary extra objects that will be overidden.
5897 *
5898 * @param {Object} menuConfig Configuration options
5899 * @return {OO.ui.MenuSelectWidget} Menu widget
5900 */
5901 OO.ui.MenuTagMultiselectWidget.prototype.createMenuWidget = function ( menuConfig ) {
5902 return new OO.ui.MenuSelectWidget( menuConfig );
5903 };
5904
5905 /**
5906 * Add options to the menu
5907 *
5908 * @param {Object[]} menuOptions Object defining options
5909 */
5910 OO.ui.MenuTagMultiselectWidget.prototype.addOptions = function ( menuOptions ) {
5911 var widget = this,
5912 items = menuOptions.map( function ( obj ) {
5913 return widget.createMenuOptionWidget( obj.data, obj.label );
5914 } );
5915
5916 this.menu.addItems( items );
5917 };
5918
5919 /**
5920 * Create a menu option widget.
5921 *
5922 * @param {string} data Item data
5923 * @param {string} [label] Item label
5924 * @return {OO.ui.OptionWidget} Option widget
5925 */
5926 OO.ui.MenuTagMultiselectWidget.prototype.createMenuOptionWidget = function ( data, label ) {
5927 return new OO.ui.MenuOptionWidget( {
5928 data: data,
5929 label: label || data
5930 } );
5931 };
5932
5933 /**
5934 * Get the menu
5935 *
5936 * @return {OO.ui.MenuSelectWidget} Menu
5937 */
5938 OO.ui.MenuTagMultiselectWidget.prototype.getMenu = function () {
5939 return this.menu;
5940 };
5941
5942 /**
5943 * Get the allowed values list
5944 *
5945 * @return {string[]} Allowed data values
5946 */
5947 OO.ui.MenuTagMultiselectWidget.prototype.getAllowedValues = function () {
5948 var menuDatas = [];
5949 if ( this.menu ) {
5950 // If the parent constructor is calling us, we're not ready yet, this.menu is not set up.
5951 menuDatas = this.menu.getItems().map( function ( menuItem ) {
5952 return menuItem.getData();
5953 } );
5954 }
5955 return this.allowedValues.concat( menuDatas );
5956 };
5957
5958 /**
5959 * SelectFileWidgets allow for selecting files, using the HTML5 File API. These
5960 * widgets can be configured with {@link OO.ui.mixin.IconElement icons} and {@link
5961 * OO.ui.mixin.IndicatorElement indicators}.
5962 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
5963 *
5964 * @example
5965 * // Example of a file select widget
5966 * var selectFile = new OO.ui.SelectFileWidget();
5967 * $( 'body' ).append( selectFile.$element );
5968 *
5969 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets
5970 *
5971 * @class
5972 * @extends OO.ui.Widget
5973 * @mixins OO.ui.mixin.IconElement
5974 * @mixins OO.ui.mixin.IndicatorElement
5975 * @mixins OO.ui.mixin.PendingElement
5976 * @mixins OO.ui.mixin.LabelElement
5977 *
5978 * @constructor
5979 * @param {Object} [config] Configuration options
5980 * @cfg {string[]|null} [accept=null] MIME types to accept. null accepts all types.
5981 * @cfg {string} [placeholder] Text to display when no file is selected.
5982 * @cfg {string} [notsupported] Text to display when file support is missing in the browser.
5983 * @cfg {boolean} [droppable=true] Whether to accept files by drag and drop.
5984 * @cfg {boolean} [showDropTarget=false] Whether to show a drop target. Requires droppable to be true.
5985 * @cfg {number} [thumbnailSizeLimit=20] File size limit in MiB above which to not try and show a
5986 * preview (for performance)
5987 */
5988 OO.ui.SelectFileWidget = function OoUiSelectFileWidget( config ) {
5989 var dragHandler;
5990
5991 // Configuration initialization
5992 config = $.extend( {
5993 accept: null,
5994 placeholder: OO.ui.msg( 'ooui-selectfile-placeholder' ),
5995 notsupported: OO.ui.msg( 'ooui-selectfile-not-supported' ),
5996 droppable: true,
5997 showDropTarget: false,
5998 thumbnailSizeLimit: 20
5999 }, config );
6000
6001 // Parent constructor
6002 OO.ui.SelectFileWidget.parent.call( this, config );
6003
6004 // Mixin constructors
6005 OO.ui.mixin.IconElement.call( this, config );
6006 OO.ui.mixin.IndicatorElement.call( this, config );
6007 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$info } ) );
6008 OO.ui.mixin.LabelElement.call( this, config );
6009
6010 // Properties
6011 this.$info = $( '<span>' );
6012 this.showDropTarget = config.showDropTarget;
6013 this.thumbnailSizeLimit = config.thumbnailSizeLimit;
6014 this.isSupported = this.constructor.static.isSupported();
6015 this.currentFile = null;
6016 if ( Array.isArray( config.accept ) ) {
6017 this.accept = config.accept;
6018 } else {
6019 this.accept = null;
6020 }
6021 this.placeholder = config.placeholder;
6022 this.notsupported = config.notsupported;
6023 this.onFileSelectedHandler = this.onFileSelected.bind( this );
6024
6025 this.selectButton = new OO.ui.ButtonWidget( {
6026 classes: [ 'oo-ui-selectFileWidget-selectButton' ],
6027 label: OO.ui.msg( 'ooui-selectfile-button-select' ),
6028 disabled: this.disabled || !this.isSupported
6029 } );
6030
6031 this.clearButton = new OO.ui.ButtonWidget( {
6032 classes: [ 'oo-ui-selectFileWidget-clearButton' ],
6033 framed: false,
6034 icon: 'close',
6035 disabled: this.disabled
6036 } );
6037
6038 // Events
6039 this.selectButton.$button.on( {
6040 keypress: this.onKeyPress.bind( this )
6041 } );
6042 this.clearButton.connect( this, {
6043 click: 'onClearClick'
6044 } );
6045 if ( config.droppable ) {
6046 dragHandler = this.onDragEnterOrOver.bind( this );
6047 this.$element.on( {
6048 dragenter: dragHandler,
6049 dragover: dragHandler,
6050 dragleave: this.onDragLeave.bind( this ),
6051 drop: this.onDrop.bind( this )
6052 } );
6053 }
6054
6055 // Initialization
6056 this.addInput();
6057 this.$label.addClass( 'oo-ui-selectFileWidget-label' );
6058 this.$info
6059 .addClass( 'oo-ui-selectFileWidget-info' )
6060 .append( this.$icon, this.$label, this.clearButton.$element, this.$indicator );
6061
6062 if ( config.droppable && config.showDropTarget ) {
6063 this.selectButton.setIcon( 'upload' );
6064 this.$thumbnail = $( '<div>' ).addClass( 'oo-ui-selectFileWidget-thumbnail' );
6065 this.setPendingElement( this.$thumbnail );
6066 this.$element
6067 .addClass( 'oo-ui-selectFileWidget-dropTarget oo-ui-selectFileWidget' )
6068 .on( {
6069 click: this.onDropTargetClick.bind( this )
6070 } )
6071 .append(
6072 this.$thumbnail,
6073 this.$info,
6074 this.selectButton.$element,
6075 $( '<span>' )
6076 .addClass( 'oo-ui-selectFileWidget-dropLabel' )
6077 .text( OO.ui.msg( 'ooui-selectfile-dragdrop-placeholder' ) )
6078 );
6079 } else {
6080 this.$element
6081 .addClass( 'oo-ui-selectFileWidget' )
6082 .append( this.$info, this.selectButton.$element );
6083 }
6084 this.updateUI();
6085 };
6086
6087 /* Setup */
6088
6089 OO.inheritClass( OO.ui.SelectFileWidget, OO.ui.Widget );
6090 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IconElement );
6091 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IndicatorElement );
6092 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.PendingElement );
6093 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.LabelElement );
6094
6095 /* Static Properties */
6096
6097 /**
6098 * Check if this widget is supported
6099 *
6100 * @static
6101 * @return {boolean}
6102 */
6103 OO.ui.SelectFileWidget.static.isSupported = function () {
6104 var $input;
6105 if ( OO.ui.SelectFileWidget.static.isSupportedCache === null ) {
6106 $input = $( '<input>' ).attr( 'type', 'file' );
6107 OO.ui.SelectFileWidget.static.isSupportedCache = $input[ 0 ].files !== undefined;
6108 }
6109 return OO.ui.SelectFileWidget.static.isSupportedCache;
6110 };
6111
6112 OO.ui.SelectFileWidget.static.isSupportedCache = null;
6113
6114 /* Events */
6115
6116 /**
6117 * @event change
6118 *
6119 * A change event is emitted when the on/off state of the toggle changes.
6120 *
6121 * @param {File|null} value New value
6122 */
6123
6124 /* Methods */
6125
6126 /**
6127 * Get the current value of the field
6128 *
6129 * @return {File|null}
6130 */
6131 OO.ui.SelectFileWidget.prototype.getValue = function () {
6132 return this.currentFile;
6133 };
6134
6135 /**
6136 * Set the current value of the field
6137 *
6138 * @param {File|null} file File to select
6139 */
6140 OO.ui.SelectFileWidget.prototype.setValue = function ( file ) {
6141 if ( this.currentFile !== file ) {
6142 this.currentFile = file;
6143 this.updateUI();
6144 this.emit( 'change', this.currentFile );
6145 }
6146 };
6147
6148 /**
6149 * Focus the widget.
6150 *
6151 * Focusses the select file button.
6152 *
6153 * @chainable
6154 */
6155 OO.ui.SelectFileWidget.prototype.focus = function () {
6156 this.selectButton.focus();
6157 return this;
6158 };
6159
6160 /**
6161 * Blur the widget.
6162 *
6163 * @chainable
6164 */
6165 OO.ui.SelectFileWidget.prototype.blur = function () {
6166 this.selectButton.blur();
6167 return this;
6168 };
6169
6170 /**
6171 * @inheritdoc
6172 */
6173 OO.ui.SelectFileWidget.prototype.simulateLabelClick = function () {
6174 this.focus();
6175 };
6176
6177 /**
6178 * Update the user interface when a file is selected or unselected
6179 *
6180 * @protected
6181 */
6182 OO.ui.SelectFileWidget.prototype.updateUI = function () {
6183 var $label;
6184 if ( !this.isSupported ) {
6185 this.$element.addClass( 'oo-ui-selectFileWidget-notsupported' );
6186 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
6187 this.setLabel( this.notsupported );
6188 } else {
6189 this.$element.addClass( 'oo-ui-selectFileWidget-supported' );
6190 if ( this.currentFile ) {
6191 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
6192 $label = $( [] );
6193 $label = $label.add(
6194 $( '<span>' )
6195 .addClass( 'oo-ui-selectFileWidget-fileName' )
6196 .text( this.currentFile.name )
6197 );
6198 this.setLabel( $label );
6199
6200 if ( this.showDropTarget ) {
6201 this.pushPending();
6202 this.loadAndGetImageUrl().done( function ( url ) {
6203 this.$thumbnail.css( 'background-image', 'url( ' + url + ' )' );
6204 }.bind( this ) ).fail( function () {
6205 this.$thumbnail.append(
6206 new OO.ui.IconWidget( {
6207 icon: 'attachment',
6208 classes: [ 'oo-ui-selectFileWidget-noThumbnail-icon' ]
6209 } ).$element
6210 );
6211 }.bind( this ) ).always( function () {
6212 this.popPending();
6213 }.bind( this ) );
6214 this.$element.off( 'click' );
6215 }
6216 } else {
6217 if ( this.showDropTarget ) {
6218 this.$element.off( 'click' );
6219 this.$element.on( {
6220 click: this.onDropTargetClick.bind( this )
6221 } );
6222 this.$thumbnail
6223 .empty()
6224 .css( 'background-image', '' );
6225 }
6226 this.$element.addClass( 'oo-ui-selectFileWidget-empty' );
6227 this.setLabel( this.placeholder );
6228 }
6229 }
6230 };
6231
6232 /**
6233 * If the selected file is an image, get its URL and load it.
6234 *
6235 * @return {jQuery.Promise} Promise resolves with the image URL after it has loaded
6236 */
6237 OO.ui.SelectFileWidget.prototype.loadAndGetImageUrl = function () {
6238 var deferred = $.Deferred(),
6239 file = this.currentFile,
6240 reader = new FileReader();
6241
6242 if (
6243 file &&
6244 ( OO.getProp( file, 'type' ) || '' ).indexOf( 'image/' ) === 0 &&
6245 file.size < this.thumbnailSizeLimit * 1024 * 1024
6246 ) {
6247 reader.onload = function ( event ) {
6248 var img = document.createElement( 'img' );
6249 img.addEventListener( 'load', function () {
6250 if (
6251 img.naturalWidth === 0 ||
6252 img.naturalHeight === 0 ||
6253 img.complete === false
6254 ) {
6255 deferred.reject();
6256 } else {
6257 deferred.resolve( event.target.result );
6258 }
6259 } );
6260 img.src = event.target.result;
6261 };
6262 reader.readAsDataURL( file );
6263 } else {
6264 deferred.reject();
6265 }
6266
6267 return deferred.promise();
6268 };
6269
6270 /**
6271 * Add the input to the widget
6272 *
6273 * @private
6274 */
6275 OO.ui.SelectFileWidget.prototype.addInput = function () {
6276 if ( this.$input ) {
6277 this.$input.remove();
6278 }
6279
6280 if ( !this.isSupported ) {
6281 this.$input = null;
6282 return;
6283 }
6284
6285 this.$input = $( '<input>' ).attr( 'type', 'file' );
6286 this.$input.on( 'change', this.onFileSelectedHandler );
6287 this.$input.on( 'click', function ( e ) {
6288 // Prevents dropTarget to get clicked which calls
6289 // a click on this input
6290 e.stopPropagation();
6291 } );
6292 this.$input.attr( {
6293 tabindex: -1
6294 } );
6295 if ( this.accept ) {
6296 this.$input.attr( 'accept', this.accept.join( ', ' ) );
6297 }
6298 this.selectButton.$button.append( this.$input );
6299 };
6300
6301 /**
6302 * Determine if we should accept this file
6303 *
6304 * @private
6305 * @param {string} mimeType File MIME type
6306 * @return {boolean}
6307 */
6308 OO.ui.SelectFileWidget.prototype.isAllowedType = function ( mimeType ) {
6309 var i, mimeTest;
6310
6311 if ( !this.accept || !mimeType ) {
6312 return true;
6313 }
6314
6315 for ( i = 0; i < this.accept.length; i++ ) {
6316 mimeTest = this.accept[ i ];
6317 if ( mimeTest === mimeType ) {
6318 return true;
6319 } else if ( mimeTest.substr( -2 ) === '/*' ) {
6320 mimeTest = mimeTest.substr( 0, mimeTest.length - 1 );
6321 if ( mimeType.substr( 0, mimeTest.length ) === mimeTest ) {
6322 return true;
6323 }
6324 }
6325 }
6326
6327 return false;
6328 };
6329
6330 /**
6331 * Handle file selection from the input
6332 *
6333 * @private
6334 * @param {jQuery.Event} e
6335 */
6336 OO.ui.SelectFileWidget.prototype.onFileSelected = function ( e ) {
6337 var file = OO.getProp( e.target, 'files', 0 ) || null;
6338
6339 if ( file && !this.isAllowedType( file.type ) ) {
6340 file = null;
6341 }
6342
6343 this.setValue( file );
6344 this.addInput();
6345 };
6346
6347 /**
6348 * Handle clear button click events.
6349 *
6350 * @private
6351 */
6352 OO.ui.SelectFileWidget.prototype.onClearClick = function () {
6353 this.setValue( null );
6354 return false;
6355 };
6356
6357 /**
6358 * Handle key press events.
6359 *
6360 * @private
6361 * @param {jQuery.Event} e Key press event
6362 */
6363 OO.ui.SelectFileWidget.prototype.onKeyPress = function ( e ) {
6364 if ( this.isSupported && !this.isDisabled() && this.$input &&
6365 ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
6366 ) {
6367 this.$input.click();
6368 return false;
6369 }
6370 };
6371
6372 /**
6373 * Handle drop target click events.
6374 *
6375 * @private
6376 * @param {jQuery.Event} e Key press event
6377 */
6378 OO.ui.SelectFileWidget.prototype.onDropTargetClick = function () {
6379 if ( this.isSupported && !this.isDisabled() && this.$input ) {
6380 this.$input.click();
6381 return false;
6382 }
6383 };
6384
6385 /**
6386 * Handle drag enter and over events
6387 *
6388 * @private
6389 * @param {jQuery.Event} e Drag event
6390 */
6391 OO.ui.SelectFileWidget.prototype.onDragEnterOrOver = function ( e ) {
6392 var itemOrFile,
6393 droppableFile = false,
6394 dt = e.originalEvent.dataTransfer;
6395
6396 e.preventDefault();
6397 e.stopPropagation();
6398
6399 if ( this.isDisabled() || !this.isSupported ) {
6400 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
6401 dt.dropEffect = 'none';
6402 return false;
6403 }
6404
6405 // DataTransferItem and File both have a type property, but in Chrome files
6406 // have no information at this point.
6407 itemOrFile = OO.getProp( dt, 'items', 0 ) || OO.getProp( dt, 'files', 0 );
6408 if ( itemOrFile ) {
6409 if ( this.isAllowedType( itemOrFile.type ) ) {
6410 droppableFile = true;
6411 }
6412 // dt.types is Array-like, but not an Array
6413 } else if ( Array.prototype.indexOf.call( OO.getProp( dt, 'types' ) || [], 'Files' ) !== -1 ) {
6414 // File information is not available at this point for security so just assume
6415 // it is acceptable for now.
6416 // https://bugzilla.mozilla.org/show_bug.cgi?id=640534
6417 droppableFile = true;
6418 }
6419
6420 this.$element.toggleClass( 'oo-ui-selectFileWidget-canDrop', droppableFile );
6421 if ( !droppableFile ) {
6422 dt.dropEffect = 'none';
6423 }
6424
6425 return false;
6426 };
6427
6428 /**
6429 * Handle drag leave events
6430 *
6431 * @private
6432 * @param {jQuery.Event} e Drag event
6433 */
6434 OO.ui.SelectFileWidget.prototype.onDragLeave = function () {
6435 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
6436 };
6437
6438 /**
6439 * Handle drop events
6440 *
6441 * @private
6442 * @param {jQuery.Event} e Drop event
6443 */
6444 OO.ui.SelectFileWidget.prototype.onDrop = function ( e ) {
6445 var file = null,
6446 dt = e.originalEvent.dataTransfer;
6447
6448 e.preventDefault();
6449 e.stopPropagation();
6450 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
6451
6452 if ( this.isDisabled() || !this.isSupported ) {
6453 return false;
6454 }
6455
6456 file = OO.getProp( dt, 'files', 0 );
6457 if ( file && !this.isAllowedType( file.type ) ) {
6458 file = null;
6459 }
6460 if ( file ) {
6461 this.setValue( file );
6462 }
6463
6464 return false;
6465 };
6466
6467 /**
6468 * @inheritdoc
6469 */
6470 OO.ui.SelectFileWidget.prototype.setDisabled = function ( disabled ) {
6471 OO.ui.SelectFileWidget.parent.prototype.setDisabled.call( this, disabled );
6472 if ( this.selectButton ) {
6473 this.selectButton.setDisabled( disabled );
6474 }
6475 if ( this.clearButton ) {
6476 this.clearButton.setDisabled( disabled );
6477 }
6478 return this;
6479 };
6480
6481 /**
6482 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
6483 * and a menu of search results, which is displayed beneath the query
6484 * field. Unlike {@link OO.ui.mixin.LookupElement lookup menus}, search result menus are always visible to the user.
6485 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
6486 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
6487 *
6488 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
6489 * the [OOjs UI demos][1] for an example.
6490 *
6491 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
6492 *
6493 * @class
6494 * @extends OO.ui.Widget
6495 *
6496 * @constructor
6497 * @param {Object} [config] Configuration options
6498 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
6499 * @cfg {string} [value] Initial query value
6500 */
6501 OO.ui.SearchWidget = function OoUiSearchWidget( config ) {
6502 // Configuration initialization
6503 config = config || {};
6504
6505 // Parent constructor
6506 OO.ui.SearchWidget.parent.call( this, config );
6507
6508 // Properties
6509 this.query = new OO.ui.TextInputWidget( {
6510 icon: 'search',
6511 placeholder: config.placeholder,
6512 value: config.value
6513 } );
6514 this.results = new OO.ui.SelectWidget();
6515 this.$query = $( '<div>' );
6516 this.$results = $( '<div>' );
6517
6518 // Events
6519 this.query.connect( this, {
6520 change: 'onQueryChange',
6521 enter: 'onQueryEnter'
6522 } );
6523 this.query.$input.on( 'keydown', this.onQueryKeydown.bind( this ) );
6524
6525 // Initialization
6526 this.$query
6527 .addClass( 'oo-ui-searchWidget-query' )
6528 .append( this.query.$element );
6529 this.$results
6530 .addClass( 'oo-ui-searchWidget-results' )
6531 .append( this.results.$element );
6532 this.$element
6533 .addClass( 'oo-ui-searchWidget' )
6534 .append( this.$results, this.$query );
6535 };
6536
6537 /* Setup */
6538
6539 OO.inheritClass( OO.ui.SearchWidget, OO.ui.Widget );
6540
6541 /* Methods */
6542
6543 /**
6544 * Handle query key down events.
6545 *
6546 * @private
6547 * @param {jQuery.Event} e Key down event
6548 */
6549 OO.ui.SearchWidget.prototype.onQueryKeydown = function ( e ) {
6550 var highlightedItem, nextItem,
6551 dir = e.which === OO.ui.Keys.DOWN ? 1 : ( e.which === OO.ui.Keys.UP ? -1 : 0 );
6552
6553 if ( dir ) {
6554 highlightedItem = this.results.findHighlightedItem();
6555 if ( !highlightedItem ) {
6556 highlightedItem = this.results.getSelectedItem();
6557 }
6558 nextItem = this.results.findRelativeSelectableItem( highlightedItem, dir );
6559 this.results.highlightItem( nextItem );
6560 nextItem.scrollElementIntoView();
6561 }
6562 };
6563
6564 /**
6565 * Handle select widget select events.
6566 *
6567 * Clears existing results. Subclasses should repopulate items according to new query.
6568 *
6569 * @private
6570 * @param {string} value New value
6571 */
6572 OO.ui.SearchWidget.prototype.onQueryChange = function () {
6573 // Reset
6574 this.results.clearItems();
6575 };
6576
6577 /**
6578 * Handle select widget enter key events.
6579 *
6580 * Chooses highlighted item.
6581 *
6582 * @private
6583 * @param {string} value New value
6584 */
6585 OO.ui.SearchWidget.prototype.onQueryEnter = function () {
6586 var highlightedItem = this.results.findHighlightedItem();
6587 if ( highlightedItem ) {
6588 this.results.chooseItem( highlightedItem );
6589 }
6590 };
6591
6592 /**
6593 * Get the query input.
6594 *
6595 * @return {OO.ui.TextInputWidget} Query input
6596 */
6597 OO.ui.SearchWidget.prototype.getQuery = function () {
6598 return this.query;
6599 };
6600
6601 /**
6602 * Get the search results menu.
6603 *
6604 * @return {OO.ui.SelectWidget} Menu of search results
6605 */
6606 OO.ui.SearchWidget.prototype.getResults = function () {
6607 return this.results;
6608 };
6609
6610 /**
6611 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
6612 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
6613 * (to adjust the value in increments) to allow the user to enter a number.
6614 *
6615 * @example
6616 * // Example: A NumberInputWidget.
6617 * var numberInput = new OO.ui.NumberInputWidget( {
6618 * label: 'NumberInputWidget',
6619 * input: { value: 5 },
6620 * min: 1,
6621 * max: 10
6622 * } );
6623 * $( 'body' ).append( numberInput.$element );
6624 *
6625 * @class
6626 * @extends OO.ui.TextInputWidget
6627 *
6628 * @constructor
6629 * @param {Object} [config] Configuration options
6630 * @cfg {Object} [minusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget decrementing button widget}.
6631 * @cfg {Object} [plusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget incrementing button widget}.
6632 * @cfg {boolean} [allowInteger=false] Whether the field accepts only integer values.
6633 * @cfg {number} [min=-Infinity] Minimum allowed value
6634 * @cfg {number} [max=Infinity] Maximum allowed value
6635 * @cfg {number} [step=1] Delta when using the buttons or up/down arrow keys
6636 * @cfg {number|null} [pageStep] Delta when using the page-up/page-down keys. Defaults to 10 times #step.
6637 * @cfg {boolean} [showButtons=true] Whether to show the plus and minus buttons.
6638 */
6639 OO.ui.NumberInputWidget = function OoUiNumberInputWidget( config ) {
6640 var $field = $( '<div>' )
6641 .addClass( 'oo-ui-numberInputWidget-field' );
6642
6643 // Configuration initialization
6644 config = $.extend( {
6645 allowInteger: false,
6646 min: -Infinity,
6647 max: Infinity,
6648 step: 1,
6649 pageStep: null,
6650 showButtons: true
6651 }, config );
6652
6653 // For backward compatibility
6654 $.extend( config, config.input );
6655 this.input = this;
6656
6657 // Parent constructor
6658 OO.ui.NumberInputWidget.parent.call( this, $.extend( config, {
6659 type: 'number'
6660 } ) );
6661
6662 if ( config.showButtons ) {
6663 this.minusButton = new OO.ui.ButtonWidget( $.extend(
6664 {
6665 disabled: this.isDisabled(),
6666 tabIndex: -1,
6667 classes: [ 'oo-ui-numberInputWidget-minusButton' ],
6668 icon: 'subtract'
6669 },
6670 config.minusButton
6671 ) );
6672 this.plusButton = new OO.ui.ButtonWidget( $.extend(
6673 {
6674 disabled: this.isDisabled(),
6675 tabIndex: -1,
6676 classes: [ 'oo-ui-numberInputWidget-plusButton' ],
6677 icon: 'add'
6678 },
6679 config.plusButton
6680 ) );
6681 }
6682
6683 // Events
6684 this.$input.on( {
6685 keydown: this.onKeyDown.bind( this ),
6686 'wheel mousewheel DOMMouseScroll': this.onWheel.bind( this )
6687 } );
6688 if ( config.showButtons ) {
6689 this.plusButton.connect( this, {
6690 click: [ 'onButtonClick', +1 ]
6691 } );
6692 this.minusButton.connect( this, {
6693 click: [ 'onButtonClick', -1 ]
6694 } );
6695 }
6696
6697 // Build the field
6698 $field.append( this.$input );
6699 if ( config.showButtons ) {
6700 $field
6701 .prepend( this.minusButton.$element )
6702 .append( this.plusButton.$element );
6703 }
6704
6705 // Initialization
6706 this.setAllowInteger( config.allowInteger || config.isInteger );
6707 this.setRange( config.min, config.max );
6708 this.setStep( config.step, config.pageStep );
6709 // Set the validation method after we set allowInteger and range
6710 // so that it doesn't immediately call setValidityFlag
6711 this.setValidation( this.validateNumber.bind( this ) );
6712
6713 this.$element
6714 .addClass( 'oo-ui-numberInputWidget' )
6715 .toggleClass( 'oo-ui-numberInputWidget-buttoned', config.showButtons )
6716 .append( $field );
6717 };
6718
6719 /* Setup */
6720
6721 OO.inheritClass( OO.ui.NumberInputWidget, OO.ui.TextInputWidget );
6722
6723 /* Methods */
6724
6725 /**
6726 * Set whether only integers are allowed
6727 *
6728 * @param {boolean} flag
6729 */
6730 OO.ui.NumberInputWidget.prototype.setAllowInteger = function ( flag ) {
6731 this.allowInteger = !!flag;
6732 this.setValidityFlag();
6733 };
6734 // Backward compatibility
6735 OO.ui.NumberInputWidget.prototype.setIsInteger = OO.ui.NumberInputWidget.prototype.setAllowInteger;
6736
6737 /**
6738 * Get whether only integers are allowed
6739 *
6740 * @return {boolean} Flag value
6741 */
6742 OO.ui.NumberInputWidget.prototype.getAllowInteger = function () {
6743 return this.allowInteger;
6744 };
6745 // Backward compatibility
6746 OO.ui.NumberInputWidget.prototype.getIsInteger = OO.ui.NumberInputWidget.prototype.getAllowInteger;
6747
6748 /**
6749 * Set the range of allowed values
6750 *
6751 * @param {number} min Minimum allowed value
6752 * @param {number} max Maximum allowed value
6753 */
6754 OO.ui.NumberInputWidget.prototype.setRange = function ( min, max ) {
6755 if ( min > max ) {
6756 throw new Error( 'Minimum (' + min + ') must not be greater than maximum (' + max + ')' );
6757 }
6758 this.min = min;
6759 this.max = max;
6760 this.setValidityFlag();
6761 };
6762
6763 /**
6764 * Get the current range
6765 *
6766 * @return {number[]} Minimum and maximum values
6767 */
6768 OO.ui.NumberInputWidget.prototype.getRange = function () {
6769 return [ this.min, this.max ];
6770 };
6771
6772 /**
6773 * Set the stepping deltas
6774 *
6775 * @param {number} step Normal step
6776 * @param {number|null} pageStep Page step. If null, 10 * step will be used.
6777 */
6778 OO.ui.NumberInputWidget.prototype.setStep = function ( step, pageStep ) {
6779 if ( step <= 0 ) {
6780 throw new Error( 'Step value must be positive' );
6781 }
6782 if ( pageStep === null ) {
6783 pageStep = step * 10;
6784 } else if ( pageStep <= 0 ) {
6785 throw new Error( 'Page step value must be positive' );
6786 }
6787 this.step = step;
6788 this.pageStep = pageStep;
6789 };
6790
6791 /**
6792 * Get the current stepping values
6793 *
6794 * @return {number[]} Step and page step
6795 */
6796 OO.ui.NumberInputWidget.prototype.getStep = function () {
6797 return [ this.step, this.pageStep ];
6798 };
6799
6800 /**
6801 * Get the current value of the widget as a number
6802 *
6803 * @return {number} May be NaN, or an invalid number
6804 */
6805 OO.ui.NumberInputWidget.prototype.getNumericValue = function () {
6806 return +this.getValue();
6807 };
6808
6809 /**
6810 * Adjust the value of the widget
6811 *
6812 * @param {number} delta Adjustment amount
6813 */
6814 OO.ui.NumberInputWidget.prototype.adjustValue = function ( delta ) {
6815 var n, v = this.getNumericValue();
6816
6817 delta = +delta;
6818 if ( isNaN( delta ) || !isFinite( delta ) ) {
6819 throw new Error( 'Delta must be a finite number' );
6820 }
6821
6822 if ( isNaN( v ) ) {
6823 n = 0;
6824 } else {
6825 n = v + delta;
6826 n = Math.max( Math.min( n, this.max ), this.min );
6827 if ( this.allowInteger ) {
6828 n = Math.round( n );
6829 }
6830 }
6831
6832 if ( n !== v ) {
6833 this.setValue( n );
6834 }
6835 };
6836 /**
6837 * Validate input
6838 *
6839 * @private
6840 * @param {string} value Field value
6841 * @return {boolean}
6842 */
6843 OO.ui.NumberInputWidget.prototype.validateNumber = function ( value ) {
6844 var n = +value;
6845 if ( value === '' ) {
6846 return !this.isRequired();
6847 }
6848
6849 if ( isNaN( n ) || !isFinite( n ) ) {
6850 return false;
6851 }
6852
6853 if ( this.allowInteger && Math.floor( n ) !== n ) {
6854 return false;
6855 }
6856
6857 if ( n < this.min || n > this.max ) {
6858 return false;
6859 }
6860
6861 return true;
6862 };
6863
6864 /**
6865 * Handle mouse click events.
6866 *
6867 * @private
6868 * @param {number} dir +1 or -1
6869 */
6870 OO.ui.NumberInputWidget.prototype.onButtonClick = function ( dir ) {
6871 this.adjustValue( dir * this.step );
6872 };
6873
6874 /**
6875 * Handle mouse wheel events.
6876 *
6877 * @private
6878 * @param {jQuery.Event} event
6879 */
6880 OO.ui.NumberInputWidget.prototype.onWheel = function ( event ) {
6881 var delta = 0;
6882
6883 if ( !this.isDisabled() && this.$input.is( ':focus' ) ) {
6884 // Standard 'wheel' event
6885 if ( event.originalEvent.deltaMode !== undefined ) {
6886 this.sawWheelEvent = true;
6887 }
6888 if ( event.originalEvent.deltaY ) {
6889 delta = -event.originalEvent.deltaY;
6890 } else if ( event.originalEvent.deltaX ) {
6891 delta = event.originalEvent.deltaX;
6892 }
6893
6894 // Non-standard events
6895 if ( !this.sawWheelEvent ) {
6896 if ( event.originalEvent.wheelDeltaX ) {
6897 delta = -event.originalEvent.wheelDeltaX;
6898 } else if ( event.originalEvent.wheelDeltaY ) {
6899 delta = event.originalEvent.wheelDeltaY;
6900 } else if ( event.originalEvent.wheelDelta ) {
6901 delta = event.originalEvent.wheelDelta;
6902 } else if ( event.originalEvent.detail ) {
6903 delta = -event.originalEvent.detail;
6904 }
6905 }
6906
6907 if ( delta ) {
6908 delta = delta < 0 ? -1 : 1;
6909 this.adjustValue( delta * this.step );
6910 }
6911
6912 return false;
6913 }
6914 };
6915
6916 /**
6917 * Handle key down events.
6918 *
6919 * @private
6920 * @param {jQuery.Event} e Key down event
6921 */
6922 OO.ui.NumberInputWidget.prototype.onKeyDown = function ( e ) {
6923 if ( !this.isDisabled() ) {
6924 switch ( e.which ) {
6925 case OO.ui.Keys.UP:
6926 this.adjustValue( this.step );
6927 return false;
6928 case OO.ui.Keys.DOWN:
6929 this.adjustValue( -this.step );
6930 return false;
6931 case OO.ui.Keys.PAGEUP:
6932 this.adjustValue( this.pageStep );
6933 return false;
6934 case OO.ui.Keys.PAGEDOWN:
6935 this.adjustValue( -this.pageStep );
6936 return false;
6937 }
6938 }
6939 };
6940
6941 /**
6942 * @inheritdoc
6943 */
6944 OO.ui.NumberInputWidget.prototype.setDisabled = function ( disabled ) {
6945 // Parent method
6946 OO.ui.NumberInputWidget.parent.prototype.setDisabled.call( this, disabled );
6947
6948 if ( this.minusButton ) {
6949 this.minusButton.setDisabled( this.isDisabled() );
6950 }
6951 if ( this.plusButton ) {
6952 this.plusButton.setDisabled( this.isDisabled() );
6953 }
6954
6955 return this;
6956 };
6957
6958 }( OO ) );
6959
6960 //# sourceMappingURL=oojs-ui-widgets.js.map