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