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