Update OOjs UI to v0.23.2
[lhc/web/wiklou.git] / resources / lib / oojs-ui / oojs-ui-widgets.js
1 /*!
2 * OOjs UI v0.23.2
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-09-26T20:18:42Z
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 layout = this;
1887 if ( !this.scrolling && page ) {
1888 page.scrollElementIntoView().done( function () {
1889 if ( layout.autoFocus && !OO.ui.isMobile() ) {
1890 layout.focus();
1891 }
1892 } );
1893 }
1894 };
1895
1896 /**
1897 * Focus the first input in the current page.
1898 *
1899 * If no page is selected, the first selectable page will be selected.
1900 * If the focus is already in an element on the current page, nothing will happen.
1901 *
1902 * @param {number} [itemIndex] A specific item to focus on
1903 */
1904 OO.ui.BookletLayout.prototype.focus = function ( itemIndex ) {
1905 var page,
1906 items = this.stackLayout.getItems();
1907
1908 if ( itemIndex !== undefined && items[ itemIndex ] ) {
1909 page = items[ itemIndex ];
1910 } else {
1911 page = this.stackLayout.getCurrentItem();
1912 }
1913
1914 if ( !page && this.outlined ) {
1915 this.selectFirstSelectablePage();
1916 page = this.stackLayout.getCurrentItem();
1917 }
1918 if ( !page ) {
1919 return;
1920 }
1921 // Only change the focus if is not already in the current page
1922 if ( !OO.ui.contains( page.$element[ 0 ], this.getElementDocument().activeElement, true ) ) {
1923 page.focus();
1924 }
1925 };
1926
1927 /**
1928 * Find the first focusable input in the booklet layout and focus
1929 * on it.
1930 */
1931 OO.ui.BookletLayout.prototype.focusFirstFocusable = function () {
1932 OO.ui.findFocusable( this.stackLayout.$element ).focus();
1933 };
1934
1935 /**
1936 * Handle outline widget select events.
1937 *
1938 * @private
1939 * @param {OO.ui.OptionWidget|null} item Selected item
1940 */
1941 OO.ui.BookletLayout.prototype.onOutlineSelectWidgetSelect = function ( item ) {
1942 if ( item ) {
1943 this.setPage( item.getData() );
1944 }
1945 };
1946
1947 /**
1948 * Check if booklet has an outline.
1949 *
1950 * @return {boolean} Booklet has an outline
1951 */
1952 OO.ui.BookletLayout.prototype.isOutlined = function () {
1953 return this.outlined;
1954 };
1955
1956 /**
1957 * Check if booklet has editing controls.
1958 *
1959 * @return {boolean} Booklet is editable
1960 */
1961 OO.ui.BookletLayout.prototype.isEditable = function () {
1962 return this.editable;
1963 };
1964
1965 /**
1966 * Check if booklet has a visible outline.
1967 *
1968 * @return {boolean} Outline is visible
1969 */
1970 OO.ui.BookletLayout.prototype.isOutlineVisible = function () {
1971 return this.outlined && this.outlineVisible;
1972 };
1973
1974 /**
1975 * Hide or show the outline.
1976 *
1977 * @param {boolean} [show] Show outline, omit to invert current state
1978 * @chainable
1979 */
1980 OO.ui.BookletLayout.prototype.toggleOutline = function ( show ) {
1981 var booklet = this;
1982
1983 if ( this.outlined ) {
1984 show = show === undefined ? !this.outlineVisible : !!show;
1985 this.outlineVisible = show;
1986 this.toggleMenu( show );
1987 if ( show && this.editable ) {
1988 // HACK: Kill dumb scrollbars when the sidebar stops animating, see T161798. Only necessary when
1989 // outline controls are present, delay matches transition on `.oo-ui-menuLayout-menu`.
1990 setTimeout( function () {
1991 OO.ui.Element.static.reconsiderScrollbars( booklet.outlinePanel.$element[ 0 ] );
1992 }, 200 );
1993 }
1994 }
1995
1996 return this;
1997 };
1998
1999 /**
2000 * Find the page closest to the specified page.
2001 *
2002 * @param {OO.ui.PageLayout} page Page to use as a reference point
2003 * @return {OO.ui.PageLayout|null} Page closest to the specified page
2004 */
2005 OO.ui.BookletLayout.prototype.findClosestPage = function ( page ) {
2006 var next, prev, level,
2007 pages = this.stackLayout.getItems(),
2008 index = pages.indexOf( page );
2009
2010 if ( index !== -1 ) {
2011 next = pages[ index + 1 ];
2012 prev = pages[ index - 1 ];
2013 // Prefer adjacent pages at the same level
2014 if ( this.outlined ) {
2015 level = this.outlineSelectWidget.getItemFromData( page.getName() ).getLevel();
2016 if (
2017 prev &&
2018 level === this.outlineSelectWidget.getItemFromData( prev.getName() ).getLevel()
2019 ) {
2020 return prev;
2021 }
2022 if (
2023 next &&
2024 level === this.outlineSelectWidget.getItemFromData( next.getName() ).getLevel()
2025 ) {
2026 return next;
2027 }
2028 }
2029 }
2030 return prev || next || null;
2031 };
2032
2033 /**
2034 * Get the page closest to the specified page.
2035 *
2036 * @deprecated 0.23.0 Use {@link OO.ui.BookletLayout#findClosestPage} instead.
2037 * @param {OO.ui.PageLayout} page Page to use as a reference point
2038 * @return {OO.ui.PageLayout|null} Page closest to the specified page
2039 */
2040 OO.ui.BookletLayout.prototype.getClosestPage = function ( page ) {
2041 OO.ui.warnDeprecation( 'BookletLayout#getClosestPage: Deprecated function. Use findClosestPage instead. See T76630.' );
2042 return this.findClosestPage( page );
2043 };
2044
2045 /**
2046 * Get the outline widget.
2047 *
2048 * If the booklet is not outlined, the method will return `null`.
2049 *
2050 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
2051 */
2052 OO.ui.BookletLayout.prototype.getOutline = function () {
2053 return this.outlineSelectWidget;
2054 };
2055
2056 /**
2057 * Get the outline controls widget.
2058 *
2059 * If the outline is not editable, the method will return `null`.
2060 *
2061 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
2062 */
2063 OO.ui.BookletLayout.prototype.getOutlineControls = function () {
2064 return this.outlineControlsWidget;
2065 };
2066
2067 /**
2068 * Get a page by its symbolic name.
2069 *
2070 * @param {string} name Symbolic name of page
2071 * @return {OO.ui.PageLayout|undefined} Page, if found
2072 */
2073 OO.ui.BookletLayout.prototype.getPage = function ( name ) {
2074 return this.pages[ name ];
2075 };
2076
2077 /**
2078 * Get the current page.
2079 *
2080 * @return {OO.ui.PageLayout|undefined} Current page, if found
2081 */
2082 OO.ui.BookletLayout.prototype.getCurrentPage = function () {
2083 var name = this.getCurrentPageName();
2084 return name ? this.getPage( name ) : undefined;
2085 };
2086
2087 /**
2088 * Get the symbolic name of the current page.
2089 *
2090 * @return {string|null} Symbolic name of the current page
2091 */
2092 OO.ui.BookletLayout.prototype.getCurrentPageName = function () {
2093 return this.currentPageName;
2094 };
2095
2096 /**
2097 * Add pages to the booklet layout
2098 *
2099 * When pages are added with the same names as existing pages, the existing pages will be
2100 * automatically removed before the new pages are added.
2101 *
2102 * @param {OO.ui.PageLayout[]} pages Pages to add
2103 * @param {number} index Index of the insertion point
2104 * @fires add
2105 * @chainable
2106 */
2107 OO.ui.BookletLayout.prototype.addPages = function ( pages, index ) {
2108 var i, len, name, page, item, currentIndex,
2109 stackLayoutPages = this.stackLayout.getItems(),
2110 remove = [],
2111 items = [];
2112
2113 // Remove pages with same names
2114 for ( i = 0, len = pages.length; i < len; i++ ) {
2115 page = pages[ i ];
2116 name = page.getName();
2117
2118 if ( Object.prototype.hasOwnProperty.call( this.pages, name ) ) {
2119 // Correct the insertion index
2120 currentIndex = stackLayoutPages.indexOf( this.pages[ name ] );
2121 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
2122 index--;
2123 }
2124 remove.push( this.pages[ name ] );
2125 }
2126 }
2127 if ( remove.length ) {
2128 this.removePages( remove );
2129 }
2130
2131 // Add new pages
2132 for ( i = 0, len = pages.length; i < len; i++ ) {
2133 page = pages[ i ];
2134 name = page.getName();
2135 this.pages[ page.getName() ] = page;
2136 if ( this.outlined ) {
2137 item = new OO.ui.OutlineOptionWidget( { data: name } );
2138 page.setOutlineItem( item );
2139 items.push( item );
2140 }
2141 }
2142
2143 if ( this.outlined && items.length ) {
2144 this.outlineSelectWidget.addItems( items, index );
2145 this.selectFirstSelectablePage();
2146 }
2147 this.stackLayout.addItems( pages, index );
2148 this.emit( 'add', pages, index );
2149
2150 return this;
2151 };
2152
2153 /**
2154 * Remove the specified pages from the booklet layout.
2155 *
2156 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
2157 *
2158 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
2159 * @fires remove
2160 * @chainable
2161 */
2162 OO.ui.BookletLayout.prototype.removePages = function ( pages ) {
2163 var i, len, name, page,
2164 items = [];
2165
2166 for ( i = 0, len = pages.length; i < len; i++ ) {
2167 page = pages[ i ];
2168 name = page.getName();
2169 delete this.pages[ name ];
2170 if ( this.outlined ) {
2171 items.push( this.outlineSelectWidget.getItemFromData( name ) );
2172 page.setOutlineItem( null );
2173 }
2174 }
2175 if ( this.outlined && items.length ) {
2176 this.outlineSelectWidget.removeItems( items );
2177 this.selectFirstSelectablePage();
2178 }
2179 this.stackLayout.removeItems( pages );
2180 this.emit( 'remove', pages );
2181
2182 return this;
2183 };
2184
2185 /**
2186 * Clear all pages from the booklet layout.
2187 *
2188 * To remove only a subset of pages from the booklet, use the #removePages method.
2189 *
2190 * @fires remove
2191 * @chainable
2192 */
2193 OO.ui.BookletLayout.prototype.clearPages = function () {
2194 var i, len,
2195 pages = this.stackLayout.getItems();
2196
2197 this.pages = {};
2198 this.currentPageName = null;
2199 if ( this.outlined ) {
2200 this.outlineSelectWidget.clearItems();
2201 for ( i = 0, len = pages.length; i < len; i++ ) {
2202 pages[ i ].setOutlineItem( null );
2203 }
2204 }
2205 this.stackLayout.clearItems();
2206
2207 this.emit( 'remove', pages );
2208
2209 return this;
2210 };
2211
2212 /**
2213 * Set the current page by symbolic name.
2214 *
2215 * @fires set
2216 * @param {string} name Symbolic name of page
2217 */
2218 OO.ui.BookletLayout.prototype.setPage = function ( name ) {
2219 var selectedItem,
2220 $focused,
2221 page = this.pages[ name ],
2222 previousPage = this.currentPageName && this.pages[ this.currentPageName ];
2223
2224 if ( name !== this.currentPageName ) {
2225 if ( this.outlined ) {
2226 selectedItem = this.outlineSelectWidget.getSelectedItem();
2227 if ( selectedItem && selectedItem.getData() !== name ) {
2228 this.outlineSelectWidget.selectItemByData( name );
2229 }
2230 }
2231 if ( page ) {
2232 if ( previousPage ) {
2233 previousPage.setActive( false );
2234 // Blur anything focused if the next page doesn't have anything focusable.
2235 // This is not needed if the next page has something focusable (because once it is focused
2236 // this blur happens automatically). If the layout is non-continuous, this check is
2237 // meaningless because the next page is not visible yet and thus can't hold focus.
2238 if (
2239 this.autoFocus &&
2240 !OO.ui.isMobile() &&
2241 this.stackLayout.continuous &&
2242 OO.ui.findFocusable( page.$element ).length !== 0
2243 ) {
2244 $focused = previousPage.$element.find( ':focus' );
2245 if ( $focused.length ) {
2246 $focused[ 0 ].blur();
2247 }
2248 }
2249 }
2250 this.currentPageName = name;
2251 page.setActive( true );
2252 this.stackLayout.setItem( page );
2253 if ( !this.stackLayout.continuous && previousPage ) {
2254 // This should not be necessary, since any inputs on the previous page should have been
2255 // blurred when it was hidden, but browsers are not very consistent about this.
2256 $focused = previousPage.$element.find( ':focus' );
2257 if ( $focused.length ) {
2258 $focused[ 0 ].blur();
2259 }
2260 }
2261 this.emit( 'set', page );
2262 }
2263 }
2264 };
2265
2266 /**
2267 * Select the first selectable page.
2268 *
2269 * @chainable
2270 */
2271 OO.ui.BookletLayout.prototype.selectFirstSelectablePage = function () {
2272 if ( !this.outlineSelectWidget.getSelectedItem() ) {
2273 this.outlineSelectWidget.selectItem( this.outlineSelectWidget.findFirstSelectableItem() );
2274 }
2275
2276 return this;
2277 };
2278
2279 /**
2280 * IndexLayouts contain {@link OO.ui.TabPanelLayout tab panel layouts} as well as
2281 * {@link OO.ui.TabSelectWidget tabs} that allow users to easily navigate through the tab panels and
2282 * select which one to display. By default, only one tab panel is displayed at a time. When a user
2283 * navigates to a new tab panel, the index layout automatically focuses on the first focusable element,
2284 * unless the default setting is changed.
2285 *
2286 * TODO: This class is similar to BookletLayout, we may want to refactor to reduce duplication
2287 *
2288 * @example
2289 * // Example of a IndexLayout that contains two TabPanelLayouts.
2290 *
2291 * function TabPanelOneLayout( name, config ) {
2292 * TabPanelOneLayout.parent.call( this, name, config );
2293 * this.$element.append( '<p>First tab panel</p>' );
2294 * }
2295 * OO.inheritClass( TabPanelOneLayout, OO.ui.TabPanelLayout );
2296 * TabPanelOneLayout.prototype.setupTabItem = function () {
2297 * this.tabItem.setLabel( 'Tab panel one' );
2298 * };
2299 *
2300 * var tabPanel1 = new TabPanelOneLayout( 'one' ),
2301 * tabPanel2 = new OO.ui.TabPanelLayout( 'two', { label: 'Tab panel two' } );
2302 *
2303 * tabPanel2.$element.append( '<p>Second tab panel</p>' );
2304 *
2305 * var index = new OO.ui.IndexLayout();
2306 *
2307 * index.addTabPanels ( [ tabPanel1, tabPanel2 ] );
2308 * $( 'body' ).append( index.$element );
2309 *
2310 * @class
2311 * @extends OO.ui.MenuLayout
2312 *
2313 * @constructor
2314 * @param {Object} [config] Configuration options
2315 * @cfg {boolean} [continuous=false] Show all tab panels, one after another
2316 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new tab panel is displayed. Disabled on mobile.
2317 */
2318 OO.ui.IndexLayout = function OoUiIndexLayout( config ) {
2319 // Configuration initialization
2320 config = $.extend( {}, config, { menuPosition: 'top' } );
2321
2322 // Parent constructor
2323 OO.ui.IndexLayout.parent.call( this, config );
2324
2325 // Properties
2326 this.currentTabPanelName = null;
2327 this.tabPanels = {};
2328
2329 this.ignoreFocus = false;
2330 this.stackLayout = new OO.ui.StackLayout( {
2331 continuous: !!config.continuous,
2332 expanded: this.expanded
2333 } );
2334 this.$content.append( this.stackLayout.$element );
2335 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
2336
2337 this.tabSelectWidget = new OO.ui.TabSelectWidget();
2338 this.tabPanel = new OO.ui.PanelLayout( {
2339 expanded: this.expanded
2340 } );
2341 this.$menu.append( this.tabPanel.$element );
2342
2343 this.toggleMenu( true );
2344
2345 // Events
2346 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
2347 this.tabSelectWidget.connect( this, { select: 'onTabSelectWidgetSelect' } );
2348 if ( this.autoFocus ) {
2349 // Event 'focus' does not bubble, but 'focusin' does
2350 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
2351 }
2352
2353 // Initialization
2354 this.$element.addClass( 'oo-ui-indexLayout' );
2355 this.stackLayout.$element.addClass( 'oo-ui-indexLayout-stackLayout' );
2356 this.tabPanel.$element
2357 .addClass( 'oo-ui-indexLayout-tabPanel' )
2358 .append( this.tabSelectWidget.$element );
2359 };
2360
2361 /* Setup */
2362
2363 OO.inheritClass( OO.ui.IndexLayout, OO.ui.MenuLayout );
2364
2365 /* Events */
2366
2367 /**
2368 * A 'set' event is emitted when a tab panel is {@link #setTabPanel set} to be displayed by the index layout.
2369 * @event set
2370 * @param {OO.ui.TabPanelLayout} tabPanel Current tab panel
2371 */
2372
2373 /**
2374 * An 'add' event is emitted when tab panels are {@link #addTabPanels added} to the index layout.
2375 *
2376 * @event add
2377 * @param {OO.ui.TabPanelLayout[]} tabPanel Added tab panels
2378 * @param {number} index Index tab panels were added at
2379 */
2380
2381 /**
2382 * A 'remove' event is emitted when tab panels are {@link #clearTabPanels cleared} or
2383 * {@link #removeTabPanels removed} from the index.
2384 *
2385 * @event remove
2386 * @param {OO.ui.TabPanelLayout[]} tabPanel Removed tab panels
2387 */
2388
2389 /* Methods */
2390
2391 /**
2392 * Handle stack layout focus.
2393 *
2394 * @private
2395 * @param {jQuery.Event} e Focusing event
2396 */
2397 OO.ui.IndexLayout.prototype.onStackLayoutFocus = function ( e ) {
2398 var name, $target;
2399
2400 // Find the tab panel that an element was focused within
2401 $target = $( e.target ).closest( '.oo-ui-tabPanelLayout' );
2402 for ( name in this.tabPanels ) {
2403 // Check for tab panel match, exclude current tab panel to find only tab panel changes
2404 if ( this.tabPanels[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentTabPanelName ) {
2405 this.setTabPanel( name );
2406 break;
2407 }
2408 }
2409 };
2410
2411 /**
2412 * Handle stack layout set events.
2413 *
2414 * @private
2415 * @param {OO.ui.PanelLayout|null} tabPanel The tab panel that is now the current panel
2416 */
2417 OO.ui.IndexLayout.prototype.onStackLayoutSet = function ( tabPanel ) {
2418 var layout = this;
2419 if ( tabPanel ) {
2420 tabPanel.scrollElementIntoView().done( function () {
2421 if ( layout.autoFocus && !OO.ui.isMobile() ) {
2422 layout.focus();
2423 }
2424 } );
2425 }
2426 };
2427
2428 /**
2429 * Focus the first input in the current tab panel.
2430 *
2431 * If no tab panel is selected, the first selectable tab panel will be selected.
2432 * If the focus is already in an element on the current tab panel, nothing will happen.
2433 *
2434 * @param {number} [itemIndex] A specific item to focus on
2435 */
2436 OO.ui.IndexLayout.prototype.focus = function ( itemIndex ) {
2437 var tabPanel,
2438 items = this.stackLayout.getItems();
2439
2440 if ( itemIndex !== undefined && items[ itemIndex ] ) {
2441 tabPanel = items[ itemIndex ];
2442 } else {
2443 tabPanel = this.stackLayout.getCurrentItem();
2444 }
2445
2446 if ( !tabPanel ) {
2447 this.selectFirstSelectableTabPanel();
2448 tabPanel = this.stackLayout.getCurrentItem();
2449 }
2450 if ( !tabPanel ) {
2451 return;
2452 }
2453 // Only change the focus if is not already in the current page
2454 if ( !OO.ui.contains( tabPanel.$element[ 0 ], this.getElementDocument().activeElement, true ) ) {
2455 tabPanel.focus();
2456 }
2457 };
2458
2459 /**
2460 * Find the first focusable input in the index layout and focus
2461 * on it.
2462 */
2463 OO.ui.IndexLayout.prototype.focusFirstFocusable = function () {
2464 OO.ui.findFocusable( this.stackLayout.$element ).focus();
2465 };
2466
2467 /**
2468 * Handle tab widget select events.
2469 *
2470 * @private
2471 * @param {OO.ui.OptionWidget|null} item Selected item
2472 */
2473 OO.ui.IndexLayout.prototype.onTabSelectWidgetSelect = function ( item ) {
2474 if ( item ) {
2475 this.setTabPanel( item.getData() );
2476 }
2477 };
2478
2479 /**
2480 * Get the tab panel closest to the specified tab panel.
2481 *
2482 * @param {OO.ui.TabPanelLayout} tabPanel Tab panel to use as a reference point
2483 * @return {OO.ui.TabPanelLayout|null} Tab panel closest to the specified
2484 */
2485 OO.ui.IndexLayout.prototype.getClosestTabPanel = function ( tabPanel ) {
2486 var next, prev, level,
2487 tabPanels = this.stackLayout.getItems(),
2488 index = tabPanels.indexOf( tabPanel );
2489
2490 if ( index !== -1 ) {
2491 next = tabPanels[ index + 1 ];
2492 prev = tabPanels[ index - 1 ];
2493 // Prefer adjacent tab panels at the same level
2494 level = this.tabSelectWidget.getItemFromData( tabPanel.getName() ).getLevel();
2495 if (
2496 prev &&
2497 level === this.tabSelectWidget.getItemFromData( prev.getName() ).getLevel()
2498 ) {
2499 return prev;
2500 }
2501 if (
2502 next &&
2503 level === this.tabSelectWidget.getItemFromData( next.getName() ).getLevel()
2504 ) {
2505 return next;
2506 }
2507 }
2508 return prev || next || null;
2509 };
2510
2511 /**
2512 * Get the tabs widget.
2513 *
2514 * @return {OO.ui.TabSelectWidget} Tabs widget
2515 */
2516 OO.ui.IndexLayout.prototype.getTabs = function () {
2517 return this.tabSelectWidget;
2518 };
2519
2520 /**
2521 * Get a tab panel by its symbolic name.
2522 *
2523 * @param {string} name Symbolic name of tab panel
2524 * @return {OO.ui.TabPanelLayout|undefined} Tab panel, if found
2525 */
2526 OO.ui.IndexLayout.prototype.getTabPanel = function ( name ) {
2527 return this.tabPanels[ name ];
2528 };
2529
2530 /**
2531 * Get the current tab panel.
2532 *
2533 * @return {OO.ui.TabPanelLayout|undefined} Current tab panel, if found
2534 */
2535 OO.ui.IndexLayout.prototype.getCurrentTabPanel = function () {
2536 var name = this.getCurrentTabPanelName();
2537 return name ? this.getTabPanel( name ) : undefined;
2538 };
2539
2540 /**
2541 * Get the symbolic name of the current tab panel.
2542 *
2543 * @return {string|null} Symbolic name of the current tab panel
2544 */
2545 OO.ui.IndexLayout.prototype.getCurrentTabPanelName = function () {
2546 return this.currentTabPanelName;
2547 };
2548
2549 /**
2550 * Add tab panels to the index layout
2551 *
2552 * When tab panels are added with the same names as existing tab panels, the existing tab panels
2553 * will be automatically removed before the new tab panels are added.
2554 *
2555 * @param {OO.ui.TabPanelLayout[]} tabPanels Tab panels to add
2556 * @param {number} index Index of the insertion point
2557 * @fires add
2558 * @chainable
2559 */
2560 OO.ui.IndexLayout.prototype.addTabPanels = function ( tabPanels, index ) {
2561 var i, len, name, tabPanel, item, currentIndex,
2562 stackLayoutTabPanels = this.stackLayout.getItems(),
2563 remove = [],
2564 items = [];
2565
2566 // Remove tab panels with same names
2567 for ( i = 0, len = tabPanels.length; i < len; i++ ) {
2568 tabPanel = tabPanels[ i ];
2569 name = tabPanel.getName();
2570
2571 if ( Object.prototype.hasOwnProperty.call( this.tabPanels, name ) ) {
2572 // Correct the insertion index
2573 currentIndex = stackLayoutTabPanels.indexOf( this.tabPanels[ name ] );
2574 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
2575 index--;
2576 }
2577 remove.push( this.tabPanels[ name ] );
2578 }
2579 }
2580 if ( remove.length ) {
2581 this.removeTabPanels( remove );
2582 }
2583
2584 // Add new tab panels
2585 for ( i = 0, len = tabPanels.length; i < len; i++ ) {
2586 tabPanel = tabPanels[ i ];
2587 name = tabPanel.getName();
2588 this.tabPanels[ tabPanel.getName() ] = tabPanel;
2589 item = new OO.ui.TabOptionWidget( { data: name } );
2590 tabPanel.setTabItem( item );
2591 items.push( item );
2592 }
2593
2594 if ( items.length ) {
2595 this.tabSelectWidget.addItems( items, index );
2596 this.selectFirstSelectableTabPanel();
2597 }
2598 this.stackLayout.addItems( tabPanels, index );
2599 this.emit( 'add', tabPanels, index );
2600
2601 return this;
2602 };
2603
2604 /**
2605 * Remove the specified tab panels from the index layout.
2606 *
2607 * To remove all tab panels from the index, you may wish to use the #clearTabPanels method instead.
2608 *
2609 * @param {OO.ui.TabPanelLayout[]} tabPanels An array of tab panels to remove
2610 * @fires remove
2611 * @chainable
2612 */
2613 OO.ui.IndexLayout.prototype.removeTabPanels = function ( tabPanels ) {
2614 var i, len, name, tabPanel,
2615 items = [];
2616
2617 for ( i = 0, len = tabPanels.length; i < len; i++ ) {
2618 tabPanel = tabPanels[ i ];
2619 name = tabPanel.getName();
2620 delete this.tabPanels[ name ];
2621 items.push( this.tabSelectWidget.getItemFromData( name ) );
2622 tabPanel.setTabItem( null );
2623 }
2624 if ( items.length ) {
2625 this.tabSelectWidget.removeItems( items );
2626 this.selectFirstSelectableTabPanel();
2627 }
2628 this.stackLayout.removeItems( tabPanels );
2629 this.emit( 'remove', tabPanels );
2630
2631 return this;
2632 };
2633
2634 /**
2635 * Clear all tab panels from the index layout.
2636 *
2637 * To remove only a subset of tab panels from the index, use the #removeTabPanels method.
2638 *
2639 * @fires remove
2640 * @chainable
2641 */
2642 OO.ui.IndexLayout.prototype.clearTabPanels = function () {
2643 var i, len,
2644 tabPanels = this.stackLayout.getItems();
2645
2646 this.tabPanels = {};
2647 this.currentTabPanelName = null;
2648 this.tabSelectWidget.clearItems();
2649 for ( i = 0, len = tabPanels.length; i < len; i++ ) {
2650 tabPanels[ i ].setTabItem( null );
2651 }
2652 this.stackLayout.clearItems();
2653
2654 this.emit( 'remove', tabPanels );
2655
2656 return this;
2657 };
2658
2659 /**
2660 * Set the current tab panel by symbolic name.
2661 *
2662 * @fires set
2663 * @param {string} name Symbolic name of tab panel
2664 */
2665 OO.ui.IndexLayout.prototype.setTabPanel = function ( name ) {
2666 var selectedItem,
2667 $focused,
2668 tabPanel = this.tabPanels[ name ],
2669 previousTabPanel = this.currentTabPanelName && this.tabPanels[ this.currentTabPanelName ];
2670
2671 if ( name !== this.currentTabPanelName ) {
2672 selectedItem = this.tabSelectWidget.getSelectedItem();
2673 if ( selectedItem && selectedItem.getData() !== name ) {
2674 this.tabSelectWidget.selectItemByData( name );
2675 }
2676 if ( tabPanel ) {
2677 if ( previousTabPanel ) {
2678 previousTabPanel.setActive( false );
2679 // Blur anything focused if the next tab panel doesn't have anything focusable.
2680 // This is not needed if the next tab panel has something focusable (because once it is focused
2681 // this blur happens automatically). If the layout is non-continuous, this check is
2682 // meaningless because the next tab panel is not visible yet and thus can't hold focus.
2683 if (
2684 this.autoFocus &&
2685 !OO.ui.isMobile() &&
2686 this.stackLayout.continuous &&
2687 OO.ui.findFocusable( tabPanel.$element ).length !== 0
2688 ) {
2689 $focused = previousTabPanel.$element.find( ':focus' );
2690 if ( $focused.length ) {
2691 $focused[ 0 ].blur();
2692 }
2693 }
2694 }
2695 this.currentTabPanelName = name;
2696 tabPanel.setActive( true );
2697 this.stackLayout.setItem( tabPanel );
2698 if ( !this.stackLayout.continuous && previousTabPanel ) {
2699 // This should not be necessary, since any inputs on the previous tab panel should have been
2700 // blurred when it was hidden, but browsers are not very consistent about this.
2701 $focused = previousTabPanel.$element.find( ':focus' );
2702 if ( $focused.length ) {
2703 $focused[ 0 ].blur();
2704 }
2705 }
2706 this.emit( 'set', tabPanel );
2707 }
2708 }
2709 };
2710
2711 /**
2712 * Select the first selectable tab panel.
2713 *
2714 * @chainable
2715 */
2716 OO.ui.IndexLayout.prototype.selectFirstSelectableTabPanel = function () {
2717 if ( !this.tabSelectWidget.getSelectedItem() ) {
2718 this.tabSelectWidget.selectItem( this.tabSelectWidget.findFirstSelectableItem() );
2719 }
2720
2721 return this;
2722 };
2723
2724 /**
2725 * ToggleWidget implements basic behavior of widgets with an on/off state.
2726 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
2727 *
2728 * @abstract
2729 * @class
2730 * @extends OO.ui.Widget
2731 *
2732 * @constructor
2733 * @param {Object} [config] Configuration options
2734 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
2735 * By default, the toggle is in the 'off' state.
2736 */
2737 OO.ui.ToggleWidget = function OoUiToggleWidget( config ) {
2738 // Configuration initialization
2739 config = config || {};
2740
2741 // Parent constructor
2742 OO.ui.ToggleWidget.parent.call( this, config );
2743
2744 // Properties
2745 this.value = null;
2746
2747 // Initialization
2748 this.$element.addClass( 'oo-ui-toggleWidget' );
2749 this.setValue( !!config.value );
2750 };
2751
2752 /* Setup */
2753
2754 OO.inheritClass( OO.ui.ToggleWidget, OO.ui.Widget );
2755
2756 /* Events */
2757
2758 /**
2759 * @event change
2760 *
2761 * A change event is emitted when the on/off state of the toggle changes.
2762 *
2763 * @param {boolean} value Value representing the new state of the toggle
2764 */
2765
2766 /* Methods */
2767
2768 /**
2769 * Get the value representing the toggle’s state.
2770 *
2771 * @return {boolean} The on/off state of the toggle
2772 */
2773 OO.ui.ToggleWidget.prototype.getValue = function () {
2774 return this.value;
2775 };
2776
2777 /**
2778 * Set the state of the toggle: `true` for 'on', `false` for 'off'.
2779 *
2780 * @param {boolean} value The state of the toggle
2781 * @fires change
2782 * @chainable
2783 */
2784 OO.ui.ToggleWidget.prototype.setValue = function ( value ) {
2785 value = !!value;
2786 if ( this.value !== value ) {
2787 this.value = value;
2788 this.emit( 'change', value );
2789 this.$element.toggleClass( 'oo-ui-toggleWidget-on', value );
2790 this.$element.toggleClass( 'oo-ui-toggleWidget-off', !value );
2791 }
2792 return this;
2793 };
2794
2795 /**
2796 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
2797 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
2798 * configured with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators},
2799 * {@link OO.ui.mixin.TitledElement titles}, {@link OO.ui.mixin.FlaggedElement styling flags},
2800 * and {@link OO.ui.mixin.LabelElement labels}. Please see
2801 * the [OOjs UI documentation][1] on MediaWiki for more information.
2802 *
2803 * @example
2804 * // Toggle buttons in the 'off' and 'on' state.
2805 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
2806 * label: 'Toggle Button off'
2807 * } );
2808 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
2809 * label: 'Toggle Button on',
2810 * value: true
2811 * } );
2812 * // Append the buttons to the DOM.
2813 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
2814 *
2815 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
2816 *
2817 * @class
2818 * @extends OO.ui.ToggleWidget
2819 * @mixins OO.ui.mixin.ButtonElement
2820 * @mixins OO.ui.mixin.IconElement
2821 * @mixins OO.ui.mixin.IndicatorElement
2822 * @mixins OO.ui.mixin.LabelElement
2823 * @mixins OO.ui.mixin.TitledElement
2824 * @mixins OO.ui.mixin.FlaggedElement
2825 * @mixins OO.ui.mixin.TabIndexedElement
2826 *
2827 * @constructor
2828 * @param {Object} [config] Configuration options
2829 * @cfg {boolean} [value=false] The toggle button’s initial on/off
2830 * state. By default, the button is in the 'off' state.
2831 */
2832 OO.ui.ToggleButtonWidget = function OoUiToggleButtonWidget( config ) {
2833 // Configuration initialization
2834 config = config || {};
2835
2836 // Parent constructor
2837 OO.ui.ToggleButtonWidget.parent.call( this, config );
2838
2839 // Mixin constructors
2840 OO.ui.mixin.ButtonElement.call( this, $.extend( {}, config, { active: this.active } ) );
2841 OO.ui.mixin.IconElement.call( this, config );
2842 OO.ui.mixin.IndicatorElement.call( this, config );
2843 OO.ui.mixin.LabelElement.call( this, config );
2844 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
2845 OO.ui.mixin.FlaggedElement.call( this, config );
2846 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
2847
2848 // Events
2849 this.connect( this, { click: 'onAction' } );
2850
2851 // Initialization
2852 this.$button.append( this.$icon, this.$label, this.$indicator );
2853 this.$element
2854 .addClass( 'oo-ui-toggleButtonWidget' )
2855 .append( this.$button );
2856 };
2857
2858 /* Setup */
2859
2860 OO.inheritClass( OO.ui.ToggleButtonWidget, OO.ui.ToggleWidget );
2861 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.ButtonElement );
2862 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IconElement );
2863 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IndicatorElement );
2864 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.LabelElement );
2865 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TitledElement );
2866 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.FlaggedElement );
2867 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TabIndexedElement );
2868
2869 /* Static Properties */
2870
2871 /**
2872 * @static
2873 * @inheritdoc
2874 */
2875 OO.ui.ToggleButtonWidget.static.tagName = 'span';
2876
2877 /* Methods */
2878
2879 /**
2880 * Handle the button action being triggered.
2881 *
2882 * @private
2883 */
2884 OO.ui.ToggleButtonWidget.prototype.onAction = function () {
2885 this.setValue( !this.value );
2886 };
2887
2888 /**
2889 * @inheritdoc
2890 */
2891 OO.ui.ToggleButtonWidget.prototype.setValue = function ( value ) {
2892 value = !!value;
2893 if ( value !== this.value ) {
2894 // Might be called from parent constructor before ButtonElement constructor
2895 if ( this.$button ) {
2896 this.$button.attr( 'aria-pressed', value.toString() );
2897 }
2898 this.setActive( value );
2899 }
2900
2901 // Parent method
2902 OO.ui.ToggleButtonWidget.parent.prototype.setValue.call( this, value );
2903
2904 return this;
2905 };
2906
2907 /**
2908 * @inheritdoc
2909 */
2910 OO.ui.ToggleButtonWidget.prototype.setButtonElement = function ( $button ) {
2911 if ( this.$button ) {
2912 this.$button.removeAttr( 'aria-pressed' );
2913 }
2914 OO.ui.mixin.ButtonElement.prototype.setButtonElement.call( this, $button );
2915 this.$button.attr( 'aria-pressed', this.value.toString() );
2916 };
2917
2918 /**
2919 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
2920 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
2921 * visually by a slider in the leftmost position.
2922 *
2923 * @example
2924 * // Toggle switches in the 'off' and 'on' position.
2925 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
2926 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
2927 * value: true
2928 * } );
2929 *
2930 * // Create a FieldsetLayout to layout and label switches
2931 * var fieldset = new OO.ui.FieldsetLayout( {
2932 * label: 'Toggle switches'
2933 * } );
2934 * fieldset.addItems( [
2935 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
2936 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
2937 * ] );
2938 * $( 'body' ).append( fieldset.$element );
2939 *
2940 * @class
2941 * @extends OO.ui.ToggleWidget
2942 * @mixins OO.ui.mixin.TabIndexedElement
2943 *
2944 * @constructor
2945 * @param {Object} [config] Configuration options
2946 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
2947 * By default, the toggle switch is in the 'off' position.
2948 */
2949 OO.ui.ToggleSwitchWidget = function OoUiToggleSwitchWidget( config ) {
2950 // Parent constructor
2951 OO.ui.ToggleSwitchWidget.parent.call( this, config );
2952
2953 // Mixin constructors
2954 OO.ui.mixin.TabIndexedElement.call( this, config );
2955
2956 // Properties
2957 this.dragging = false;
2958 this.dragStart = null;
2959 this.sliding = false;
2960 this.$glow = $( '<span>' );
2961 this.$grip = $( '<span>' );
2962
2963 // Events
2964 this.$element.on( {
2965 click: this.onClick.bind( this ),
2966 keypress: this.onKeyPress.bind( this )
2967 } );
2968
2969 // Initialization
2970 this.$glow.addClass( 'oo-ui-toggleSwitchWidget-glow' );
2971 this.$grip.addClass( 'oo-ui-toggleSwitchWidget-grip' );
2972 this.$element
2973 .addClass( 'oo-ui-toggleSwitchWidget' )
2974 .attr( 'role', 'checkbox' )
2975 .append( this.$glow, this.$grip );
2976 };
2977
2978 /* Setup */
2979
2980 OO.inheritClass( OO.ui.ToggleSwitchWidget, OO.ui.ToggleWidget );
2981 OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.mixin.TabIndexedElement );
2982
2983 /* Methods */
2984
2985 /**
2986 * Handle mouse click events.
2987 *
2988 * @private
2989 * @param {jQuery.Event} e Mouse click event
2990 */
2991 OO.ui.ToggleSwitchWidget.prototype.onClick = function ( e ) {
2992 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
2993 this.setValue( !this.value );
2994 }
2995 return false;
2996 };
2997
2998 /**
2999 * Handle key press events.
3000 *
3001 * @private
3002 * @param {jQuery.Event} e Key press event
3003 */
3004 OO.ui.ToggleSwitchWidget.prototype.onKeyPress = function ( e ) {
3005 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
3006 this.setValue( !this.value );
3007 return false;
3008 }
3009 };
3010
3011 /**
3012 * @inheritdoc
3013 */
3014 OO.ui.ToggleSwitchWidget.prototype.setValue = function ( value ) {
3015 OO.ui.ToggleSwitchWidget.parent.prototype.setValue.call( this, value );
3016 this.$element.attr( 'aria-checked', this.value.toString() );
3017 return this;
3018 };
3019
3020 /**
3021 * @inheritdoc
3022 */
3023 OO.ui.ToggleSwitchWidget.prototype.simulateLabelClick = function () {
3024 if ( !this.isDisabled() ) {
3025 this.setValue( !this.value );
3026 }
3027 this.focus();
3028 };
3029
3030 /**
3031 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
3032 * Controls include moving items up and down, removing items, and adding different kinds of items.
3033 *
3034 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
3035 *
3036 * @class
3037 * @extends OO.ui.Widget
3038 * @mixins OO.ui.mixin.GroupElement
3039 * @mixins OO.ui.mixin.IconElement
3040 *
3041 * @constructor
3042 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
3043 * @param {Object} [config] Configuration options
3044 * @cfg {Object} [abilities] List of abilties
3045 * @cfg {boolean} [abilities.move=true] Allow moving movable items
3046 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
3047 */
3048 OO.ui.OutlineControlsWidget = function OoUiOutlineControlsWidget( outline, config ) {
3049 // Allow passing positional parameters inside the config object
3050 if ( OO.isPlainObject( outline ) && config === undefined ) {
3051 config = outline;
3052 outline = config.outline;
3053 }
3054
3055 // Configuration initialization
3056 config = $.extend( { icon: 'add' }, config );
3057
3058 // Parent constructor
3059 OO.ui.OutlineControlsWidget.parent.call( this, config );
3060
3061 // Mixin constructors
3062 OO.ui.mixin.GroupElement.call( this, config );
3063 OO.ui.mixin.IconElement.call( this, config );
3064
3065 // Properties
3066 this.outline = outline;
3067 this.$movers = $( '<div>' );
3068 this.upButton = new OO.ui.ButtonWidget( {
3069 framed: false,
3070 icon: 'collapse',
3071 title: OO.ui.msg( 'ooui-outline-control-move-up' )
3072 } );
3073 this.downButton = new OO.ui.ButtonWidget( {
3074 framed: false,
3075 icon: 'expand',
3076 title: OO.ui.msg( 'ooui-outline-control-move-down' )
3077 } );
3078 this.removeButton = new OO.ui.ButtonWidget( {
3079 framed: false,
3080 icon: 'trash',
3081 title: OO.ui.msg( 'ooui-outline-control-remove' )
3082 } );
3083 this.abilities = { move: true, remove: true };
3084
3085 // Events
3086 outline.connect( this, {
3087 select: 'onOutlineChange',
3088 add: 'onOutlineChange',
3089 remove: 'onOutlineChange'
3090 } );
3091 this.upButton.connect( this, { click: [ 'emit', 'move', -1 ] } );
3092 this.downButton.connect( this, { click: [ 'emit', 'move', 1 ] } );
3093 this.removeButton.connect( this, { click: [ 'emit', 'remove' ] } );
3094
3095 // Initialization
3096 this.$element.addClass( 'oo-ui-outlineControlsWidget' );
3097 this.$group.addClass( 'oo-ui-outlineControlsWidget-items' );
3098 this.$movers
3099 .addClass( 'oo-ui-outlineControlsWidget-movers' )
3100 .append( this.removeButton.$element, this.upButton.$element, this.downButton.$element );
3101 this.$element.append( this.$icon, this.$group, this.$movers );
3102 this.setAbilities( config.abilities || {} );
3103 };
3104
3105 /* Setup */
3106
3107 OO.inheritClass( OO.ui.OutlineControlsWidget, OO.ui.Widget );
3108 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.GroupElement );
3109 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.IconElement );
3110
3111 /* Events */
3112
3113 /**
3114 * @event move
3115 * @param {number} places Number of places to move
3116 */
3117
3118 /**
3119 * @event remove
3120 */
3121
3122 /* Methods */
3123
3124 /**
3125 * Set abilities.
3126 *
3127 * @param {Object} abilities List of abilties
3128 * @param {boolean} [abilities.move] Allow moving movable items
3129 * @param {boolean} [abilities.remove] Allow removing removable items
3130 */
3131 OO.ui.OutlineControlsWidget.prototype.setAbilities = function ( abilities ) {
3132 var ability;
3133
3134 for ( ability in this.abilities ) {
3135 if ( abilities[ ability ] !== undefined ) {
3136 this.abilities[ ability ] = !!abilities[ ability ];
3137 }
3138 }
3139
3140 this.onOutlineChange();
3141 };
3142
3143 /**
3144 * Handle outline change events.
3145 *
3146 * @private
3147 */
3148 OO.ui.OutlineControlsWidget.prototype.onOutlineChange = function () {
3149 var i, len, firstMovable, lastMovable,
3150 items = this.outline.getItems(),
3151 selectedItem = this.outline.getSelectedItem(),
3152 movable = this.abilities.move && selectedItem && selectedItem.isMovable(),
3153 removable = this.abilities.remove && selectedItem && selectedItem.isRemovable();
3154
3155 if ( movable ) {
3156 i = -1;
3157 len = items.length;
3158 while ( ++i < len ) {
3159 if ( items[ i ].isMovable() ) {
3160 firstMovable = items[ i ];
3161 break;
3162 }
3163 }
3164 i = len;
3165 while ( i-- ) {
3166 if ( items[ i ].isMovable() ) {
3167 lastMovable = items[ i ];
3168 break;
3169 }
3170 }
3171 }
3172 this.upButton.setDisabled( !movable || selectedItem === firstMovable );
3173 this.downButton.setDisabled( !movable || selectedItem === lastMovable );
3174 this.removeButton.setDisabled( !removable );
3175 };
3176
3177 /**
3178 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
3179 *
3180 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
3181 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
3182 * for an example.
3183 *
3184 * @class
3185 * @extends OO.ui.DecoratedOptionWidget
3186 *
3187 * @constructor
3188 * @param {Object} [config] Configuration options
3189 * @cfg {number} [level] Indentation level
3190 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
3191 */
3192 OO.ui.OutlineOptionWidget = function OoUiOutlineOptionWidget( config ) {
3193 // Configuration initialization
3194 config = config || {};
3195
3196 // Parent constructor
3197 OO.ui.OutlineOptionWidget.parent.call( this, config );
3198
3199 // Properties
3200 this.level = 0;
3201 this.movable = !!config.movable;
3202 this.removable = !!config.removable;
3203
3204 // Initialization
3205 this.$element.addClass( 'oo-ui-outlineOptionWidget' );
3206 this.setLevel( config.level );
3207 };
3208
3209 /* Setup */
3210
3211 OO.inheritClass( OO.ui.OutlineOptionWidget, OO.ui.DecoratedOptionWidget );
3212
3213 /* Static Properties */
3214
3215 /**
3216 * @static
3217 * @inheritdoc
3218 */
3219 OO.ui.OutlineOptionWidget.static.highlightable = true;
3220
3221 /**
3222 * @static
3223 * @inheritdoc
3224 */
3225 OO.ui.OutlineOptionWidget.static.scrollIntoViewOnSelect = true;
3226
3227 /**
3228 * @static
3229 * @inheritable
3230 * @property {string}
3231 */
3232 OO.ui.OutlineOptionWidget.static.levelClass = 'oo-ui-outlineOptionWidget-level-';
3233
3234 /**
3235 * @static
3236 * @inheritable
3237 * @property {number}
3238 */
3239 OO.ui.OutlineOptionWidget.static.levels = 3;
3240
3241 /* Methods */
3242
3243 /**
3244 * Check if item is movable.
3245 *
3246 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
3247 *
3248 * @return {boolean} Item is movable
3249 */
3250 OO.ui.OutlineOptionWidget.prototype.isMovable = function () {
3251 return this.movable;
3252 };
3253
3254 /**
3255 * Check if item is removable.
3256 *
3257 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
3258 *
3259 * @return {boolean} Item is removable
3260 */
3261 OO.ui.OutlineOptionWidget.prototype.isRemovable = function () {
3262 return this.removable;
3263 };
3264
3265 /**
3266 * Get indentation level.
3267 *
3268 * @return {number} Indentation level
3269 */
3270 OO.ui.OutlineOptionWidget.prototype.getLevel = function () {
3271 return this.level;
3272 };
3273
3274 /**
3275 * @inheritdoc
3276 */
3277 OO.ui.OutlineOptionWidget.prototype.setPressed = function ( state ) {
3278 OO.ui.OutlineOptionWidget.parent.prototype.setPressed.call( this, state );
3279 if ( this.pressed ) {
3280 this.setFlags( { progressive: true } );
3281 } else if ( !this.selected ) {
3282 this.setFlags( { progressive: false } );
3283 }
3284 return this;
3285 };
3286
3287 /**
3288 * Set movability.
3289 *
3290 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
3291 *
3292 * @param {boolean} movable Item is movable
3293 * @chainable
3294 */
3295 OO.ui.OutlineOptionWidget.prototype.setMovable = function ( movable ) {
3296 this.movable = !!movable;
3297 this.updateThemeClasses();
3298 return this;
3299 };
3300
3301 /**
3302 * Set removability.
3303 *
3304 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
3305 *
3306 * @param {boolean} removable Item is removable
3307 * @chainable
3308 */
3309 OO.ui.OutlineOptionWidget.prototype.setRemovable = function ( removable ) {
3310 this.removable = !!removable;
3311 this.updateThemeClasses();
3312 return this;
3313 };
3314
3315 /**
3316 * @inheritdoc
3317 */
3318 OO.ui.OutlineOptionWidget.prototype.setSelected = function ( state ) {
3319 OO.ui.OutlineOptionWidget.parent.prototype.setSelected.call( this, state );
3320 if ( this.selected ) {
3321 this.setFlags( { progressive: true } );
3322 } else {
3323 this.setFlags( { progressive: false } );
3324 }
3325 return this;
3326 };
3327
3328 /**
3329 * Set indentation level.
3330 *
3331 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
3332 * @chainable
3333 */
3334 OO.ui.OutlineOptionWidget.prototype.setLevel = function ( level ) {
3335 var levels = this.constructor.static.levels,
3336 levelClass = this.constructor.static.levelClass,
3337 i = levels;
3338
3339 this.level = level ? Math.max( 0, Math.min( levels - 1, level ) ) : 0;
3340 while ( i-- ) {
3341 if ( this.level === i ) {
3342 this.$element.addClass( levelClass + i );
3343 } else {
3344 this.$element.removeClass( levelClass + i );
3345 }
3346 }
3347 this.updateThemeClasses();
3348
3349 return this;
3350 };
3351
3352 /**
3353 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
3354 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
3355 *
3356 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
3357 *
3358 * @class
3359 * @extends OO.ui.SelectWidget
3360 * @mixins OO.ui.mixin.TabIndexedElement
3361 *
3362 * @constructor
3363 * @param {Object} [config] Configuration options
3364 */
3365 OO.ui.OutlineSelectWidget = function OoUiOutlineSelectWidget( config ) {
3366 // Parent constructor
3367 OO.ui.OutlineSelectWidget.parent.call( this, config );
3368
3369 // Mixin constructors
3370 OO.ui.mixin.TabIndexedElement.call( this, config );
3371
3372 // Events
3373 this.$element.on( {
3374 focus: this.bindKeyDownListener.bind( this ),
3375 blur: this.unbindKeyDownListener.bind( this )
3376 } );
3377
3378 // Initialization
3379 this.$element.addClass( 'oo-ui-outlineSelectWidget' );
3380 };
3381
3382 /* Setup */
3383
3384 OO.inheritClass( OO.ui.OutlineSelectWidget, OO.ui.SelectWidget );
3385 OO.mixinClass( OO.ui.OutlineSelectWidget, OO.ui.mixin.TabIndexedElement );
3386
3387 /**
3388 * ButtonOptionWidget is a special type of {@link OO.ui.mixin.ButtonElement button element} that
3389 * can be selected and configured with data. The class is
3390 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
3391 * [OOjs UI documentation on MediaWiki] [1] for more information.
3392 *
3393 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
3394 *
3395 * @class
3396 * @extends OO.ui.OptionWidget
3397 * @mixins OO.ui.mixin.ButtonElement
3398 * @mixins OO.ui.mixin.IconElement
3399 * @mixins OO.ui.mixin.IndicatorElement
3400 * @mixins OO.ui.mixin.TitledElement
3401 *
3402 * @constructor
3403 * @param {Object} [config] Configuration options
3404 */
3405 OO.ui.ButtonOptionWidget = function OoUiButtonOptionWidget( config ) {
3406 // Configuration initialization
3407 config = config || {};
3408
3409 // Parent constructor
3410 OO.ui.ButtonOptionWidget.parent.call( this, config );
3411
3412 // Mixin constructors
3413 OO.ui.mixin.ButtonElement.call( this, config );
3414 OO.ui.mixin.IconElement.call( this, config );
3415 OO.ui.mixin.IndicatorElement.call( this, config );
3416 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
3417
3418 // Initialization
3419 this.$element.addClass( 'oo-ui-buttonOptionWidget' );
3420 this.$button.append( this.$icon, this.$label, this.$indicator );
3421 this.$element.append( this.$button );
3422 };
3423
3424 /* Setup */
3425
3426 OO.inheritClass( OO.ui.ButtonOptionWidget, OO.ui.OptionWidget );
3427 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.ButtonElement );
3428 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.IconElement );
3429 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.IndicatorElement );
3430 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.TitledElement );
3431
3432 /* Static Properties */
3433
3434 /**
3435 * Allow button mouse down events to pass through so they can be handled by the parent select widget
3436 *
3437 * @static
3438 * @inheritdoc
3439 */
3440 OO.ui.ButtonOptionWidget.static.cancelButtonMouseDownEvents = false;
3441
3442 /**
3443 * @static
3444 * @inheritdoc
3445 */
3446 OO.ui.ButtonOptionWidget.static.highlightable = false;
3447
3448 /* Methods */
3449
3450 /**
3451 * @inheritdoc
3452 */
3453 OO.ui.ButtonOptionWidget.prototype.setSelected = function ( state ) {
3454 OO.ui.ButtonOptionWidget.parent.prototype.setSelected.call( this, state );
3455
3456 if ( this.constructor.static.selectable ) {
3457 this.setActive( state );
3458 }
3459
3460 return this;
3461 };
3462
3463 /**
3464 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
3465 * button options and is used together with
3466 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
3467 * highlighting, choosing, and selecting mutually exclusive options. Please see
3468 * the [OOjs UI documentation on MediaWiki] [1] for more information.
3469 *
3470 * @example
3471 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
3472 * var option1 = new OO.ui.ButtonOptionWidget( {
3473 * data: 1,
3474 * label: 'Option 1',
3475 * title: 'Button option 1'
3476 * } );
3477 *
3478 * var option2 = new OO.ui.ButtonOptionWidget( {
3479 * data: 2,
3480 * label: 'Option 2',
3481 * title: 'Button option 2'
3482 * } );
3483 *
3484 * var option3 = new OO.ui.ButtonOptionWidget( {
3485 * data: 3,
3486 * label: 'Option 3',
3487 * title: 'Button option 3'
3488 * } );
3489 *
3490 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
3491 * items: [ option1, option2, option3 ]
3492 * } );
3493 * $( 'body' ).append( buttonSelect.$element );
3494 *
3495 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
3496 *
3497 * @class
3498 * @extends OO.ui.SelectWidget
3499 * @mixins OO.ui.mixin.TabIndexedElement
3500 *
3501 * @constructor
3502 * @param {Object} [config] Configuration options
3503 */
3504 OO.ui.ButtonSelectWidget = function OoUiButtonSelectWidget( config ) {
3505 // Parent constructor
3506 OO.ui.ButtonSelectWidget.parent.call( this, config );
3507
3508 // Mixin constructors
3509 OO.ui.mixin.TabIndexedElement.call( this, config );
3510
3511 // Events
3512 this.$element.on( {
3513 focus: this.bindKeyDownListener.bind( this ),
3514 blur: this.unbindKeyDownListener.bind( this )
3515 } );
3516
3517 // Initialization
3518 this.$element.addClass( 'oo-ui-buttonSelectWidget' );
3519 };
3520
3521 /* Setup */
3522
3523 OO.inheritClass( OO.ui.ButtonSelectWidget, OO.ui.SelectWidget );
3524 OO.mixinClass( OO.ui.ButtonSelectWidget, OO.ui.mixin.TabIndexedElement );
3525
3526 /**
3527 * TabOptionWidget is an item in a {@link OO.ui.TabSelectWidget TabSelectWidget}.
3528 *
3529 * Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}, which contain
3530 * {@link OO.ui.TabPanelLayout tab panel layouts}. See {@link OO.ui.IndexLayout IndexLayout}
3531 * for an example.
3532 *
3533 * @class
3534 * @extends OO.ui.OptionWidget
3535 *
3536 * @constructor
3537 * @param {Object} [config] Configuration options
3538 */
3539 OO.ui.TabOptionWidget = function OoUiTabOptionWidget( config ) {
3540 // Configuration initialization
3541 config = config || {};
3542
3543 // Parent constructor
3544 OO.ui.TabOptionWidget.parent.call( this, config );
3545
3546 // Initialization
3547 this.$element.addClass( 'oo-ui-tabOptionWidget' );
3548 };
3549
3550 /* Setup */
3551
3552 OO.inheritClass( OO.ui.TabOptionWidget, OO.ui.OptionWidget );
3553
3554 /* Static Properties */
3555
3556 /**
3557 * @static
3558 * @inheritdoc
3559 */
3560 OO.ui.TabOptionWidget.static.highlightable = false;
3561
3562 /**
3563 * TabSelectWidget is a list that contains {@link OO.ui.TabOptionWidget tab options}
3564 *
3565 * **Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}.**
3566 *
3567 * @class
3568 * @extends OO.ui.SelectWidget
3569 * @mixins OO.ui.mixin.TabIndexedElement
3570 *
3571 * @constructor
3572 * @param {Object} [config] Configuration options
3573 */
3574 OO.ui.TabSelectWidget = function OoUiTabSelectWidget( config ) {
3575 // Parent constructor
3576 OO.ui.TabSelectWidget.parent.call( this, config );
3577
3578 // Mixin constructors
3579 OO.ui.mixin.TabIndexedElement.call( this, config );
3580
3581 // Events
3582 this.$element.on( {
3583 focus: this.bindKeyDownListener.bind( this ),
3584 blur: this.unbindKeyDownListener.bind( this )
3585 } );
3586
3587 // Initialization
3588 this.$element.addClass( 'oo-ui-tabSelectWidget' );
3589 };
3590
3591 /* Setup */
3592
3593 OO.inheritClass( OO.ui.TabSelectWidget, OO.ui.SelectWidget );
3594 OO.mixinClass( OO.ui.TabSelectWidget, OO.ui.mixin.TabIndexedElement );
3595
3596 /**
3597 * CapsuleItemWidgets are used within a {@link OO.ui.CapsuleMultiselectWidget
3598 * CapsuleMultiselectWidget} to display the selected items.
3599 *
3600 * @class
3601 * @extends OO.ui.Widget
3602 * @mixins OO.ui.mixin.ItemWidget
3603 * @mixins OO.ui.mixin.LabelElement
3604 * @mixins OO.ui.mixin.FlaggedElement
3605 * @mixins OO.ui.mixin.TabIndexedElement
3606 *
3607 * @constructor
3608 * @param {Object} [config] Configuration options
3609 */
3610 OO.ui.CapsuleItemWidget = function OoUiCapsuleItemWidget( config ) {
3611 // Configuration initialization
3612 config = config || {};
3613
3614 // Parent constructor
3615 OO.ui.CapsuleItemWidget.parent.call( this, config );
3616
3617 // Mixin constructors
3618 OO.ui.mixin.ItemWidget.call( this );
3619 OO.ui.mixin.LabelElement.call( this, config );
3620 OO.ui.mixin.FlaggedElement.call( this, config );
3621 OO.ui.mixin.TabIndexedElement.call( this, config );
3622
3623 // Events
3624 this.closeButton = new OO.ui.ButtonWidget( {
3625 framed: false,
3626 icon: 'close',
3627 tabIndex: -1,
3628 title: OO.ui.msg( 'ooui-item-remove' )
3629 } ).on( 'click', this.onCloseClick.bind( this ) );
3630
3631 this.on( 'disable', function ( disabled ) {
3632 this.closeButton.setDisabled( disabled );
3633 }.bind( this ) );
3634
3635 // Initialization
3636 this.$element
3637 .on( {
3638 click: this.onClick.bind( this ),
3639 keydown: this.onKeyDown.bind( this )
3640 } )
3641 .addClass( 'oo-ui-capsuleItemWidget' )
3642 .append( this.$label, this.closeButton.$element );
3643 };
3644
3645 /* Setup */
3646
3647 OO.inheritClass( OO.ui.CapsuleItemWidget, OO.ui.Widget );
3648 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.ItemWidget );
3649 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.LabelElement );
3650 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.FlaggedElement );
3651 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.TabIndexedElement );
3652
3653 /* Methods */
3654
3655 /**
3656 * Handle close icon clicks
3657 */
3658 OO.ui.CapsuleItemWidget.prototype.onCloseClick = function () {
3659 var element = this.getElementGroup();
3660
3661 if ( element && $.isFunction( element.removeItems ) ) {
3662 element.removeItems( [ this ] );
3663 element.focus();
3664 }
3665 };
3666
3667 /**
3668 * Handle click event for the entire capsule
3669 */
3670 OO.ui.CapsuleItemWidget.prototype.onClick = function () {
3671 var element = this.getElementGroup();
3672
3673 if ( !this.isDisabled() && element && $.isFunction( element.editItem ) ) {
3674 element.editItem( this );
3675 }
3676 };
3677
3678 /**
3679 * Handle keyDown event for the entire capsule
3680 *
3681 * @param {jQuery.Event} e Key down event
3682 */
3683 OO.ui.CapsuleItemWidget.prototype.onKeyDown = function ( e ) {
3684 var element = this.getElementGroup();
3685
3686 if ( e.keyCode === OO.ui.Keys.BACKSPACE || e.keyCode === OO.ui.Keys.DELETE ) {
3687 element.removeItems( [ this ] );
3688 element.focus();
3689 return false;
3690 } else if ( e.keyCode === OO.ui.Keys.ENTER ) {
3691 element.editItem( this );
3692 return false;
3693 } else if ( e.keyCode === OO.ui.Keys.LEFT ) {
3694 element.getPreviousItem( this ).focus();
3695 } else if ( e.keyCode === OO.ui.Keys.RIGHT ) {
3696 element.getNextItem( this ).focus();
3697 }
3698 };
3699
3700 /**
3701 * CapsuleMultiselectWidgets are something like a {@link OO.ui.ComboBoxInputWidget combo box widget}
3702 * that allows for selecting multiple values.
3703 *
3704 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
3705 *
3706 * @example
3707 * // Example: A CapsuleMultiselectWidget.
3708 * var capsule = new OO.ui.CapsuleMultiselectWidget( {
3709 * label: 'CapsuleMultiselectWidget',
3710 * selected: [ 'Option 1', 'Option 3' ],
3711 * menu: {
3712 * items: [
3713 * new OO.ui.MenuOptionWidget( {
3714 * data: 'Option 1',
3715 * label: 'Option One'
3716 * } ),
3717 * new OO.ui.MenuOptionWidget( {
3718 * data: 'Option 2',
3719 * label: 'Option Two'
3720 * } ),
3721 * new OO.ui.MenuOptionWidget( {
3722 * data: 'Option 3',
3723 * label: 'Option Three'
3724 * } ),
3725 * new OO.ui.MenuOptionWidget( {
3726 * data: 'Option 4',
3727 * label: 'Option Four'
3728 * } ),
3729 * new OO.ui.MenuOptionWidget( {
3730 * data: 'Option 5',
3731 * label: 'Option Five'
3732 * } )
3733 * ]
3734 * }
3735 * } );
3736 * $( 'body' ).append( capsule.$element );
3737 *
3738 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
3739 *
3740 * @class
3741 * @extends OO.ui.Widget
3742 * @mixins OO.ui.mixin.GroupElement
3743 * @mixins OO.ui.mixin.PopupElement
3744 * @mixins OO.ui.mixin.TabIndexedElement
3745 * @mixins OO.ui.mixin.IndicatorElement
3746 * @mixins OO.ui.mixin.IconElement
3747 * @uses OO.ui.CapsuleItemWidget
3748 * @uses OO.ui.MenuSelectWidget
3749 *
3750 * @constructor
3751 * @param {Object} [config] Configuration options
3752 * @cfg {string} [placeholder] Placeholder text
3753 * @cfg {boolean} [allowArbitrary=false] Allow data items to be added even if not present in the menu.
3754 * @cfg {boolean} [allowDuplicates=false] Allow duplicate items to be added.
3755 * @cfg {Object} [menu] (required) Configuration options to pass to the
3756 * {@link OO.ui.MenuSelectWidget menu select widget}.
3757 * @cfg {Object} [popup] Configuration options to pass to the {@link OO.ui.PopupWidget popup widget}.
3758 * If specified, this popup will be shown instead of the menu (but the menu
3759 * will still be used for item labels and allowArbitrary=false). The widgets
3760 * in the popup should use {@link #addItemsFromData} or {@link #addItems} as necessary.
3761 * @cfg {jQuery} [$overlay=this.$element] Render the menu or popup into a separate layer.
3762 * This configuration is useful in cases where the expanded menu is larger than
3763 * its containing `<div>`. The specified overlay layer is usually on top of
3764 * the containing `<div>` and has a larger area. By default, the menu uses
3765 * relative positioning.
3766 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
3767 */
3768 OO.ui.CapsuleMultiselectWidget = function OoUiCapsuleMultiselectWidget( config ) {
3769 var $tabFocus;
3770
3771 // Parent constructor
3772 OO.ui.CapsuleMultiselectWidget.parent.call( this, config );
3773
3774 // Configuration initialization
3775 config = $.extend( {
3776 allowArbitrary: false,
3777 allowDuplicates: false,
3778 $overlay: this.$element
3779 }, config );
3780
3781 // Properties (must be set before mixin constructor calls)
3782 this.$handle = $( '<div>' );
3783 this.$input = config.popup ? null : $( '<input>' );
3784 if ( config.placeholder !== undefined && config.placeholder !== '' ) {
3785 this.$input.attr( 'placeholder', config.placeholder );
3786 }
3787
3788 // Mixin constructors
3789 OO.ui.mixin.GroupElement.call( this, config );
3790 if ( config.popup ) {
3791 config.popup = $.extend( {}, config.popup, {
3792 align: 'forwards',
3793 anchor: false
3794 } );
3795 OO.ui.mixin.PopupElement.call( this, config );
3796 $tabFocus = $( '<span>' );
3797 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: $tabFocus } ) );
3798 } else {
3799 this.popup = null;
3800 $tabFocus = null;
3801 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
3802 }
3803 OO.ui.mixin.IndicatorElement.call( this, config );
3804 OO.ui.mixin.IconElement.call( this, config );
3805
3806 // Properties
3807 this.$content = $( '<div>' );
3808 this.allowArbitrary = config.allowArbitrary;
3809 this.allowDuplicates = config.allowDuplicates;
3810 this.$overlay = config.$overlay;
3811 this.menu = new OO.ui.MenuSelectWidget( $.extend(
3812 {
3813 widget: this,
3814 $input: this.$input,
3815 $floatableContainer: this.$element,
3816 filterFromInput: true,
3817 disabled: this.isDisabled()
3818 },
3819 config.menu
3820 ) );
3821
3822 // Events
3823 if ( this.popup ) {
3824 $tabFocus.on( {
3825 focus: this.focus.bind( this )
3826 } );
3827 this.popup.$element.on( 'focusout', this.onPopupFocusOut.bind( this ) );
3828 if ( this.popup.$autoCloseIgnore ) {
3829 this.popup.$autoCloseIgnore.on( 'focusout', this.onPopupFocusOut.bind( this ) );
3830 }
3831 this.popup.connect( this, {
3832 toggle: function ( visible ) {
3833 $tabFocus.toggle( !visible );
3834 }
3835 } );
3836 } else {
3837 this.$input.on( {
3838 focus: this.onInputFocus.bind( this ),
3839 blur: this.onInputBlur.bind( this ),
3840 'propertychange change click mouseup keydown keyup input cut paste select focus':
3841 OO.ui.debounce( this.updateInputSize.bind( this ) ),
3842 keydown: this.onKeyDown.bind( this ),
3843 keypress: this.onKeyPress.bind( this )
3844 } );
3845 }
3846 this.menu.connect( this, {
3847 choose: 'onMenuChoose',
3848 toggle: 'onMenuToggle',
3849 add: 'onMenuItemsChange',
3850 remove: 'onMenuItemsChange'
3851 } );
3852 this.$handle.on( {
3853 mousedown: this.onMouseDown.bind( this )
3854 } );
3855
3856 // Initialization
3857 if ( this.$input ) {
3858 this.$input.prop( 'disabled', this.isDisabled() );
3859 this.$input.attr( {
3860 role: 'combobox',
3861 'aria-owns': this.menu.getElementId(),
3862 'aria-autocomplete': 'list'
3863 } );
3864 }
3865 if ( config.data ) {
3866 this.setItemsFromData( config.data );
3867 }
3868 this.$content.addClass( 'oo-ui-capsuleMultiselectWidget-content' )
3869 .append( this.$group );
3870 this.$group.addClass( 'oo-ui-capsuleMultiselectWidget-group' );
3871 this.$handle.addClass( 'oo-ui-capsuleMultiselectWidget-handle' )
3872 .append( this.$indicator, this.$icon, this.$content );
3873 this.$element.addClass( 'oo-ui-capsuleMultiselectWidget' )
3874 .append( this.$handle );
3875 if ( this.popup ) {
3876 this.popup.$element.addClass( 'oo-ui-capsuleMultiselectWidget-popup' );
3877 this.$content.append( $tabFocus );
3878 this.$overlay.append( this.popup.$element );
3879 } else {
3880 this.$content.append( this.$input );
3881 this.$overlay.append( this.menu.$element );
3882 }
3883 if ( $tabFocus ) {
3884 $tabFocus.addClass( 'oo-ui-capsuleMultiselectWidget-focusTrap' );
3885 }
3886
3887 // Input size needs to be calculated after everything else is rendered
3888 setTimeout( function () {
3889 if ( this.$input ) {
3890 this.updateInputSize();
3891 }
3892 }.bind( this ) );
3893
3894 this.onMenuItemsChange();
3895 };
3896
3897 /* Setup */
3898
3899 OO.inheritClass( OO.ui.CapsuleMultiselectWidget, OO.ui.Widget );
3900 OO.mixinClass( OO.ui.CapsuleMultiselectWidget, OO.ui.mixin.GroupElement );
3901 OO.mixinClass( OO.ui.CapsuleMultiselectWidget, OO.ui.mixin.PopupElement );
3902 OO.mixinClass( OO.ui.CapsuleMultiselectWidget, OO.ui.mixin.TabIndexedElement );
3903 OO.mixinClass( OO.ui.CapsuleMultiselectWidget, OO.ui.mixin.IndicatorElement );
3904 OO.mixinClass( OO.ui.CapsuleMultiselectWidget, OO.ui.mixin.IconElement );
3905
3906 /* Events */
3907
3908 /**
3909 * @event change
3910 *
3911 * A change event is emitted when the set of selected items changes.
3912 *
3913 * @param {Mixed[]} datas Data of the now-selected items
3914 */
3915
3916 /**
3917 * @event resize
3918 *
3919 * A resize event is emitted when the widget's dimensions change to accomodate newly added items or
3920 * current user input.
3921 */
3922
3923 /* Methods */
3924
3925 /**
3926 * Construct a OO.ui.CapsuleItemWidget (or a subclass thereof) from given label and data.
3927 * May return `null` if the given label and data are not valid.
3928 *
3929 * @protected
3930 * @param {Mixed} data Custom data of any type.
3931 * @param {string} label The label text.
3932 * @return {OO.ui.CapsuleItemWidget|null}
3933 */
3934 OO.ui.CapsuleMultiselectWidget.prototype.createItemWidget = function ( data, label ) {
3935 if ( label === '' ) {
3936 return null;
3937 }
3938 return new OO.ui.CapsuleItemWidget( { data: data, label: label } );
3939 };
3940
3941 /**
3942 * @inheritdoc
3943 */
3944 OO.ui.CapsuleMultiselectWidget.prototype.getInputId = function () {
3945 if ( !this.$input ) {
3946 return null;
3947 }
3948 return OO.ui.mixin.TabIndexedElement.prototype.getInputId.call( this );
3949 };
3950
3951 /**
3952 * Get the data of the items in the capsule
3953 *
3954 * @return {Mixed[]}
3955 */
3956 OO.ui.CapsuleMultiselectWidget.prototype.getItemsData = function () {
3957 return this.getItems().map( function ( item ) {
3958 return item.data;
3959 } );
3960 };
3961
3962 /**
3963 * Set the items in the capsule by providing data
3964 *
3965 * @chainable
3966 * @param {Mixed[]} datas
3967 * @return {OO.ui.CapsuleMultiselectWidget}
3968 */
3969 OO.ui.CapsuleMultiselectWidget.prototype.setItemsFromData = function ( datas ) {
3970 var widget = this,
3971 menu = this.menu,
3972 items = this.getItems();
3973
3974 $.each( datas, function ( i, data ) {
3975 var j, label,
3976 item = menu.getItemFromData( data );
3977
3978 if ( item ) {
3979 label = item.label;
3980 } else if ( widget.allowArbitrary ) {
3981 label = String( data );
3982 } else {
3983 return;
3984 }
3985
3986 item = null;
3987 for ( j = 0; j < items.length; j++ ) {
3988 if ( items[ j ].data === data && items[ j ].label === label ) {
3989 item = items[ j ];
3990 items.splice( j, 1 );
3991 break;
3992 }
3993 }
3994 if ( !item ) {
3995 item = widget.createItemWidget( data, label );
3996 }
3997 if ( item ) {
3998 widget.addItems( [ item ], i );
3999 }
4000 } );
4001
4002 if ( items.length ) {
4003 widget.removeItems( items );
4004 }
4005
4006 return this;
4007 };
4008
4009 /**
4010 * Add items to the capsule by providing their data
4011 *
4012 * @chainable
4013 * @param {Mixed[]} datas
4014 * @return {OO.ui.CapsuleMultiselectWidget}
4015 */
4016 OO.ui.CapsuleMultiselectWidget.prototype.addItemsFromData = function ( datas ) {
4017 var widget = this,
4018 menu = this.menu,
4019 items = [];
4020
4021 $.each( datas, function ( i, data ) {
4022 var item;
4023
4024 if ( !widget.getItemFromData( data ) || widget.allowDuplicates ) {
4025 item = menu.getItemFromData( data );
4026 if ( item ) {
4027 item = widget.createItemWidget( data, item.label );
4028 } else if ( widget.allowArbitrary ) {
4029 item = widget.createItemWidget( data, String( data ) );
4030 }
4031 if ( item ) {
4032 items.push( item );
4033 }
4034 }
4035 } );
4036
4037 if ( items.length ) {
4038 this.addItems( items );
4039 }
4040
4041 return this;
4042 };
4043
4044 /**
4045 * Add items to the capsule by providing a label
4046 *
4047 * @param {string} label
4048 * @return {boolean} Whether the item was added or not
4049 */
4050 OO.ui.CapsuleMultiselectWidget.prototype.addItemFromLabel = function ( label ) {
4051 var item, items;
4052 item = this.menu.getItemFromLabel( label, true );
4053 if ( item ) {
4054 this.addItemsFromData( [ item.data ] );
4055 return true;
4056 } else if ( this.allowArbitrary ) {
4057 items = this.getItems();
4058 this.addItemsFromData( [ label ] );
4059 return !OO.compare( this.getItems(), items );
4060 }
4061 return false;
4062 };
4063
4064 /**
4065 * Remove items by data
4066 *
4067 * @chainable
4068 * @param {Mixed[]} datas
4069 * @return {OO.ui.CapsuleMultiselectWidget}
4070 */
4071 OO.ui.CapsuleMultiselectWidget.prototype.removeItemsFromData = function ( datas ) {
4072 var widget = this,
4073 items = [];
4074
4075 $.each( datas, function ( i, data ) {
4076 var item = widget.getItemFromData( data );
4077 if ( item ) {
4078 items.push( item );
4079 }
4080 } );
4081
4082 if ( items.length ) {
4083 this.removeItems( items );
4084 }
4085
4086 return this;
4087 };
4088
4089 /**
4090 * @inheritdoc
4091 */
4092 OO.ui.CapsuleMultiselectWidget.prototype.addItems = function ( items ) {
4093 var same, i, l,
4094 oldItems = this.items.slice();
4095
4096 OO.ui.mixin.GroupElement.prototype.addItems.call( this, items );
4097
4098 if ( this.items.length !== oldItems.length ) {
4099 same = false;
4100 } else {
4101 same = true;
4102 for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
4103 same = same && this.items[ i ] === oldItems[ i ];
4104 }
4105 }
4106 if ( !same ) {
4107 this.emit( 'change', this.getItemsData() );
4108 this.updateInputSize();
4109 }
4110
4111 return this;
4112 };
4113
4114 /**
4115 * Removes the item from the list and copies its label to `this.$input`.
4116 *
4117 * @param {Object} item
4118 */
4119 OO.ui.CapsuleMultiselectWidget.prototype.editItem = function ( item ) {
4120 this.addItemFromLabel( this.$input.val() );
4121 this.clearInput();
4122 this.$input.val( item.label );
4123 this.updateInputSize();
4124 this.focus();
4125 this.menu.updateItemVisibility(); // Hack, we shouldn't be calling this method directly
4126 this.removeItems( [ item ] );
4127 };
4128
4129 /**
4130 * @inheritdoc
4131 */
4132 OO.ui.CapsuleMultiselectWidget.prototype.removeItems = function ( items ) {
4133 var same, i, l,
4134 oldItems = this.items.slice();
4135
4136 OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items );
4137
4138 if ( this.items.length !== oldItems.length ) {
4139 same = false;
4140 } else {
4141 same = true;
4142 for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
4143 same = same && this.items[ i ] === oldItems[ i ];
4144 }
4145 }
4146 if ( !same ) {
4147 this.emit( 'change', this.getItemsData() );
4148 this.updateInputSize();
4149 }
4150
4151 return this;
4152 };
4153
4154 /**
4155 * @inheritdoc
4156 */
4157 OO.ui.CapsuleMultiselectWidget.prototype.clearItems = function () {
4158 if ( this.items.length ) {
4159 OO.ui.mixin.GroupElement.prototype.clearItems.call( this );
4160 this.emit( 'change', this.getItemsData() );
4161 this.updateInputSize();
4162 }
4163 return this;
4164 };
4165
4166 /**
4167 * Given an item, returns the item after it. If its the last item,
4168 * returns `this.$input`. If no item is passed, returns the very first
4169 * item.
4170 *
4171 * @param {OO.ui.CapsuleItemWidget} [item]
4172 * @return {OO.ui.CapsuleItemWidget|jQuery|boolean}
4173 */
4174 OO.ui.CapsuleMultiselectWidget.prototype.getNextItem = function ( item ) {
4175 var itemIndex;
4176
4177 if ( item === undefined ) {
4178 return this.items[ 0 ];
4179 }
4180
4181 itemIndex = this.items.indexOf( item );
4182 if ( itemIndex < 0 ) { // Item not in list
4183 return false;
4184 } else if ( itemIndex === this.items.length - 1 ) { // Last item
4185 return this.$input;
4186 } else {
4187 return this.items[ itemIndex + 1 ];
4188 }
4189 };
4190
4191 /**
4192 * Given an item, returns the item before it. If its the first item,
4193 * returns `this.$input`. If no item is passed, returns the very last
4194 * item.
4195 *
4196 * @param {OO.ui.CapsuleItemWidget} [item]
4197 * @return {OO.ui.CapsuleItemWidget|jQuery|boolean}
4198 */
4199 OO.ui.CapsuleMultiselectWidget.prototype.getPreviousItem = function ( item ) {
4200 var itemIndex;
4201
4202 if ( item === undefined ) {
4203 return this.items[ this.items.length - 1 ];
4204 }
4205
4206 itemIndex = this.items.indexOf( item );
4207 if ( itemIndex < 0 ) { // Item not in list
4208 return false;
4209 } else if ( itemIndex === 0 ) { // First item
4210 return this.$input;
4211 } else {
4212 return this.items[ itemIndex - 1 ];
4213 }
4214 };
4215
4216 /**
4217 * Get the capsule widget's menu.
4218 *
4219 * @return {OO.ui.MenuSelectWidget} Menu widget
4220 */
4221 OO.ui.CapsuleMultiselectWidget.prototype.getMenu = function () {
4222 return this.menu;
4223 };
4224
4225 /**
4226 * Handle focus events
4227 *
4228 * @private
4229 * @param {jQuery.Event} event
4230 */
4231 OO.ui.CapsuleMultiselectWidget.prototype.onInputFocus = function () {
4232 if ( !this.isDisabled() ) {
4233 this.updateInputSize();
4234 this.menu.toggle( true );
4235 }
4236 };
4237
4238 /**
4239 * Handle blur events
4240 *
4241 * @private
4242 * @param {jQuery.Event} event
4243 */
4244 OO.ui.CapsuleMultiselectWidget.prototype.onInputBlur = function () {
4245 this.addItemFromLabel( this.$input.val() );
4246 this.clearInput();
4247 };
4248
4249 /**
4250 * Handles popup focus out events.
4251 *
4252 * @private
4253 * @param {jQuery.Event} e Focus out event
4254 */
4255 OO.ui.CapsuleMultiselectWidget.prototype.onPopupFocusOut = function () {
4256 var widget = this.popup;
4257
4258 setTimeout( function () {
4259 if (
4260 widget.isVisible() &&
4261 !OO.ui.contains( widget.$element.add( widget.$autoCloseIgnore ).get(), document.activeElement, true )
4262 ) {
4263 widget.toggle( false );
4264 }
4265 } );
4266 };
4267
4268 /**
4269 * Handle mouse down events.
4270 *
4271 * @private
4272 * @param {jQuery.Event} e Mouse down event
4273 */
4274 OO.ui.CapsuleMultiselectWidget.prototype.onMouseDown = function ( e ) {
4275 if ( e.which === OO.ui.MouseButtons.LEFT ) {
4276 this.focus();
4277 return false;
4278 } else {
4279 this.updateInputSize();
4280 }
4281 };
4282
4283 /**
4284 * Handle key press events.
4285 *
4286 * @private
4287 * @param {jQuery.Event} e Key press event
4288 */
4289 OO.ui.CapsuleMultiselectWidget.prototype.onKeyPress = function ( e ) {
4290 if ( !this.isDisabled() ) {
4291 if ( e.which === OO.ui.Keys.ESCAPE ) {
4292 this.clearInput();
4293 return false;
4294 }
4295
4296 if ( !this.popup ) {
4297 this.menu.toggle( true );
4298 if ( e.which === OO.ui.Keys.ENTER ) {
4299 if ( this.addItemFromLabel( this.$input.val() ) ) {
4300 this.clearInput();
4301 }
4302 return false;
4303 }
4304
4305 // Make sure the input gets resized.
4306 setTimeout( this.updateInputSize.bind( this ), 0 );
4307 }
4308 }
4309 };
4310
4311 /**
4312 * Handle key down events.
4313 *
4314 * @private
4315 * @param {jQuery.Event} e Key down event
4316 */
4317 OO.ui.CapsuleMultiselectWidget.prototype.onKeyDown = function ( e ) {
4318 if (
4319 !this.isDisabled() &&
4320 this.$input.val() === '' &&
4321 this.items.length
4322 ) {
4323 // 'keypress' event is not triggered for Backspace
4324 if ( e.keyCode === OO.ui.Keys.BACKSPACE ) {
4325 if ( e.metaKey || e.ctrlKey ) {
4326 this.removeItems( this.items.slice( -1 ) );
4327 } else {
4328 this.editItem( this.items[ this.items.length - 1 ] );
4329 }
4330 return false;
4331 } else if ( e.keyCode === OO.ui.Keys.LEFT ) {
4332 this.getPreviousItem().focus();
4333 } else if ( e.keyCode === OO.ui.Keys.RIGHT ) {
4334 this.getNextItem().focus();
4335 }
4336 }
4337 };
4338
4339 /**
4340 * Update the dimensions of the text input field to encompass all available area.
4341 *
4342 * @private
4343 * @param {jQuery.Event} e Event of some sort
4344 */
4345 OO.ui.CapsuleMultiselectWidget.prototype.updateInputSize = function () {
4346 var $lastItem, direction, contentWidth, currentWidth, bestWidth;
4347 if ( this.$input && !this.isDisabled() ) {
4348 this.$input.css( 'width', '1em' );
4349 $lastItem = this.$group.children().last();
4350 direction = OO.ui.Element.static.getDir( this.$handle );
4351
4352 // Get the width of the input with the placeholder text as
4353 // the value and save it so that we don't keep recalculating
4354 if (
4355 this.contentWidthWithPlaceholder === undefined &&
4356 this.$input.val() === '' &&
4357 this.$input.attr( 'placeholder' ) !== undefined
4358 ) {
4359 this.$input.val( this.$input.attr( 'placeholder' ) );
4360 this.contentWidthWithPlaceholder = this.$input[ 0 ].scrollWidth;
4361 this.$input.val( '' );
4362
4363 }
4364
4365 // Always keep the input wide enough for the placeholder text
4366 contentWidth = Math.max(
4367 this.$input[ 0 ].scrollWidth,
4368 // undefined arguments in Math.max lead to NaN
4369 ( this.contentWidthWithPlaceholder === undefined ) ?
4370 0 : this.contentWidthWithPlaceholder
4371 );
4372 currentWidth = this.$input.width();
4373
4374 if ( contentWidth < currentWidth ) {
4375 this.updateIfHeightChanged();
4376 // All is fine, don't perform expensive calculations
4377 return;
4378 }
4379
4380 if ( $lastItem.length === 0 ) {
4381 bestWidth = this.$content.innerWidth();
4382 } else {
4383 bestWidth = direction === 'ltr' ?
4384 this.$content.innerWidth() - $lastItem.position().left - $lastItem.outerWidth() :
4385 $lastItem.position().left;
4386 }
4387
4388 // Some safety margin for sanity, because I *really* don't feel like finding out where the few
4389 // pixels this is off by are coming from.
4390 bestWidth -= 10;
4391 if ( contentWidth > bestWidth ) {
4392 // This will result in the input getting shifted to the next line
4393 bestWidth = this.$content.innerWidth() - 10;
4394 }
4395 this.$input.width( Math.floor( bestWidth ) );
4396 this.updateIfHeightChanged();
4397 } else {
4398 this.updateIfHeightChanged();
4399 }
4400 };
4401
4402 /**
4403 * Determine if widget height changed, and if so, update menu position and emit 'resize' event.
4404 *
4405 * @private
4406 */
4407 OO.ui.CapsuleMultiselectWidget.prototype.updateIfHeightChanged = function () {
4408 var height = this.$element.height();
4409 if ( height !== this.height ) {
4410 this.height = height;
4411 this.menu.position();
4412 if ( this.popup ) {
4413 this.popup.updateDimensions();
4414 }
4415 this.emit( 'resize' );
4416 }
4417 };
4418
4419 /**
4420 * Handle menu choose events.
4421 *
4422 * @private
4423 * @param {OO.ui.OptionWidget} item Chosen item
4424 */
4425 OO.ui.CapsuleMultiselectWidget.prototype.onMenuChoose = function ( item ) {
4426 if ( item && item.isVisible() ) {
4427 this.addItemsFromData( [ item.getData() ] );
4428 this.clearInput();
4429 }
4430 };
4431
4432 /**
4433 * Handle menu toggle events.
4434 *
4435 * @private
4436 * @param {boolean} isVisible Menu toggle event
4437 */
4438 OO.ui.CapsuleMultiselectWidget.prototype.onMenuToggle = function ( isVisible ) {
4439 this.$element.toggleClass( 'oo-ui-capsuleMultiselectWidget-open', isVisible );
4440 };
4441
4442 /**
4443 * Handle menu item change events.
4444 *
4445 * @private
4446 */
4447 OO.ui.CapsuleMultiselectWidget.prototype.onMenuItemsChange = function () {
4448 this.setItemsFromData( this.getItemsData() );
4449 this.$element.toggleClass( 'oo-ui-capsuleMultiselectWidget-empty', this.menu.isEmpty() );
4450 };
4451
4452 /**
4453 * Clear the input field
4454 *
4455 * @private
4456 */
4457 OO.ui.CapsuleMultiselectWidget.prototype.clearInput = function () {
4458 if ( this.$input ) {
4459 this.$input.val( '' );
4460 this.updateInputSize();
4461 }
4462 if ( this.popup ) {
4463 this.popup.toggle( false );
4464 }
4465 this.menu.toggle( false );
4466 this.menu.selectItem();
4467 this.menu.highlightItem();
4468 };
4469
4470 /**
4471 * @inheritdoc
4472 */
4473 OO.ui.CapsuleMultiselectWidget.prototype.setDisabled = function ( disabled ) {
4474 var i, len;
4475
4476 // Parent method
4477 OO.ui.CapsuleMultiselectWidget.parent.prototype.setDisabled.call( this, disabled );
4478
4479 if ( this.$input ) {
4480 this.$input.prop( 'disabled', this.isDisabled() );
4481 }
4482 if ( this.menu ) {
4483 this.menu.setDisabled( this.isDisabled() );
4484 }
4485 if ( this.popup ) {
4486 this.popup.setDisabled( this.isDisabled() );
4487 }
4488
4489 if ( this.items ) {
4490 for ( i = 0, len = this.items.length; i < len; i++ ) {
4491 this.items[ i ].updateDisabled();
4492 }
4493 }
4494
4495 return this;
4496 };
4497
4498 /**
4499 * Focus the widget
4500 *
4501 * @chainable
4502 */
4503 OO.ui.CapsuleMultiselectWidget.prototype.focus = function () {
4504 if ( !this.isDisabled() ) {
4505 if ( this.popup ) {
4506 this.popup.setSize( this.$handle.outerWidth() );
4507 this.popup.toggle( true );
4508 OO.ui.findFocusable( this.popup.$element ).focus();
4509 } else {
4510 OO.ui.mixin.TabIndexedElement.prototype.focus.call( this );
4511 }
4512 }
4513 return this;
4514 };
4515
4516 /**
4517 * TagItemWidgets are used within a {@link OO.ui.TagMultiselectWidget
4518 * TagMultiselectWidget} to display the selected items.
4519 *
4520 * @class
4521 * @extends OO.ui.Widget
4522 * @mixins OO.ui.mixin.ItemWidget
4523 * @mixins OO.ui.mixin.LabelElement
4524 * @mixins OO.ui.mixin.FlaggedElement
4525 * @mixins OO.ui.mixin.TabIndexedElement
4526 * @mixins OO.ui.mixin.DraggableElement
4527 *
4528 * @constructor
4529 * @param {Object} [config] Configuration object
4530 * @cfg {boolean} [valid=true] Item is valid
4531 */
4532 OO.ui.TagItemWidget = function OoUiTagItemWidget( config ) {
4533 config = config || {};
4534
4535 // Parent constructor
4536 OO.ui.TagItemWidget.parent.call( this, config );
4537
4538 // Mixin constructors
4539 OO.ui.mixin.ItemWidget.call( this );
4540 OO.ui.mixin.LabelElement.call( this, config );
4541 OO.ui.mixin.FlaggedElement.call( this, config );
4542 OO.ui.mixin.TabIndexedElement.call( this, config );
4543 OO.ui.mixin.DraggableElement.call( this, config );
4544
4545 this.valid = config.valid === undefined ? true : !!config.valid;
4546
4547 this.closeButton = new OO.ui.ButtonWidget( {
4548 framed: false,
4549 icon: 'close',
4550 tabIndex: -1,
4551 title: OO.ui.msg( 'ooui-item-remove' )
4552 } );
4553 this.closeButton.setDisabled( this.isDisabled() );
4554
4555 // Events
4556 this.closeButton
4557 .connect( this, { click: 'remove' } );
4558 this.$element
4559 .on( 'click', this.select.bind( this ) )
4560 .on( 'keydown', this.onKeyDown.bind( this ) )
4561 // Prevent propagation of mousedown; the tag item "lives" in the
4562 // clickable area of the TagMultiselectWidget, which listens to
4563 // mousedown to open the menu or popup. We want to prevent that
4564 // for clicks specifically on the tag itself, so the actions taken
4565 // are more deliberate. When the tag is clicked, it will emit the
4566 // selection event (similar to how #OO.ui.MultioptionWidget emits 'change')
4567 // and can be handled separately.
4568 .on( 'mousedown', function ( e ) { e.stopPropagation(); } );
4569
4570 // Initialization
4571 this.$element
4572 .addClass( 'oo-ui-tagItemWidget' )
4573 .append( this.$label, this.closeButton.$element );
4574 };
4575
4576 /* Initialization */
4577
4578 OO.inheritClass( OO.ui.TagItemWidget, OO.ui.Widget );
4579 OO.mixinClass( OO.ui.TagItemWidget, OO.ui.mixin.ItemWidget );
4580 OO.mixinClass( OO.ui.TagItemWidget, OO.ui.mixin.LabelElement );
4581 OO.mixinClass( OO.ui.TagItemWidget, OO.ui.mixin.FlaggedElement );
4582 OO.mixinClass( OO.ui.TagItemWidget, OO.ui.mixin.TabIndexedElement );
4583 OO.mixinClass( OO.ui.TagItemWidget, OO.ui.mixin.DraggableElement );
4584
4585 /* Events */
4586
4587 /**
4588 * @event remove
4589 *
4590 * A remove action was performed on the item
4591 */
4592
4593 /**
4594 * @event navigate
4595 * @param {string} direction Direction of the movement, forward or backwards
4596 *
4597 * A navigate action was performed on the item
4598 */
4599
4600 /**
4601 * @event select
4602 *
4603 * The tag widget was selected. This can occur when the widget
4604 * is either clicked or enter was pressed on it.
4605 */
4606
4607 /**
4608 * @event valid
4609 * @param {boolean} isValid Item is valid
4610 *
4611 * Item validity has changed
4612 */
4613
4614 /* Methods */
4615
4616 /**
4617 * @inheritdoc
4618 */
4619 OO.ui.TagItemWidget.prototype.setDisabled = function ( state ) {
4620 // Parent method
4621 OO.ui.TagItemWidget.parent.prototype.setDisabled.call( this, state );
4622
4623 if ( this.closeButton ) {
4624 this.closeButton.setDisabled( state );
4625 }
4626 return this;
4627 };
4628
4629 /**
4630 * Handle removal of the item
4631 *
4632 * This is mainly for extensibility concerns, so other children
4633 * of this class can change the behavior if they need to. This
4634 * is called by both clicking the 'remove' button but also
4635 * on keypress, which is harder to override if needed.
4636 *
4637 * @fires remove
4638 */
4639 OO.ui.TagItemWidget.prototype.remove = function () {
4640 if ( !this.isDisabled() ) {
4641 this.emit( 'remove' );
4642 }
4643 };
4644
4645 /**
4646 * Handle a keydown event on the widget
4647 *
4648 * @fires navigate
4649 * @fires remove
4650 * @param {jQuery.Event} e Key down event
4651 * @return {boolean|undefined} false to stop the operation
4652 */
4653 OO.ui.TagItemWidget.prototype.onKeyDown = function ( e ) {
4654 var movement;
4655
4656 if ( e.keyCode === OO.ui.Keys.BACKSPACE || e.keyCode === OO.ui.Keys.DELETE ) {
4657 this.remove();
4658 return false;
4659 } else if ( e.keyCode === OO.ui.Keys.ENTER ) {
4660 this.select();
4661 return false;
4662 } else if (
4663 e.keyCode === OO.ui.Keys.LEFT ||
4664 e.keyCode === OO.ui.Keys.RIGHT
4665 ) {
4666 if ( OO.ui.Element.static.getDir( this.$element ) === 'rtl' ) {
4667 movement = {
4668 left: 'forwards',
4669 right: 'backwards'
4670 };
4671 } else {
4672 movement = {
4673 left: 'backwards',
4674 right: 'forwards'
4675 };
4676 }
4677
4678 this.emit(
4679 'navigate',
4680 e.keyCode === OO.ui.Keys.LEFT ?
4681 movement.left : movement.right
4682 );
4683 }
4684 };
4685
4686 /**
4687 * Select this item
4688 *
4689 * @fires select
4690 */
4691 OO.ui.TagItemWidget.prototype.select = function () {
4692 if ( !this.isDisabled() ) {
4693 this.emit( 'select' );
4694 }
4695 };
4696
4697 /**
4698 * Set the valid state of this item
4699 *
4700 * @param {boolean} [valid] Item is valid
4701 * @fires valid
4702 */
4703 OO.ui.TagItemWidget.prototype.toggleValid = function ( valid ) {
4704 valid = valid === undefined ? !this.valid : !!valid;
4705
4706 if ( this.valid !== valid ) {
4707 this.valid = valid;
4708
4709 this.setFlags( { invalid: !this.valid } );
4710
4711 this.emit( 'valid', this.valid );
4712 }
4713 };
4714
4715 /**
4716 * Check whether the item is valid
4717 *
4718 * @return {boolean} Item is valid
4719 */
4720 OO.ui.TagItemWidget.prototype.isValid = function () {
4721 return this.valid;
4722 };
4723
4724 /**
4725 * A basic tag multiselect widget, similar in concept to {@link OO.ui.ComboBoxInputWidget combo box widget}
4726 * that allows the user to add multiple values that are displayed in a tag area.
4727 *
4728 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
4729 *
4730 * This widget is a base widget; see {@link OO.ui.MenuTagMultiselectWidget MenuTagMultiselectWidget} and
4731 * {@link OO.ui.PopupTagMultiselectWidget PopupTagMultiselectWidget} for the implementations that use
4732 * a menu and a popup respectively.
4733 *
4734 * @example
4735 * // Example: A basic TagMultiselectWidget.
4736 * var widget = new OO.ui.TagMultiselectWidget( {
4737 * inputPosition: 'outline',
4738 * allowedValues: [ 'Option 1', 'Option 2', 'Option 3' ],
4739 * selected: [ 'Option 1' ]
4740 * } );
4741 * $( 'body' ).append( widget.$element );
4742 *
4743 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
4744 *
4745 * @class
4746 * @extends OO.ui.Widget
4747 * @mixins OO.ui.mixin.GroupWidget
4748 * @mixins OO.ui.mixin.DraggableGroupElement
4749 * @mixins OO.ui.mixin.IndicatorElement
4750 * @mixins OO.ui.mixin.IconElement
4751 * @mixins OO.ui.mixin.TabIndexedElement
4752 * @mixins OO.ui.mixin.FlaggedElement
4753 *
4754 * @constructor
4755 * @param {Object} config Configuration object
4756 * @cfg {Object} [input] Configuration options for the input widget
4757 * @cfg {OO.ui.InputWidget} [inputWidget] An optional input widget. If given, it will
4758 * replace the input widget used in the TagMultiselectWidget. If not given,
4759 * TagMultiselectWidget creates its own.
4760 * @cfg {boolean} [inputPosition='inline'] Position of the input. Options are:
4761 * - inline: The input is invisible, but exists inside the tag list, so
4762 * the user types into the tag groups to add tags.
4763 * - outline: The input is underneath the tag area.
4764 * - none: No input supplied
4765 * @cfg {boolean} [allowEditTags=true] Allow editing of the tags by clicking them
4766 * @cfg {boolean} [allowArbitrary=false] Allow data items to be added even if
4767 * not present in the menu.
4768 * @cfg {Object[]} [allowedValues] An array representing the allowed items
4769 * by their datas.
4770 * @cfg {boolean} [allowDuplicates=false] Allow duplicate items to be added
4771 * @cfg {boolean} [allowDisplayInvalidTags=false] Allow the display of
4772 * invalid tags. These tags will display with an invalid state, and
4773 * the widget as a whole will have an invalid state if any invalid tags
4774 * are present.
4775 * @cfg {boolean} [allowReordering=true] Allow reordering of the items
4776 * @cfg {Object[]|String[]} [selected] A set of selected tags. If given,
4777 * these will appear in the tag list on initialization, as long as they
4778 * pass the validity tests.
4779 */
4780 OO.ui.TagMultiselectWidget = function OoUiTagMultiselectWidget( config ) {
4781 var inputEvents,
4782 rAF = window.requestAnimationFrame || setTimeout,
4783 widget = this,
4784 $tabFocus = $( '<span>' )
4785 .addClass( 'oo-ui-tagMultiselectWidget-focusTrap' );
4786
4787 config = config || {};
4788
4789 // Parent constructor
4790 OO.ui.TagMultiselectWidget.parent.call( this, config );
4791
4792 // Mixin constructors
4793 OO.ui.mixin.GroupWidget.call( this, config );
4794 OO.ui.mixin.IndicatorElement.call( this, config );
4795 OO.ui.mixin.IconElement.call( this, config );
4796 OO.ui.mixin.TabIndexedElement.call( this, config );
4797 OO.ui.mixin.FlaggedElement.call( this, config );
4798 OO.ui.mixin.DraggableGroupElement.call( this, config );
4799
4800 this.toggleDraggable(
4801 config.allowReordering === undefined ?
4802 true : !!config.allowReordering
4803 );
4804
4805 this.inputPosition =
4806 this.constructor.static.allowedInputPositions.indexOf( config.inputPosition ) > -1 ?
4807 config.inputPosition : 'inline';
4808 this.allowEditTags = config.allowEditTags === undefined ? true : !!config.allowEditTags;
4809 this.allowArbitrary = !!config.allowArbitrary;
4810 this.allowDuplicates = !!config.allowDuplicates;
4811 this.allowedValues = config.allowedValues || [];
4812 this.allowDisplayInvalidTags = config.allowDisplayInvalidTags;
4813 this.hasInput = this.inputPosition !== 'none';
4814 this.height = null;
4815 this.valid = true;
4816
4817 this.$content = $( '<div>' )
4818 .addClass( 'oo-ui-tagMultiselectWidget-content' );
4819 this.$handle = $( '<div>' )
4820 .addClass( 'oo-ui-tagMultiselectWidget-handle' )
4821 .append(
4822 this.$indicator,
4823 this.$icon,
4824 this.$content
4825 .append(
4826 this.$group
4827 .addClass( 'oo-ui-tagMultiselectWidget-group' )
4828 )
4829 );
4830
4831 // Events
4832 this.aggregate( {
4833 remove: 'itemRemove',
4834 navigate: 'itemNavigate',
4835 select: 'itemSelect'
4836 } );
4837 this.connect( this, {
4838 itemRemove: 'onTagRemove',
4839 itemSelect: 'onTagSelect',
4840 itemNavigate: 'onTagNavigate',
4841 change: 'onChangeTags'
4842 } );
4843 this.$handle.on( {
4844 mousedown: this.onMouseDown.bind( this )
4845 } );
4846
4847 // Initialize
4848 this.$element
4849 .addClass( 'oo-ui-tagMultiselectWidget' )
4850 .append( this.$handle );
4851
4852 if ( this.hasInput ) {
4853 if ( config.inputWidget ) {
4854 this.input = config.inputWidget;
4855 } else {
4856 this.input = new OO.ui.TextInputWidget( $.extend( {
4857 placeholder: config.placeholder,
4858 classes: [ 'oo-ui-tagMultiselectWidget-input' ]
4859 }, config.input ) );
4860 }
4861 this.input.setDisabled( this.isDisabled() );
4862
4863 inputEvents = {
4864 focus: this.onInputFocus.bind( this ),
4865 blur: this.onInputBlur.bind( this ),
4866 'propertychange change click mouseup keydown keyup input cut paste select focus':
4867 OO.ui.debounce( this.updateInputSize.bind( this ) ),
4868 keydown: this.onInputKeyDown.bind( this ),
4869 keypress: this.onInputKeyPress.bind( this )
4870 };
4871
4872 this.input.$input.on( inputEvents );
4873
4874 if ( this.inputPosition === 'outline' ) {
4875 // Override max-height for the input widget
4876 // in the case the widget is outline so it can
4877 // stretch all the way if the widet is wide
4878 this.input.$element.css( 'max-width', 'inherit' );
4879 this.$element
4880 .addClass( 'oo-ui-tagMultiselectWidget-outlined' )
4881 .append( this.input.$element );
4882 } else {
4883 this.$element.addClass( 'oo-ui-tagMultiselectWidget-inlined' );
4884 // HACK: When the widget is using 'inline' input, the
4885 // behavior needs to only use the $input itself
4886 // so we style and size it accordingly (otherwise
4887 // the styling and sizing can get very convoluted
4888 // when the wrapping divs and other elements)
4889 // We are taking advantage of still being able to
4890 // call the widget itself for operations like
4891 // .getValue() and setDisabled() and .focus() but
4892 // having only the $input attached to the DOM
4893 this.$content.append( this.input.$input );
4894 }
4895 } else {
4896 this.$content.append( $tabFocus );
4897 }
4898
4899 this.setTabIndexedElement(
4900 this.hasInput ?
4901 this.input.$input :
4902 $tabFocus
4903 );
4904
4905 if ( config.selected ) {
4906 this.setValue( config.selected );
4907 }
4908
4909 // HACK: Input size needs to be calculated after everything
4910 // else is rendered
4911 rAF( function () {
4912 if ( widget.hasInput ) {
4913 widget.updateInputSize();
4914 }
4915 } );
4916 };
4917
4918 /* Initialization */
4919
4920 OO.inheritClass( OO.ui.TagMultiselectWidget, OO.ui.Widget );
4921 OO.mixinClass( OO.ui.TagMultiselectWidget, OO.ui.mixin.GroupWidget );
4922 OO.mixinClass( OO.ui.TagMultiselectWidget, OO.ui.mixin.DraggableGroupElement );
4923 OO.mixinClass( OO.ui.TagMultiselectWidget, OO.ui.mixin.IndicatorElement );
4924 OO.mixinClass( OO.ui.TagMultiselectWidget, OO.ui.mixin.IconElement );
4925 OO.mixinClass( OO.ui.TagMultiselectWidget, OO.ui.mixin.TabIndexedElement );
4926 OO.mixinClass( OO.ui.TagMultiselectWidget, OO.ui.mixin.FlaggedElement );
4927
4928 /* Static properties */
4929
4930 /**
4931 * Allowed input positions.
4932 * - inline: The input is inside the tag list
4933 * - outline: The input is under the tag list
4934 * - none: There is no input
4935 *
4936 * @property {Array}
4937 */
4938 OO.ui.TagMultiselectWidget.static.allowedInputPositions = [ 'inline', 'outline', 'none' ];
4939
4940 /* Methods */
4941
4942 /**
4943 * Handle mouse down events.
4944 *
4945 * @private
4946 * @param {jQuery.Event} e Mouse down event
4947 * @return {boolean} False to prevent defaults
4948 */
4949 OO.ui.TagMultiselectWidget.prototype.onMouseDown = function ( e ) {
4950 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
4951 this.focus();
4952 return false;
4953 }
4954 };
4955
4956 /**
4957 * Handle key press events.
4958 *
4959 * @private
4960 * @param {jQuery.Event} e Key press event
4961 * @return {boolean} Whether to prevent defaults
4962 */
4963 OO.ui.TagMultiselectWidget.prototype.onInputKeyPress = function ( e ) {
4964 var stopOrContinue,
4965 withMetaKey = e.metaKey || e.ctrlKey;
4966
4967 if ( !this.isDisabled() ) {
4968 if ( e.which === OO.ui.Keys.ENTER ) {
4969 stopOrContinue = this.doInputEnter( e, withMetaKey );
4970 }
4971
4972 // Make sure the input gets resized.
4973 setTimeout( this.updateInputSize.bind( this ), 0 );
4974 return stopOrContinue;
4975 }
4976 };
4977
4978 /**
4979 * Handle key down events.
4980 *
4981 * @private
4982 * @param {jQuery.Event} e Key down event
4983 * @return {boolean}
4984 */
4985 OO.ui.TagMultiselectWidget.prototype.onInputKeyDown = function ( e ) {
4986 var movement, direction,
4987 withMetaKey = e.metaKey || e.ctrlKey;
4988
4989 if ( !this.isDisabled() ) {
4990 // 'keypress' event is not triggered for Backspace
4991 if ( e.keyCode === OO.ui.Keys.BACKSPACE ) {
4992 return this.doInputBackspace( e, withMetaKey );
4993 } else if ( e.keyCode === OO.ui.Keys.ESCAPE ) {
4994 return this.doInputEscape( e );
4995 } else if (
4996 e.keyCode === OO.ui.Keys.LEFT ||
4997 e.keyCode === OO.ui.Keys.RIGHT
4998 ) {
4999 if ( OO.ui.Element.static.getDir( this.$element ) === 'rtl' ) {
5000 movement = {
5001 left: 'forwards',
5002 right: 'backwards'
5003 };
5004 } else {
5005 movement = {
5006 left: 'backwards',
5007 right: 'forwards'
5008 };
5009 }
5010 direction = e.keyCode === OO.ui.Keys.LEFT ?
5011 movement.left : movement.right;
5012
5013 return this.doInputArrow( e, direction, withMetaKey );
5014 }
5015 }
5016 };
5017
5018 /**
5019 * Respond to input focus event
5020 */
5021 OO.ui.TagMultiselectWidget.prototype.onInputFocus = function () {
5022 this.$element.addClass( 'oo-ui-tagMultiselectWidget-focus' );
5023 };
5024
5025 /**
5026 * Respond to input blur event
5027 */
5028 OO.ui.TagMultiselectWidget.prototype.onInputBlur = function () {
5029 this.$element.removeClass( 'oo-ui-tagMultiselectWidget-focus' );
5030 };
5031
5032 /**
5033 * Perform an action after the enter key on the input
5034 *
5035 * @param {jQuery.Event} e Event data
5036 * @param {boolean} [withMetaKey] Whether this key was pressed with
5037 * a meta key like 'ctrl'
5038 * @return {boolean} Whether to prevent defaults
5039 */
5040 OO.ui.TagMultiselectWidget.prototype.doInputEnter = function () {
5041 this.addTagFromInput();
5042 return false;
5043 };
5044
5045 /**
5046 * Perform an action responding to the enter key on the input
5047 *
5048 * @param {jQuery.Event} e Event data
5049 * @param {boolean} [withMetaKey] Whether this key was pressed with
5050 * a meta key like 'ctrl'
5051 * @return {boolean} Whether to prevent defaults
5052 */
5053 OO.ui.TagMultiselectWidget.prototype.doInputBackspace = function ( e, withMetaKey ) {
5054 var items, item;
5055
5056 if (
5057 this.inputPosition === 'inline' &&
5058 this.input.getValue() === '' &&
5059 !this.isEmpty()
5060 ) {
5061 // Delete the last item
5062 items = this.getItems();
5063 item = items[ items.length - 1 ];
5064 this.removeItems( [ item ] );
5065 // If Ctrl/Cmd was pressed, delete item entirely.
5066 // Otherwise put it into the text field for editing.
5067 if ( !withMetaKey ) {
5068 this.input.setValue( item.getData() );
5069 }
5070
5071 return false;
5072 }
5073 };
5074
5075 /**
5076 * Perform an action after the escape key on the input
5077 *
5078 * @param {jQuery.Event} e Event data
5079 */
5080 OO.ui.TagMultiselectWidget.prototype.doInputEscape = function () {
5081 this.clearInput();
5082 };
5083
5084 /**
5085 * Perform an action after the arrow key on the input, select the previous
5086 * or next item from the input.
5087 * See #getPreviousItem and #getNextItem
5088 *
5089 * @param {jQuery.Event} e Event data
5090 * @param {string} direction Direction of the movement; forwards or backwards
5091 * @param {boolean} [withMetaKey] Whether this key was pressed with
5092 * a meta key like 'ctrl'
5093 */
5094 OO.ui.TagMultiselectWidget.prototype.doInputArrow = function ( e, direction ) {
5095 if (
5096 this.inputPosition === 'inline' &&
5097 !this.isEmpty()
5098 ) {
5099 if ( direction === 'backwards' ) {
5100 // Get previous item
5101 this.getPreviousItem().focus();
5102 } else {
5103 // Get next item
5104 this.getNextItem().focus();
5105 }
5106 }
5107 };
5108
5109 /**
5110 * Respond to item select event
5111 *
5112 * @param {OO.ui.TagItemWidget} item Selected item
5113 */
5114 OO.ui.TagMultiselectWidget.prototype.onTagSelect = function ( item ) {
5115 if ( this.hasInput && this.allowEditTags ) {
5116 if ( this.input.getValue() ) {
5117 this.addTagFromInput();
5118 }
5119 // 1. Get the label of the tag into the input
5120 this.input.setValue( item.getData() );
5121 // 2. Remove the tag
5122 this.removeItems( [ item ] );
5123 // 3. Focus the input
5124 this.focus();
5125 }
5126 };
5127
5128 /**
5129 * Respond to change event, where items were added, removed, or cleared.
5130 */
5131 OO.ui.TagMultiselectWidget.prototype.onChangeTags = function () {
5132 this.toggleValid( this.checkValidity() );
5133 if ( this.hasInput ) {
5134 this.updateInputSize();
5135 }
5136 this.updateIfHeightChanged();
5137 };
5138
5139 /**
5140 * @inheritdoc
5141 */
5142 OO.ui.TagMultiselectWidget.prototype.setDisabled = function ( isDisabled ) {
5143 // Parent method
5144 OO.ui.TagMultiselectWidget.parent.prototype.setDisabled.call( this, isDisabled );
5145
5146 if ( this.hasInput && this.input ) {
5147 this.input.setDisabled( !!isDisabled );
5148 }
5149
5150 if ( this.items ) {
5151 this.getItems().forEach( function ( item ) {
5152 item.setDisabled( !!isDisabled );
5153 } );
5154 }
5155 };
5156
5157 /**
5158 * Respond to tag remove event
5159 * @param {OO.ui.TagItemWidget} item Removed tag
5160 */
5161 OO.ui.TagMultiselectWidget.prototype.onTagRemove = function ( item ) {
5162 this.removeTagByData( item.getData() );
5163 };
5164
5165 /**
5166 * Respond to navigate event on the tag
5167 *
5168 * @param {OO.ui.TagItemWidget} item Removed tag
5169 * @param {string} direction Direction of movement; 'forwards' or 'backwards'
5170 */
5171 OO.ui.TagMultiselectWidget.prototype.onTagNavigate = function ( item, direction ) {
5172 if ( direction === 'forwards' ) {
5173 this.getNextItem( item ).focus();
5174 } else {
5175 this.getPreviousItem( item ).focus();
5176 }
5177 };
5178
5179 /**
5180 * Add tag from input value
5181 */
5182 OO.ui.TagMultiselectWidget.prototype.addTagFromInput = function () {
5183 var val = this.input.getValue(),
5184 isValid = this.isAllowedData( val );
5185
5186 if ( !val ) {
5187 return;
5188 }
5189
5190 if ( isValid || this.allowDisplayInvalidTags ) {
5191 this.addTag( val );
5192 this.clearInput();
5193 this.focus();
5194 }
5195 };
5196
5197 /**
5198 * Clear the input
5199 */
5200 OO.ui.TagMultiselectWidget.prototype.clearInput = function () {
5201 this.input.setValue( '' );
5202 };
5203
5204 /**
5205 * Check whether the given value is a duplicate of an existing
5206 * tag already in the list.
5207 *
5208 * @param {string|Object} data Requested value
5209 * @return {boolean} Value is duplicate
5210 */
5211 OO.ui.TagMultiselectWidget.prototype.isDuplicateData = function ( data ) {
5212 return !!this.getItemFromData( data );
5213 };
5214
5215 /**
5216 * Check whether a given value is allowed to be added
5217 *
5218 * @param {string|Object} data Requested value
5219 * @return {boolean} Value is allowed
5220 */
5221 OO.ui.TagMultiselectWidget.prototype.isAllowedData = function ( data ) {
5222 if (
5223 !this.allowDuplicates &&
5224 this.isDuplicateData( data )
5225 ) {
5226 return false;
5227 }
5228
5229 if ( this.allowArbitrary ) {
5230 return true;
5231 }
5232
5233 // Check with allowed values
5234 if (
5235 this.getAllowedValues().some( function ( value ) {
5236 return data === value;
5237 } )
5238 ) {
5239 return true;
5240 }
5241
5242 return false;
5243 };
5244
5245 /**
5246 * Get the allowed values list
5247 *
5248 * @return {string[]} Allowed data values
5249 */
5250 OO.ui.TagMultiselectWidget.prototype.getAllowedValues = function () {
5251 return this.allowedValues;
5252 };
5253
5254 /**
5255 * Add a value to the allowed values list
5256 *
5257 * @param {string} value Allowed data value
5258 */
5259 OO.ui.TagMultiselectWidget.prototype.addAllowedValue = function ( value ) {
5260 if ( this.allowedValues.indexOf( value ) === -1 ) {
5261 this.allowedValues.push( value );
5262 }
5263 };
5264
5265 /**
5266 * Get the datas of the currently selected items
5267 *
5268 * @return {string[]|Object[]} Datas of currently selected items
5269 */
5270 OO.ui.TagMultiselectWidget.prototype.getValue = function () {
5271 return this.getItems()
5272 .filter( function ( item ) {
5273 return item.isValid();
5274 } )
5275 .map( function ( item ) {
5276 return item.getData();
5277 } );
5278 };
5279
5280 /**
5281 * Set the value of this widget by datas.
5282 *
5283 * @param {string|string[]|Object|Object[]} valueObject An object representing the data
5284 * and label of the value. If the widget allows arbitrary values,
5285 * the items will be added as-is. Otherwise, the data value will
5286 * be checked against allowedValues.
5287 * This object must contain at least a data key. Example:
5288 * { data: 'foo', label: 'Foo item' }
5289 * For multiple items, use an array of objects. For example:
5290 * [
5291 * { data: 'foo', label: 'Foo item' },
5292 * { data: 'bar', label: 'Bar item' }
5293 * ]
5294 * Value can also be added with plaintext array, for example:
5295 * [ 'foo', 'bar', 'bla' ] or a single string, like 'foo'
5296 */
5297 OO.ui.TagMultiselectWidget.prototype.setValue = function ( valueObject ) {
5298 valueObject = Array.isArray( valueObject ) ? valueObject : [ valueObject ];
5299
5300 this.clearItems();
5301 valueObject.forEach( function ( obj ) {
5302 if ( typeof obj === 'string' ) {
5303 this.addTag( obj );
5304 } else {
5305 this.addTag( obj.data, obj.label );
5306 }
5307 }.bind( this ) );
5308 };
5309
5310 /**
5311 * Add tag to the display area
5312 *
5313 * @param {string|Object} data Tag data
5314 * @param {string} [label] Tag label. If no label is provided, the
5315 * stringified version of the data will be used instead.
5316 * @return {boolean} Item was added successfully
5317 */
5318 OO.ui.TagMultiselectWidget.prototype.addTag = function ( data, label ) {
5319 var newItemWidget,
5320 isValid = this.isAllowedData( data );
5321
5322 if ( isValid || this.allowDisplayInvalidTags ) {
5323 newItemWidget = this.createTagItemWidget( data, label );
5324 newItemWidget.toggleValid( isValid );
5325 this.addItems( [ newItemWidget ] );
5326 return true;
5327 }
5328 return false;
5329 };
5330
5331 /**
5332 * Remove tag by its data property.
5333 *
5334 * @param {string|Object} data Tag data
5335 */
5336 OO.ui.TagMultiselectWidget.prototype.removeTagByData = function ( data ) {
5337 var item = this.getItemFromData( data );
5338
5339 this.removeItems( [ item ] );
5340 };
5341
5342 /**
5343 * Construct a OO.ui.TagItemWidget (or a subclass thereof) from given label and data.
5344 *
5345 * @protected
5346 * @param {string} data Item data
5347 * @param {string} label The label text.
5348 * @return {OO.ui.TagItemWidget}
5349 */
5350 OO.ui.TagMultiselectWidget.prototype.createTagItemWidget = function ( data, label ) {
5351 label = label || data;
5352
5353 return new OO.ui.TagItemWidget( { data: data, label: label } );
5354 };
5355
5356 /**
5357 * Given an item, returns the item after it. If the item is already the
5358 * last item, return `this.input`. If no item is passed, returns the
5359 * very first item.
5360 *
5361 * @protected
5362 * @param {OO.ui.TagItemWidget} [item] Tag item
5363 * @return {OO.ui.Widget} The next widget available.
5364 */
5365 OO.ui.TagMultiselectWidget.prototype.getNextItem = function ( item ) {
5366 var itemIndex = this.items.indexOf( item );
5367
5368 if ( item === undefined || itemIndex === -1 ) {
5369 return this.items[ 0 ];
5370 }
5371
5372 if ( itemIndex === this.items.length - 1 ) { // Last item
5373 if ( this.hasInput ) {
5374 return this.input;
5375 } else {
5376 // Return first item
5377 return this.items[ 0 ];
5378 }
5379 } else {
5380 return this.items[ itemIndex + 1 ];
5381 }
5382 };
5383
5384 /**
5385 * Given an item, returns the item before it. If the item is already the
5386 * first item, return `this.input`. If no item is passed, returns the
5387 * very last item.
5388 *
5389 * @protected
5390 * @param {OO.ui.TagItemWidget} [item] Tag item
5391 * @return {OO.ui.Widget} The previous widget available.
5392 */
5393 OO.ui.TagMultiselectWidget.prototype.getPreviousItem = function ( item ) {
5394 var itemIndex = this.items.indexOf( item );
5395
5396 if ( item === undefined || itemIndex === -1 ) {
5397 return this.items[ this.items.length - 1 ];
5398 }
5399
5400 if ( itemIndex === 0 ) {
5401 if ( this.hasInput ) {
5402 return this.input;
5403 } else {
5404 // Return the last item
5405 return this.items[ this.items.length - 1 ];
5406 }
5407 } else {
5408 return this.items[ itemIndex - 1 ];
5409 }
5410 };
5411
5412 /**
5413 * Update the dimensions of the text input field to encompass all available area.
5414 * This is especially relevant for when the input is at the edge of a line
5415 * and should get smaller. The usual operation (as an inline-block with min-width)
5416 * does not work in that case, pushing the input downwards to the next line.
5417 *
5418 * @private
5419 */
5420 OO.ui.TagMultiselectWidget.prototype.updateInputSize = function () {
5421 var $lastItem, direction, contentWidth, currentWidth, bestWidth;
5422 if ( this.inputPosition === 'inline' && !this.isDisabled() ) {
5423 if ( this.input.$input[ 0 ].scrollWidth === 0 ) {
5424 // Input appears to be attached but not visible.
5425 // Don't attempt to adjust its size, because our measurements
5426 // are going to fail anyway.
5427 return;
5428 }
5429 this.input.$input.css( 'width', '1em' );
5430 $lastItem = this.$group.children().last();
5431 direction = OO.ui.Element.static.getDir( this.$handle );
5432
5433 // Get the width of the input with the placeholder text as
5434 // the value and save it so that we don't keep recalculating
5435 if (
5436 this.contentWidthWithPlaceholder === undefined &&
5437 this.input.getValue() === '' &&
5438 this.input.$input.attr( 'placeholder' ) !== undefined
5439 ) {
5440 this.input.setValue( this.input.$input.attr( 'placeholder' ) );
5441 this.contentWidthWithPlaceholder = this.input.$input[ 0 ].scrollWidth;
5442 this.input.setValue( '' );
5443
5444 }
5445
5446 // Always keep the input wide enough for the placeholder text
5447 contentWidth = Math.max(
5448 this.input.$input[ 0 ].scrollWidth,
5449 // undefined arguments in Math.max lead to NaN
5450 ( this.contentWidthWithPlaceholder === undefined ) ?
5451 0 : this.contentWidthWithPlaceholder
5452 );
5453 currentWidth = this.input.$input.width();
5454
5455 if ( contentWidth < currentWidth ) {
5456 this.updateIfHeightChanged();
5457 // All is fine, don't perform expensive calculations
5458 return;
5459 }
5460
5461 if ( $lastItem.length === 0 ) {
5462 bestWidth = this.$content.innerWidth();
5463 } else {
5464 bestWidth = direction === 'ltr' ?
5465 this.$content.innerWidth() - $lastItem.position().left - $lastItem.outerWidth() :
5466 $lastItem.position().left;
5467 }
5468
5469 // Some safety margin for sanity, because I *really* don't feel like finding out where the few
5470 // pixels this is off by are coming from.
5471 bestWidth -= 10;
5472 if ( contentWidth > bestWidth ) {
5473 // This will result in the input getting shifted to the next line
5474 bestWidth = this.$content.innerWidth() - 10;
5475 }
5476 this.input.$input.width( Math.floor( bestWidth ) );
5477 this.updateIfHeightChanged();
5478 } else {
5479 this.updateIfHeightChanged();
5480 }
5481 };
5482
5483 /**
5484 * Determine if widget height changed, and if so,
5485 * emit the resize event. This is useful for when there are either
5486 * menus or popups attached to the bottom of the widget, to allow
5487 * them to change their positioning in case the widget moved down
5488 * or up.
5489 *
5490 * @private
5491 */
5492 OO.ui.TagMultiselectWidget.prototype.updateIfHeightChanged = function () {
5493 var height = this.$element.height();
5494 if ( height !== this.height ) {
5495 this.height = height;
5496 this.emit( 'resize' );
5497 }
5498 };
5499
5500 /**
5501 * Check whether all items in the widget are valid
5502 *
5503 * @return {boolean} Widget is valid
5504 */
5505 OO.ui.TagMultiselectWidget.prototype.checkValidity = function () {
5506 return this.getItems().every( function ( item ) {
5507 return item.isValid();
5508 } );
5509 };
5510
5511 /**
5512 * Set the valid state of this item
5513 *
5514 * @param {boolean} [valid] Item is valid
5515 * @fires valid
5516 */
5517 OO.ui.TagMultiselectWidget.prototype.toggleValid = function ( valid ) {
5518 valid = valid === undefined ? !this.valid : !!valid;
5519
5520 if ( this.valid !== valid ) {
5521 this.valid = valid;
5522
5523 this.setFlags( { invalid: !this.valid } );
5524
5525 this.emit( 'valid', this.valid );
5526 }
5527 };
5528
5529 /**
5530 * Get the current valid state of the widget
5531 *
5532 * @return {boolean} Widget is valid
5533 */
5534 OO.ui.TagMultiselectWidget.prototype.isValid = function () {
5535 return this.valid;
5536 };
5537
5538 /**
5539 * PopupTagMultiselectWidget is a {@link OO.ui.TagMultiselectWidget OO.ui.TagMultiselectWidget} intended
5540 * to use a popup. The popup can be configured to have a default input to insert values into the widget.
5541 *
5542 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
5543 *
5544 * @example
5545 * // Example: A basic PopupTagMultiselectWidget.
5546 * var widget = new OO.ui.PopupTagMultiselectWidget();
5547 * $( 'body' ).append( widget.$element );
5548 *
5549 * // Example: A PopupTagMultiselectWidget with an external popup.
5550 * var popupInput = new OO.ui.TextInputWidget(),
5551 * widget = new OO.ui.PopupTagMultiselectWidget( {
5552 * popupInput: popupInput,
5553 * popup: {
5554 * $content: popupInput.$element
5555 * }
5556 * } );
5557 * $( 'body' ).append( widget.$element );
5558 *
5559 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
5560 *
5561 * @class
5562 * @extends OO.ui.TagMultiselectWidget
5563 * @mixins OO.ui.mixin.PopupElement
5564 *
5565 * @param {Object} config Configuration object
5566 * @cfg {jQuery} [$overlay] An overlay for the popup.
5567 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
5568 * @cfg {Object} [popup] Configuration options for the popup
5569 * @cfg {OO.ui.InputWidget} [popupInput] An input widget inside the popup that will be
5570 * focused when the popup is opened and will be used as replacement for the
5571 * general input in the widget.
5572 */
5573 OO.ui.PopupTagMultiselectWidget = function OoUiPopupTagMultiselectWidget( config ) {
5574 var defaultInput,
5575 defaultConfig = { popup: {} };
5576
5577 config = config || {};
5578
5579 // Parent constructor
5580 OO.ui.PopupTagMultiselectWidget.parent.call( this, $.extend( { inputPosition: 'none' }, config ) );
5581
5582 this.$overlay = config.$overlay || this.$element;
5583
5584 if ( !config.popup ) {
5585 // For the default base implementation, we give a popup
5586 // with an input widget inside it. For any other use cases
5587 // the popup needs to be populated externally and the
5588 // event handled to add tags separately and manually
5589 defaultInput = new OO.ui.TextInputWidget();
5590
5591 defaultConfig.popupInput = defaultInput;
5592 defaultConfig.popup.$content = defaultInput.$element;
5593
5594 this.$element.addClass( 'oo-ui-popupTagMultiselectWidget-defaultPopup' );
5595 }
5596
5597 // Add overlay, and add that to the autoCloseIgnore
5598 defaultConfig.popup.$overlay = this.$overlay;
5599 defaultConfig.popup.$autoCloseIgnore = this.hasInput ?
5600 this.input.$element.add( this.$overlay ) : this.$overlay;
5601
5602 // Allow extending any of the above
5603 config = $.extend( defaultConfig, config );
5604
5605 // Mixin constructors
5606 OO.ui.mixin.PopupElement.call( this, config );
5607
5608 if ( this.hasInput ) {
5609 this.input.$input.on( 'focus', this.popup.toggle.bind( this.popup, true ) );
5610 }
5611
5612 // Configuration options
5613 this.popupInput = config.popupInput;
5614 if ( this.popupInput ) {
5615 this.popupInput.connect( this, {
5616 enter: 'onPopupInputEnter'
5617 } );
5618 }
5619
5620 // Events
5621 this.on( 'resize', this.popup.updateDimensions.bind( this.popup ) );
5622 this.popup.connect( this, { toggle: 'onPopupToggle' } );
5623 this.$tabIndexed
5624 .on( 'focus', this.onFocus.bind( this ) );
5625
5626 // Initialize
5627 this.$element
5628 .append( this.popup.$element )
5629 .addClass( 'oo-ui-popupTagMultiselectWidget' );
5630 };
5631
5632 /* Initialization */
5633
5634 OO.inheritClass( OO.ui.PopupTagMultiselectWidget, OO.ui.TagMultiselectWidget );
5635 OO.mixinClass( OO.ui.PopupTagMultiselectWidget, OO.ui.mixin.PopupElement );
5636
5637 /* Methods */
5638
5639 /**
5640 * Focus event handler.
5641 *
5642 * @private
5643 */
5644 OO.ui.PopupTagMultiselectWidget.prototype.onFocus = function () {
5645 this.popup.toggle( true );
5646 };
5647
5648 /**
5649 * Respond to popup toggle event
5650 *
5651 * @param {boolean} isVisible Popup is visible
5652 */
5653 OO.ui.PopupTagMultiselectWidget.prototype.onPopupToggle = function ( isVisible ) {
5654 if ( isVisible && this.popupInput ) {
5655 this.popupInput.focus();
5656 }
5657 };
5658
5659 /**
5660 * Respond to popup input enter event
5661 */
5662 OO.ui.PopupTagMultiselectWidget.prototype.onPopupInputEnter = function () {
5663 if ( this.popupInput ) {
5664 this.addTagByPopupValue( this.popupInput.getValue() );
5665 this.popupInput.setValue( '' );
5666 }
5667 };
5668
5669 /**
5670 * @inheritdoc
5671 */
5672 OO.ui.PopupTagMultiselectWidget.prototype.onTagSelect = function ( item ) {
5673 if ( this.popupInput && this.allowEditTags ) {
5674 this.popupInput.setValue( item.getData() );
5675 this.removeItems( [ item ] );
5676
5677 this.popup.toggle( true );
5678 this.popupInput.focus();
5679 } else {
5680 // Parent
5681 OO.ui.PopupTagMultiselectWidget.parent.prototype.onTagSelect.call( this, item );
5682 }
5683 };
5684
5685 /**
5686 * Add a tag by the popup value.
5687 * Whatever is responsible for setting the value in the popup should call
5688 * this method to add a tag, or use the regular methods like #addTag or
5689 * #setValue directly.
5690 *
5691 * @param {string} data The value of item
5692 * @param {string} [label] The label of the tag. If not given, the data is used.
5693 */
5694 OO.ui.PopupTagMultiselectWidget.prototype.addTagByPopupValue = function ( data, label ) {
5695 this.addTag( data, label );
5696 };
5697
5698 /**
5699 * MenuTagMultiselectWidget is a {@link OO.ui.TagMultiselectWidget OO.ui.TagMultiselectWidget} intended
5700 * to use a menu of selectable options.
5701 *
5702 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
5703 *
5704 * @example
5705 * // Example: A basic MenuTagMultiselectWidget.
5706 * var widget = new OO.ui.MenuTagMultiselectWidget( {
5707 * inputPosition: 'outline',
5708 * options: [
5709 * { data: 'option1', label: 'Option 1' },
5710 * { data: 'option2', label: 'Option 2' },
5711 * { data: 'option3', label: 'Option 3' },
5712 * ],
5713 * selected: [ 'option1', 'option2' ]
5714 * } );
5715 * $( 'body' ).append( widget.$element );
5716 *
5717 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
5718 *
5719 * @class
5720 * @extends OO.ui.TagMultiselectWidget
5721 *
5722 * @constructor
5723 * @param {Object} [config] Configuration object
5724 * @cfg {Object} [menu] Configuration object for the menu widget
5725 * @cfg {jQuery} [$overlay] An overlay for the menu.
5726 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
5727 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
5728 */
5729 OO.ui.MenuTagMultiselectWidget = function OoUiMenuTagMultiselectWidget( config ) {
5730 config = config || {};
5731
5732 // Parent constructor
5733 OO.ui.MenuTagMultiselectWidget.parent.call( this, config );
5734
5735 this.$overlay = config.$overlay || this.$element;
5736
5737 this.menu = this.createMenuWidget( $.extend( {
5738 widget: this,
5739 input: this.hasInput ? this.input : null,
5740 $input: this.hasInput ? this.input.$input : null,
5741 filterFromInput: !!this.hasInput,
5742 $autoCloseIgnore: this.hasInput ?
5743 this.input.$element.add( this.$overlay ) : this.$overlay,
5744 $floatableContainer: this.hasInput && this.inputPosition === 'outline' ?
5745 this.input.$element : this.$element,
5746 $overlay: this.$overlay,
5747 disabled: this.isDisabled()
5748 }, config.menu ) );
5749 this.addOptions( config.options || [] );
5750
5751 // Events
5752 this.menu.connect( this, {
5753 choose: 'onMenuChoose',
5754 toggle: 'onMenuToggle'
5755 } );
5756 if ( this.hasInput ) {
5757 this.input.connect( this, { change: 'onInputChange' } );
5758 }
5759 this.connect( this, { resize: 'onResize' } );
5760
5761 // Initialization
5762 this.$overlay
5763 .append( this.menu.$element );
5764 this.$element
5765 .addClass( 'oo-ui-menuTagMultiselectWidget' );
5766 // TagMultiselectWidget already does this, but it doesn't work right because this.menu is not yet
5767 // set up while the parent constructor runs, and #getAllowedValues rejects everything.
5768 if ( config.selected ) {
5769 this.setValue( config.selected );
5770 }
5771 };
5772
5773 /* Initialization */
5774
5775 OO.inheritClass( OO.ui.MenuTagMultiselectWidget, OO.ui.TagMultiselectWidget );
5776
5777 /* Methods */
5778
5779 /**
5780 * Respond to resize event
5781 */
5782 OO.ui.MenuTagMultiselectWidget.prototype.onResize = function () {
5783 // Reposition the menu
5784 this.menu.position();
5785 };
5786
5787 /**
5788 * @inheritdoc
5789 */
5790 OO.ui.MenuTagMultiselectWidget.prototype.onInputFocus = function () {
5791 // Parent method
5792 OO.ui.MenuTagMultiselectWidget.parent.prototype.onInputFocus.call( this );
5793
5794 this.menu.toggle( true );
5795 };
5796
5797 /**
5798 * Respond to input change event
5799 */
5800 OO.ui.MenuTagMultiselectWidget.prototype.onInputChange = function () {
5801 this.menu.toggle( true );
5802 };
5803
5804 /**
5805 * Respond to menu choose event
5806 *
5807 * @param {OO.ui.OptionWidget} menuItem Chosen menu item
5808 */
5809 OO.ui.MenuTagMultiselectWidget.prototype.onMenuChoose = function ( menuItem ) {
5810 // Add tag
5811 this.addTag( menuItem.getData(), menuItem.getLabel() );
5812 };
5813
5814 /**
5815 * Respond to menu toggle event. Reset item highlights on hide.
5816 *
5817 * @param {boolean} isVisible The menu is visible
5818 */
5819 OO.ui.MenuTagMultiselectWidget.prototype.onMenuToggle = function ( isVisible ) {
5820 if ( !isVisible ) {
5821 this.menu.selectItem( null );
5822 this.menu.highlightItem( null );
5823 }
5824 };
5825
5826 /**
5827 * @inheritdoc
5828 */
5829 OO.ui.MenuTagMultiselectWidget.prototype.onTagSelect = function ( tagItem ) {
5830 var menuItem = this.menu.getItemFromData( tagItem.getData() );
5831 // Override the base behavior from TagMultiselectWidget; the base behavior
5832 // in TagMultiselectWidget is to remove the tag to edit it in the input,
5833 // but in our case, we want to utilize the menu selection behavior, and
5834 // definitely not remove the item.
5835
5836 // Select the menu item
5837 this.menu.selectItem( menuItem );
5838
5839 this.focus();
5840 };
5841
5842 /**
5843 * @inheritdoc
5844 */
5845 OO.ui.MenuTagMultiselectWidget.prototype.addTagFromInput = function () {
5846 var inputValue = this.input.getValue(),
5847 validated = false,
5848 highlightedItem = this.menu.findHighlightedItem(),
5849 item = this.menu.getItemFromData( inputValue );
5850
5851 // Override the parent method so we add from the menu
5852 // rather than directly from the input
5853
5854 // Look for a highlighted item first
5855 if ( highlightedItem ) {
5856 validated = this.addTag( highlightedItem.getData(), highlightedItem.getLabel() );
5857 } else if ( item ) {
5858 // Look for the element that fits the data
5859 validated = this.addTag( item.getData(), item.getLabel() );
5860 } else {
5861 // Otherwise, add the tag - the method will only add if the
5862 // tag is valid or if invalid tags are allowed
5863 validated = this.addTag( inputValue );
5864 }
5865
5866 if ( validated ) {
5867 this.clearInput();
5868 this.focus();
5869 }
5870 };
5871
5872 /**
5873 * Return the visible items in the menu. This is mainly used for when
5874 * the menu is filtering results.
5875 *
5876 * @return {OO.ui.MenuOptionWidget[]} Visible results
5877 */
5878 OO.ui.MenuTagMultiselectWidget.prototype.getMenuVisibleItems = function () {
5879 return this.menu.getItems().filter( function ( menuItem ) {
5880 return menuItem.isVisible();
5881 } );
5882 };
5883
5884 /**
5885 * Create the menu for this widget. This is in a separate method so that
5886 * child classes can override this without polluting the constructor with
5887 * unnecessary extra objects that will be overidden.
5888 *
5889 * @param {Object} menuConfig Configuration options
5890 * @return {OO.ui.MenuSelectWidget} Menu widget
5891 */
5892 OO.ui.MenuTagMultiselectWidget.prototype.createMenuWidget = function ( menuConfig ) {
5893 return new OO.ui.MenuSelectWidget( menuConfig );
5894 };
5895
5896 /**
5897 * Add options to the menu
5898 *
5899 * @param {Object[]} menuOptions Object defining options
5900 */
5901 OO.ui.MenuTagMultiselectWidget.prototype.addOptions = function ( menuOptions ) {
5902 var widget = this,
5903 items = menuOptions.map( function ( obj ) {
5904 return widget.createMenuOptionWidget( obj.data, obj.label );
5905 } );
5906
5907 this.menu.addItems( items );
5908 };
5909
5910 /**
5911 * Create a menu option widget.
5912 *
5913 * @param {string} data Item data
5914 * @param {string} [label] Item label
5915 * @return {OO.ui.OptionWidget} Option widget
5916 */
5917 OO.ui.MenuTagMultiselectWidget.prototype.createMenuOptionWidget = function ( data, label ) {
5918 return new OO.ui.MenuOptionWidget( {
5919 data: data,
5920 label: label || data
5921 } );
5922 };
5923
5924 /**
5925 * Get the menu
5926 *
5927 * @return {OO.ui.MenuSelectWidget} Menu
5928 */
5929 OO.ui.MenuTagMultiselectWidget.prototype.getMenu = function () {
5930 return this.menu;
5931 };
5932
5933 /**
5934 * Get the allowed values list
5935 *
5936 * @return {string[]} Allowed data values
5937 */
5938 OO.ui.MenuTagMultiselectWidget.prototype.getAllowedValues = function () {
5939 var menuDatas = [];
5940 if ( this.menu ) {
5941 // If the parent constructor is calling us, we're not ready yet, this.menu is not set up.
5942 menuDatas = this.menu.getItems().map( function ( menuItem ) {
5943 return menuItem.getData();
5944 } );
5945 }
5946 return this.allowedValues.concat( menuDatas );
5947 };
5948
5949 /**
5950 * SelectFileWidgets allow for selecting files, using the HTML5 File API. These
5951 * widgets can be configured with {@link OO.ui.mixin.IconElement icons} and {@link
5952 * OO.ui.mixin.IndicatorElement indicators}.
5953 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
5954 *
5955 * @example
5956 * // Example of a file select widget
5957 * var selectFile = new OO.ui.SelectFileWidget();
5958 * $( 'body' ).append( selectFile.$element );
5959 *
5960 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets
5961 *
5962 * @class
5963 * @extends OO.ui.Widget
5964 * @mixins OO.ui.mixin.IconElement
5965 * @mixins OO.ui.mixin.IndicatorElement
5966 * @mixins OO.ui.mixin.PendingElement
5967 * @mixins OO.ui.mixin.LabelElement
5968 *
5969 * @constructor
5970 * @param {Object} [config] Configuration options
5971 * @cfg {string[]|null} [accept=null] MIME types to accept. null accepts all types.
5972 * @cfg {string} [placeholder] Text to display when no file is selected.
5973 * @cfg {string} [notsupported] Text to display when file support is missing in the browser.
5974 * @cfg {boolean} [droppable=true] Whether to accept files by drag and drop.
5975 * @cfg {boolean} [showDropTarget=false] Whether to show a drop target. Requires droppable to be true.
5976 * @cfg {number} [thumbnailSizeLimit=20] File size limit in MiB above which to not try and show a
5977 * preview (for performance)
5978 */
5979 OO.ui.SelectFileWidget = function OoUiSelectFileWidget( config ) {
5980 var dragHandler;
5981
5982 // Configuration initialization
5983 config = $.extend( {
5984 accept: null,
5985 placeholder: OO.ui.msg( 'ooui-selectfile-placeholder' ),
5986 notsupported: OO.ui.msg( 'ooui-selectfile-not-supported' ),
5987 droppable: true,
5988 showDropTarget: false,
5989 thumbnailSizeLimit: 20
5990 }, config );
5991
5992 // Parent constructor
5993 OO.ui.SelectFileWidget.parent.call( this, config );
5994
5995 // Mixin constructors
5996 OO.ui.mixin.IconElement.call( this, config );
5997 OO.ui.mixin.IndicatorElement.call( this, config );
5998 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$info } ) );
5999 OO.ui.mixin.LabelElement.call( this, config );
6000
6001 // Properties
6002 this.$info = $( '<span>' );
6003 this.showDropTarget = config.showDropTarget;
6004 this.thumbnailSizeLimit = config.thumbnailSizeLimit;
6005 this.isSupported = this.constructor.static.isSupported();
6006 this.currentFile = null;
6007 if ( Array.isArray( config.accept ) ) {
6008 this.accept = config.accept;
6009 } else {
6010 this.accept = null;
6011 }
6012 this.placeholder = config.placeholder;
6013 this.notsupported = config.notsupported;
6014 this.onFileSelectedHandler = this.onFileSelected.bind( this );
6015
6016 this.selectButton = new OO.ui.ButtonWidget( {
6017 classes: [ 'oo-ui-selectFileWidget-selectButton' ],
6018 label: OO.ui.msg( 'ooui-selectfile-button-select' ),
6019 disabled: this.disabled || !this.isSupported
6020 } );
6021
6022 this.clearButton = new OO.ui.ButtonWidget( {
6023 classes: [ 'oo-ui-selectFileWidget-clearButton' ],
6024 framed: false,
6025 icon: 'close',
6026 disabled: this.disabled
6027 } );
6028
6029 // Events
6030 this.selectButton.$button.on( {
6031 keypress: this.onKeyPress.bind( this )
6032 } );
6033 this.clearButton.connect( this, {
6034 click: 'onClearClick'
6035 } );
6036 if ( config.droppable ) {
6037 dragHandler = this.onDragEnterOrOver.bind( this );
6038 this.$element.on( {
6039 dragenter: dragHandler,
6040 dragover: dragHandler,
6041 dragleave: this.onDragLeave.bind( this ),
6042 drop: this.onDrop.bind( this )
6043 } );
6044 }
6045
6046 // Initialization
6047 this.addInput();
6048 this.$label.addClass( 'oo-ui-selectFileWidget-label' );
6049 this.$info
6050 .addClass( 'oo-ui-selectFileWidget-info' )
6051 .append( this.$icon, this.$label, this.clearButton.$element, this.$indicator );
6052
6053 if ( config.droppable && config.showDropTarget ) {
6054 this.selectButton.setIcon( 'upload' );
6055 this.$thumbnail = $( '<div>' ).addClass( 'oo-ui-selectFileWidget-thumbnail' );
6056 this.setPendingElement( this.$thumbnail );
6057 this.$element
6058 .addClass( 'oo-ui-selectFileWidget-dropTarget oo-ui-selectFileWidget' )
6059 .on( {
6060 click: this.onDropTargetClick.bind( this )
6061 } )
6062 .append(
6063 this.$thumbnail,
6064 this.$info,
6065 this.selectButton.$element,
6066 $( '<span>' )
6067 .addClass( 'oo-ui-selectFileWidget-dropLabel' )
6068 .text( OO.ui.msg( 'ooui-selectfile-dragdrop-placeholder' ) )
6069 );
6070 } else {
6071 this.$element
6072 .addClass( 'oo-ui-selectFileWidget' )
6073 .append( this.$info, this.selectButton.$element );
6074 }
6075 this.updateUI();
6076 };
6077
6078 /* Setup */
6079
6080 OO.inheritClass( OO.ui.SelectFileWidget, OO.ui.Widget );
6081 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IconElement );
6082 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IndicatorElement );
6083 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.PendingElement );
6084 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.LabelElement );
6085
6086 /* Static Properties */
6087
6088 /**
6089 * Check if this widget is supported
6090 *
6091 * @static
6092 * @return {boolean}
6093 */
6094 OO.ui.SelectFileWidget.static.isSupported = function () {
6095 var $input;
6096 if ( OO.ui.SelectFileWidget.static.isSupportedCache === null ) {
6097 $input = $( '<input>' ).attr( 'type', 'file' );
6098 OO.ui.SelectFileWidget.static.isSupportedCache = $input[ 0 ].files !== undefined;
6099 }
6100 return OO.ui.SelectFileWidget.static.isSupportedCache;
6101 };
6102
6103 OO.ui.SelectFileWidget.static.isSupportedCache = null;
6104
6105 /* Events */
6106
6107 /**
6108 * @event change
6109 *
6110 * A change event is emitted when the on/off state of the toggle changes.
6111 *
6112 * @param {File|null} value New value
6113 */
6114
6115 /* Methods */
6116
6117 /**
6118 * Get the current value of the field
6119 *
6120 * @return {File|null}
6121 */
6122 OO.ui.SelectFileWidget.prototype.getValue = function () {
6123 return this.currentFile;
6124 };
6125
6126 /**
6127 * Set the current value of the field
6128 *
6129 * @param {File|null} file File to select
6130 */
6131 OO.ui.SelectFileWidget.prototype.setValue = function ( file ) {
6132 if ( this.currentFile !== file ) {
6133 this.currentFile = file;
6134 this.updateUI();
6135 this.emit( 'change', this.currentFile );
6136 }
6137 };
6138
6139 /**
6140 * Focus the widget.
6141 *
6142 * Focusses the select file button.
6143 *
6144 * @chainable
6145 */
6146 OO.ui.SelectFileWidget.prototype.focus = function () {
6147 this.selectButton.focus();
6148 return this;
6149 };
6150
6151 /**
6152 * Blur the widget.
6153 *
6154 * @chainable
6155 */
6156 OO.ui.SelectFileWidget.prototype.blur = function () {
6157 this.selectButton.blur();
6158 return this;
6159 };
6160
6161 /**
6162 * @inheritdoc
6163 */
6164 OO.ui.SelectFileWidget.prototype.simulateLabelClick = function () {
6165 this.focus();
6166 };
6167
6168 /**
6169 * Update the user interface when a file is selected or unselected
6170 *
6171 * @protected
6172 */
6173 OO.ui.SelectFileWidget.prototype.updateUI = function () {
6174 var $label;
6175 if ( !this.isSupported ) {
6176 this.$element.addClass( 'oo-ui-selectFileWidget-notsupported' );
6177 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
6178 this.setLabel( this.notsupported );
6179 } else {
6180 this.$element.addClass( 'oo-ui-selectFileWidget-supported' );
6181 if ( this.currentFile ) {
6182 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
6183 $label = $( [] );
6184 $label = $label.add(
6185 $( '<span>' )
6186 .addClass( 'oo-ui-selectFileWidget-fileName' )
6187 .text( this.currentFile.name )
6188 );
6189 this.setLabel( $label );
6190
6191 if ( this.showDropTarget ) {
6192 this.pushPending();
6193 this.loadAndGetImageUrl().done( function ( url ) {
6194 this.$thumbnail.css( 'background-image', 'url( ' + url + ' )' );
6195 }.bind( this ) ).fail( function () {
6196 this.$thumbnail.append(
6197 new OO.ui.IconWidget( {
6198 icon: 'attachment',
6199 classes: [ 'oo-ui-selectFileWidget-noThumbnail-icon' ]
6200 } ).$element
6201 );
6202 }.bind( this ) ).always( function () {
6203 this.popPending();
6204 }.bind( this ) );
6205 this.$element.off( 'click' );
6206 }
6207 } else {
6208 if ( this.showDropTarget ) {
6209 this.$element.off( 'click' );
6210 this.$element.on( {
6211 click: this.onDropTargetClick.bind( this )
6212 } );
6213 this.$thumbnail
6214 .empty()
6215 .css( 'background-image', '' );
6216 }
6217 this.$element.addClass( 'oo-ui-selectFileWidget-empty' );
6218 this.setLabel( this.placeholder );
6219 }
6220 }
6221 };
6222
6223 /**
6224 * If the selected file is an image, get its URL and load it.
6225 *
6226 * @return {jQuery.Promise} Promise resolves with the image URL after it has loaded
6227 */
6228 OO.ui.SelectFileWidget.prototype.loadAndGetImageUrl = function () {
6229 var deferred = $.Deferred(),
6230 file = this.currentFile,
6231 reader = new FileReader();
6232
6233 if (
6234 file &&
6235 ( OO.getProp( file, 'type' ) || '' ).indexOf( 'image/' ) === 0 &&
6236 file.size < this.thumbnailSizeLimit * 1024 * 1024
6237 ) {
6238 reader.onload = function ( event ) {
6239 var img = document.createElement( 'img' );
6240 img.addEventListener( 'load', function () {
6241 if (
6242 img.naturalWidth === 0 ||
6243 img.naturalHeight === 0 ||
6244 img.complete === false
6245 ) {
6246 deferred.reject();
6247 } else {
6248 deferred.resolve( event.target.result );
6249 }
6250 } );
6251 img.src = event.target.result;
6252 };
6253 reader.readAsDataURL( file );
6254 } else {
6255 deferred.reject();
6256 }
6257
6258 return deferred.promise();
6259 };
6260
6261 /**
6262 * Add the input to the widget
6263 *
6264 * @private
6265 */
6266 OO.ui.SelectFileWidget.prototype.addInput = function () {
6267 if ( this.$input ) {
6268 this.$input.remove();
6269 }
6270
6271 if ( !this.isSupported ) {
6272 this.$input = null;
6273 return;
6274 }
6275
6276 this.$input = $( '<input>' ).attr( 'type', 'file' );
6277 this.$input.on( 'change', this.onFileSelectedHandler );
6278 this.$input.on( 'click', function ( e ) {
6279 // Prevents dropTarget to get clicked which calls
6280 // a click on this input
6281 e.stopPropagation();
6282 } );
6283 this.$input.attr( {
6284 tabindex: -1
6285 } );
6286 if ( this.accept ) {
6287 this.$input.attr( 'accept', this.accept.join( ', ' ) );
6288 }
6289 this.selectButton.$button.append( this.$input );
6290 };
6291
6292 /**
6293 * Determine if we should accept this file
6294 *
6295 * @private
6296 * @param {string} mimeType File MIME type
6297 * @return {boolean}
6298 */
6299 OO.ui.SelectFileWidget.prototype.isAllowedType = function ( mimeType ) {
6300 var i, mimeTest;
6301
6302 if ( !this.accept || !mimeType ) {
6303 return true;
6304 }
6305
6306 for ( i = 0; i < this.accept.length; i++ ) {
6307 mimeTest = this.accept[ i ];
6308 if ( mimeTest === mimeType ) {
6309 return true;
6310 } else if ( mimeTest.substr( -2 ) === '/*' ) {
6311 mimeTest = mimeTest.substr( 0, mimeTest.length - 1 );
6312 if ( mimeType.substr( 0, mimeTest.length ) === mimeTest ) {
6313 return true;
6314 }
6315 }
6316 }
6317
6318 return false;
6319 };
6320
6321 /**
6322 * Handle file selection from the input
6323 *
6324 * @private
6325 * @param {jQuery.Event} e
6326 */
6327 OO.ui.SelectFileWidget.prototype.onFileSelected = function ( e ) {
6328 var file = OO.getProp( e.target, 'files', 0 ) || null;
6329
6330 if ( file && !this.isAllowedType( file.type ) ) {
6331 file = null;
6332 }
6333
6334 this.setValue( file );
6335 this.addInput();
6336 };
6337
6338 /**
6339 * Handle clear button click events.
6340 *
6341 * @private
6342 */
6343 OO.ui.SelectFileWidget.prototype.onClearClick = function () {
6344 this.setValue( null );
6345 return false;
6346 };
6347
6348 /**
6349 * Handle key press events.
6350 *
6351 * @private
6352 * @param {jQuery.Event} e Key press event
6353 */
6354 OO.ui.SelectFileWidget.prototype.onKeyPress = function ( e ) {
6355 if ( this.isSupported && !this.isDisabled() && this.$input &&
6356 ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
6357 ) {
6358 this.$input.click();
6359 return false;
6360 }
6361 };
6362
6363 /**
6364 * Handle drop target click events.
6365 *
6366 * @private
6367 * @param {jQuery.Event} e Key press event
6368 */
6369 OO.ui.SelectFileWidget.prototype.onDropTargetClick = function () {
6370 if ( this.isSupported && !this.isDisabled() && this.$input ) {
6371 this.$input.click();
6372 return false;
6373 }
6374 };
6375
6376 /**
6377 * Handle drag enter and over events
6378 *
6379 * @private
6380 * @param {jQuery.Event} e Drag event
6381 */
6382 OO.ui.SelectFileWidget.prototype.onDragEnterOrOver = function ( e ) {
6383 var itemOrFile,
6384 droppableFile = false,
6385 dt = e.originalEvent.dataTransfer;
6386
6387 e.preventDefault();
6388 e.stopPropagation();
6389
6390 if ( this.isDisabled() || !this.isSupported ) {
6391 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
6392 dt.dropEffect = 'none';
6393 return false;
6394 }
6395
6396 // DataTransferItem and File both have a type property, but in Chrome files
6397 // have no information at this point.
6398 itemOrFile = OO.getProp( dt, 'items', 0 ) || OO.getProp( dt, 'files', 0 );
6399 if ( itemOrFile ) {
6400 if ( this.isAllowedType( itemOrFile.type ) ) {
6401 droppableFile = true;
6402 }
6403 // dt.types is Array-like, but not an Array
6404 } else if ( Array.prototype.indexOf.call( OO.getProp( dt, 'types' ) || [], 'Files' ) !== -1 ) {
6405 // File information is not available at this point for security so just assume
6406 // it is acceptable for now.
6407 // https://bugzilla.mozilla.org/show_bug.cgi?id=640534
6408 droppableFile = true;
6409 }
6410
6411 this.$element.toggleClass( 'oo-ui-selectFileWidget-canDrop', droppableFile );
6412 if ( !droppableFile ) {
6413 dt.dropEffect = 'none';
6414 }
6415
6416 return false;
6417 };
6418
6419 /**
6420 * Handle drag leave events
6421 *
6422 * @private
6423 * @param {jQuery.Event} e Drag event
6424 */
6425 OO.ui.SelectFileWidget.prototype.onDragLeave = function () {
6426 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
6427 };
6428
6429 /**
6430 * Handle drop events
6431 *
6432 * @private
6433 * @param {jQuery.Event} e Drop event
6434 */
6435 OO.ui.SelectFileWidget.prototype.onDrop = function ( e ) {
6436 var file = null,
6437 dt = e.originalEvent.dataTransfer;
6438
6439 e.preventDefault();
6440 e.stopPropagation();
6441 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
6442
6443 if ( this.isDisabled() || !this.isSupported ) {
6444 return false;
6445 }
6446
6447 file = OO.getProp( dt, 'files', 0 );
6448 if ( file && !this.isAllowedType( file.type ) ) {
6449 file = null;
6450 }
6451 if ( file ) {
6452 this.setValue( file );
6453 }
6454
6455 return false;
6456 };
6457
6458 /**
6459 * @inheritdoc
6460 */
6461 OO.ui.SelectFileWidget.prototype.setDisabled = function ( disabled ) {
6462 OO.ui.SelectFileWidget.parent.prototype.setDisabled.call( this, disabled );
6463 if ( this.selectButton ) {
6464 this.selectButton.setDisabled( disabled );
6465 }
6466 if ( this.clearButton ) {
6467 this.clearButton.setDisabled( disabled );
6468 }
6469 return this;
6470 };
6471
6472 /**
6473 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
6474 * and a menu of search results, which is displayed beneath the query
6475 * field. Unlike {@link OO.ui.mixin.LookupElement lookup menus}, search result menus are always visible to the user.
6476 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
6477 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
6478 *
6479 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
6480 * the [OOjs UI demos][1] for an example.
6481 *
6482 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
6483 *
6484 * @class
6485 * @extends OO.ui.Widget
6486 *
6487 * @constructor
6488 * @param {Object} [config] Configuration options
6489 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
6490 * @cfg {string} [value] Initial query value
6491 */
6492 OO.ui.SearchWidget = function OoUiSearchWidget( config ) {
6493 // Configuration initialization
6494 config = config || {};
6495
6496 // Parent constructor
6497 OO.ui.SearchWidget.parent.call( this, config );
6498
6499 // Properties
6500 this.query = new OO.ui.TextInputWidget( {
6501 icon: 'search',
6502 placeholder: config.placeholder,
6503 value: config.value
6504 } );
6505 this.results = new OO.ui.SelectWidget();
6506 this.$query = $( '<div>' );
6507 this.$results = $( '<div>' );
6508
6509 // Events
6510 this.query.connect( this, {
6511 change: 'onQueryChange',
6512 enter: 'onQueryEnter'
6513 } );
6514 this.query.$input.on( 'keydown', this.onQueryKeydown.bind( this ) );
6515
6516 // Initialization
6517 this.$query
6518 .addClass( 'oo-ui-searchWidget-query' )
6519 .append( this.query.$element );
6520 this.$results
6521 .addClass( 'oo-ui-searchWidget-results' )
6522 .append( this.results.$element );
6523 this.$element
6524 .addClass( 'oo-ui-searchWidget' )
6525 .append( this.$results, this.$query );
6526 };
6527
6528 /* Setup */
6529
6530 OO.inheritClass( OO.ui.SearchWidget, OO.ui.Widget );
6531
6532 /* Methods */
6533
6534 /**
6535 * Handle query key down events.
6536 *
6537 * @private
6538 * @param {jQuery.Event} e Key down event
6539 */
6540 OO.ui.SearchWidget.prototype.onQueryKeydown = function ( e ) {
6541 var highlightedItem, nextItem,
6542 dir = e.which === OO.ui.Keys.DOWN ? 1 : ( e.which === OO.ui.Keys.UP ? -1 : 0 );
6543
6544 if ( dir ) {
6545 highlightedItem = this.results.findHighlightedItem();
6546 if ( !highlightedItem ) {
6547 highlightedItem = this.results.getSelectedItem();
6548 }
6549 nextItem = this.results.findRelativeSelectableItem( highlightedItem, dir );
6550 this.results.highlightItem( nextItem );
6551 nextItem.scrollElementIntoView();
6552 }
6553 };
6554
6555 /**
6556 * Handle select widget select events.
6557 *
6558 * Clears existing results. Subclasses should repopulate items according to new query.
6559 *
6560 * @private
6561 * @param {string} value New value
6562 */
6563 OO.ui.SearchWidget.prototype.onQueryChange = function () {
6564 // Reset
6565 this.results.clearItems();
6566 };
6567
6568 /**
6569 * Handle select widget enter key events.
6570 *
6571 * Chooses highlighted item.
6572 *
6573 * @private
6574 * @param {string} value New value
6575 */
6576 OO.ui.SearchWidget.prototype.onQueryEnter = function () {
6577 var highlightedItem = this.results.findHighlightedItem();
6578 if ( highlightedItem ) {
6579 this.results.chooseItem( highlightedItem );
6580 }
6581 };
6582
6583 /**
6584 * Get the query input.
6585 *
6586 * @return {OO.ui.TextInputWidget} Query input
6587 */
6588 OO.ui.SearchWidget.prototype.getQuery = function () {
6589 return this.query;
6590 };
6591
6592 /**
6593 * Get the search results menu.
6594 *
6595 * @return {OO.ui.SelectWidget} Menu of search results
6596 */
6597 OO.ui.SearchWidget.prototype.getResults = function () {
6598 return this.results;
6599 };
6600
6601 /**
6602 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
6603 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
6604 * (to adjust the value in increments) to allow the user to enter a number.
6605 *
6606 * @example
6607 * // Example: A NumberInputWidget.
6608 * var numberInput = new OO.ui.NumberInputWidget( {
6609 * label: 'NumberInputWidget',
6610 * input: { value: 5 },
6611 * min: 1,
6612 * max: 10
6613 * } );
6614 * $( 'body' ).append( numberInput.$element );
6615 *
6616 * @class
6617 * @extends OO.ui.TextInputWidget
6618 *
6619 * @constructor
6620 * @param {Object} [config] Configuration options
6621 * @cfg {Object} [minusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget decrementing button widget}.
6622 * @cfg {Object} [plusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget incrementing button widget}.
6623 * @cfg {boolean} [allowInteger=false] Whether the field accepts only integer values.
6624 * @cfg {number} [min=-Infinity] Minimum allowed value
6625 * @cfg {number} [max=Infinity] Maximum allowed value
6626 * @cfg {number} [step=1] Delta when using the buttons or up/down arrow keys
6627 * @cfg {number|null} [pageStep] Delta when using the page-up/page-down keys. Defaults to 10 times #step.
6628 * @cfg {boolean} [showButtons=true] Whether to show the plus and minus buttons.
6629 */
6630 OO.ui.NumberInputWidget = function OoUiNumberInputWidget( config ) {
6631 var $field = $( '<div>' )
6632 .addClass( 'oo-ui-numberInputWidget-field' );
6633
6634 // Configuration initialization
6635 config = $.extend( {
6636 allowInteger: false,
6637 min: -Infinity,
6638 max: Infinity,
6639 step: 1,
6640 pageStep: null,
6641 showButtons: true
6642 }, config );
6643
6644 // For backward compatibility
6645 $.extend( config, config.input );
6646 this.input = this;
6647
6648 // Parent constructor
6649 OO.ui.NumberInputWidget.parent.call( this, $.extend( config, {
6650 type: 'number'
6651 } ) );
6652
6653 if ( config.showButtons ) {
6654 this.minusButton = new OO.ui.ButtonWidget( $.extend(
6655 {
6656 disabled: this.isDisabled(),
6657 tabIndex: -1,
6658 classes: [ 'oo-ui-numberInputWidget-minusButton' ],
6659 icon: 'subtract'
6660 },
6661 config.minusButton
6662 ) );
6663 this.plusButton = new OO.ui.ButtonWidget( $.extend(
6664 {
6665 disabled: this.isDisabled(),
6666 tabIndex: -1,
6667 classes: [ 'oo-ui-numberInputWidget-plusButton' ],
6668 icon: 'add'
6669 },
6670 config.plusButton
6671 ) );
6672 }
6673
6674 // Events
6675 this.$input.on( {
6676 keydown: this.onKeyDown.bind( this ),
6677 'wheel mousewheel DOMMouseScroll': this.onWheel.bind( this )
6678 } );
6679 if ( config.showButtons ) {
6680 this.plusButton.connect( this, {
6681 click: [ 'onButtonClick', +1 ]
6682 } );
6683 this.minusButton.connect( this, {
6684 click: [ 'onButtonClick', -1 ]
6685 } );
6686 }
6687
6688 // Build the field
6689 $field.append( this.$input );
6690 if ( config.showButtons ) {
6691 $field
6692 .prepend( this.minusButton.$element )
6693 .append( this.plusButton.$element );
6694 }
6695
6696 // Initialization
6697 this.setAllowInteger( config.allowInteger || config.isInteger );
6698 this.setRange( config.min, config.max );
6699 this.setStep( config.step, config.pageStep );
6700 // Set the validation method after we set allowInteger and range
6701 // so that it doesn't immediately call setValidityFlag
6702 this.setValidation( this.validateNumber.bind( this ) );
6703
6704 this.$element
6705 .addClass( 'oo-ui-numberInputWidget' )
6706 .toggleClass( 'oo-ui-numberInputWidget-buttoned', config.showButtons )
6707 .append( $field );
6708 };
6709
6710 /* Setup */
6711
6712 OO.inheritClass( OO.ui.NumberInputWidget, OO.ui.TextInputWidget );
6713
6714 /* Methods */
6715
6716 /**
6717 * Set whether only integers are allowed
6718 *
6719 * @param {boolean} flag
6720 */
6721 OO.ui.NumberInputWidget.prototype.setAllowInteger = function ( flag ) {
6722 this.allowInteger = !!flag;
6723 this.setValidityFlag();
6724 };
6725 // Backward compatibility
6726 OO.ui.NumberInputWidget.prototype.setIsInteger = OO.ui.NumberInputWidget.prototype.setAllowInteger;
6727
6728 /**
6729 * Get whether only integers are allowed
6730 *
6731 * @return {boolean} Flag value
6732 */
6733 OO.ui.NumberInputWidget.prototype.getAllowInteger = function () {
6734 return this.allowInteger;
6735 };
6736 // Backward compatibility
6737 OO.ui.NumberInputWidget.prototype.getIsInteger = OO.ui.NumberInputWidget.prototype.getAllowInteger;
6738
6739 /**
6740 * Set the range of allowed values
6741 *
6742 * @param {number} min Minimum allowed value
6743 * @param {number} max Maximum allowed value
6744 */
6745 OO.ui.NumberInputWidget.prototype.setRange = function ( min, max ) {
6746 if ( min > max ) {
6747 throw new Error( 'Minimum (' + min + ') must not be greater than maximum (' + max + ')' );
6748 }
6749 this.min = min;
6750 this.max = max;
6751 this.setValidityFlag();
6752 };
6753
6754 /**
6755 * Get the current range
6756 *
6757 * @return {number[]} Minimum and maximum values
6758 */
6759 OO.ui.NumberInputWidget.prototype.getRange = function () {
6760 return [ this.min, this.max ];
6761 };
6762
6763 /**
6764 * Set the stepping deltas
6765 *
6766 * @param {number} step Normal step
6767 * @param {number|null} pageStep Page step. If null, 10 * step will be used.
6768 */
6769 OO.ui.NumberInputWidget.prototype.setStep = function ( step, pageStep ) {
6770 if ( step <= 0 ) {
6771 throw new Error( 'Step value must be positive' );
6772 }
6773 if ( pageStep === null ) {
6774 pageStep = step * 10;
6775 } else if ( pageStep <= 0 ) {
6776 throw new Error( 'Page step value must be positive' );
6777 }
6778 this.step = step;
6779 this.pageStep = pageStep;
6780 };
6781
6782 /**
6783 * Get the current stepping values
6784 *
6785 * @return {number[]} Step and page step
6786 */
6787 OO.ui.NumberInputWidget.prototype.getStep = function () {
6788 return [ this.step, this.pageStep ];
6789 };
6790
6791 /**
6792 * Get the current value of the widget as a number
6793 *
6794 * @return {number} May be NaN, or an invalid number
6795 */
6796 OO.ui.NumberInputWidget.prototype.getNumericValue = function () {
6797 return +this.getValue();
6798 };
6799
6800 /**
6801 * Adjust the value of the widget
6802 *
6803 * @param {number} delta Adjustment amount
6804 */
6805 OO.ui.NumberInputWidget.prototype.adjustValue = function ( delta ) {
6806 var n, v = this.getNumericValue();
6807
6808 delta = +delta;
6809 if ( isNaN( delta ) || !isFinite( delta ) ) {
6810 throw new Error( 'Delta must be a finite number' );
6811 }
6812
6813 if ( isNaN( v ) ) {
6814 n = 0;
6815 } else {
6816 n = v + delta;
6817 n = Math.max( Math.min( n, this.max ), this.min );
6818 if ( this.allowInteger ) {
6819 n = Math.round( n );
6820 }
6821 }
6822
6823 if ( n !== v ) {
6824 this.setValue( n );
6825 }
6826 };
6827 /**
6828 * Validate input
6829 *
6830 * @private
6831 * @param {string} value Field value
6832 * @return {boolean}
6833 */
6834 OO.ui.NumberInputWidget.prototype.validateNumber = function ( value ) {
6835 var n = +value;
6836 if ( value === '' ) {
6837 return !this.isRequired();
6838 }
6839
6840 if ( isNaN( n ) || !isFinite( n ) ) {
6841 return false;
6842 }
6843
6844 if ( this.allowInteger && Math.floor( n ) !== n ) {
6845 return false;
6846 }
6847
6848 if ( n < this.min || n > this.max ) {
6849 return false;
6850 }
6851
6852 return true;
6853 };
6854
6855 /**
6856 * Handle mouse click events.
6857 *
6858 * @private
6859 * @param {number} dir +1 or -1
6860 */
6861 OO.ui.NumberInputWidget.prototype.onButtonClick = function ( dir ) {
6862 this.adjustValue( dir * this.step );
6863 };
6864
6865 /**
6866 * Handle mouse wheel events.
6867 *
6868 * @private
6869 * @param {jQuery.Event} event
6870 */
6871 OO.ui.NumberInputWidget.prototype.onWheel = function ( event ) {
6872 var delta = 0;
6873
6874 if ( !this.isDisabled() && this.$input.is( ':focus' ) ) {
6875 // Standard 'wheel' event
6876 if ( event.originalEvent.deltaMode !== undefined ) {
6877 this.sawWheelEvent = true;
6878 }
6879 if ( event.originalEvent.deltaY ) {
6880 delta = -event.originalEvent.deltaY;
6881 } else if ( event.originalEvent.deltaX ) {
6882 delta = event.originalEvent.deltaX;
6883 }
6884
6885 // Non-standard events
6886 if ( !this.sawWheelEvent ) {
6887 if ( event.originalEvent.wheelDeltaX ) {
6888 delta = -event.originalEvent.wheelDeltaX;
6889 } else if ( event.originalEvent.wheelDeltaY ) {
6890 delta = event.originalEvent.wheelDeltaY;
6891 } else if ( event.originalEvent.wheelDelta ) {
6892 delta = event.originalEvent.wheelDelta;
6893 } else if ( event.originalEvent.detail ) {
6894 delta = -event.originalEvent.detail;
6895 }
6896 }
6897
6898 if ( delta ) {
6899 delta = delta < 0 ? -1 : 1;
6900 this.adjustValue( delta * this.step );
6901 }
6902
6903 return false;
6904 }
6905 };
6906
6907 /**
6908 * Handle key down events.
6909 *
6910 * @private
6911 * @param {jQuery.Event} e Key down event
6912 */
6913 OO.ui.NumberInputWidget.prototype.onKeyDown = function ( e ) {
6914 if ( !this.isDisabled() ) {
6915 switch ( e.which ) {
6916 case OO.ui.Keys.UP:
6917 this.adjustValue( this.step );
6918 return false;
6919 case OO.ui.Keys.DOWN:
6920 this.adjustValue( -this.step );
6921 return false;
6922 case OO.ui.Keys.PAGEUP:
6923 this.adjustValue( this.pageStep );
6924 return false;
6925 case OO.ui.Keys.PAGEDOWN:
6926 this.adjustValue( -this.pageStep );
6927 return false;
6928 }
6929 }
6930 };
6931
6932 /**
6933 * @inheritdoc
6934 */
6935 OO.ui.NumberInputWidget.prototype.setDisabled = function ( disabled ) {
6936 // Parent method
6937 OO.ui.NumberInputWidget.parent.prototype.setDisabled.call( this, disabled );
6938
6939 if ( this.minusButton ) {
6940 this.minusButton.setDisabled( this.isDisabled() );
6941 }
6942 if ( this.plusButton ) {
6943 this.plusButton.setDisabled( this.isDisabled() );
6944 }
6945
6946 return this;
6947 };
6948
6949 }( OO ) );
6950
6951 //# sourceMappingURL=oojs-ui-widgets.js.map