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