Merge "Fix return typehint"
[lhc/web/wiklou.git] / resources / lib / ooui / oojs-ui-widgets.js
1 /*!
2 * OOUI v0.29.6
3 * https://www.mediawiki.org/wiki/OOUI
4 *
5 * Copyright 2011–2018 OOUI Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
8 *
9 * Date: 2018-12-05T00:15:55Z
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/OOUI-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 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation === 'horizontal' );
283 };
284
285 /* Setup */
286 OO.mixinClass( OO.ui.mixin.DraggableGroupElement, OO.ui.mixin.GroupElement );
287
288 /* Events */
289
290 /**
291 * An item has been dragged to a new position, but not yet dropped.
292 *
293 * @event drag
294 * @param {OO.ui.mixin.DraggableElement} item Dragged item
295 * @param {number} [newIndex] New index for the item
296 */
297
298 /**
299 * An item has been dropped at a new position.
300 *
301 * @event reorder
302 * @param {OO.ui.mixin.DraggableElement} item Reordered item
303 * @param {number} [newIndex] New index for the item
304 */
305
306 /**
307 * Draggable state of this widget has changed.
308 *
309 * @event draggable
310 * @param {boolean} [draggable] Widget is draggable
311 */
312
313 /* Methods */
314
315 /**
316 * Change the draggable state of this widget.
317 * This allows users to temporarily halt the dragging operations.
318 *
319 * @param {boolean} isDraggable Widget supports draggable operations
320 * @fires draggable
321 */
322 OO.ui.mixin.DraggableGroupElement.prototype.toggleDraggable = function ( isDraggable ) {
323 isDraggable = isDraggable !== undefined ? !!isDraggable : !this.draggable;
324
325 if ( this.draggable !== isDraggable ) {
326 this.draggable = isDraggable;
327
328 // Tell the items their draggable state changed
329 this.getItems().forEach( function ( item ) {
330 item.toggleDraggable( this.draggable );
331 }.bind( this ) );
332
333 // Emit event
334 this.emit( 'draggable', this.draggable );
335 }
336 };
337
338 /**
339 * Check the draggable state of this widget
340 *
341 * @return {boolean} Widget supports draggable operations
342 */
343 OO.ui.mixin.DraggableGroupElement.prototype.isDraggable = function () {
344 return this.draggable;
345 };
346
347 /**
348 * Respond to item drag start event
349 *
350 * @private
351 * @param {OO.ui.mixin.DraggableElement} item Dragged item
352 */
353 OO.ui.mixin.DraggableGroupElement.prototype.onItemDragStart = function ( item ) {
354 if ( !this.isDraggable() ) {
355 return;
356 }
357 // Make a shallow copy of this.items so we can re-order it during previews
358 // without affecting the original array.
359 this.itemsOrder = this.items.slice();
360 this.updateIndexes();
361 if ( this.orientation === 'horizontal' ) {
362 // Calculate and cache directionality on drag start - it's a little
363 // expensive and it shouldn't change while dragging.
364 this.dir = this.$element.css( 'direction' );
365 }
366 this.setDragItem( item );
367 };
368
369 /**
370 * Update the index properties of the items
371 */
372 OO.ui.mixin.DraggableGroupElement.prototype.updateIndexes = function () {
373 var i, len;
374
375 // Map the index of each object
376 for ( i = 0, len = this.itemsOrder.length; i < len; i++ ) {
377 this.itemsOrder[ i ].setIndex( i );
378 }
379 };
380
381 /**
382 * Handle drop or dragend event and switch the order of the items accordingly
383 *
384 * @private
385 * @param {OO.ui.mixin.DraggableElement} item Dropped item
386 * @return {OO.ui.Element} The element, for chaining
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 [OOUI demos][1] for an example.
623 *
624 * [1]: https://doc.wikimedia.org/oojs-ui/master/demos/#LookupElement-try-inputting-an-integer
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/OOUI/Concepts#Overlays>.
634 * @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element.
635 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.MenuSelectWidget menu select widget}
636 * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty.
637 * By default, the lookup menu is not generated and displayed until the user begins to type.
638 * @cfg {boolean} [highlightFirst=true] Whether the first lookup result should be highlighted (so, that the user can
639 * take it over into the input with simply pressing return) automatically or not.
640 */
641 OO.ui.mixin.LookupElement = function OoUiMixinLookupElement( config ) {
642 // Configuration initialization
643 config = $.extend( { highlightFirst: true }, config );
644
645 // Mixin constructors
646 OO.ui.mixin.RequestManager.call( this, config );
647
648 // Properties
649 this.$overlay = ( config.$overlay === true ? OO.ui.getDefaultOverlay() : config.$overlay ) || this.$element;
650 this.lookupMenu = new OO.ui.MenuSelectWidget( $.extend( {
651 widget: this,
652 input: this,
653 $floatableContainer: config.$container || this.$element
654 }, config.menu ) );
655
656 this.allowSuggestionsWhenEmpty = config.allowSuggestionsWhenEmpty || false;
657
658 this.lookupsDisabled = false;
659 this.lookupInputFocused = false;
660 this.lookupHighlightFirstItem = config.highlightFirst;
661
662 // Events
663 this.$input.on( {
664 focus: this.onLookupInputFocus.bind( this ),
665 blur: this.onLookupInputBlur.bind( this ),
666 mousedown: this.onLookupInputMouseDown.bind( this )
667 } );
668 this.connect( this, { change: 'onLookupInputChange' } );
669 this.lookupMenu.connect( this, {
670 toggle: 'onLookupMenuToggle',
671 choose: 'onLookupMenuItemChoose'
672 } );
673
674 // Initialization
675 this.$input.attr( {
676 role: 'combobox',
677 'aria-owns': this.lookupMenu.getElementId(),
678 'aria-autocomplete': 'list'
679 } );
680 this.$element.addClass( 'oo-ui-lookupElement' );
681 this.lookupMenu.$element.addClass( 'oo-ui-lookupElement-menu' );
682 this.$overlay.append( this.lookupMenu.$element );
683 };
684
685 /* Setup */
686
687 OO.mixinClass( OO.ui.mixin.LookupElement, OO.ui.mixin.RequestManager );
688
689 /* Methods */
690
691 /**
692 * Handle input focus event.
693 *
694 * @protected
695 * @param {jQuery.Event} e Input focus event
696 */
697 OO.ui.mixin.LookupElement.prototype.onLookupInputFocus = function () {
698 this.lookupInputFocused = true;
699 this.populateLookupMenu();
700 };
701
702 /**
703 * Handle input blur event.
704 *
705 * @protected
706 * @param {jQuery.Event} e Input blur event
707 */
708 OO.ui.mixin.LookupElement.prototype.onLookupInputBlur = function () {
709 this.closeLookupMenu();
710 this.lookupInputFocused = false;
711 };
712
713 /**
714 * Handle input mouse down event.
715 *
716 * @protected
717 * @param {jQuery.Event} e Input mouse down event
718 */
719 OO.ui.mixin.LookupElement.prototype.onLookupInputMouseDown = function () {
720 // Only open the menu if the input was already focused.
721 // This way we allow the user to open the menu again after closing it with Esc
722 // by clicking in the input. Opening (and populating) the menu when initially
723 // clicking into the input is handled by the focus handler.
724 if ( this.lookupInputFocused && !this.lookupMenu.isVisible() ) {
725 this.populateLookupMenu();
726 }
727 };
728
729 /**
730 * Handle input change event.
731 *
732 * @protected
733 * @param {string} value New input value
734 */
735 OO.ui.mixin.LookupElement.prototype.onLookupInputChange = function () {
736 if ( this.lookupInputFocused ) {
737 this.populateLookupMenu();
738 }
739 };
740
741 /**
742 * Handle the lookup menu being shown/hidden.
743 *
744 * @protected
745 * @param {boolean} visible Whether the lookup menu is now visible.
746 */
747 OO.ui.mixin.LookupElement.prototype.onLookupMenuToggle = function ( visible ) {
748 if ( !visible ) {
749 // When the menu is hidden, abort any active request and clear the menu.
750 // This has to be done here in addition to closeLookupMenu(), because
751 // MenuSelectWidget will close itself when the user presses Esc.
752 this.abortLookupRequest();
753 this.lookupMenu.clearItems();
754 }
755 };
756
757 /**
758 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
759 *
760 * @protected
761 * @param {OO.ui.MenuOptionWidget} item Selected item
762 */
763 OO.ui.mixin.LookupElement.prototype.onLookupMenuItemChoose = function ( item ) {
764 this.setValue( item.getData() );
765 };
766
767 /**
768 * Get lookup menu.
769 *
770 * @private
771 * @return {OO.ui.MenuSelectWidget}
772 */
773 OO.ui.mixin.LookupElement.prototype.getLookupMenu = function () {
774 return this.lookupMenu;
775 };
776
777 /**
778 * Disable or re-enable lookups.
779 *
780 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
781 *
782 * @param {boolean} disabled Disable lookups
783 */
784 OO.ui.mixin.LookupElement.prototype.setLookupsDisabled = function ( disabled ) {
785 this.lookupsDisabled = !!disabled;
786 };
787
788 /**
789 * Open the menu. If there are no entries in the menu, this does nothing.
790 *
791 * @private
792 * @chainable
793 * @return {OO.ui.Element} The element, for chaining
794 */
795 OO.ui.mixin.LookupElement.prototype.openLookupMenu = function () {
796 if ( !this.lookupMenu.isEmpty() ) {
797 this.lookupMenu.toggle( true );
798 }
799 return this;
800 };
801
802 /**
803 * Close the menu, empty it, and abort any pending request.
804 *
805 * @private
806 * @chainable
807 * @return {OO.ui.Element} The element, for chaining
808 */
809 OO.ui.mixin.LookupElement.prototype.closeLookupMenu = function () {
810 this.lookupMenu.toggle( false );
811 this.abortLookupRequest();
812 this.lookupMenu.clearItems();
813 return this;
814 };
815
816 /**
817 * Request menu items based on the input's current value, and when they arrive,
818 * populate the menu with these items and show the menu.
819 *
820 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
821 *
822 * @private
823 * @chainable
824 * @return {OO.ui.Element} The element, for chaining
825 */
826 OO.ui.mixin.LookupElement.prototype.populateLookupMenu = function () {
827 var widget = this,
828 value = this.getValue();
829
830 if ( this.lookupsDisabled || this.isReadOnly() ) {
831 return;
832 }
833
834 // If the input is empty, clear the menu, unless suggestions when empty are allowed.
835 if ( !this.allowSuggestionsWhenEmpty && value === '' ) {
836 this.closeLookupMenu();
837 // Skip population if there is already a request pending for the current value
838 } else if ( value !== this.lookupQuery ) {
839 this.getLookupMenuItems()
840 .done( function ( items ) {
841 widget.lookupMenu.clearItems();
842 if ( items.length ) {
843 widget.lookupMenu
844 .addItems( items )
845 .toggle( true );
846 widget.initializeLookupMenuSelection();
847 } else {
848 widget.lookupMenu.toggle( false );
849 }
850 } )
851 .fail( function () {
852 widget.lookupMenu.clearItems();
853 widget.lookupMenu.toggle( false );
854 } );
855 }
856
857 return this;
858 };
859
860 /**
861 * Highlight the first selectable item in the menu, if configured.
862 *
863 * @private
864 * @chainable
865 */
866 OO.ui.mixin.LookupElement.prototype.initializeLookupMenuSelection = function () {
867 if ( this.lookupHighlightFirstItem && !this.lookupMenu.findSelectedItem() ) {
868 this.lookupMenu.highlightItem( this.lookupMenu.findFirstSelectableItem() );
869 }
870 };
871
872 /**
873 * Get lookup menu items for the current query.
874 *
875 * @private
876 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
877 * the done event. If the request was aborted to make way for a subsequent request, this promise
878 * will not be rejected: it will remain pending forever.
879 */
880 OO.ui.mixin.LookupElement.prototype.getLookupMenuItems = function () {
881 return this.getRequestData().then( function ( data ) {
882 return this.getLookupMenuOptionsFromData( data );
883 }.bind( this ) );
884 };
885
886 /**
887 * Abort the currently pending lookup request, if any.
888 *
889 * @private
890 */
891 OO.ui.mixin.LookupElement.prototype.abortLookupRequest = function () {
892 this.abortRequest();
893 };
894
895 /**
896 * Get a new request object of the current lookup query value.
897 *
898 * @protected
899 * @method
900 * @abstract
901 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
902 */
903 OO.ui.mixin.LookupElement.prototype.getLookupRequest = null;
904
905 /**
906 * Pre-process data returned by the request from #getLookupRequest.
907 *
908 * The return value of this function will be cached, and any further queries for the given value
909 * will use the cache rather than doing API requests.
910 *
911 * @protected
912 * @method
913 * @abstract
914 * @param {Mixed} response Response from server
915 * @return {Mixed} Cached result data
916 */
917 OO.ui.mixin.LookupElement.prototype.getLookupCacheDataFromResponse = null;
918
919 /**
920 * Get a list of menu option widgets from the (possibly cached) data returned by
921 * #getLookupCacheDataFromResponse.
922 *
923 * @protected
924 * @method
925 * @abstract
926 * @param {Mixed} data Cached result data, usually an array
927 * @return {OO.ui.MenuOptionWidget[]} Menu items
928 */
929 OO.ui.mixin.LookupElement.prototype.getLookupMenuOptionsFromData = null;
930
931 /**
932 * Set the read-only state of the widget.
933 *
934 * This will also disable/enable the lookups functionality.
935 *
936 * @param {boolean} readOnly Make input read-only
937 * @chainable
938 * @return {OO.ui.Element} The element, for chaining
939 */
940 OO.ui.mixin.LookupElement.prototype.setReadOnly = function ( readOnly ) {
941 // Parent method
942 // Note: Calling #setReadOnly this way assumes this is mixed into an OO.ui.TextInputWidget
943 OO.ui.TextInputWidget.prototype.setReadOnly.call( this, readOnly );
944
945 // During construction, #setReadOnly is called before the OO.ui.mixin.LookupElement constructor
946 if ( this.isReadOnly() && this.lookupMenu ) {
947 this.closeLookupMenu();
948 }
949
950 return this;
951 };
952
953 /**
954 * @inheritdoc OO.ui.mixin.RequestManager
955 */
956 OO.ui.mixin.LookupElement.prototype.getRequestQuery = function () {
957 return this.getValue();
958 };
959
960 /**
961 * @inheritdoc OO.ui.mixin.RequestManager
962 */
963 OO.ui.mixin.LookupElement.prototype.getRequest = function () {
964 return this.getLookupRequest();
965 };
966
967 /**
968 * @inheritdoc OO.ui.mixin.RequestManager
969 */
970 OO.ui.mixin.LookupElement.prototype.getRequestCacheDataFromResponse = function ( response ) {
971 return this.getLookupCacheDataFromResponse( response );
972 };
973
974 /**
975 * TabPanelLayouts are used within {@link OO.ui.IndexLayout index layouts} to create tab panels that
976 * users can select and display from the index's optional {@link OO.ui.TabSelectWidget tab}
977 * navigation. TabPanels are usually not instantiated directly, rather extended to include the
978 * required content and functionality.
979 *
980 * Each tab panel must have a unique symbolic name, which is passed to the constructor. In addition,
981 * the tab panel's tab item is customized (with a label) using the #setupTabItem method. See
982 * {@link OO.ui.IndexLayout IndexLayout} for an example.
983 *
984 * @class
985 * @extends OO.ui.PanelLayout
986 *
987 * @constructor
988 * @param {string} name Unique symbolic name of tab panel
989 * @param {Object} [config] Configuration options
990 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] Label for tab panel's tab
991 */
992 OO.ui.TabPanelLayout = function OoUiTabPanelLayout( name, config ) {
993 // Allow passing positional parameters inside the config object
994 if ( OO.isPlainObject( name ) && config === undefined ) {
995 config = name;
996 name = config.name;
997 }
998
999 // Configuration initialization
1000 config = $.extend( { scrollable: true }, config );
1001
1002 // Parent constructor
1003 OO.ui.TabPanelLayout.parent.call( this, config );
1004
1005 // Properties
1006 this.name = name;
1007 this.label = config.label;
1008 this.tabItem = null;
1009 this.active = false;
1010
1011 // Initialization
1012 this.$element
1013 .addClass( 'oo-ui-tabPanelLayout' )
1014 .attr( 'role', 'tabpanel' );
1015 };
1016
1017 /* Setup */
1018
1019 OO.inheritClass( OO.ui.TabPanelLayout, OO.ui.PanelLayout );
1020
1021 /* Events */
1022
1023 /**
1024 * An 'active' event is emitted when the tab panel becomes active. Tab panels become active when they are
1025 * shown in a index layout that is configured to display only one tab panel at a time.
1026 *
1027 * @event active
1028 * @param {boolean} active Tab panel is active
1029 */
1030
1031 /* Methods */
1032
1033 /**
1034 * Get the symbolic name of the tab panel.
1035 *
1036 * @return {string} Symbolic name of tab panel
1037 */
1038 OO.ui.TabPanelLayout.prototype.getName = function () {
1039 return this.name;
1040 };
1041
1042 /**
1043 * Check if tab panel is active.
1044 *
1045 * Tab panels become active when they are shown in a {@link OO.ui.IndexLayout index layout} that is configured to
1046 * display only one tab panel at a time. Additional CSS is applied to the tab panel's tab item to reflect the
1047 * active state.
1048 *
1049 * @return {boolean} Tab panel is active
1050 */
1051 OO.ui.TabPanelLayout.prototype.isActive = function () {
1052 return this.active;
1053 };
1054
1055 /**
1056 * Get tab item.
1057 *
1058 * The tab item allows users to access the tab panel from the index's tab
1059 * navigation. The tab item itself can be customized (with a label, level, etc.) using the #setupTabItem method.
1060 *
1061 * @return {OO.ui.TabOptionWidget|null} Tab option widget
1062 */
1063 OO.ui.TabPanelLayout.prototype.getTabItem = function () {
1064 return this.tabItem;
1065 };
1066
1067 /**
1068 * Set or unset the tab item.
1069 *
1070 * Specify a {@link OO.ui.TabOptionWidget tab option} to set it,
1071 * or `null` to clear the tab item. To customize the tab item itself (e.g., to set a label or tab
1072 * level), use #setupTabItem instead of this method.
1073 *
1074 * @param {OO.ui.TabOptionWidget|null} tabItem Tab option widget, null to clear
1075 * @chainable
1076 * @return {OO.ui.TabPanelLayout} The layout, for chaining
1077 */
1078 OO.ui.TabPanelLayout.prototype.setTabItem = function ( tabItem ) {
1079 this.tabItem = tabItem || null;
1080 if ( tabItem ) {
1081 this.setupTabItem();
1082 }
1083 return this;
1084 };
1085
1086 /**
1087 * Set up the tab item.
1088 *
1089 * Use this method to customize the tab item (e.g., to add a label or tab level). To set or unset
1090 * the tab item itself (with a {@link OO.ui.TabOptionWidget tab option} or `null`), use
1091 * the #setTabItem method instead.
1092 *
1093 * @param {OO.ui.TabOptionWidget} tabItem Tab option widget to set up
1094 * @chainable
1095 * @return {OO.ui.TabPanelLayout} The layout, for chaining
1096 */
1097 OO.ui.TabPanelLayout.prototype.setupTabItem = function () {
1098 this.$element.attr( 'aria-labelledby', this.tabItem.getElementId() );
1099
1100 this.tabItem.$element.attr( 'aria-controls', this.getElementId() );
1101
1102 if ( this.label ) {
1103 this.tabItem.setLabel( this.label );
1104 }
1105 return this;
1106 };
1107
1108 /**
1109 * Set the tab panel to its 'active' state.
1110 *
1111 * Tab panels become active when they are shown in a index layout that is configured to display only
1112 * one tab panel at a time. Additional CSS is applied to the tab item to reflect the tab panel's
1113 * active state. Outside of the index context, setting the active state on a tab panel does nothing.
1114 *
1115 * @param {boolean} active Tab panel is active
1116 * @fires active
1117 */
1118 OO.ui.TabPanelLayout.prototype.setActive = function ( active ) {
1119 active = !!active;
1120
1121 if ( active !== this.active ) {
1122 this.active = active;
1123 this.$element.toggleClass( 'oo-ui-tabPanelLayout-active', this.active );
1124 this.emit( 'active', this.active );
1125 }
1126 };
1127
1128 /**
1129 * PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display
1130 * from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly,
1131 * rather extended to include the required content and functionality.
1132 *
1133 * Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline
1134 * item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See
1135 * {@link OO.ui.BookletLayout BookletLayout} for an example.
1136 *
1137 * @class
1138 * @extends OO.ui.PanelLayout
1139 *
1140 * @constructor
1141 * @param {string} name Unique symbolic name of page
1142 * @param {Object} [config] Configuration options
1143 */
1144 OO.ui.PageLayout = function OoUiPageLayout( name, config ) {
1145 // Allow passing positional parameters inside the config object
1146 if ( OO.isPlainObject( name ) && config === undefined ) {
1147 config = name;
1148 name = config.name;
1149 }
1150
1151 // Configuration initialization
1152 config = $.extend( { scrollable: true }, config );
1153
1154 // Parent constructor
1155 OO.ui.PageLayout.parent.call( this, config );
1156
1157 // Properties
1158 this.name = name;
1159 this.outlineItem = null;
1160 this.active = false;
1161
1162 // Initialization
1163 this.$element.addClass( 'oo-ui-pageLayout' );
1164 };
1165
1166 /* Setup */
1167
1168 OO.inheritClass( OO.ui.PageLayout, OO.ui.PanelLayout );
1169
1170 /* Events */
1171
1172 /**
1173 * An 'active' event is emitted when the page becomes active. Pages become active when they are
1174 * shown in a booklet layout that is configured to display only one page at a time.
1175 *
1176 * @event active
1177 * @param {boolean} active Page is active
1178 */
1179
1180 /* Methods */
1181
1182 /**
1183 * Get the symbolic name of the page.
1184 *
1185 * @return {string} Symbolic name of page
1186 */
1187 OO.ui.PageLayout.prototype.getName = function () {
1188 return this.name;
1189 };
1190
1191 /**
1192 * Check if page is active.
1193 *
1194 * Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display
1195 * only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state.
1196 *
1197 * @return {boolean} Page is active
1198 */
1199 OO.ui.PageLayout.prototype.isActive = function () {
1200 return this.active;
1201 };
1202
1203 /**
1204 * Get outline item.
1205 *
1206 * The outline item allows users to access the page from the booklet's outline
1207 * navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method.
1208 *
1209 * @return {OO.ui.OutlineOptionWidget|null} Outline option widget
1210 */
1211 OO.ui.PageLayout.prototype.getOutlineItem = function () {
1212 return this.outlineItem;
1213 };
1214
1215 /**
1216 * Set or unset the outline item.
1217 *
1218 * Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it,
1219 * or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline
1220 * level), use #setupOutlineItem instead of this method.
1221 *
1222 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear
1223 * @chainable
1224 * @return {OO.ui.PageLayout} The layout, for chaining
1225 */
1226 OO.ui.PageLayout.prototype.setOutlineItem = function ( outlineItem ) {
1227 this.outlineItem = outlineItem || null;
1228 if ( outlineItem ) {
1229 this.setupOutlineItem();
1230 }
1231 return this;
1232 };
1233
1234 /**
1235 * Set up the outline item.
1236 *
1237 * Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset
1238 * the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use
1239 * the #setOutlineItem method instead.
1240 *
1241 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up
1242 * @chainable
1243 * @return {OO.ui.PageLayout} The layout, for chaining
1244 */
1245 OO.ui.PageLayout.prototype.setupOutlineItem = function () {
1246 return this;
1247 };
1248
1249 /**
1250 * Set the page to its 'active' state.
1251 *
1252 * Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional
1253 * CSS is applied to the outline item to reflect the page's active state. Outside of the booklet
1254 * context, setting the active state on a page does nothing.
1255 *
1256 * @param {boolean} active Page is active
1257 * @fires active
1258 */
1259 OO.ui.PageLayout.prototype.setActive = function ( active ) {
1260 active = !!active;
1261
1262 if ( active !== this.active ) {
1263 this.active = active;
1264 this.$element.toggleClass( 'oo-ui-pageLayout-active', active );
1265 this.emit( 'active', this.active );
1266 }
1267 };
1268
1269 /**
1270 * StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed
1271 * at a time, though the stack layout can also be configured to show all contained panels, one after another,
1272 * by setting the #continuous option to 'true'.
1273 *
1274 * @example
1275 * // A stack layout with two panels, configured to be displayed continuously
1276 * var myStack = new OO.ui.StackLayout( {
1277 * items: [
1278 * new OO.ui.PanelLayout( {
1279 * $content: $( '<p>Panel One</p>' ),
1280 * padded: true,
1281 * framed: true
1282 * } ),
1283 * new OO.ui.PanelLayout( {
1284 * $content: $( '<p>Panel Two</p>' ),
1285 * padded: true,
1286 * framed: true
1287 * } )
1288 * ],
1289 * continuous: true
1290 * } );
1291 * $( 'body' ).append( myStack.$element );
1292 *
1293 * @class
1294 * @extends OO.ui.PanelLayout
1295 * @mixins OO.ui.mixin.GroupElement
1296 *
1297 * @constructor
1298 * @param {Object} [config] Configuration options
1299 * @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time.
1300 * @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout.
1301 */
1302 OO.ui.StackLayout = function OoUiStackLayout( config ) {
1303 // Configuration initialization
1304 config = $.extend( { scrollable: true }, config );
1305
1306 // Parent constructor
1307 OO.ui.StackLayout.parent.call( this, config );
1308
1309 // Mixin constructors
1310 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
1311
1312 // Properties
1313 this.currentItem = null;
1314 this.continuous = !!config.continuous;
1315
1316 // Initialization
1317 this.$element.addClass( 'oo-ui-stackLayout' );
1318 if ( this.continuous ) {
1319 this.$element.addClass( 'oo-ui-stackLayout-continuous' );
1320 this.$element.on( 'scroll', OO.ui.debounce( this.onScroll.bind( this ), 250 ) );
1321 }
1322 if ( Array.isArray( config.items ) ) {
1323 this.addItems( config.items );
1324 }
1325 };
1326
1327 /* Setup */
1328
1329 OO.inheritClass( OO.ui.StackLayout, OO.ui.PanelLayout );
1330 OO.mixinClass( OO.ui.StackLayout, OO.ui.mixin.GroupElement );
1331
1332 /* Events */
1333
1334 /**
1335 * A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed},
1336 * {@link #clearItems cleared} or {@link #setItem displayed}.
1337 *
1338 * @event set
1339 * @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown
1340 */
1341
1342 /**
1343 * When used in continuous mode, this event is emitted when the user scrolls down
1344 * far enough such that currentItem is no longer visible.
1345 *
1346 * @event visibleItemChange
1347 * @param {OO.ui.PanelLayout} panel The next visible item in the layout
1348 */
1349
1350 /* Methods */
1351
1352 /**
1353 * Handle scroll events from the layout element
1354 *
1355 * @param {jQuery.Event} e
1356 * @fires visibleItemChange
1357 */
1358 OO.ui.StackLayout.prototype.onScroll = function () {
1359 var currentRect,
1360 len = this.items.length,
1361 currentIndex = this.items.indexOf( this.currentItem ),
1362 newIndex = currentIndex,
1363 containerRect = this.$element[ 0 ].getBoundingClientRect();
1364
1365 if ( !containerRect || ( !containerRect.top && !containerRect.bottom ) ) {
1366 // Can't get bounding rect, possibly not attached.
1367 return;
1368 }
1369
1370 function getRect( item ) {
1371 return item.$element[ 0 ].getBoundingClientRect();
1372 }
1373
1374 function isVisible( item ) {
1375 var rect = getRect( item );
1376 return rect.bottom > containerRect.top && rect.top < containerRect.bottom;
1377 }
1378
1379 currentRect = getRect( this.currentItem );
1380
1381 if ( currentRect.bottom < containerRect.top ) {
1382 // Scrolled down past current item
1383 while ( ++newIndex < len ) {
1384 if ( isVisible( this.items[ newIndex ] ) ) {
1385 break;
1386 }
1387 }
1388 } else if ( currentRect.top > containerRect.bottom ) {
1389 // Scrolled up past current item
1390 while ( --newIndex >= 0 ) {
1391 if ( isVisible( this.items[ newIndex ] ) ) {
1392 break;
1393 }
1394 }
1395 }
1396
1397 if ( newIndex !== currentIndex ) {
1398 this.emit( 'visibleItemChange', this.items[ newIndex ] );
1399 }
1400 };
1401
1402 /**
1403 * Get the current panel.
1404 *
1405 * @return {OO.ui.Layout|null}
1406 */
1407 OO.ui.StackLayout.prototype.getCurrentItem = function () {
1408 return this.currentItem;
1409 };
1410
1411 /**
1412 * Unset the current item.
1413 *
1414 * @private
1415 * @param {OO.ui.StackLayout} layout
1416 * @fires set
1417 */
1418 OO.ui.StackLayout.prototype.unsetCurrentItem = function () {
1419 var prevItem = this.currentItem;
1420 if ( prevItem === null ) {
1421 return;
1422 }
1423
1424 this.currentItem = null;
1425 this.emit( 'set', null );
1426 };
1427
1428 /**
1429 * Add panel layouts to the stack layout.
1430 *
1431 * Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different
1432 * insertion point. Adding a panel that is already in the stack will move it to the end of the array or the point specified
1433 * by the index.
1434 *
1435 * @param {OO.ui.Layout[]} items Panels to add
1436 * @param {number} [index] Index of the insertion point
1437 * @chainable
1438 * @return {OO.ui.StackLayout} The layout, for chaining
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 * @return {OO.ui.StackLayout} The layout, for chaining
1463 * @fires set
1464 */
1465 OO.ui.StackLayout.prototype.removeItems = function ( items ) {
1466 // Mixin method
1467 OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items );
1468
1469 if ( items.indexOf( this.currentItem ) !== -1 ) {
1470 if ( this.items.length ) {
1471 this.setItem( this.items[ 0 ] );
1472 } else {
1473 this.unsetCurrentItem();
1474 }
1475 }
1476
1477 return this;
1478 };
1479
1480 /**
1481 * Clear all panels from the stack layout.
1482 *
1483 * Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only
1484 * a subset of panels, use the #removeItems method.
1485 *
1486 * @chainable
1487 * @return {OO.ui.StackLayout} The layout, for chaining
1488 * @fires set
1489 */
1490 OO.ui.StackLayout.prototype.clearItems = function () {
1491 this.unsetCurrentItem();
1492 OO.ui.mixin.GroupElement.prototype.clearItems.call( this );
1493
1494 return this;
1495 };
1496
1497 /**
1498 * Show the specified panel.
1499 *
1500 * If another panel is currently displayed, it will be hidden.
1501 *
1502 * @param {OO.ui.Layout} item Panel to show
1503 * @chainable
1504 * @return {OO.ui.StackLayout} The layout, for chaining
1505 * @fires set
1506 */
1507 OO.ui.StackLayout.prototype.setItem = function ( item ) {
1508 if ( item !== this.currentItem ) {
1509 this.updateHiddenState( this.items, item );
1510
1511 if ( this.items.indexOf( item ) !== -1 ) {
1512 this.currentItem = item;
1513 this.emit( 'set', item );
1514 } else {
1515 this.unsetCurrentItem();
1516 }
1517 }
1518
1519 return this;
1520 };
1521
1522 /**
1523 * Reset the scroll offset of all panels, or the container if continuous
1524 *
1525 * @inheritdoc
1526 */
1527 OO.ui.StackLayout.prototype.resetScroll = function () {
1528 if ( this.continuous ) {
1529 // Parent method
1530 return OO.ui.StackLayout.parent.prototype.resetScroll.call( this );
1531 }
1532 // Reset each panel
1533 this.getItems().forEach( function ( panel ) {
1534 var hidden = panel.$element.hasClass( 'oo-ui-element-hidden' );
1535 // Scroll can only be reset when panel is visible
1536 panel.$element.removeClass( 'oo-ui-element-hidden' );
1537 panel.resetScroll();
1538 if ( hidden ) {
1539 panel.$element.addClass( 'oo-ui-element-hidden' );
1540 }
1541 } );
1542
1543 return this;
1544 };
1545
1546 /**
1547 * Update the visibility of all items in case of non-continuous view.
1548 *
1549 * Ensure all items are hidden except for the selected one.
1550 * This method does nothing when the stack is continuous.
1551 *
1552 * @private
1553 * @param {OO.ui.Layout[]} items Item list iterate over
1554 * @param {OO.ui.Layout} [selectedItem] Selected item to show
1555 */
1556 OO.ui.StackLayout.prototype.updateHiddenState = function ( items, selectedItem ) {
1557 var i, len;
1558
1559 if ( !this.continuous ) {
1560 for ( i = 0, len = items.length; i < len; i++ ) {
1561 if ( !selectedItem || selectedItem !== items[ i ] ) {
1562 items[ i ].$element.addClass( 'oo-ui-element-hidden' );
1563 items[ i ].$element.attr( 'aria-hidden', 'true' );
1564 }
1565 }
1566 if ( selectedItem ) {
1567 selectedItem.$element.removeClass( 'oo-ui-element-hidden' );
1568 selectedItem.$element.removeAttr( 'aria-hidden' );
1569 }
1570 }
1571 };
1572
1573 /**
1574 * 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)
1575 * and its size is customized with the #menuSize config. The content area will fill all remaining space.
1576 *
1577 * @example
1578 * var menuLayout,
1579 * menuPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
1580 * contentPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
1581 * select = new OO.ui.SelectWidget( {
1582 * items: [
1583 * new OO.ui.OptionWidget( {
1584 * data: 'before',
1585 * label: 'Before'
1586 * } ),
1587 * new OO.ui.OptionWidget( {
1588 * data: 'after',
1589 * label: 'After'
1590 * } ),
1591 * new OO.ui.OptionWidget( {
1592 * data: 'top',
1593 * label: 'Top'
1594 * } ),
1595 * new OO.ui.OptionWidget( {
1596 * data: 'bottom',
1597 * label: 'Bottom'
1598 * } )
1599 * ]
1600 * } ).on( 'select', function ( item ) {
1601 * menuLayout.setMenuPosition( item.getData() );
1602 * } );
1603 *
1604 * menuLayout = new OO.ui.MenuLayout( {
1605 * position: 'top',
1606 * menuPanel: menuPanel,
1607 * contentPanel: contentPanel
1608 * } )
1609 * menuLayout.$menu.append(
1610 * menuPanel.$element.append( '<b>Menu panel</b>', select.$element )
1611 * );
1612 * menuLayout.$content.append(
1613 * contentPanel.$element.append( '<b>Content panel</b>', '<p>Note that the menu is positioned relative to the content panel: top, bottom, after, before.</p>')
1614 * );
1615 * $( 'body' ).append( menuLayout.$element );
1616 *
1617 * If menu size needs to be overridden, it can be accomplished using CSS similar to the snippet
1618 * below. MenuLayout's CSS will override the appropriate values with 'auto' or '0' to display the
1619 * menu correctly. If `menuPosition` is known beforehand, CSS rules corresponding to other positions
1620 * may be omitted.
1621 *
1622 * .oo-ui-menuLayout-menu {
1623 * width: 200px;
1624 * height: 200px;
1625 * }
1626 *
1627 * .oo-ui-menuLayout-content {
1628 * top: 200px;
1629 * left: 200px;
1630 * right: 200px;
1631 * bottom: 200px;
1632 * }
1633 *
1634 * @class
1635 * @extends OO.ui.Layout
1636 *
1637 * @constructor
1638 * @param {Object} [config] Configuration options
1639 * @cfg {OO.ui.PanelLayout} [menuPanel] Menu panel
1640 * @cfg {OO.ui.PanelLayout} [contentPanel] Content panel
1641 * @cfg {boolean} [expanded=true] Expand the layout to fill the entire parent element.
1642 * @cfg {boolean} [showMenu=true] Show menu
1643 * @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before`
1644 */
1645 OO.ui.MenuLayout = function OoUiMenuLayout( config ) {
1646 // Configuration initialization
1647 config = $.extend( {
1648 expanded: true,
1649 showMenu: true,
1650 menuPosition: 'before'
1651 }, config );
1652
1653 // Parent constructor
1654 OO.ui.MenuLayout.parent.call( this, config );
1655
1656 this.menuPanel = null;
1657 this.contentPanel = null;
1658 this.expanded = !!config.expanded;
1659 /**
1660 * Menu DOM node
1661 *
1662 * @property {jQuery}
1663 */
1664 this.$menu = $( '<div>' );
1665 /**
1666 * Content DOM node
1667 *
1668 * @property {jQuery}
1669 */
1670 this.$content = $( '<div>' );
1671
1672 // Initialization
1673 this.$menu
1674 .addClass( 'oo-ui-menuLayout-menu' );
1675 this.$content.addClass( 'oo-ui-menuLayout-content' );
1676 this.$element
1677 .addClass( 'oo-ui-menuLayout' );
1678 if ( config.expanded ) {
1679 this.$element.addClass( 'oo-ui-menuLayout-expanded' );
1680 } else {
1681 this.$element.addClass( 'oo-ui-menuLayout-static' );
1682 }
1683 if ( config.menuPanel ) {
1684 this.setMenuPanel( config.menuPanel );
1685 }
1686 if ( config.contentPanel ) {
1687 this.setContentPanel( config.contentPanel );
1688 }
1689 this.setMenuPosition( config.menuPosition );
1690 this.toggleMenu( config.showMenu );
1691 };
1692
1693 /* Setup */
1694
1695 OO.inheritClass( OO.ui.MenuLayout, OO.ui.Layout );
1696
1697 /* Methods */
1698
1699 /**
1700 * Toggle menu.
1701 *
1702 * @param {boolean} showMenu Show menu, omit to toggle
1703 * @chainable
1704 * @return {OO.ui.MenuLayout} The layout, for chaining
1705 */
1706 OO.ui.MenuLayout.prototype.toggleMenu = function ( showMenu ) {
1707 showMenu = showMenu === undefined ? !this.showMenu : !!showMenu;
1708
1709 if ( this.showMenu !== showMenu ) {
1710 this.showMenu = showMenu;
1711 this.$element
1712 .toggleClass( 'oo-ui-menuLayout-showMenu', this.showMenu )
1713 .toggleClass( 'oo-ui-menuLayout-hideMenu', !this.showMenu );
1714 this.$menu.attr( 'aria-hidden', this.showMenu ? 'false' : 'true' );
1715 }
1716
1717 return this;
1718 };
1719
1720 /**
1721 * Check if menu is visible
1722 *
1723 * @return {boolean} Menu is visible
1724 */
1725 OO.ui.MenuLayout.prototype.isMenuVisible = function () {
1726 return this.showMenu;
1727 };
1728
1729 /**
1730 * Set menu position.
1731 *
1732 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
1733 * @throws {Error} If position value is not supported
1734 * @chainable
1735 * @return {OO.ui.MenuLayout} The layout, for chaining
1736 */
1737 OO.ui.MenuLayout.prototype.setMenuPosition = function ( position ) {
1738 this.$element.removeClass( 'oo-ui-menuLayout-' + this.menuPosition );
1739 this.menuPosition = position;
1740 if ( this.menuPosition === 'top' || this.menuPosition === 'before' ) {
1741 this.$element.append( this.$menu, this.$content );
1742 } else {
1743 this.$element.append( this.$content, this.$menu );
1744 }
1745 this.$element.addClass( 'oo-ui-menuLayout-' + position );
1746
1747 return this;
1748 };
1749
1750 /**
1751 * Get menu position.
1752 *
1753 * @return {string} Menu position
1754 */
1755 OO.ui.MenuLayout.prototype.getMenuPosition = function () {
1756 return this.menuPosition;
1757 };
1758
1759 /**
1760 * Set the menu panel.
1761 *
1762 * @param {OO.ui.PanelLayout} menuPanel Menu panel
1763 */
1764 OO.ui.MenuLayout.prototype.setMenuPanel = function ( menuPanel ) {
1765 this.menuPanel = menuPanel;
1766 this.$menu.append( this.menuPanel.$element );
1767 };
1768
1769 /**
1770 * Set the content panel.
1771 *
1772 * @param {OO.ui.PanelLayout} contentPanel Content panel
1773 */
1774 OO.ui.MenuLayout.prototype.setContentPanel = function ( contentPanel ) {
1775 this.contentPanel = contentPanel;
1776 this.$content.append( this.contentPanel.$element );
1777 };
1778
1779 /**
1780 * Clear the menu panel.
1781 */
1782 OO.ui.MenuLayout.prototype.clearMenuPanel = function () {
1783 this.menuPanel = null;
1784 this.$menu.empty();
1785 };
1786
1787 /**
1788 * Clear the content panel.
1789 */
1790 OO.ui.MenuLayout.prototype.clearContentPanel = function () {
1791 this.contentPanel = null;
1792 this.$content.empty();
1793 };
1794
1795 /**
1796 * Reset the scroll offset of all panels and the tab select widget
1797 *
1798 * @inheritdoc
1799 */
1800 OO.ui.MenuLayout.prototype.resetScroll = function () {
1801 if ( this.menuPanel ) {
1802 this.menuPanel.resetScroll();
1803 }
1804 if ( this.contentPanel ) {
1805 this.contentPanel.resetScroll();
1806 }
1807
1808 return this;
1809 };
1810
1811 /**
1812 * BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as
1813 * an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate
1814 * through the pages and select which one to display. By default, only one page is
1815 * displayed at a time and the outline is hidden. When a user navigates to a new page,
1816 * the booklet layout automatically focuses on the first focusable element, unless the
1817 * default setting is changed. Optionally, booklets can be configured to show
1818 * {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items.
1819 *
1820 * @example
1821 * // Example of a BookletLayout that contains two PageLayouts.
1822 *
1823 * function PageOneLayout( name, config ) {
1824 * PageOneLayout.parent.call( this, name, config );
1825 * this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' );
1826 * }
1827 * OO.inheritClass( PageOneLayout, OO.ui.PageLayout );
1828 * PageOneLayout.prototype.setupOutlineItem = function () {
1829 * this.outlineItem.setLabel( 'Page One' );
1830 * };
1831 *
1832 * function PageTwoLayout( name, config ) {
1833 * PageTwoLayout.parent.call( this, name, config );
1834 * this.$element.append( '<p>Second page</p>' );
1835 * }
1836 * OO.inheritClass( PageTwoLayout, OO.ui.PageLayout );
1837 * PageTwoLayout.prototype.setupOutlineItem = function () {
1838 * this.outlineItem.setLabel( 'Page Two' );
1839 * };
1840 *
1841 * var page1 = new PageOneLayout( 'one' ),
1842 * page2 = new PageTwoLayout( 'two' );
1843 *
1844 * var booklet = new OO.ui.BookletLayout( {
1845 * outlined: true
1846 * } );
1847 *
1848 * booklet.addPages( [ page1, page2 ] );
1849 * $( 'body' ).append( booklet.$element );
1850 *
1851 * @class
1852 * @extends OO.ui.MenuLayout
1853 *
1854 * @constructor
1855 * @param {Object} [config] Configuration options
1856 * @cfg {boolean} [continuous=false] Show all pages, one after another
1857 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed. Disabled on mobile.
1858 * @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet.
1859 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
1860 */
1861 OO.ui.BookletLayout = function OoUiBookletLayout( config ) {
1862 // Configuration initialization
1863 config = config || {};
1864
1865 // Parent constructor
1866 OO.ui.BookletLayout.parent.call( this, config );
1867
1868 // Properties
1869 this.currentPageName = null;
1870 this.pages = {};
1871 this.ignoreFocus = false;
1872 this.stackLayout = new OO.ui.StackLayout( {
1873 continuous: !!config.continuous,
1874 expanded: this.expanded
1875 } );
1876 this.setContentPanel( this.stackLayout );
1877 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
1878 this.outlineVisible = false;
1879 this.outlined = !!config.outlined;
1880 if ( this.outlined ) {
1881 this.editable = !!config.editable;
1882 this.outlineControlsWidget = null;
1883 this.outlineSelectWidget = new OO.ui.OutlineSelectWidget();
1884 this.outlinePanel = new OO.ui.PanelLayout( {
1885 expanded: this.expanded,
1886 scrollable: true
1887 } );
1888 this.setMenuPanel( this.outlinePanel );
1889 this.outlineVisible = true;
1890 if ( this.editable ) {
1891 this.outlineControlsWidget = new OO.ui.OutlineControlsWidget(
1892 this.outlineSelectWidget
1893 );
1894 }
1895 }
1896 this.toggleMenu( this.outlined );
1897
1898 // Events
1899 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
1900 if ( this.outlined ) {
1901 this.outlineSelectWidget.connect( this, { select: 'onOutlineSelectWidgetSelect' } );
1902 this.scrolling = false;
1903 this.stackLayout.connect( this, { visibleItemChange: 'onStackLayoutVisibleItemChange' } );
1904 }
1905 if ( this.autoFocus ) {
1906 // Event 'focus' does not bubble, but 'focusin' does
1907 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
1908 }
1909
1910 // Initialization
1911 this.$element.addClass( 'oo-ui-bookletLayout' );
1912 this.stackLayout.$element.addClass( 'oo-ui-bookletLayout-stackLayout' );
1913 if ( this.outlined ) {
1914 this.outlinePanel.$element
1915 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
1916 .append( this.outlineSelectWidget.$element );
1917 if ( this.editable ) {
1918 this.outlinePanel.$element
1919 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
1920 .append( this.outlineControlsWidget.$element );
1921 }
1922 }
1923 };
1924
1925 /* Setup */
1926
1927 OO.inheritClass( OO.ui.BookletLayout, OO.ui.MenuLayout );
1928
1929 /* Events */
1930
1931 /**
1932 * A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout.
1933 * @event set
1934 * @param {OO.ui.PageLayout} page Current page
1935 */
1936
1937 /**
1938 * An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout.
1939 *
1940 * @event add
1941 * @param {OO.ui.PageLayout[]} page Added pages
1942 * @param {number} index Index pages were added at
1943 */
1944
1945 /**
1946 * A 'remove' event is emitted when pages are {@link #clearPages cleared} or
1947 * {@link #removePages removed} from the booklet.
1948 *
1949 * @event remove
1950 * @param {OO.ui.PageLayout[]} pages Removed pages
1951 */
1952
1953 /* Methods */
1954
1955 /**
1956 * Handle stack layout focus.
1957 *
1958 * @private
1959 * @param {jQuery.Event} e Focusin event
1960 */
1961 OO.ui.BookletLayout.prototype.onStackLayoutFocus = function ( e ) {
1962 var name, $target;
1963
1964 // Find the page that an element was focused within
1965 $target = $( e.target ).closest( '.oo-ui-pageLayout' );
1966 for ( name in this.pages ) {
1967 // Check for page match, exclude current page to find only page changes
1968 if ( this.pages[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentPageName ) {
1969 this.setPage( name );
1970 break;
1971 }
1972 }
1973 };
1974
1975 /**
1976 * Handle visibleItemChange events from the stackLayout
1977 *
1978 * The next visible page is set as the current page by selecting it
1979 * in the outline
1980 *
1981 * @param {OO.ui.PageLayout} page The next visible page in the layout
1982 */
1983 OO.ui.BookletLayout.prototype.onStackLayoutVisibleItemChange = function ( page ) {
1984 // Set a flag to so that the resulting call to #onStackLayoutSet doesn't
1985 // try and scroll the item into view again.
1986 this.scrolling = true;
1987 this.outlineSelectWidget.selectItemByData( page.getName() );
1988 this.scrolling = false;
1989 };
1990
1991 /**
1992 * Handle stack layout set events.
1993 *
1994 * @private
1995 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
1996 */
1997 OO.ui.BookletLayout.prototype.onStackLayoutSet = function ( page ) {
1998 var promise, layout = this;
1999 // If everything is unselected, do nothing
2000 if ( !page ) {
2001 return;
2002 }
2003 // For continuous BookletLayouts, scroll the selected page into view first
2004 if ( this.stackLayout.continuous && !this.scrolling ) {
2005 promise = page.scrollElementIntoView();
2006 } else {
2007 promise = $.Deferred().resolve();
2008 }
2009 // Focus the first element on the newly selected panel.
2010 // Don't focus if the page was set by scrolling.
2011 if ( this.autoFocus && !OO.ui.isMobile() && !this.scrolling ) {
2012 promise.done( function () {
2013 layout.focus();
2014 } );
2015 }
2016 };
2017
2018 /**
2019 * Focus the first input in the current page.
2020 *
2021 * If no page is selected, the first selectable page will be selected.
2022 * If the focus is already in an element on the current page, nothing will happen.
2023 *
2024 * @param {number} [itemIndex] A specific item to focus on
2025 */
2026 OO.ui.BookletLayout.prototype.focus = function ( itemIndex ) {
2027 var page,
2028 items = this.stackLayout.getItems();
2029
2030 if ( itemIndex !== undefined && items[ itemIndex ] ) {
2031 page = items[ itemIndex ];
2032 } else {
2033 page = this.stackLayout.getCurrentItem();
2034 }
2035
2036 if ( !page && this.outlined ) {
2037 this.selectFirstSelectablePage();
2038 page = this.stackLayout.getCurrentItem();
2039 }
2040 if ( !page ) {
2041 return;
2042 }
2043 // Only change the focus if is not already in the current page
2044 if ( !OO.ui.contains( page.$element[ 0 ], this.getElementDocument().activeElement, true ) ) {
2045 page.focus();
2046 }
2047 };
2048
2049 /**
2050 * Find the first focusable input in the booklet layout and focus
2051 * on it.
2052 */
2053 OO.ui.BookletLayout.prototype.focusFirstFocusable = function () {
2054 OO.ui.findFocusable( this.stackLayout.$element ).focus();
2055 };
2056
2057 /**
2058 * Handle outline widget select events.
2059 *
2060 * @private
2061 * @param {OO.ui.OptionWidget|null} item Selected item
2062 */
2063 OO.ui.BookletLayout.prototype.onOutlineSelectWidgetSelect = function ( item ) {
2064 if ( item ) {
2065 this.setPage( item.getData() );
2066 }
2067 };
2068
2069 /**
2070 * Check if booklet has an outline.
2071 *
2072 * @return {boolean} Booklet has an outline
2073 */
2074 OO.ui.BookletLayout.prototype.isOutlined = function () {
2075 return this.outlined;
2076 };
2077
2078 /**
2079 * Check if booklet has editing controls.
2080 *
2081 * @return {boolean} Booklet is editable
2082 */
2083 OO.ui.BookletLayout.prototype.isEditable = function () {
2084 return this.editable;
2085 };
2086
2087 /**
2088 * Check if booklet has a visible outline.
2089 *
2090 * @return {boolean} Outline is visible
2091 */
2092 OO.ui.BookletLayout.prototype.isOutlineVisible = function () {
2093 return this.outlined && this.outlineVisible;
2094 };
2095
2096 /**
2097 * Hide or show the outline.
2098 *
2099 * @param {boolean} [show] Show outline, omit to invert current state
2100 * @chainable
2101 * @return {OO.ui.BookletLayout} The layout, for chaining
2102 */
2103 OO.ui.BookletLayout.prototype.toggleOutline = function ( show ) {
2104 var booklet = this;
2105
2106 if ( this.outlined ) {
2107 show = show === undefined ? !this.outlineVisible : !!show;
2108 this.outlineVisible = show;
2109 this.toggleMenu( show );
2110 if ( show && this.editable ) {
2111 // HACK: Kill dumb scrollbars when the sidebar stops animating, see T161798. Only necessary when
2112 // outline controls are present, delay matches transition on `.oo-ui-menuLayout-menu`.
2113 setTimeout( function () {
2114 OO.ui.Element.static.reconsiderScrollbars( booklet.outlinePanel.$element[ 0 ] );
2115 }, OO.ui.theme.getDialogTransitionDuration() );
2116 }
2117 }
2118
2119 return this;
2120 };
2121
2122 /**
2123 * Find the page closest to the specified page.
2124 *
2125 * @param {OO.ui.PageLayout} page Page to use as a reference point
2126 * @return {OO.ui.PageLayout|null} Page closest to the specified page
2127 */
2128 OO.ui.BookletLayout.prototype.findClosestPage = function ( page ) {
2129 var next, prev, level,
2130 pages = this.stackLayout.getItems(),
2131 index = pages.indexOf( page );
2132
2133 if ( index !== -1 ) {
2134 next = pages[ index + 1 ];
2135 prev = pages[ index - 1 ];
2136 // Prefer adjacent pages at the same level
2137 if ( this.outlined ) {
2138 level = this.outlineSelectWidget.findItemFromData( page.getName() ).getLevel();
2139 if (
2140 prev &&
2141 level === this.outlineSelectWidget.findItemFromData( prev.getName() ).getLevel()
2142 ) {
2143 return prev;
2144 }
2145 if (
2146 next &&
2147 level === this.outlineSelectWidget.findItemFromData( next.getName() ).getLevel()
2148 ) {
2149 return next;
2150 }
2151 }
2152 }
2153 return prev || next || null;
2154 };
2155
2156 /**
2157 * Get the outline widget.
2158 *
2159 * If the booklet is not outlined, the method will return `null`.
2160 *
2161 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
2162 */
2163 OO.ui.BookletLayout.prototype.getOutline = function () {
2164 return this.outlineSelectWidget;
2165 };
2166
2167 /**
2168 * Get the outline controls widget.
2169 *
2170 * If the outline is not editable, the method will return `null`.
2171 *
2172 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
2173 */
2174 OO.ui.BookletLayout.prototype.getOutlineControls = function () {
2175 return this.outlineControlsWidget;
2176 };
2177
2178 /**
2179 * Get a page by its symbolic name.
2180 *
2181 * @param {string} name Symbolic name of page
2182 * @return {OO.ui.PageLayout|undefined} Page, if found
2183 */
2184 OO.ui.BookletLayout.prototype.getPage = function ( name ) {
2185 return this.pages[ name ];
2186 };
2187
2188 /**
2189 * Get the current page.
2190 *
2191 * @return {OO.ui.PageLayout|undefined} Current page, if found
2192 */
2193 OO.ui.BookletLayout.prototype.getCurrentPage = function () {
2194 var name = this.getCurrentPageName();
2195 return name ? this.getPage( name ) : undefined;
2196 };
2197
2198 /**
2199 * Get the symbolic name of the current page.
2200 *
2201 * @return {string|null} Symbolic name of the current page
2202 */
2203 OO.ui.BookletLayout.prototype.getCurrentPageName = function () {
2204 return this.currentPageName;
2205 };
2206
2207 /**
2208 * Add pages to the booklet layout
2209 *
2210 * When pages are added with the same names as existing pages, the existing pages will be
2211 * automatically removed before the new pages are added.
2212 *
2213 * @param {OO.ui.PageLayout[]} pages Pages to add
2214 * @param {number} index Index of the insertion point
2215 * @fires add
2216 * @chainable
2217 * @return {OO.ui.BookletLayout} The layout, for chaining
2218 */
2219 OO.ui.BookletLayout.prototype.addPages = function ( pages, index ) {
2220 var i, len, name, page, item, currentIndex,
2221 stackLayoutPages = this.stackLayout.getItems(),
2222 remove = [],
2223 items = [];
2224
2225 // Remove pages with same names
2226 for ( i = 0, len = pages.length; i < len; i++ ) {
2227 page = pages[ i ];
2228 name = page.getName();
2229
2230 if ( Object.prototype.hasOwnProperty.call( this.pages, name ) ) {
2231 // Correct the insertion index
2232 currentIndex = stackLayoutPages.indexOf( this.pages[ name ] );
2233 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
2234 index--;
2235 }
2236 remove.push( this.pages[ name ] );
2237 }
2238 }
2239 if ( remove.length ) {
2240 this.removePages( remove );
2241 }
2242
2243 // Add new pages
2244 for ( i = 0, len = pages.length; i < len; i++ ) {
2245 page = pages[ i ];
2246 name = page.getName();
2247 this.pages[ page.getName() ] = page;
2248 if ( this.outlined ) {
2249 item = new OO.ui.OutlineOptionWidget( { data: name } );
2250 page.setOutlineItem( item );
2251 items.push( item );
2252 }
2253 }
2254
2255 if ( this.outlined && items.length ) {
2256 this.outlineSelectWidget.addItems( items, index );
2257 this.selectFirstSelectablePage();
2258 }
2259 this.stackLayout.addItems( pages, index );
2260 this.emit( 'add', pages, index );
2261
2262 return this;
2263 };
2264
2265 /**
2266 * Remove the specified pages from the booklet layout.
2267 *
2268 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
2269 *
2270 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
2271 * @fires remove
2272 * @chainable
2273 * @return {OO.ui.BookletLayout} The layout, for chaining
2274 */
2275 OO.ui.BookletLayout.prototype.removePages = function ( pages ) {
2276 var i, len, name, page,
2277 items = [];
2278
2279 for ( i = 0, len = pages.length; i < len; i++ ) {
2280 page = pages[ i ];
2281 name = page.getName();
2282 delete this.pages[ name ];
2283 if ( this.outlined ) {
2284 items.push( this.outlineSelectWidget.findItemFromData( name ) );
2285 page.setOutlineItem( null );
2286 }
2287 }
2288 if ( this.outlined && items.length ) {
2289 this.outlineSelectWidget.removeItems( items );
2290 this.selectFirstSelectablePage();
2291 }
2292 this.stackLayout.removeItems( pages );
2293 this.emit( 'remove', pages );
2294
2295 return this;
2296 };
2297
2298 /**
2299 * Clear all pages from the booklet layout.
2300 *
2301 * To remove only a subset of pages from the booklet, use the #removePages method.
2302 *
2303 * @fires remove
2304 * @chainable
2305 * @return {OO.ui.BookletLayout} The layout, for chaining
2306 */
2307 OO.ui.BookletLayout.prototype.clearPages = function () {
2308 var i, len,
2309 pages = this.stackLayout.getItems();
2310
2311 this.pages = {};
2312 this.currentPageName = null;
2313 if ( this.outlined ) {
2314 this.outlineSelectWidget.clearItems();
2315 for ( i = 0, len = pages.length; i < len; i++ ) {
2316 pages[ i ].setOutlineItem( null );
2317 }
2318 }
2319 this.stackLayout.clearItems();
2320
2321 this.emit( 'remove', pages );
2322
2323 return this;
2324 };
2325
2326 /**
2327 * Set the current page by symbolic name.
2328 *
2329 * @fires set
2330 * @param {string} name Symbolic name of page
2331 */
2332 OO.ui.BookletLayout.prototype.setPage = function ( name ) {
2333 var selectedItem,
2334 $focused,
2335 page = this.pages[ name ],
2336 previousPage = this.currentPageName && this.pages[ this.currentPageName ];
2337
2338 if ( name !== this.currentPageName ) {
2339 if ( this.outlined ) {
2340 selectedItem = this.outlineSelectWidget.findSelectedItem();
2341 if ( selectedItem && selectedItem.getData() !== name ) {
2342 this.outlineSelectWidget.selectItemByData( name );
2343 }
2344 }
2345 if ( page ) {
2346 if ( previousPage ) {
2347 previousPage.setActive( false );
2348 // Blur anything focused if the next page doesn't have anything focusable.
2349 // This is not needed if the next page has something focusable (because once it is focused
2350 // this blur happens automatically). If the layout is non-continuous, this check is
2351 // meaningless because the next page is not visible yet and thus can't hold focus.
2352 if (
2353 this.autoFocus &&
2354 !OO.ui.isMobile() &&
2355 this.stackLayout.continuous &&
2356 OO.ui.findFocusable( page.$element ).length !== 0
2357 ) {
2358 $focused = previousPage.$element.find( ':focus' );
2359 if ( $focused.length ) {
2360 $focused[ 0 ].blur();
2361 }
2362 }
2363 }
2364 this.currentPageName = name;
2365 page.setActive( true );
2366 this.stackLayout.setItem( page );
2367 if ( !this.stackLayout.continuous && previousPage ) {
2368 // This should not be necessary, since any inputs on the previous page should have been
2369 // blurred when it was hidden, but browsers are not very consistent about this.
2370 $focused = previousPage.$element.find( ':focus' );
2371 if ( $focused.length ) {
2372 $focused[ 0 ].blur();
2373 }
2374 }
2375 this.emit( 'set', page );
2376 }
2377 }
2378 };
2379
2380 /**
2381 * For outlined-continuous booklets, also reset the outlineSelectWidget to the first item.
2382 *
2383 * @inheritdoc
2384 */
2385 OO.ui.BookletLayout.prototype.resetScroll = function () {
2386 // Parent method
2387 OO.ui.BookletLayout.parent.prototype.resetScroll.call( this );
2388
2389 if ( this.outlined && this.stackLayout.continuous && this.outlineSelectWidget.findFirstSelectableItem() ) {
2390 this.scrolling = true;
2391 this.outlineSelectWidget.selectItem( this.outlineSelectWidget.findFirstSelectableItem() );
2392 this.scrolling = false;
2393 }
2394 return this;
2395 };
2396
2397 /**
2398 * Select the first selectable page.
2399 *
2400 * @chainable
2401 * @return {OO.ui.BookletLayout} The layout, for chaining
2402 */
2403 OO.ui.BookletLayout.prototype.selectFirstSelectablePage = function () {
2404 if ( !this.outlineSelectWidget.findSelectedItem() ) {
2405 this.outlineSelectWidget.selectItem( this.outlineSelectWidget.findFirstSelectableItem() );
2406 }
2407
2408 return this;
2409 };
2410
2411 /**
2412 * IndexLayouts contain {@link OO.ui.TabPanelLayout tab panel layouts} as well as
2413 * {@link OO.ui.TabSelectWidget tabs} that allow users to easily navigate through the tab panels and
2414 * select which one to display. By default, only one tab panel is displayed at a time. When a user
2415 * navigates to a new tab panel, the index layout automatically focuses on the first focusable element,
2416 * unless the default setting is changed.
2417 *
2418 * TODO: This class is similar to BookletLayout, we may want to refactor to reduce duplication
2419 *
2420 * @example
2421 * // Example of a IndexLayout that contains two TabPanelLayouts.
2422 *
2423 * function TabPanelOneLayout( name, config ) {
2424 * TabPanelOneLayout.parent.call( this, name, config );
2425 * this.$element.append( '<p>First tab panel</p>' );
2426 * }
2427 * OO.inheritClass( TabPanelOneLayout, OO.ui.TabPanelLayout );
2428 * TabPanelOneLayout.prototype.setupTabItem = function () {
2429 * this.tabItem.setLabel( 'Tab panel one' );
2430 * };
2431 *
2432 * var tabPanel1 = new TabPanelOneLayout( 'one' ),
2433 * tabPanel2 = new OO.ui.TabPanelLayout( 'two', { label: 'Tab panel two' } );
2434 *
2435 * tabPanel2.$element.append( '<p>Second tab panel</p>' );
2436 *
2437 * var index = new OO.ui.IndexLayout();
2438 *
2439 * index.addTabPanels( [ tabPanel1, tabPanel2 ] );
2440 * $( 'body' ).append( index.$element );
2441 *
2442 * @class
2443 * @extends OO.ui.MenuLayout
2444 *
2445 * @constructor
2446 * @param {Object} [config] Configuration options
2447 * @cfg {boolean} [continuous=false] Show all tab panels, one after another
2448 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new tab panel is displayed. Disabled on mobile.
2449 */
2450 OO.ui.IndexLayout = function OoUiIndexLayout( config ) {
2451 // Configuration initialization
2452 config = $.extend( {}, config, { menuPosition: 'top' } );
2453
2454 // Parent constructor
2455 OO.ui.IndexLayout.parent.call( this, config );
2456
2457 // Properties
2458 this.currentTabPanelName = null;
2459 this.tabPanels = {};
2460
2461 this.ignoreFocus = false;
2462 this.stackLayout = new OO.ui.StackLayout( {
2463 continuous: !!config.continuous,
2464 expanded: this.expanded
2465 } );
2466 this.setContentPanel( this.stackLayout );
2467 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
2468
2469 this.tabSelectWidget = new OO.ui.TabSelectWidget();
2470 this.tabPanel = new OO.ui.PanelLayout( {
2471 expanded: this.expanded
2472 } );
2473 this.setMenuPanel( this.tabPanel );
2474
2475 this.toggleMenu( true );
2476
2477 // Events
2478 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
2479 this.tabSelectWidget.connect( this, { select: 'onTabSelectWidgetSelect' } );
2480 if ( this.autoFocus ) {
2481 // Event 'focus' does not bubble, but 'focusin' does
2482 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
2483 }
2484
2485 // Initialization
2486 this.$element.addClass( 'oo-ui-indexLayout' );
2487 this.stackLayout.$element.addClass( 'oo-ui-indexLayout-stackLayout' );
2488 this.tabPanel.$element
2489 .addClass( 'oo-ui-indexLayout-tabPanel' )
2490 .append( this.tabSelectWidget.$element );
2491 };
2492
2493 /* Setup */
2494
2495 OO.inheritClass( OO.ui.IndexLayout, OO.ui.MenuLayout );
2496
2497 /* Events */
2498
2499 /**
2500 * A 'set' event is emitted when a tab panel is {@link #setTabPanel set} to be displayed by the index layout.
2501 * @event set
2502 * @param {OO.ui.TabPanelLayout} tabPanel Current tab panel
2503 */
2504
2505 /**
2506 * An 'add' event is emitted when tab panels are {@link #addTabPanels added} to the index layout.
2507 *
2508 * @event add
2509 * @param {OO.ui.TabPanelLayout[]} tabPanel Added tab panels
2510 * @param {number} index Index tab panels were added at
2511 */
2512
2513 /**
2514 * A 'remove' event is emitted when tab panels are {@link #clearTabPanels cleared} or
2515 * {@link #removeTabPanels removed} from the index.
2516 *
2517 * @event remove
2518 * @param {OO.ui.TabPanelLayout[]} tabPanel Removed tab panels
2519 */
2520
2521 /* Methods */
2522
2523 /**
2524 * Handle stack layout focus.
2525 *
2526 * @private
2527 * @param {jQuery.Event} e Focusing event
2528 */
2529 OO.ui.IndexLayout.prototype.onStackLayoutFocus = function ( e ) {
2530 var name, $target;
2531
2532 // Find the tab panel that an element was focused within
2533 $target = $( e.target ).closest( '.oo-ui-tabPanelLayout' );
2534 for ( name in this.tabPanels ) {
2535 // Check for tab panel match, exclude current tab panel to find only tab panel changes
2536 if ( this.tabPanels[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentTabPanelName ) {
2537 this.setTabPanel( name );
2538 break;
2539 }
2540 }
2541 };
2542
2543 /**
2544 * Handle stack layout set events.
2545 *
2546 * @private
2547 * @param {OO.ui.PanelLayout|null} tabPanel The tab panel that is now the current panel
2548 */
2549 OO.ui.IndexLayout.prototype.onStackLayoutSet = function ( tabPanel ) {
2550 // If everything is unselected, do nothing
2551 if ( !tabPanel ) {
2552 return;
2553 }
2554 // Focus the first element on the newly selected panel
2555 if ( this.autoFocus && !OO.ui.isMobile() ) {
2556 this.focus();
2557 }
2558 };
2559
2560 /**
2561 * Focus the first input in the current tab panel.
2562 *
2563 * If no tab panel is selected, the first selectable tab panel will be selected.
2564 * If the focus is already in an element on the current tab panel, nothing will happen.
2565 *
2566 * @param {number} [itemIndex] A specific item to focus on
2567 */
2568 OO.ui.IndexLayout.prototype.focus = function ( itemIndex ) {
2569 var tabPanel,
2570 items = this.stackLayout.getItems();
2571
2572 if ( itemIndex !== undefined && items[ itemIndex ] ) {
2573 tabPanel = items[ itemIndex ];
2574 } else {
2575 tabPanel = this.stackLayout.getCurrentItem();
2576 }
2577
2578 if ( !tabPanel ) {
2579 this.selectFirstSelectableTabPanel();
2580 tabPanel = this.stackLayout.getCurrentItem();
2581 }
2582 if ( !tabPanel ) {
2583 return;
2584 }
2585 // Only change the focus if is not already in the current page
2586 if ( !OO.ui.contains( tabPanel.$element[ 0 ], this.getElementDocument().activeElement, true ) ) {
2587 tabPanel.focus();
2588 }
2589 };
2590
2591 /**
2592 * Find the first focusable input in the index layout and focus
2593 * on it.
2594 */
2595 OO.ui.IndexLayout.prototype.focusFirstFocusable = function () {
2596 OO.ui.findFocusable( this.stackLayout.$element ).focus();
2597 };
2598
2599 /**
2600 * Handle tab widget select events.
2601 *
2602 * @private
2603 * @param {OO.ui.OptionWidget|null} item Selected item
2604 */
2605 OO.ui.IndexLayout.prototype.onTabSelectWidgetSelect = function ( item ) {
2606 if ( item ) {
2607 this.setTabPanel( item.getData() );
2608 }
2609 };
2610
2611 /**
2612 * Get the tab panel closest to the specified tab panel.
2613 *
2614 * @param {OO.ui.TabPanelLayout} tabPanel Tab panel to use as a reference point
2615 * @return {OO.ui.TabPanelLayout|null} Tab panel closest to the specified
2616 */
2617 OO.ui.IndexLayout.prototype.getClosestTabPanel = function ( tabPanel ) {
2618 var next, prev, level,
2619 tabPanels = this.stackLayout.getItems(),
2620 index = tabPanels.indexOf( tabPanel );
2621
2622 if ( index !== -1 ) {
2623 next = tabPanels[ index + 1 ];
2624 prev = tabPanels[ index - 1 ];
2625 // Prefer adjacent tab panels at the same level
2626 level = this.tabSelectWidget.findItemFromData( tabPanel.getName() ).getLevel();
2627 if (
2628 prev &&
2629 level === this.tabSelectWidget.findItemFromData( prev.getName() ).getLevel()
2630 ) {
2631 return prev;
2632 }
2633 if (
2634 next &&
2635 level === this.tabSelectWidget.findItemFromData( next.getName() ).getLevel()
2636 ) {
2637 return next;
2638 }
2639 }
2640 return prev || next || null;
2641 };
2642
2643 /**
2644 * Get the tabs widget.
2645 *
2646 * @return {OO.ui.TabSelectWidget} Tabs widget
2647 */
2648 OO.ui.IndexLayout.prototype.getTabs = function () {
2649 return this.tabSelectWidget;
2650 };
2651
2652 /**
2653 * Get a tab panel by its symbolic name.
2654 *
2655 * @param {string} name Symbolic name of tab panel
2656 * @return {OO.ui.TabPanelLayout|undefined} Tab panel, if found
2657 */
2658 OO.ui.IndexLayout.prototype.getTabPanel = function ( name ) {
2659 return this.tabPanels[ name ];
2660 };
2661
2662 /**
2663 * Get the current tab panel.
2664 *
2665 * @return {OO.ui.TabPanelLayout|undefined} Current tab panel, if found
2666 */
2667 OO.ui.IndexLayout.prototype.getCurrentTabPanel = function () {
2668 var name = this.getCurrentTabPanelName();
2669 return name ? this.getTabPanel( name ) : undefined;
2670 };
2671
2672 /**
2673 * Get the symbolic name of the current tab panel.
2674 *
2675 * @return {string|null} Symbolic name of the current tab panel
2676 */
2677 OO.ui.IndexLayout.prototype.getCurrentTabPanelName = function () {
2678 return this.currentTabPanelName;
2679 };
2680
2681 /**
2682 * Add tab panels to the index layout
2683 *
2684 * When tab panels are added with the same names as existing tab panels, the existing tab panels
2685 * will be automatically removed before the new tab panels are added.
2686 *
2687 * @param {OO.ui.TabPanelLayout[]} tabPanels Tab panels to add
2688 * @param {number} index Index of the insertion point
2689 * @fires add
2690 * @chainable
2691 * @return {OO.ui.BookletLayout} The layout, for chaining
2692 */
2693 OO.ui.IndexLayout.prototype.addTabPanels = function ( tabPanels, index ) {
2694 var i, len, name, tabPanel, item, currentIndex,
2695 stackLayoutTabPanels = this.stackLayout.getItems(),
2696 remove = [],
2697 items = [];
2698
2699 // Remove tab panels with same names
2700 for ( i = 0, len = tabPanels.length; i < len; i++ ) {
2701 tabPanel = tabPanels[ i ];
2702 name = tabPanel.getName();
2703
2704 if ( Object.prototype.hasOwnProperty.call( this.tabPanels, name ) ) {
2705 // Correct the insertion index
2706 currentIndex = stackLayoutTabPanels.indexOf( this.tabPanels[ name ] );
2707 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
2708 index--;
2709 }
2710 remove.push( this.tabPanels[ name ] );
2711 }
2712 }
2713 if ( remove.length ) {
2714 this.removeTabPanels( remove );
2715 }
2716
2717 // Add new tab panels
2718 for ( i = 0, len = tabPanels.length; i < len; i++ ) {
2719 tabPanel = tabPanels[ i ];
2720 name = tabPanel.getName();
2721 this.tabPanels[ tabPanel.getName() ] = tabPanel;
2722 item = new OO.ui.TabOptionWidget( { data: name } );
2723 tabPanel.setTabItem( item );
2724 items.push( item );
2725 }
2726
2727 if ( items.length ) {
2728 this.tabSelectWidget.addItems( items, index );
2729 this.selectFirstSelectableTabPanel();
2730 }
2731 this.stackLayout.addItems( tabPanels, index );
2732 this.emit( 'add', tabPanels, index );
2733
2734 return this;
2735 };
2736
2737 /**
2738 * Remove the specified tab panels from the index layout.
2739 *
2740 * To remove all tab panels from the index, you may wish to use the #clearTabPanels method instead.
2741 *
2742 * @param {OO.ui.TabPanelLayout[]} tabPanels An array of tab panels to remove
2743 * @fires remove
2744 * @chainable
2745 * @return {OO.ui.BookletLayout} The layout, for chaining
2746 */
2747 OO.ui.IndexLayout.prototype.removeTabPanels = function ( tabPanels ) {
2748 var i, len, name, tabPanel,
2749 items = [];
2750
2751 for ( i = 0, len = tabPanels.length; i < len; i++ ) {
2752 tabPanel = tabPanels[ i ];
2753 name = tabPanel.getName();
2754 delete this.tabPanels[ name ];
2755 items.push( this.tabSelectWidget.findItemFromData( name ) );
2756 tabPanel.setTabItem( null );
2757 }
2758 if ( items.length ) {
2759 this.tabSelectWidget.removeItems( items );
2760 this.selectFirstSelectableTabPanel();
2761 }
2762 this.stackLayout.removeItems( tabPanels );
2763 this.emit( 'remove', tabPanels );
2764
2765 return this;
2766 };
2767
2768 /**
2769 * Clear all tab panels from the index layout.
2770 *
2771 * To remove only a subset of tab panels from the index, use the #removeTabPanels method.
2772 *
2773 * @fires remove
2774 * @chainable
2775 * @return {OO.ui.BookletLayout} The layout, for chaining
2776 */
2777 OO.ui.IndexLayout.prototype.clearTabPanels = function () {
2778 var i, len,
2779 tabPanels = this.stackLayout.getItems();
2780
2781 this.tabPanels = {};
2782 this.currentTabPanelName = null;
2783 this.tabSelectWidget.clearItems();
2784 for ( i = 0, len = tabPanels.length; i < len; i++ ) {
2785 tabPanels[ i ].setTabItem( null );
2786 }
2787 this.stackLayout.clearItems();
2788
2789 this.emit( 'remove', tabPanels );
2790
2791 return this;
2792 };
2793
2794 /**
2795 * Set the current tab panel by symbolic name.
2796 *
2797 * @fires set
2798 * @param {string} name Symbolic name of tab panel
2799 */
2800 OO.ui.IndexLayout.prototype.setTabPanel = function ( name ) {
2801 var selectedItem,
2802 $focused,
2803 previousTabPanel,
2804 tabPanel = this.tabPanels[ name ];
2805
2806 if ( name !== this.currentTabPanelName ) {
2807 previousTabPanel = this.getCurrentTabPanel();
2808 selectedItem = this.tabSelectWidget.findSelectedItem();
2809 if ( selectedItem && selectedItem.getData() !== name ) {
2810 this.tabSelectWidget.selectItemByData( name );
2811 }
2812 if ( tabPanel ) {
2813 if ( previousTabPanel ) {
2814 previousTabPanel.setActive( false );
2815 // Blur anything focused if the next tab panel doesn't have anything focusable.
2816 // This is not needed if the next tab panel has something focusable (because once it is focused
2817 // this blur happens automatically). If the layout is non-continuous, this check is
2818 // meaningless because the next tab panel is not visible yet and thus can't hold focus.
2819 if (
2820 this.autoFocus &&
2821 !OO.ui.isMobile() &&
2822 this.stackLayout.continuous &&
2823 OO.ui.findFocusable( tabPanel.$element ).length !== 0
2824 ) {
2825 $focused = previousTabPanel.$element.find( ':focus' );
2826 if ( $focused.length ) {
2827 $focused[ 0 ].blur();
2828 }
2829 }
2830 }
2831 this.currentTabPanelName = name;
2832 tabPanel.setActive( true );
2833 this.stackLayout.setItem( tabPanel );
2834 if ( !this.stackLayout.continuous && previousTabPanel ) {
2835 // This should not be necessary, since any inputs on the previous tab panel should have been
2836 // blurred when it was hidden, but browsers are not very consistent about this.
2837 $focused = previousTabPanel.$element.find( ':focus' );
2838 if ( $focused.length ) {
2839 $focused[ 0 ].blur();
2840 }
2841 }
2842 this.emit( 'set', tabPanel );
2843 }
2844 }
2845 };
2846
2847 /**
2848 * Select the first selectable tab panel.
2849 *
2850 * @chainable
2851 * @return {OO.ui.BookletLayout} The layout, for chaining
2852 */
2853 OO.ui.IndexLayout.prototype.selectFirstSelectableTabPanel = function () {
2854 if ( !this.tabSelectWidget.findSelectedItem() ) {
2855 this.tabSelectWidget.selectItem( this.tabSelectWidget.findFirstSelectableItem() );
2856 }
2857
2858 return this;
2859 };
2860
2861 /**
2862 * ToggleWidget implements basic behavior of widgets with an on/off state.
2863 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
2864 *
2865 * @abstract
2866 * @class
2867 * @extends OO.ui.Widget
2868 *
2869 * @constructor
2870 * @param {Object} [config] Configuration options
2871 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
2872 * By default, the toggle is in the 'off' state.
2873 */
2874 OO.ui.ToggleWidget = function OoUiToggleWidget( config ) {
2875 // Configuration initialization
2876 config = config || {};
2877
2878 // Parent constructor
2879 OO.ui.ToggleWidget.parent.call( this, config );
2880
2881 // Properties
2882 this.value = null;
2883
2884 // Initialization
2885 this.$element.addClass( 'oo-ui-toggleWidget' );
2886 this.setValue( !!config.value );
2887 };
2888
2889 /* Setup */
2890
2891 OO.inheritClass( OO.ui.ToggleWidget, OO.ui.Widget );
2892
2893 /* Events */
2894
2895 /**
2896 * @event change
2897 *
2898 * A change event is emitted when the on/off state of the toggle changes.
2899 *
2900 * @param {boolean} value Value representing the new state of the toggle
2901 */
2902
2903 /* Methods */
2904
2905 /**
2906 * Get the value representing the toggle’s state.
2907 *
2908 * @return {boolean} The on/off state of the toggle
2909 */
2910 OO.ui.ToggleWidget.prototype.getValue = function () {
2911 return this.value;
2912 };
2913
2914 /**
2915 * Set the state of the toggle: `true` for 'on', `false` for 'off'.
2916 *
2917 * @param {boolean} value The state of the toggle
2918 * @fires change
2919 * @chainable
2920 * @return {OO.ui.Widget} The widget, for chaining
2921 */
2922 OO.ui.ToggleWidget.prototype.setValue = function ( value ) {
2923 value = !!value;
2924 if ( this.value !== value ) {
2925 this.value = value;
2926 this.emit( 'change', value );
2927 this.$element.toggleClass( 'oo-ui-toggleWidget-on', value );
2928 this.$element.toggleClass( 'oo-ui-toggleWidget-off', !value );
2929 }
2930 return this;
2931 };
2932
2933 /**
2934 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
2935 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
2936 * configured with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators},
2937 * {@link OO.ui.mixin.TitledElement titles}, {@link OO.ui.mixin.FlaggedElement styling flags},
2938 * and {@link OO.ui.mixin.LabelElement labels}. Please see
2939 * the [OOUI documentation][1] on MediaWiki for more information.
2940 *
2941 * @example
2942 * // Toggle buttons in the 'off' and 'on' state.
2943 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
2944 * label: 'Toggle Button off'
2945 * } );
2946 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
2947 * label: 'Toggle Button on',
2948 * value: true
2949 * } );
2950 * // Append the buttons to the DOM.
2951 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
2952 *
2953 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches#Toggle_buttons
2954 *
2955 * @class
2956 * @extends OO.ui.ToggleWidget
2957 * @mixins OO.ui.mixin.ButtonElement
2958 * @mixins OO.ui.mixin.IconElement
2959 * @mixins OO.ui.mixin.IndicatorElement
2960 * @mixins OO.ui.mixin.LabelElement
2961 * @mixins OO.ui.mixin.TitledElement
2962 * @mixins OO.ui.mixin.FlaggedElement
2963 * @mixins OO.ui.mixin.TabIndexedElement
2964 *
2965 * @constructor
2966 * @param {Object} [config] Configuration options
2967 * @cfg {boolean} [value=false] The toggle button’s initial on/off
2968 * state. By default, the button is in the 'off' state.
2969 */
2970 OO.ui.ToggleButtonWidget = function OoUiToggleButtonWidget( config ) {
2971 // Configuration initialization
2972 config = config || {};
2973
2974 // Parent constructor
2975 OO.ui.ToggleButtonWidget.parent.call( this, config );
2976
2977 // Mixin constructors
2978 OO.ui.mixin.ButtonElement.call( this, $.extend( {}, config, { active: this.active } ) );
2979 OO.ui.mixin.IconElement.call( this, config );
2980 OO.ui.mixin.IndicatorElement.call( this, config );
2981 OO.ui.mixin.LabelElement.call( this, config );
2982 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
2983 OO.ui.mixin.FlaggedElement.call( this, config );
2984 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
2985
2986 // Events
2987 this.connect( this, { click: 'onAction' } );
2988
2989 // Initialization
2990 this.$button.append( this.$icon, this.$label, this.$indicator );
2991 this.$element
2992 .addClass( 'oo-ui-toggleButtonWidget' )
2993 .append( this.$button );
2994 };
2995
2996 /* Setup */
2997
2998 OO.inheritClass( OO.ui.ToggleButtonWidget, OO.ui.ToggleWidget );
2999 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.ButtonElement );
3000 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IconElement );
3001 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IndicatorElement );
3002 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.LabelElement );
3003 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TitledElement );
3004 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.FlaggedElement );
3005 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TabIndexedElement );
3006
3007 /* Static Properties */
3008
3009 /**
3010 * @static
3011 * @inheritdoc
3012 */
3013 OO.ui.ToggleButtonWidget.static.tagName = 'span';
3014
3015 /* Methods */
3016
3017 /**
3018 * Handle the button action being triggered.
3019 *
3020 * @private
3021 */
3022 OO.ui.ToggleButtonWidget.prototype.onAction = function () {
3023 this.setValue( !this.value );
3024 };
3025
3026 /**
3027 * @inheritdoc
3028 */
3029 OO.ui.ToggleButtonWidget.prototype.setValue = function ( value ) {
3030 value = !!value;
3031 if ( value !== this.value ) {
3032 // Might be called from parent constructor before ButtonElement constructor
3033 if ( this.$button ) {
3034 this.$button.attr( 'aria-pressed', value.toString() );
3035 }
3036 this.setActive( value );
3037 }
3038
3039 // Parent method
3040 OO.ui.ToggleButtonWidget.parent.prototype.setValue.call( this, value );
3041
3042 return this;
3043 };
3044
3045 /**
3046 * @inheritdoc
3047 */
3048 OO.ui.ToggleButtonWidget.prototype.setButtonElement = function ( $button ) {
3049 if ( this.$button ) {
3050 this.$button.removeAttr( 'aria-pressed' );
3051 }
3052 OO.ui.mixin.ButtonElement.prototype.setButtonElement.call( this, $button );
3053 this.$button.attr( 'aria-pressed', this.value.toString() );
3054 };
3055
3056 /**
3057 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
3058 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
3059 * visually by a slider in the leftmost position.
3060 *
3061 * @example
3062 * // Toggle switches in the 'off' and 'on' position.
3063 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
3064 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
3065 * value: true
3066 * } );
3067 *
3068 * // Create a FieldsetLayout to layout and label switches
3069 * var fieldset = new OO.ui.FieldsetLayout( {
3070 * label: 'Toggle switches'
3071 * } );
3072 * fieldset.addItems( [
3073 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
3074 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
3075 * ] );
3076 * $( 'body' ).append( fieldset.$element );
3077 *
3078 * @class
3079 * @extends OO.ui.ToggleWidget
3080 * @mixins OO.ui.mixin.TabIndexedElement
3081 *
3082 * @constructor
3083 * @param {Object} [config] Configuration options
3084 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
3085 * By default, the toggle switch is in the 'off' position.
3086 */
3087 OO.ui.ToggleSwitchWidget = function OoUiToggleSwitchWidget( config ) {
3088 // Parent constructor
3089 OO.ui.ToggleSwitchWidget.parent.call( this, config );
3090
3091 // Mixin constructors
3092 OO.ui.mixin.TabIndexedElement.call( this, config );
3093
3094 // Properties
3095 this.dragging = false;
3096 this.dragStart = null;
3097 this.sliding = false;
3098 this.$glow = $( '<span>' );
3099 this.$grip = $( '<span>' );
3100
3101 // Events
3102 this.$element.on( {
3103 click: this.onClick.bind( this ),
3104 keypress: this.onKeyPress.bind( this )
3105 } );
3106
3107 // Initialization
3108 this.$glow.addClass( 'oo-ui-toggleSwitchWidget-glow' );
3109 this.$grip.addClass( 'oo-ui-toggleSwitchWidget-grip' );
3110 this.$element
3111 .addClass( 'oo-ui-toggleSwitchWidget' )
3112 .attr( 'role', 'checkbox' )
3113 .append( this.$glow, this.$grip );
3114 };
3115
3116 /* Setup */
3117
3118 OO.inheritClass( OO.ui.ToggleSwitchWidget, OO.ui.ToggleWidget );
3119 OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.mixin.TabIndexedElement );
3120
3121 /* Methods */
3122
3123 /**
3124 * Handle mouse click events.
3125 *
3126 * @private
3127 * @param {jQuery.Event} e Mouse click event
3128 * @return {undefined/boolean} False to prevent default if event is handled
3129 */
3130 OO.ui.ToggleSwitchWidget.prototype.onClick = function ( e ) {
3131 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
3132 this.setValue( !this.value );
3133 }
3134 return false;
3135 };
3136
3137 /**
3138 * Handle key press events.
3139 *
3140 * @private
3141 * @param {jQuery.Event} e Key press event
3142 * @return {undefined/boolean} False to prevent default if event is handled
3143 */
3144 OO.ui.ToggleSwitchWidget.prototype.onKeyPress = function ( e ) {
3145 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
3146 this.setValue( !this.value );
3147 return false;
3148 }
3149 };
3150
3151 /**
3152 * @inheritdoc
3153 */
3154 OO.ui.ToggleSwitchWidget.prototype.setValue = function ( value ) {
3155 OO.ui.ToggleSwitchWidget.parent.prototype.setValue.call( this, value );
3156 this.$element.attr( 'aria-checked', this.value.toString() );
3157 return this;
3158 };
3159
3160 /**
3161 * @inheritdoc
3162 */
3163 OO.ui.ToggleSwitchWidget.prototype.simulateLabelClick = function () {
3164 if ( !this.isDisabled() ) {
3165 this.setValue( !this.value );
3166 }
3167 this.focus();
3168 };
3169
3170 /**
3171 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
3172 * Controls include moving items up and down, removing items, and adding different kinds of items.
3173 *
3174 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
3175 *
3176 * @class
3177 * @extends OO.ui.Widget
3178 * @mixins OO.ui.mixin.GroupElement
3179 *
3180 * @constructor
3181 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
3182 * @param {Object} [config] Configuration options
3183 * @cfg {Object} [abilities] List of abilties
3184 * @cfg {boolean} [abilities.move=true] Allow moving movable items
3185 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
3186 */
3187 OO.ui.OutlineControlsWidget = function OoUiOutlineControlsWidget( outline, config ) {
3188 // Allow passing positional parameters inside the config object
3189 if ( OO.isPlainObject( outline ) && config === undefined ) {
3190 config = outline;
3191 outline = config.outline;
3192 }
3193
3194 // Configuration initialization
3195 config = config || {};
3196
3197 // Parent constructor
3198 OO.ui.OutlineControlsWidget.parent.call( this, config );
3199
3200 // Mixin constructors
3201 OO.ui.mixin.GroupElement.call( this, config );
3202
3203 // Properties
3204 this.outline = outline;
3205 this.$movers = $( '<div>' );
3206 this.upButton = new OO.ui.ButtonWidget( {
3207 framed: false,
3208 icon: 'collapse',
3209 title: OO.ui.msg( 'ooui-outline-control-move-up' )
3210 } );
3211 this.downButton = new OO.ui.ButtonWidget( {
3212 framed: false,
3213 icon: 'expand',
3214 title: OO.ui.msg( 'ooui-outline-control-move-down' )
3215 } );
3216 this.removeButton = new OO.ui.ButtonWidget( {
3217 framed: false,
3218 icon: 'trash',
3219 title: OO.ui.msg( 'ooui-outline-control-remove' )
3220 } );
3221 this.abilities = { move: true, remove: true };
3222
3223 // Events
3224 outline.connect( this, {
3225 select: 'onOutlineChange',
3226 add: 'onOutlineChange',
3227 remove: 'onOutlineChange'
3228 } );
3229 this.upButton.connect( this, { click: [ 'emit', 'move', -1 ] } );
3230 this.downButton.connect( this, { click: [ 'emit', 'move', 1 ] } );
3231 this.removeButton.connect( this, { click: [ 'emit', 'remove' ] } );
3232
3233 // Initialization
3234 this.$element.addClass( 'oo-ui-outlineControlsWidget' );
3235 this.$group.addClass( 'oo-ui-outlineControlsWidget-items' );
3236 this.$movers
3237 .addClass( 'oo-ui-outlineControlsWidget-movers' )
3238 .append( this.removeButton.$element, this.upButton.$element, this.downButton.$element );
3239 this.$element.append( this.$icon, this.$group, this.$movers );
3240 this.setAbilities( config.abilities || {} );
3241 };
3242
3243 /* Setup */
3244
3245 OO.inheritClass( OO.ui.OutlineControlsWidget, OO.ui.Widget );
3246 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.GroupElement );
3247
3248 /* Events */
3249
3250 /**
3251 * @event move
3252 * @param {number} places Number of places to move
3253 */
3254
3255 /**
3256 * @event remove
3257 */
3258
3259 /* Methods */
3260
3261 /**
3262 * Set abilities.
3263 *
3264 * @param {Object} abilities List of abilties
3265 * @param {boolean} [abilities.move] Allow moving movable items
3266 * @param {boolean} [abilities.remove] Allow removing removable items
3267 */
3268 OO.ui.OutlineControlsWidget.prototype.setAbilities = function ( abilities ) {
3269 var ability;
3270
3271 for ( ability in this.abilities ) {
3272 if ( abilities[ ability ] !== undefined ) {
3273 this.abilities[ ability ] = !!abilities[ ability ];
3274 }
3275 }
3276
3277 this.onOutlineChange();
3278 };
3279
3280 /**
3281 * Handle outline change events.
3282 *
3283 * @private
3284 */
3285 OO.ui.OutlineControlsWidget.prototype.onOutlineChange = function () {
3286 var i, len, firstMovable, lastMovable,
3287 items = this.outline.getItems(),
3288 selectedItem = this.outline.findSelectedItem(),
3289 movable = this.abilities.move && selectedItem && selectedItem.isMovable(),
3290 removable = this.abilities.remove && selectedItem && selectedItem.isRemovable();
3291
3292 if ( movable ) {
3293 i = -1;
3294 len = items.length;
3295 while ( ++i < len ) {
3296 if ( items[ i ].isMovable() ) {
3297 firstMovable = items[ i ];
3298 break;
3299 }
3300 }
3301 i = len;
3302 while ( i-- ) {
3303 if ( items[ i ].isMovable() ) {
3304 lastMovable = items[ i ];
3305 break;
3306 }
3307 }
3308 }
3309 this.upButton.setDisabled( !movable || selectedItem === firstMovable );
3310 this.downButton.setDisabled( !movable || selectedItem === lastMovable );
3311 this.removeButton.setDisabled( !removable );
3312 };
3313
3314 /**
3315 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
3316 *
3317 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
3318 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
3319 * for an example.
3320 *
3321 * @class
3322 * @extends OO.ui.DecoratedOptionWidget
3323 *
3324 * @constructor
3325 * @param {Object} [config] Configuration options
3326 * @cfg {number} [level] Indentation level
3327 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
3328 */
3329 OO.ui.OutlineOptionWidget = function OoUiOutlineOptionWidget( config ) {
3330 // Configuration initialization
3331 config = config || {};
3332
3333 // Parent constructor
3334 OO.ui.OutlineOptionWidget.parent.call( this, config );
3335
3336 // Properties
3337 this.level = 0;
3338 this.movable = !!config.movable;
3339 this.removable = !!config.removable;
3340
3341 // Initialization
3342 this.$element.addClass( 'oo-ui-outlineOptionWidget' );
3343 this.setLevel( config.level );
3344 };
3345
3346 /* Setup */
3347
3348 OO.inheritClass( OO.ui.OutlineOptionWidget, OO.ui.DecoratedOptionWidget );
3349
3350 /* Static Properties */
3351
3352 /**
3353 * @static
3354 * @inheritdoc
3355 */
3356 OO.ui.OutlineOptionWidget.static.highlightable = true;
3357
3358 /**
3359 * @static
3360 * @inheritdoc
3361 */
3362 OO.ui.OutlineOptionWidget.static.scrollIntoViewOnSelect = true;
3363
3364 /**
3365 * @static
3366 * @inheritable
3367 * @property {string}
3368 */
3369 OO.ui.OutlineOptionWidget.static.levelClass = 'oo-ui-outlineOptionWidget-level-';
3370
3371 /**
3372 * @static
3373 * @inheritable
3374 * @property {number}
3375 */
3376 OO.ui.OutlineOptionWidget.static.levels = 3;
3377
3378 /* Methods */
3379
3380 /**
3381 * Check if item is movable.
3382 *
3383 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
3384 *
3385 * @return {boolean} Item is movable
3386 */
3387 OO.ui.OutlineOptionWidget.prototype.isMovable = function () {
3388 return this.movable;
3389 };
3390
3391 /**
3392 * Check if item is removable.
3393 *
3394 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
3395 *
3396 * @return {boolean} Item is removable
3397 */
3398 OO.ui.OutlineOptionWidget.prototype.isRemovable = function () {
3399 return this.removable;
3400 };
3401
3402 /**
3403 * Get indentation level.
3404 *
3405 * @return {number} Indentation level
3406 */
3407 OO.ui.OutlineOptionWidget.prototype.getLevel = function () {
3408 return this.level;
3409 };
3410
3411 /**
3412 * @inheritdoc
3413 */
3414 OO.ui.OutlineOptionWidget.prototype.setPressed = function ( state ) {
3415 OO.ui.OutlineOptionWidget.parent.prototype.setPressed.call( this, state );
3416 return this;
3417 };
3418
3419 /**
3420 * Set movability.
3421 *
3422 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
3423 *
3424 * @param {boolean} movable Item is movable
3425 * @chainable
3426 * @return {OO.ui.Widget} The widget, for chaining
3427 */
3428 OO.ui.OutlineOptionWidget.prototype.setMovable = function ( movable ) {
3429 this.movable = !!movable;
3430 this.updateThemeClasses();
3431 return this;
3432 };
3433
3434 /**
3435 * Set removability.
3436 *
3437 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
3438 *
3439 * @param {boolean} removable Item is removable
3440 * @chainable
3441 * @return {OO.ui.Widget} The widget, for chaining
3442 */
3443 OO.ui.OutlineOptionWidget.prototype.setRemovable = function ( removable ) {
3444 this.removable = !!removable;
3445 this.updateThemeClasses();
3446 return this;
3447 };
3448
3449 /**
3450 * @inheritdoc
3451 */
3452 OO.ui.OutlineOptionWidget.prototype.setSelected = function ( state ) {
3453 OO.ui.OutlineOptionWidget.parent.prototype.setSelected.call( this, state );
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 * @return {OO.ui.Widget} The widget, for chaining
3463 */
3464 OO.ui.OutlineOptionWidget.prototype.setLevel = function ( level ) {
3465 var levels = this.constructor.static.levels,
3466 levelClass = this.constructor.static.levelClass,
3467 i = levels;
3468
3469 this.level = level ? Math.max( 0, Math.min( levels - 1, level ) ) : 0;
3470 while ( i-- ) {
3471 if ( this.level === i ) {
3472 this.$element.addClass( levelClass + i );
3473 } else {
3474 this.$element.removeClass( levelClass + i );
3475 }
3476 }
3477 this.updateThemeClasses();
3478
3479 return this;
3480 };
3481
3482 /**
3483 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
3484 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
3485 *
3486 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
3487 *
3488 * @class
3489 * @extends OO.ui.SelectWidget
3490 * @mixins OO.ui.mixin.TabIndexedElement
3491 *
3492 * @constructor
3493 * @param {Object} [config] Configuration options
3494 */
3495 OO.ui.OutlineSelectWidget = function OoUiOutlineSelectWidget( config ) {
3496 // Parent constructor
3497 OO.ui.OutlineSelectWidget.parent.call( this, config );
3498
3499 // Mixin constructors
3500 OO.ui.mixin.TabIndexedElement.call( this, config );
3501
3502 // Events
3503 this.$element.on( {
3504 focus: this.bindDocumentKeyDownListener.bind( this ),
3505 blur: this.unbindDocumentKeyDownListener.bind( this )
3506 } );
3507
3508 // Initialization
3509 this.$element.addClass( 'oo-ui-outlineSelectWidget' );
3510 };
3511
3512 /* Setup */
3513
3514 OO.inheritClass( OO.ui.OutlineSelectWidget, OO.ui.SelectWidget );
3515 OO.mixinClass( OO.ui.OutlineSelectWidget, OO.ui.mixin.TabIndexedElement );
3516
3517 /**
3518 * ButtonOptionWidget is a special type of {@link OO.ui.mixin.ButtonElement button element} that
3519 * can be selected and configured with data. The class is
3520 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
3521 * [OOUI documentation on MediaWiki] [1] for more information.
3522 *
3523 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Button_selects_and_options
3524 *
3525 * @class
3526 * @extends OO.ui.OptionWidget
3527 * @mixins OO.ui.mixin.ButtonElement
3528 * @mixins OO.ui.mixin.IconElement
3529 * @mixins OO.ui.mixin.IndicatorElement
3530 * @mixins OO.ui.mixin.TitledElement
3531 *
3532 * @constructor
3533 * @param {Object} [config] Configuration options
3534 */
3535 OO.ui.ButtonOptionWidget = function OoUiButtonOptionWidget( config ) {
3536 // Configuration initialization
3537 config = config || {};
3538
3539 // Parent constructor
3540 OO.ui.ButtonOptionWidget.parent.call( this, config );
3541
3542 // Mixin constructors
3543 OO.ui.mixin.ButtonElement.call( this, config );
3544 OO.ui.mixin.IconElement.call( this, config );
3545 OO.ui.mixin.IndicatorElement.call( this, config );
3546 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
3547
3548 // Initialization
3549 this.$element.addClass( 'oo-ui-buttonOptionWidget' );
3550 this.$button.append( this.$icon, this.$label, this.$indicator );
3551 this.$element.append( this.$button );
3552 };
3553
3554 /* Setup */
3555
3556 OO.inheritClass( OO.ui.ButtonOptionWidget, OO.ui.OptionWidget );
3557 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.ButtonElement );
3558 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.IconElement );
3559 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.IndicatorElement );
3560 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.TitledElement );
3561
3562 /* Static Properties */
3563
3564 /**
3565 * Allow button mouse down events to pass through so they can be handled by the parent select widget
3566 *
3567 * @static
3568 * @inheritdoc
3569 */
3570 OO.ui.ButtonOptionWidget.static.cancelButtonMouseDownEvents = false;
3571
3572 /**
3573 * @static
3574 * @inheritdoc
3575 */
3576 OO.ui.ButtonOptionWidget.static.highlightable = false;
3577
3578 /* Methods */
3579
3580 /**
3581 * @inheritdoc
3582 */
3583 OO.ui.ButtonOptionWidget.prototype.setSelected = function ( state ) {
3584 OO.ui.ButtonOptionWidget.parent.prototype.setSelected.call( this, state );
3585
3586 if ( this.constructor.static.selectable ) {
3587 this.setActive( state );
3588 }
3589
3590 return this;
3591 };
3592
3593 /**
3594 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
3595 * button options and is used together with
3596 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
3597 * highlighting, choosing, and selecting mutually exclusive options. Please see
3598 * the [OOUI documentation on MediaWiki] [1] for more information.
3599 *
3600 * @example
3601 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
3602 * var option1 = new OO.ui.ButtonOptionWidget( {
3603 * data: 1,
3604 * label: 'Option 1',
3605 * title: 'Button option 1'
3606 * } );
3607 *
3608 * var option2 = new OO.ui.ButtonOptionWidget( {
3609 * data: 2,
3610 * label: 'Option 2',
3611 * title: 'Button option 2'
3612 * } );
3613 *
3614 * var option3 = new OO.ui.ButtonOptionWidget( {
3615 * data: 3,
3616 * label: 'Option 3',
3617 * title: 'Button option 3'
3618 * } );
3619 *
3620 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
3621 * items: [ option1, option2, option3 ]
3622 * } );
3623 * $( 'body' ).append( buttonSelect.$element );
3624 *
3625 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
3626 *
3627 * @class
3628 * @extends OO.ui.SelectWidget
3629 * @mixins OO.ui.mixin.TabIndexedElement
3630 *
3631 * @constructor
3632 * @param {Object} [config] Configuration options
3633 */
3634 OO.ui.ButtonSelectWidget = function OoUiButtonSelectWidget( config ) {
3635 // Parent constructor
3636 OO.ui.ButtonSelectWidget.parent.call( this, config );
3637
3638 // Mixin constructors
3639 OO.ui.mixin.TabIndexedElement.call( this, config );
3640
3641 // Events
3642 this.$element.on( {
3643 focus: this.bindDocumentKeyDownListener.bind( this ),
3644 blur: this.unbindDocumentKeyDownListener.bind( this )
3645 } );
3646
3647 // Initialization
3648 this.$element.addClass( 'oo-ui-buttonSelectWidget' );
3649 };
3650
3651 /* Setup */
3652
3653 OO.inheritClass( OO.ui.ButtonSelectWidget, OO.ui.SelectWidget );
3654 OO.mixinClass( OO.ui.ButtonSelectWidget, OO.ui.mixin.TabIndexedElement );
3655
3656 /**
3657 * TabOptionWidget is an item in a {@link OO.ui.TabSelectWidget TabSelectWidget}.
3658 *
3659 * Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}, which contain
3660 * {@link OO.ui.TabPanelLayout tab panel layouts}. See {@link OO.ui.IndexLayout IndexLayout}
3661 * for an example.
3662 *
3663 * @class
3664 * @extends OO.ui.OptionWidget
3665 *
3666 * @constructor
3667 * @param {Object} [config] Configuration options
3668 */
3669 OO.ui.TabOptionWidget = function OoUiTabOptionWidget( config ) {
3670 // Configuration initialization
3671 config = config || {};
3672
3673 // Parent constructor
3674 OO.ui.TabOptionWidget.parent.call( this, config );
3675
3676 // Initialization
3677 this.$element
3678 .addClass( 'oo-ui-tabOptionWidget' )
3679 .attr( 'role', 'tab' );
3680 };
3681
3682 /* Setup */
3683
3684 OO.inheritClass( OO.ui.TabOptionWidget, OO.ui.OptionWidget );
3685
3686 /* Static Properties */
3687
3688 /**
3689 * @static
3690 * @inheritdoc
3691 */
3692 OO.ui.TabOptionWidget.static.highlightable = false;
3693
3694 /**
3695 * TabSelectWidget is a list that contains {@link OO.ui.TabOptionWidget tab options}
3696 *
3697 * **Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}.**
3698 *
3699 * @class
3700 * @extends OO.ui.SelectWidget
3701 * @mixins OO.ui.mixin.TabIndexedElement
3702 *
3703 * @constructor
3704 * @param {Object} [config] Configuration options
3705 */
3706 OO.ui.TabSelectWidget = function OoUiTabSelectWidget( config ) {
3707 // Parent constructor
3708 OO.ui.TabSelectWidget.parent.call( this, config );
3709
3710 // Mixin constructors
3711 OO.ui.mixin.TabIndexedElement.call( this, config );
3712
3713 // Events
3714 this.$element.on( {
3715 focus: this.bindDocumentKeyDownListener.bind( this ),
3716 blur: this.unbindDocumentKeyDownListener.bind( this )
3717 } );
3718
3719 // Initialization
3720 this.$element
3721 .addClass( 'oo-ui-tabSelectWidget' )
3722 .attr( 'role', 'tablist' );
3723 };
3724
3725 /* Setup */
3726
3727 OO.inheritClass( OO.ui.TabSelectWidget, OO.ui.SelectWidget );
3728 OO.mixinClass( OO.ui.TabSelectWidget, OO.ui.mixin.TabIndexedElement );
3729
3730 /**
3731 * TagItemWidgets are used within a {@link OO.ui.TagMultiselectWidget
3732 * TagMultiselectWidget} to display the selected items.
3733 *
3734 * @class
3735 * @extends OO.ui.Widget
3736 * @mixins OO.ui.mixin.ItemWidget
3737 * @mixins OO.ui.mixin.LabelElement
3738 * @mixins OO.ui.mixin.FlaggedElement
3739 * @mixins OO.ui.mixin.TabIndexedElement
3740 * @mixins OO.ui.mixin.DraggableElement
3741 *
3742 * @constructor
3743 * @param {Object} [config] Configuration object
3744 * @cfg {boolean} [valid=true] Item is valid
3745 * @cfg {boolean} [fixed] Item is fixed. This means the item is
3746 * always included in the values and cannot be removed.
3747 */
3748 OO.ui.TagItemWidget = function OoUiTagItemWidget( config ) {
3749 config = config || {};
3750
3751 // Parent constructor
3752 OO.ui.TagItemWidget.parent.call( this, config );
3753
3754 // Mixin constructors
3755 OO.ui.mixin.ItemWidget.call( this );
3756 OO.ui.mixin.LabelElement.call( this, config );
3757 OO.ui.mixin.FlaggedElement.call( this, config );
3758 OO.ui.mixin.TabIndexedElement.call( this, config );
3759 OO.ui.mixin.DraggableElement.call( this, config );
3760
3761 this.valid = config.valid === undefined ? true : !!config.valid;
3762 this.fixed = !!config.fixed;
3763
3764 this.closeButton = new OO.ui.ButtonWidget( {
3765 framed: false,
3766 icon: 'close',
3767 tabIndex: -1,
3768 title: OO.ui.msg( 'ooui-item-remove' )
3769 } );
3770 this.closeButton.setDisabled( this.isDisabled() );
3771
3772 // Events
3773 this.closeButton
3774 .connect( this, { click: 'remove' } );
3775 this.$element
3776 .on( 'click', this.select.bind( this ) )
3777 .on( 'keydown', this.onKeyDown.bind( this ) )
3778 // Prevent propagation of mousedown; the tag item "lives" in the
3779 // clickable area of the TagMultiselectWidget, which listens to
3780 // mousedown to open the menu or popup. We want to prevent that
3781 // for clicks specifically on the tag itself, so the actions taken
3782 // are more deliberate. When the tag is clicked, it will emit the
3783 // selection event (similar to how #OO.ui.MultioptionWidget emits 'change')
3784 // and can be handled separately.
3785 .on( 'mousedown', function ( e ) { e.stopPropagation(); } );
3786
3787 // Initialization
3788 this.$element
3789 .addClass( 'oo-ui-tagItemWidget' )
3790 .append( this.$label, this.closeButton.$element );
3791 };
3792
3793 /* Initialization */
3794
3795 OO.inheritClass( OO.ui.TagItemWidget, OO.ui.Widget );
3796 OO.mixinClass( OO.ui.TagItemWidget, OO.ui.mixin.ItemWidget );
3797 OO.mixinClass( OO.ui.TagItemWidget, OO.ui.mixin.LabelElement );
3798 OO.mixinClass( OO.ui.TagItemWidget, OO.ui.mixin.FlaggedElement );
3799 OO.mixinClass( OO.ui.TagItemWidget, OO.ui.mixin.TabIndexedElement );
3800 OO.mixinClass( OO.ui.TagItemWidget, OO.ui.mixin.DraggableElement );
3801
3802 /* Events */
3803
3804 /**
3805 * @event remove
3806 *
3807 * A remove action was performed on the item
3808 */
3809
3810 /**
3811 * @event navigate
3812 * @param {string} direction Direction of the movement, forward or backwards
3813 *
3814 * A navigate action was performed on the item
3815 */
3816
3817 /**
3818 * @event select
3819 *
3820 * The tag widget was selected. This can occur when the widget
3821 * is either clicked or enter was pressed on it.
3822 */
3823
3824 /**
3825 * @event valid
3826 * @param {boolean} isValid Item is valid
3827 *
3828 * Item validity has changed
3829 */
3830
3831 /**
3832 * @event fixed
3833 * @param {boolean} isFixed Item is fixed
3834 *
3835 * Item fixed state has changed
3836 */
3837
3838 /* Methods */
3839
3840 /**
3841 * Set this item as fixed, meaning it cannot be removed
3842 *
3843 * @param {string} [state] Item is fixed
3844 * @fires fixed
3845 * @return {OO.ui.Widget} The widget, for chaining
3846 */
3847 OO.ui.TagItemWidget.prototype.setFixed = function ( state ) {
3848 state = state === undefined ? !this.fixed : !!state;
3849
3850 if ( this.fixed !== state ) {
3851 this.fixed = state;
3852 if ( this.closeButton ) {
3853 this.closeButton.toggle( !this.fixed );
3854 }
3855
3856 if ( !this.fixed && this.elementGroup && !this.elementGroup.isDraggable() ) {
3857 // Only enable the state of the item if the
3858 // entire group is draggable
3859 this.toggleDraggable( !this.fixed );
3860 }
3861 this.$element.toggleClass( 'oo-ui-tagItemWidget-fixed', this.fixed );
3862
3863 this.emit( 'fixed', this.isFixed() );
3864 }
3865 return this;
3866 };
3867
3868 /**
3869 * Check whether the item is fixed
3870 * @return {boolean}
3871 */
3872 OO.ui.TagItemWidget.prototype.isFixed = function () {
3873 return this.fixed;
3874 };
3875
3876 /**
3877 * @inheritdoc
3878 */
3879 OO.ui.TagItemWidget.prototype.setDisabled = function ( state ) {
3880 if ( state && this.elementGroup && !this.elementGroup.isDisabled() ) {
3881 OO.ui.warnDeprecation( 'TagItemWidget#setDisabled: Disabling individual items is deprecated and will result in inconsistent behavior. Use #setFixed instead. See T193571.' );
3882 }
3883 // Parent method
3884 OO.ui.TagItemWidget.parent.prototype.setDisabled.call( this, state );
3885 if (
3886 !state &&
3887 // Verify we have a group, and that the widget is ready
3888 this.toggleDraggable && this.elementGroup &&
3889 !this.isFixed() &&
3890 !this.elementGroup.isDraggable()
3891 ) {
3892 // Only enable the draggable state of the item if the
3893 // entire group is draggable to begin with, and if the
3894 // item is not fixed
3895 this.toggleDraggable( !state );
3896 }
3897
3898 if ( this.closeButton ) {
3899 this.closeButton.setDisabled( state );
3900 }
3901
3902 return this;
3903 };
3904
3905 /**
3906 * Handle removal of the item
3907 *
3908 * This is mainly for extensibility concerns, so other children
3909 * of this class can change the behavior if they need to. This
3910 * is called by both clicking the 'remove' button but also
3911 * on keypress, which is harder to override if needed.
3912 *
3913 * @fires remove
3914 */
3915 OO.ui.TagItemWidget.prototype.remove = function () {
3916 if ( !this.isDisabled() && !this.isFixed() ) {
3917 this.emit( 'remove' );
3918 }
3919 };
3920
3921 /**
3922 * Handle a keydown event on the widget
3923 *
3924 * @fires navigate
3925 * @fires remove
3926 * @param {jQuery.Event} e Key down event
3927 * @return {boolean|undefined} false to stop the operation
3928 */
3929 OO.ui.TagItemWidget.prototype.onKeyDown = function ( e ) {
3930 var movement;
3931
3932 if ( !this.isDisabled() && !this.isFixed() && ( e.keyCode === OO.ui.Keys.BACKSPACE || e.keyCode === OO.ui.Keys.DELETE ) ) {
3933 this.remove();
3934 return false;
3935 } else if ( e.keyCode === OO.ui.Keys.ENTER ) {
3936 this.select();
3937 return false;
3938 } else if (
3939 e.keyCode === OO.ui.Keys.LEFT ||
3940 e.keyCode === OO.ui.Keys.RIGHT
3941 ) {
3942 if ( OO.ui.Element.static.getDir( this.$element ) === 'rtl' ) {
3943 movement = {
3944 left: 'forwards',
3945 right: 'backwards'
3946 };
3947 } else {
3948 movement = {
3949 left: 'backwards',
3950 right: 'forwards'
3951 };
3952 }
3953
3954 this.emit(
3955 'navigate',
3956 e.keyCode === OO.ui.Keys.LEFT ?
3957 movement.left : movement.right
3958 );
3959 return false;
3960 }
3961 };
3962
3963 /**
3964 * Select this item
3965 *
3966 * @fires select
3967 */
3968 OO.ui.TagItemWidget.prototype.select = function () {
3969 if ( !this.isDisabled() ) {
3970 this.emit( 'select' );
3971 }
3972 };
3973
3974 /**
3975 * Set the valid state of this item
3976 *
3977 * @param {boolean} [valid] Item is valid
3978 * @fires valid
3979 */
3980 OO.ui.TagItemWidget.prototype.toggleValid = function ( valid ) {
3981 valid = valid === undefined ? !this.valid : !!valid;
3982
3983 if ( this.valid !== valid ) {
3984 this.valid = valid;
3985
3986 this.setFlags( { invalid: !this.valid } );
3987
3988 this.emit( 'valid', this.valid );
3989 }
3990 };
3991
3992 /**
3993 * Check whether the item is valid
3994 *
3995 * @return {boolean} Item is valid
3996 */
3997 OO.ui.TagItemWidget.prototype.isValid = function () {
3998 return this.valid;
3999 };
4000
4001 /**
4002 * A basic tag multiselect widget, similar in concept to {@link OO.ui.ComboBoxInputWidget combo box widget}
4003 * that allows the user to add multiple values that are displayed in a tag area.
4004 *
4005 * This widget is a base widget; see {@link OO.ui.MenuTagMultiselectWidget MenuTagMultiselectWidget} and
4006 * {@link OO.ui.PopupTagMultiselectWidget PopupTagMultiselectWidget} for the implementations that use
4007 * a menu and a popup respectively.
4008 *
4009 * @example
4010 * // Example: A basic TagMultiselectWidget.
4011 * var widget = new OO.ui.TagMultiselectWidget( {
4012 * inputPosition: 'outline',
4013 * allowedValues: [ 'Option 1', 'Option 2', 'Option 3' ],
4014 * selected: [ 'Option 1' ]
4015 * } );
4016 * $( 'body' ).append( widget.$element );
4017 *
4018 * @class
4019 * @extends OO.ui.Widget
4020 * @mixins OO.ui.mixin.GroupWidget
4021 * @mixins OO.ui.mixin.DraggableGroupElement
4022 * @mixins OO.ui.mixin.IndicatorElement
4023 * @mixins OO.ui.mixin.IconElement
4024 * @mixins OO.ui.mixin.TabIndexedElement
4025 * @mixins OO.ui.mixin.FlaggedElement
4026 *
4027 * @constructor
4028 * @param {Object} config Configuration object
4029 * @cfg {Object} [input] Configuration options for the input widget
4030 * @cfg {OO.ui.InputWidget} [inputWidget] An optional input widget. If given, it will
4031 * replace the input widget used in the TagMultiselectWidget. If not given,
4032 * TagMultiselectWidget creates its own.
4033 * @cfg {boolean} [inputPosition='inline'] Position of the input. Options are:
4034 * - inline: The input is invisible, but exists inside the tag list, so
4035 * the user types into the tag groups to add tags.
4036 * - outline: The input is underneath the tag area.
4037 * - none: No input supplied
4038 * @cfg {boolean} [allowEditTags=true] Allow editing of the tags by clicking them
4039 * @cfg {boolean} [allowArbitrary=false] Allow data items to be added even if
4040 * not present in the menu.
4041 * @cfg {Object[]} [allowedValues] An array representing the allowed items
4042 * by their datas.
4043 * @cfg {boolean} [allowDuplicates=false] Allow duplicate items to be added
4044 * @cfg {boolean} [allowDisplayInvalidTags=false] Allow the display of
4045 * invalid tags. These tags will display with an invalid state, and
4046 * the widget as a whole will have an invalid state if any invalid tags
4047 * are present.
4048 * @cfg {number} [tagLimit] An optional limit on the number of selected options.
4049 * If 'tagLimit' is set and is reached, the input is disabled, not allowing any
4050 * additions. If 'tagLimit' is unset or is 0, an unlimited number of items can be
4051 * added.
4052 * @cfg {boolean} [allowReordering=true] Allow reordering of the items
4053 * @cfg {Object[]|String[]} [selected] A set of selected tags. If given,
4054 * these will appear in the tag list on initialization, as long as they
4055 * pass the validity tests.
4056 */
4057 OO.ui.TagMultiselectWidget = function OoUiTagMultiselectWidget( config ) {
4058 var inputEvents,
4059 rAF = window.requestAnimationFrame || setTimeout,
4060 widget = this,
4061 $tabFocus = $( '<span>' )
4062 .addClass( 'oo-ui-tagMultiselectWidget-focusTrap' );
4063
4064 config = config || {};
4065
4066 // Parent constructor
4067 OO.ui.TagMultiselectWidget.parent.call( this, config );
4068
4069 // Mixin constructors
4070 OO.ui.mixin.GroupWidget.call( this, config );
4071 OO.ui.mixin.IndicatorElement.call( this, config );
4072 OO.ui.mixin.IconElement.call( this, config );
4073 OO.ui.mixin.TabIndexedElement.call( this, config );
4074 OO.ui.mixin.FlaggedElement.call( this, config );
4075 OO.ui.mixin.DraggableGroupElement.call( this, config );
4076
4077 this.toggleDraggable(
4078 config.allowReordering === undefined ?
4079 true : !!config.allowReordering
4080 );
4081
4082 this.inputPosition =
4083 this.constructor.static.allowedInputPositions.indexOf( config.inputPosition ) > -1 ?
4084 config.inputPosition : 'inline';
4085 this.allowEditTags = config.allowEditTags === undefined ? true : !!config.allowEditTags;
4086 this.allowArbitrary = !!config.allowArbitrary;
4087 this.allowDuplicates = !!config.allowDuplicates;
4088 this.allowedValues = config.allowedValues || [];
4089 this.allowDisplayInvalidTags = config.allowDisplayInvalidTags;
4090 this.hasInput = this.inputPosition !== 'none';
4091 this.tagLimit = config.tagLimit;
4092 this.height = null;
4093 this.valid = true;
4094
4095 this.$content = $( '<div>' )
4096 .addClass( 'oo-ui-tagMultiselectWidget-content' );
4097 this.$handle = $( '<div>' )
4098 .addClass( 'oo-ui-tagMultiselectWidget-handle' )
4099 .append(
4100 this.$indicator,
4101 this.$icon,
4102 this.$content
4103 .append(
4104 this.$group
4105 .addClass( 'oo-ui-tagMultiselectWidget-group' )
4106 )
4107 );
4108
4109 // Events
4110 this.aggregate( {
4111 remove: 'itemRemove',
4112 navigate: 'itemNavigate',
4113 select: 'itemSelect',
4114 fixed: 'itemFixed'
4115 } );
4116 this.connect( this, {
4117 itemRemove: 'onTagRemove',
4118 itemSelect: 'onTagSelect',
4119 itemFixed: 'onTagFixed',
4120 itemNavigate: 'onTagNavigate',
4121 change: 'onChangeTags'
4122 } );
4123 this.$handle.on( {
4124 mousedown: this.onMouseDown.bind( this )
4125 } );
4126
4127 // Initialize
4128 this.$element
4129 .addClass( 'oo-ui-tagMultiselectWidget' )
4130 .append( this.$handle );
4131
4132 if ( this.hasInput ) {
4133 if ( config.inputWidget ) {
4134 this.input = config.inputWidget;
4135 } else {
4136 this.input = new OO.ui.TextInputWidget( $.extend( {
4137 placeholder: config.placeholder,
4138 classes: [ 'oo-ui-tagMultiselectWidget-input' ]
4139 }, config.input ) );
4140 }
4141 this.input.setDisabled( this.isDisabled() );
4142
4143 inputEvents = {
4144 focus: this.onInputFocus.bind( this ),
4145 blur: this.onInputBlur.bind( this ),
4146 'propertychange change click mouseup keydown keyup input cut paste select focus':
4147 OO.ui.debounce( this.updateInputSize.bind( this ) ),
4148 keydown: this.onInputKeyDown.bind( this ),
4149 keypress: this.onInputKeyPress.bind( this )
4150 };
4151
4152 this.input.$input.on( inputEvents );
4153 this.inputPlaceholder = this.input.$input.attr( 'placeholder' );
4154
4155 if ( this.inputPosition === 'outline' ) {
4156 // Override max-height for the input widget
4157 // in the case the widget is outline so it can
4158 // stretch all the way if the widget is wide
4159 this.input.$element.css( 'max-width', 'inherit' );
4160 this.$element
4161 .addClass( 'oo-ui-tagMultiselectWidget-outlined' )
4162 .append( this.input.$element );
4163 } else {
4164 this.$element.addClass( 'oo-ui-tagMultiselectWidget-inlined' );
4165 // HACK: When the widget is using 'inline' input, the
4166 // behavior needs to only use the $input itself
4167 // so we style and size it accordingly (otherwise
4168 // the styling and sizing can get very convoluted
4169 // when the wrapping divs and other elements)
4170 // We are taking advantage of still being able to
4171 // call the widget itself for operations like
4172 // .getValue() and setDisabled() and .focus() but
4173 // having only the $input attached to the DOM
4174 this.$content.append( this.input.$input );
4175 }
4176 } else {
4177 this.$content.append( $tabFocus );
4178 }
4179
4180 this.setTabIndexedElement(
4181 this.hasInput ?
4182 this.input.$input :
4183 $tabFocus
4184 );
4185
4186 if ( config.selected ) {
4187 this.setValue( config.selected );
4188 }
4189
4190 // HACK: Input size needs to be calculated after everything
4191 // else is rendered
4192 rAF( function () {
4193 if ( widget.hasInput ) {
4194 widget.updateInputSize();
4195 }
4196 } );
4197 };
4198
4199 /* Initialization */
4200
4201 OO.inheritClass( OO.ui.TagMultiselectWidget, OO.ui.Widget );
4202 OO.mixinClass( OO.ui.TagMultiselectWidget, OO.ui.mixin.GroupWidget );
4203 OO.mixinClass( OO.ui.TagMultiselectWidget, OO.ui.mixin.DraggableGroupElement );
4204 OO.mixinClass( OO.ui.TagMultiselectWidget, OO.ui.mixin.IndicatorElement );
4205 OO.mixinClass( OO.ui.TagMultiselectWidget, OO.ui.mixin.IconElement );
4206 OO.mixinClass( OO.ui.TagMultiselectWidget, OO.ui.mixin.TabIndexedElement );
4207 OO.mixinClass( OO.ui.TagMultiselectWidget, OO.ui.mixin.FlaggedElement );
4208
4209 /* Static properties */
4210
4211 /**
4212 * Allowed input positions.
4213 * - inline: The input is inside the tag list
4214 * - outline: The input is under the tag list
4215 * - none: There is no input
4216 *
4217 * @property {Array}
4218 */
4219 OO.ui.TagMultiselectWidget.static.allowedInputPositions = [ 'inline', 'outline', 'none' ];
4220
4221 /* Methods */
4222
4223 /**
4224 * Handle mouse down events.
4225 *
4226 * @private
4227 * @param {jQuery.Event} e Mouse down event
4228 * @return {boolean} False to prevent defaults
4229 */
4230 OO.ui.TagMultiselectWidget.prototype.onMouseDown = function ( e ) {
4231 if (
4232 !this.isDisabled() &&
4233 ( !this.hasInput || e.target !== this.input.$input[ 0 ] ) &&
4234 e.which === OO.ui.MouseButtons.LEFT
4235 ) {
4236 this.focus();
4237 return false;
4238 }
4239 };
4240
4241 /**
4242 * Handle key press events.
4243 *
4244 * @private
4245 * @param {jQuery.Event} e Key press event
4246 * @return {boolean} Whether to prevent defaults
4247 */
4248 OO.ui.TagMultiselectWidget.prototype.onInputKeyPress = function ( e ) {
4249 var stopOrContinue,
4250 withMetaKey = e.metaKey || e.ctrlKey;
4251
4252 if ( !this.isDisabled() ) {
4253 if ( e.which === OO.ui.Keys.ENTER ) {
4254 stopOrContinue = this.doInputEnter( e, withMetaKey );
4255 }
4256
4257 // Make sure the input gets resized.
4258 setTimeout( this.updateInputSize.bind( this ), 0 );
4259 return stopOrContinue;
4260 }
4261 };
4262
4263 /**
4264 * Handle key down events.
4265 *
4266 * @private
4267 * @param {jQuery.Event} e Key down event
4268 * @return {boolean}
4269 */
4270 OO.ui.TagMultiselectWidget.prototype.onInputKeyDown = function ( e ) {
4271 var movement, direction,
4272 widget = this,
4273 withMetaKey = e.metaKey || e.ctrlKey,
4274 isMovementInsideInput = function ( direction ) {
4275 var inputRange = widget.input.getRange(),
4276 inputValue = widget.hasInput && widget.input.getValue();
4277
4278 if ( direction === 'forwards' && inputRange.to > inputValue.length - 1 ) {
4279 return false;
4280 }
4281
4282 if ( direction === 'backwards' && inputRange.from <= 0 ) {
4283 return false;
4284 }
4285
4286 return true;
4287 };
4288
4289 if ( !this.isDisabled() ) {
4290 // 'keypress' event is not triggered for Backspace
4291 if ( e.keyCode === OO.ui.Keys.BACKSPACE ) {
4292 return this.doInputBackspace( e, withMetaKey );
4293 } else if ( e.keyCode === OO.ui.Keys.ESCAPE ) {
4294 return this.doInputEscape( e );
4295 } else if (
4296 e.keyCode === OO.ui.Keys.LEFT ||
4297 e.keyCode === OO.ui.Keys.RIGHT
4298 ) {
4299 if ( OO.ui.Element.static.getDir( this.$element ) === 'rtl' ) {
4300 movement = {
4301 left: 'forwards',
4302 right: 'backwards'
4303 };
4304 } else {
4305 movement = {
4306 left: 'backwards',
4307 right: 'forwards'
4308 };
4309 }
4310 direction = e.keyCode === OO.ui.Keys.LEFT ?
4311 movement.left : movement.right;
4312
4313 if ( !this.hasInput || !isMovementInsideInput( direction ) ) {
4314 return this.doInputArrow( e, direction, withMetaKey );
4315 }
4316 }
4317 }
4318 };
4319
4320 /**
4321 * Respond to input focus event
4322 */
4323 OO.ui.TagMultiselectWidget.prototype.onInputFocus = function () {
4324 this.$element.addClass( 'oo-ui-tagMultiselectWidget-focus' );
4325 // Reset validity
4326 this.toggleValid( true );
4327 };
4328
4329 /**
4330 * Respond to input blur event
4331 */
4332 OO.ui.TagMultiselectWidget.prototype.onInputBlur = function () {
4333 this.$element.removeClass( 'oo-ui-tagMultiselectWidget-focus' );
4334
4335 // Set the widget as invalid if there's text in the input
4336 this.addTagFromInput();
4337 this.toggleValid( this.checkValidity() && ( !this.hasInput || !this.input.getValue() ) );
4338 };
4339
4340 /**
4341 * Perform an action after the enter key on the input
4342 *
4343 * @param {jQuery.Event} e Event data
4344 * @param {boolean} [withMetaKey] Whether this key was pressed with
4345 * a meta key like 'ctrl'
4346 * @return {boolean} Whether to prevent defaults
4347 */
4348 OO.ui.TagMultiselectWidget.prototype.doInputEnter = function () {
4349 this.addTagFromInput();
4350 return false;
4351 };
4352
4353 /**
4354 * Perform an action responding to the enter key on the input
4355 *
4356 * @param {jQuery.Event} e Event data
4357 * @param {boolean} [withMetaKey] Whether this key was pressed with
4358 * a meta key like 'ctrl'
4359 * @return {boolean} Whether to prevent defaults
4360 */
4361 OO.ui.TagMultiselectWidget.prototype.doInputBackspace = function ( e, withMetaKey ) {
4362 var items, item;
4363
4364 if (
4365 this.inputPosition === 'inline' &&
4366 this.input.getValue() === '' &&
4367 !this.isEmpty()
4368 ) {
4369 // Delete the last item
4370 items = this.getItems();
4371 item = items[ items.length - 1 ];
4372
4373 if ( !item.isDisabled() && !item.isFixed() ) {
4374 this.removeItems( [ item ] );
4375 // If Ctrl/Cmd was pressed, delete item entirely.
4376 // Otherwise put it into the text field for editing.
4377 if ( !withMetaKey ) {
4378 this.input.setValue( item.getData() );
4379 }
4380 }
4381
4382 return false;
4383 }
4384 };
4385
4386 /**
4387 * Perform an action after the escape key on the input
4388 *
4389 * @param {jQuery.Event} e Event data
4390 */
4391 OO.ui.TagMultiselectWidget.prototype.doInputEscape = function () {
4392 this.clearInput();
4393 };
4394
4395 /**
4396 * Perform an action after the arrow key on the input, select the previous
4397 * item from the input.
4398 * See #getPreviousItem
4399 *
4400 * @param {jQuery.Event} e Event data
4401 * @param {string} direction Direction of the movement; forwards or backwards
4402 * @param {boolean} [withMetaKey] Whether this key was pressed with
4403 * a meta key like 'ctrl'
4404 */
4405 OO.ui.TagMultiselectWidget.prototype.doInputArrow = function ( e, direction ) {
4406 if (
4407 this.inputPosition === 'inline' &&
4408 !this.isEmpty() &&
4409 direction === 'backwards'
4410 ) {
4411 // Get previous item
4412 this.getPreviousItem().focus();
4413 }
4414 };
4415
4416 /**
4417 * Respond to item select event
4418 *
4419 * @param {OO.ui.TagItemWidget} item Selected item
4420 */
4421 OO.ui.TagMultiselectWidget.prototype.onTagSelect = function ( item ) {
4422 if ( this.hasInput && this.allowEditTags && !item.isFixed() ) {
4423 if ( this.input.getValue() ) {
4424 this.addTagFromInput();
4425 }
4426 // 1. Get the label of the tag into the input
4427 this.input.setValue( item.getData() );
4428 // 2. Remove the tag
4429 this.removeItems( [ item ] );
4430 // 3. Focus the input
4431 this.focus();
4432 }
4433 };
4434
4435 /**
4436 * Respond to item fixed state change
4437 *
4438 * @param {OO.ui.TagItemWidget} item Selected item
4439 */
4440 OO.ui.TagMultiselectWidget.prototype.onTagFixed = function ( item ) {
4441 var i,
4442 items = this.getItems();
4443
4444 // Move item to the end of the static items
4445 for ( i = 0; i < items.length; i++ ) {
4446 if ( items[ i ] !== item && !items[ i ].isFixed() ) {
4447 break;
4448 }
4449 }
4450 this.addItems( item, i );
4451 };
4452 /**
4453 * Respond to change event, where items were added, removed, or cleared.
4454 */
4455 OO.ui.TagMultiselectWidget.prototype.onChangeTags = function () {
4456 var isUnderLimit = this.isUnderLimit();
4457
4458 // Reset validity
4459 this.toggleValid(
4460 this.checkValidity() &&
4461 !( this.hasInput && this.input.getValue() )
4462 );
4463
4464 if ( this.hasInput ) {
4465 this.updateInputSize();
4466 if ( !isUnderLimit ) {
4467 // Clear the input
4468 this.input.setValue( '' );
4469 }
4470 if ( this.inputPosition === 'outline' ) {
4471 // Show/clear the placeholder and enable/disable the input
4472 // based on whether we are/aren't under the specified limit
4473 this.input.$input.attr( 'placeholder', isUnderLimit ? this.inputPlaceholder : '' );
4474 this.input.setDisabled( !isUnderLimit );
4475 } else {
4476 // Show/hide the input
4477 this.input.$input.toggleClass( 'oo-ui-element-hidden', !isUnderLimit );
4478 }
4479 }
4480 this.updateIfHeightChanged();
4481 };
4482
4483 /**
4484 * @inheritdoc
4485 */
4486 OO.ui.TagMultiselectWidget.prototype.setDisabled = function ( isDisabled ) {
4487 // Parent method
4488 OO.ui.TagMultiselectWidget.parent.prototype.setDisabled.call( this, isDisabled );
4489
4490 if ( this.hasInput && this.input ) {
4491 this.input.setDisabled( !!isDisabled && !this.isUnderLimit() );
4492 }
4493
4494 if ( this.items ) {
4495 this.getItems().forEach( function ( item ) {
4496 item.setDisabled( !!isDisabled );
4497 } );
4498 }
4499 };
4500
4501 /**
4502 * Respond to tag remove event
4503 * @param {OO.ui.TagItemWidget} item Removed tag
4504 */
4505 OO.ui.TagMultiselectWidget.prototype.onTagRemove = function ( item ) {
4506 this.removeTagByData( item.getData() );
4507 };
4508
4509 /**
4510 * Respond to navigate event on the tag
4511 *
4512 * @param {OO.ui.TagItemWidget} item Removed tag
4513 * @param {string} direction Direction of movement; 'forwards' or 'backwards'
4514 */
4515 OO.ui.TagMultiselectWidget.prototype.onTagNavigate = function ( item, direction ) {
4516 var firstItem = this.getItems()[ 0 ];
4517
4518 if ( direction === 'forwards' ) {
4519 this.getNextItem( item ).focus();
4520 } else if ( !this.inputPosition === 'inline' || item !== firstItem ) {
4521 // If the widget has an inline input, we want to stop at the starting edge
4522 // of the tags
4523 this.getPreviousItem( item ).focus();
4524 }
4525 };
4526
4527 /**
4528 * Add tag from input value
4529 */
4530 OO.ui.TagMultiselectWidget.prototype.addTagFromInput = function () {
4531 var val = this.input.getValue(),
4532 isValid = this.isAllowedData( val );
4533
4534 if ( !val ) {
4535 return;
4536 }
4537
4538 if ( isValid || this.allowDisplayInvalidTags ) {
4539 this.clearInput();
4540 this.addTag( val );
4541 }
4542 };
4543
4544 /**
4545 * Clear the input
4546 */
4547 OO.ui.TagMultiselectWidget.prototype.clearInput = function () {
4548 this.input.setValue( '' );
4549 };
4550
4551 /**
4552 * Check whether the given value is a duplicate of an existing
4553 * tag already in the list.
4554 *
4555 * @param {string|Object} data Requested value
4556 * @return {boolean} Value is duplicate
4557 */
4558 OO.ui.TagMultiselectWidget.prototype.isDuplicateData = function ( data ) {
4559 return !!this.findItemFromData( data );
4560 };
4561
4562 /**
4563 * Check whether a given value is allowed to be added
4564 *
4565 * @param {string|Object} data Requested value
4566 * @return {boolean} Value is allowed
4567 */
4568 OO.ui.TagMultiselectWidget.prototype.isAllowedData = function ( data ) {
4569 if (
4570 !this.allowDuplicates &&
4571 this.isDuplicateData( data )
4572 ) {
4573 return false;
4574 }
4575
4576 if ( this.allowArbitrary ) {
4577 return true;
4578 }
4579
4580 // Check with allowed values
4581 if (
4582 this.getAllowedValues().some( function ( value ) {
4583 return data === value;
4584 } )
4585 ) {
4586 return true;
4587 }
4588
4589 return false;
4590 };
4591
4592 /**
4593 * Get the allowed values list
4594 *
4595 * @return {string[]} Allowed data values
4596 */
4597 OO.ui.TagMultiselectWidget.prototype.getAllowedValues = function () {
4598 return this.allowedValues;
4599 };
4600
4601 /**
4602 * Add a value to the allowed values list
4603 *
4604 * @param {string} value Allowed data value
4605 */
4606 OO.ui.TagMultiselectWidget.prototype.addAllowedValue = function ( value ) {
4607 if ( this.allowedValues.indexOf( value ) === -1 ) {
4608 this.allowedValues.push( value );
4609 }
4610 };
4611
4612 /**
4613 * Get the datas of the currently selected items
4614 *
4615 * @return {string[]|Object[]} Datas of currently selected items
4616 */
4617 OO.ui.TagMultiselectWidget.prototype.getValue = function () {
4618 return this.getItems()
4619 .filter( function ( item ) {
4620 return item.isValid();
4621 } )
4622 .map( function ( item ) {
4623 return item.getData();
4624 } );
4625 };
4626
4627 /**
4628 * Set the value of this widget by datas.
4629 *
4630 * @param {string|string[]|Object|Object[]} valueObject An object representing the data
4631 * and label of the value. If the widget allows arbitrary values,
4632 * the items will be added as-is. Otherwise, the data value will
4633 * be checked against allowedValues.
4634 * This object must contain at least a data key. Example:
4635 * { data: 'foo', label: 'Foo item' }
4636 * For multiple items, use an array of objects. For example:
4637 * [
4638 * { data: 'foo', label: 'Foo item' },
4639 * { data: 'bar', label: 'Bar item' }
4640 * ]
4641 * Value can also be added with plaintext array, for example:
4642 * [ 'foo', 'bar', 'bla' ] or a single string, like 'foo'
4643 */
4644 OO.ui.TagMultiselectWidget.prototype.setValue = function ( valueObject ) {
4645 valueObject = Array.isArray( valueObject ) ? valueObject : [ valueObject ];
4646
4647 this.clearItems();
4648 valueObject.forEach( function ( obj ) {
4649 if ( typeof obj === 'string' ) {
4650 this.addTag( obj );
4651 } else {
4652 this.addTag( obj.data, obj.label );
4653 }
4654 }.bind( this ) );
4655 };
4656
4657 /**
4658 * Add tag to the display area
4659 *
4660 * @param {string|Object} data Tag data
4661 * @param {string} [label] Tag label. If no label is provided, the
4662 * stringified version of the data will be used instead.
4663 * @return {boolean} Item was added successfully
4664 */
4665 OO.ui.TagMultiselectWidget.prototype.addTag = function ( data, label ) {
4666 var newItemWidget,
4667 isValid = this.isAllowedData( data );
4668
4669 if ( this.isUnderLimit() && ( isValid || this.allowDisplayInvalidTags ) ) {
4670 newItemWidget = this.createTagItemWidget( data, label );
4671 newItemWidget.toggleValid( isValid );
4672 this.addItems( [ newItemWidget ] );
4673 return true;
4674 }
4675
4676 return false;
4677 };
4678
4679 /**
4680 * Check whether the number of current tags is within the limit.
4681 *
4682 * @return {boolean} True if current tag count is within the limit or
4683 * if 'tagLimit' is not set
4684 */
4685 OO.ui.TagMultiselectWidget.prototype.isUnderLimit = function () {
4686 return !this.tagLimit ||
4687 this.getItemCount() < this.tagLimit;
4688 };
4689
4690 /**
4691 * Remove tag by its data property.
4692 *
4693 * @param {string|Object} data Tag data
4694 */
4695 OO.ui.TagMultiselectWidget.prototype.removeTagByData = function ( data ) {
4696 var item = this.findItemFromData( data );
4697
4698 this.removeItems( [ item ] );
4699 };
4700
4701 /**
4702 * Construct a OO.ui.TagItemWidget (or a subclass thereof) from given label and data.
4703 *
4704 * @protected
4705 * @param {string} data Item data
4706 * @param {string} label The label text.
4707 * @return {OO.ui.TagItemWidget}
4708 */
4709 OO.ui.TagMultiselectWidget.prototype.createTagItemWidget = function ( data, label ) {
4710 label = label || data;
4711
4712 return new OO.ui.TagItemWidget( { data: data, label: label } );
4713 };
4714
4715 /**
4716 * Given an item, returns the item after it. If the item is already the
4717 * last item, return `this.input`. If no item is passed, returns the
4718 * very first item.
4719 *
4720 * @protected
4721 * @param {OO.ui.TagItemWidget} [item] Tag item
4722 * @return {OO.ui.Widget} The next widget available.
4723 */
4724 OO.ui.TagMultiselectWidget.prototype.getNextItem = function ( item ) {
4725 var itemIndex = this.items.indexOf( item );
4726
4727 if ( item === undefined || itemIndex === -1 ) {
4728 return this.items[ 0 ];
4729 }
4730
4731 if ( itemIndex === this.items.length - 1 ) { // Last item
4732 if ( this.hasInput ) {
4733 return this.input;
4734 } else {
4735 // Return first item
4736 return this.items[ 0 ];
4737 }
4738 } else {
4739 return this.items[ itemIndex + 1 ];
4740 }
4741 };
4742
4743 /**
4744 * Given an item, returns the item before it. If the item is already the
4745 * first item, return `this.input`. If no item is passed, returns the
4746 * very last item.
4747 *
4748 * @protected
4749 * @param {OO.ui.TagItemWidget} [item] Tag item
4750 * @return {OO.ui.Widget} The previous widget available.
4751 */
4752 OO.ui.TagMultiselectWidget.prototype.getPreviousItem = function ( item ) {
4753 var itemIndex = this.items.indexOf( item );
4754
4755 if ( item === undefined || itemIndex === -1 ) {
4756 return this.items[ this.items.length - 1 ];
4757 }
4758
4759 if ( itemIndex === 0 ) {
4760 if ( this.hasInput ) {
4761 return this.input;
4762 } else {
4763 // Return the last item
4764 return this.items[ this.items.length - 1 ];
4765 }
4766 } else {
4767 return this.items[ itemIndex - 1 ];
4768 }
4769 };
4770
4771 /**
4772 * Update the dimensions of the text input field to encompass all available area.
4773 * This is especially relevant for when the input is at the edge of a line
4774 * and should get smaller. The usual operation (as an inline-block with min-width)
4775 * does not work in that case, pushing the input downwards to the next line.
4776 *
4777 * @private
4778 */
4779 OO.ui.TagMultiselectWidget.prototype.updateInputSize = function () {
4780 var $lastItem, direction, contentWidth, currentWidth, bestWidth;
4781 if ( this.inputPosition === 'inline' && !this.isDisabled() ) {
4782 if ( this.input.$input[ 0 ].scrollWidth === 0 ) {
4783 // Input appears to be attached but not visible.
4784 // Don't attempt to adjust its size, because our measurements
4785 // are going to fail anyway.
4786 return;
4787 }
4788 this.input.$input.css( 'width', '1em' );
4789 $lastItem = this.$group.children().last();
4790 direction = OO.ui.Element.static.getDir( this.$handle );
4791
4792 // Get the width of the input with the placeholder text as
4793 // the value and save it so that we don't keep recalculating
4794 if (
4795 this.contentWidthWithPlaceholder === undefined &&
4796 this.input.getValue() === '' &&
4797 this.input.$input.attr( 'placeholder' ) !== undefined
4798 ) {
4799 this.input.setValue( this.input.$input.attr( 'placeholder' ) );
4800 this.contentWidthWithPlaceholder = this.input.$input[ 0 ].scrollWidth;
4801 this.input.setValue( '' );
4802
4803 }
4804
4805 // Always keep the input wide enough for the placeholder text
4806 contentWidth = Math.max(
4807 this.input.$input[ 0 ].scrollWidth,
4808 // undefined arguments in Math.max lead to NaN
4809 ( this.contentWidthWithPlaceholder === undefined ) ?
4810 0 : this.contentWidthWithPlaceholder
4811 );
4812 currentWidth = this.input.$input.width();
4813
4814 if ( contentWidth < currentWidth ) {
4815 this.updateIfHeightChanged();
4816 // All is fine, don't perform expensive calculations
4817 return;
4818 }
4819
4820 if ( $lastItem.length === 0 ) {
4821 bestWidth = this.$content.innerWidth();
4822 } else {
4823 bestWidth = direction === 'ltr' ?
4824 this.$content.innerWidth() - $lastItem.position().left - $lastItem.outerWidth() :
4825 $lastItem.position().left;
4826 }
4827
4828 // Some safety margin for sanity, because I *really* don't feel like finding out where the few
4829 // pixels this is off by are coming from.
4830 bestWidth -= 13;
4831 if ( contentWidth > bestWidth ) {
4832 // This will result in the input getting shifted to the next line
4833 bestWidth = this.$content.innerWidth() - 13;
4834 }
4835 this.input.$input.width( Math.floor( bestWidth ) );
4836 this.updateIfHeightChanged();
4837 } else {
4838 this.updateIfHeightChanged();
4839 }
4840 };
4841
4842 /**
4843 * Determine if widget height changed, and if so,
4844 * emit the resize event. This is useful for when there are either
4845 * menus or popups attached to the bottom of the widget, to allow
4846 * them to change their positioning in case the widget moved down
4847 * or up.
4848 *
4849 * @private
4850 */
4851 OO.ui.TagMultiselectWidget.prototype.updateIfHeightChanged = function () {
4852 var height = this.$element.height();
4853 if ( height !== this.height ) {
4854 this.height = height;
4855 this.emit( 'resize' );
4856 }
4857 };
4858
4859 /**
4860 * Check whether all items in the widget are valid
4861 *
4862 * @return {boolean} Widget is valid
4863 */
4864 OO.ui.TagMultiselectWidget.prototype.checkValidity = function () {
4865 return this.getItems().every( function ( item ) {
4866 return item.isValid();
4867 } );
4868 };
4869
4870 /**
4871 * Set the valid state of this item
4872 *
4873 * @param {boolean} [valid] Item is valid
4874 * @fires valid
4875 */
4876 OO.ui.TagMultiselectWidget.prototype.toggleValid = function ( valid ) {
4877 valid = valid === undefined ? !this.valid : !!valid;
4878
4879 if ( this.valid !== valid ) {
4880 this.valid = valid;
4881
4882 this.setFlags( { invalid: !this.valid } );
4883
4884 this.emit( 'valid', this.valid );
4885 }
4886 };
4887
4888 /**
4889 * Get the current valid state of the widget
4890 *
4891 * @return {boolean} Widget is valid
4892 */
4893 OO.ui.TagMultiselectWidget.prototype.isValid = function () {
4894 return this.valid;
4895 };
4896
4897 /**
4898 * PopupTagMultiselectWidget is a {@link OO.ui.TagMultiselectWidget OO.ui.TagMultiselectWidget} intended
4899 * to use a popup. The popup can be configured to have a default input to insert values into the widget.
4900 *
4901 * @example
4902 * // Example: A basic PopupTagMultiselectWidget.
4903 * var widget = new OO.ui.PopupTagMultiselectWidget();
4904 * $( 'body' ).append( widget.$element );
4905 *
4906 * // Example: A PopupTagMultiselectWidget with an external popup.
4907 * var popupInput = new OO.ui.TextInputWidget(),
4908 * widget = new OO.ui.PopupTagMultiselectWidget( {
4909 * popupInput: popupInput,
4910 * popup: {
4911 * $content: popupInput.$element
4912 * }
4913 * } );
4914 * $( 'body' ).append( widget.$element );
4915 *
4916 * @class
4917 * @extends OO.ui.TagMultiselectWidget
4918 * @mixins OO.ui.mixin.PopupElement
4919 *
4920 * @param {Object} config Configuration object
4921 * @cfg {jQuery} [$overlay] An overlay for the popup.
4922 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
4923 * @cfg {Object} [popup] Configuration options for the popup
4924 * @cfg {OO.ui.InputWidget} [popupInput] An input widget inside the popup that will be
4925 * focused when the popup is opened and will be used as replacement for the
4926 * general input in the widget.
4927 */
4928 OO.ui.PopupTagMultiselectWidget = function OoUiPopupTagMultiselectWidget( config ) {
4929 var defaultInput,
4930 defaultConfig = { popup: {} };
4931
4932 config = config || {};
4933
4934 // Parent constructor
4935 OO.ui.PopupTagMultiselectWidget.parent.call( this, $.extend( { inputPosition: 'none' }, config ) );
4936
4937 this.$overlay = ( config.$overlay === true ? OO.ui.getDefaultOverlay() : config.$overlay ) || this.$element;
4938
4939 if ( !config.popup ) {
4940 // For the default base implementation, we give a popup
4941 // with an input widget inside it. For any other use cases
4942 // the popup needs to be populated externally and the
4943 // event handled to add tags separately and manually
4944 defaultInput = new OO.ui.TextInputWidget();
4945
4946 defaultConfig.popupInput = defaultInput;
4947 defaultConfig.popup.$content = defaultInput.$element;
4948 defaultConfig.popup.padded = true;
4949
4950 this.$element.addClass( 'oo-ui-popupTagMultiselectWidget-defaultPopup' );
4951 }
4952
4953 // Add overlay, and add that to the autoCloseIgnore
4954 defaultConfig.popup.$overlay = this.$overlay;
4955 defaultConfig.popup.$autoCloseIgnore = this.hasInput ?
4956 this.input.$element.add( this.$overlay ) : this.$overlay;
4957
4958 // Allow extending any of the above
4959 config = $.extend( defaultConfig, config );
4960
4961 // Mixin constructors
4962 OO.ui.mixin.PopupElement.call( this, config );
4963
4964 if ( this.hasInput ) {
4965 this.input.$input.on( 'focus', this.popup.toggle.bind( this.popup, true ) );
4966 }
4967
4968 // Configuration options
4969 this.popupInput = config.popupInput;
4970 if ( this.popupInput ) {
4971 this.popupInput.connect( this, {
4972 enter: 'onPopupInputEnter'
4973 } );
4974 }
4975
4976 // Events
4977 this.on( 'resize', this.popup.updateDimensions.bind( this.popup ) );
4978 this.popup.connect( this, { toggle: 'onPopupToggle' } );
4979 this.$tabIndexed
4980 .on( 'focus', this.onFocus.bind( this ) );
4981
4982 // Initialize
4983 this.$element
4984 .append( this.popup.$element )
4985 .addClass( 'oo-ui-popupTagMultiselectWidget' );
4986 };
4987
4988 /* Initialization */
4989
4990 OO.inheritClass( OO.ui.PopupTagMultiselectWidget, OO.ui.TagMultiselectWidget );
4991 OO.mixinClass( OO.ui.PopupTagMultiselectWidget, OO.ui.mixin.PopupElement );
4992
4993 /* Methods */
4994
4995 /**
4996 * Focus event handler.
4997 *
4998 * @private
4999 */
5000 OO.ui.PopupTagMultiselectWidget.prototype.onFocus = function () {
5001 this.popup.toggle( true );
5002 };
5003
5004 /**
5005 * Respond to popup toggle event
5006 *
5007 * @param {boolean} isVisible Popup is visible
5008 */
5009 OO.ui.PopupTagMultiselectWidget.prototype.onPopupToggle = function ( isVisible ) {
5010 if ( isVisible && this.popupInput ) {
5011 this.popupInput.focus();
5012 }
5013 };
5014
5015 /**
5016 * Respond to popup input enter event
5017 */
5018 OO.ui.PopupTagMultiselectWidget.prototype.onPopupInputEnter = function () {
5019 if ( this.popupInput ) {
5020 this.addTagByPopupValue( this.popupInput.getValue() );
5021 this.popupInput.setValue( '' );
5022 }
5023 };
5024
5025 /**
5026 * @inheritdoc
5027 */
5028 OO.ui.PopupTagMultiselectWidget.prototype.onTagSelect = function ( item ) {
5029 if ( this.popupInput && this.allowEditTags ) {
5030 this.popupInput.setValue( item.getData() );
5031 this.removeItems( [ item ] );
5032
5033 this.popup.toggle( true );
5034 this.popupInput.focus();
5035 } else {
5036 // Parent
5037 OO.ui.PopupTagMultiselectWidget.parent.prototype.onTagSelect.call( this, item );
5038 }
5039 };
5040
5041 /**
5042 * Add a tag by the popup value.
5043 * Whatever is responsible for setting the value in the popup should call
5044 * this method to add a tag, or use the regular methods like #addTag or
5045 * #setValue directly.
5046 *
5047 * @param {string} data The value of item
5048 * @param {string} [label] The label of the tag. If not given, the data is used.
5049 */
5050 OO.ui.PopupTagMultiselectWidget.prototype.addTagByPopupValue = function ( data, label ) {
5051 this.addTag( data, label );
5052 };
5053
5054 /**
5055 * MenuTagMultiselectWidget is a {@link OO.ui.TagMultiselectWidget OO.ui.TagMultiselectWidget} intended
5056 * to use a menu of selectable options.
5057 *
5058 * @example
5059 * // Example: A basic MenuTagMultiselectWidget.
5060 * var widget = new OO.ui.MenuTagMultiselectWidget( {
5061 * inputPosition: 'outline',
5062 * options: [
5063 * { data: 'option1', label: 'Option 1', icon: 'tag' },
5064 * { data: 'option2', label: 'Option 2' },
5065 * { data: 'option3', label: 'Option 3' },
5066 * ],
5067 * selected: [ 'option1', 'option2' ]
5068 * } );
5069 * $( 'body' ).append( widget.$element );
5070 *
5071 * @class
5072 * @extends OO.ui.TagMultiselectWidget
5073 *
5074 * @constructor
5075 * @param {Object} [config] Configuration object
5076 * @cfg {boolean} [clearInputOnChoose=true] Clear the text input value when a menu option is chosen
5077 * @cfg {Object} [menu] Configuration object for the menu widget
5078 * @cfg {jQuery} [$overlay] An overlay for the menu.
5079 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
5080 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
5081 */
5082 OO.ui.MenuTagMultiselectWidget = function OoUiMenuTagMultiselectWidget( config ) {
5083 config = config || {};
5084
5085 // Parent constructor
5086 OO.ui.MenuTagMultiselectWidget.parent.call( this, config );
5087
5088 this.$overlay = ( config.$overlay === true ? OO.ui.getDefaultOverlay() : config.$overlay ) || this.$element;
5089 this.clearInputOnChoose = config.clearInputOnChoose === undefined || !!config.clearInputOnChoose;
5090 this.menu = this.createMenuWidget( $.extend( {
5091 widget: this,
5092 input: this.hasInput ? this.input : null,
5093 $input: this.hasInput ? this.input.$input : null,
5094 filterFromInput: !!this.hasInput,
5095 $autoCloseIgnore: this.hasInput ?
5096 this.input.$element : $( [] ),
5097 $floatableContainer: this.hasInput && this.inputPosition === 'outline' ?
5098 this.input.$element : this.$element,
5099 $overlay: this.$overlay,
5100 disabled: this.isDisabled()
5101 }, config.menu ) );
5102 this.addOptions( config.options || [] );
5103
5104 // Events
5105 this.menu.connect( this, {
5106 choose: 'onMenuChoose',
5107 toggle: 'onMenuToggle'
5108 } );
5109 if ( this.hasInput ) {
5110 this.input.connect( this, { change: 'onInputChange' } );
5111 }
5112 this.connect( this, { resize: 'onResize' } );
5113
5114 // Initialization
5115 this.$overlay
5116 .append( this.menu.$element );
5117 this.$element
5118 .addClass( 'oo-ui-menuTagMultiselectWidget' );
5119 // TagMultiselectWidget already does this, but it doesn't work right because this.menu is not yet
5120 // set up while the parent constructor runs, and #getAllowedValues rejects everything.
5121 if ( config.selected ) {
5122 this.setValue( config.selected );
5123 }
5124 };
5125
5126 /* Initialization */
5127
5128 OO.inheritClass( OO.ui.MenuTagMultiselectWidget, OO.ui.TagMultiselectWidget );
5129
5130 /* Methods */
5131
5132 /**
5133 * Respond to resize event
5134 */
5135 OO.ui.MenuTagMultiselectWidget.prototype.onResize = function () {
5136 // Reposition the menu
5137 this.menu.position();
5138 };
5139
5140 /**
5141 * @inheritdoc
5142 */
5143 OO.ui.MenuTagMultiselectWidget.prototype.onInputFocus = function () {
5144 // Parent method
5145 OO.ui.MenuTagMultiselectWidget.parent.prototype.onInputFocus.call( this );
5146
5147 this.menu.toggle( true );
5148 };
5149
5150 /**
5151 * @inheritdoc
5152 */
5153 OO.ui.MenuTagMultiselectWidget.prototype.onInputBlur = function () {
5154 // Parent method
5155 OO.ui.MenuTagMultiselectWidget.parent.prototype.onInputBlur.call( this );
5156
5157 this.menu.toggle( false );
5158 };
5159
5160 /**
5161 * Respond to input change event
5162 */
5163 OO.ui.MenuTagMultiselectWidget.prototype.onInputChange = function () {
5164 this.menu.toggle( true );
5165 this.initializeMenuSelection();
5166 };
5167
5168 /**
5169 * Respond to menu choose event
5170 *
5171 * @param {OO.ui.OptionWidget} menuItem Chosen menu item
5172 */
5173 OO.ui.MenuTagMultiselectWidget.prototype.onMenuChoose = function ( menuItem ) {
5174 // Add tag
5175 this.addTag( menuItem.getData(), menuItem.getLabel() );
5176 if ( this.hasInput && this.clearInputOnChoose ) {
5177 this.input.setValue( '' );
5178 }
5179 };
5180
5181 /**
5182 * Respond to menu toggle event. Reset item highlights on hide.
5183 *
5184 * @param {boolean} isVisible The menu is visible
5185 */
5186 OO.ui.MenuTagMultiselectWidget.prototype.onMenuToggle = function ( isVisible ) {
5187 if ( !isVisible ) {
5188 this.menu.selectItem( null );
5189 this.menu.highlightItem( null );
5190 } else {
5191 this.initializeMenuSelection();
5192 }
5193 };
5194
5195 /**
5196 * @inheritdoc
5197 */
5198 OO.ui.MenuTagMultiselectWidget.prototype.onTagSelect = function ( tagItem ) {
5199 var menuItem = this.menu.findItemFromData( tagItem.getData() );
5200 if ( !this.allowArbitrary ) {
5201 // Override the base behavior from TagMultiselectWidget; the base behavior
5202 // in TagMultiselectWidget is to remove the tag to edit it in the input,
5203 // but in our case, we want to utilize the menu selection behavior, and
5204 // definitely not remove the item.
5205
5206 // If there is an input that is used for filtering, erase the value so we don't filter
5207 if ( this.hasInput && this.menu.filterFromInput ) {
5208 this.input.setValue( '' );
5209 }
5210
5211 // Select the menu item
5212 this.menu.selectItem( menuItem );
5213
5214 this.focus();
5215 } else {
5216 // Use the default
5217 OO.ui.MenuTagMultiselectWidget.parent.prototype.onTagSelect.call( this, tagItem );
5218 }
5219 };
5220
5221 /**
5222 * @inheritdoc
5223 */
5224 OO.ui.MenuTagMultiselectWidget.prototype.setDisabled = function ( isDisabled ) {
5225 // Parent method
5226 OO.ui.MenuTagMultiselectWidget.parent.prototype.setDisabled.call( this, isDisabled );
5227
5228 if ( this.menu ) {
5229 // Protect against calling setDisabled() before the menu was initialized
5230 this.menu.setDisabled( isDisabled );
5231 }
5232 };
5233
5234 /**
5235 * Highlight the first selectable item in the menu, if configured.
5236 *
5237 * @private
5238 * @chainable
5239 */
5240 OO.ui.MenuTagMultiselectWidget.prototype.initializeMenuSelection = function () {
5241 if ( !this.menu.findSelectedItem() ) {
5242 this.menu.highlightItem(
5243 this.allowArbitrary ?
5244 null :
5245 this.menu.findFirstSelectableItem()
5246 );
5247 }
5248 };
5249
5250 /**
5251 * @inheritdoc
5252 */
5253 OO.ui.MenuTagMultiselectWidget.prototype.addTagFromInput = function () {
5254 var val = this.input.getValue(),
5255 // Look for a highlighted item first
5256 // Then look for the element that fits the data
5257 item = this.menu.findHighlightedItem() || this.menu.findItemFromData( val ),
5258 data = item ? item.getData() : val,
5259 isValid = this.isAllowedData( data );
5260
5261 // Override the parent method so we add from the menu
5262 // rather than directly from the input
5263
5264 if ( !val ) {
5265 return;
5266 }
5267
5268 if ( isValid || this.allowDisplayInvalidTags ) {
5269 this.clearInput();
5270 if ( item ) {
5271 this.addTag( data, item.getLabel() );
5272 } else {
5273 this.addTag( val );
5274 }
5275 }
5276 };
5277
5278 /**
5279 * Return the visible items in the menu. This is mainly used for when
5280 * the menu is filtering results.
5281 *
5282 * @return {OO.ui.MenuOptionWidget[]} Visible results
5283 */
5284 OO.ui.MenuTagMultiselectWidget.prototype.getMenuVisibleItems = function () {
5285 return this.menu.getItems().filter( function ( menuItem ) {
5286 return menuItem.isVisible();
5287 } );
5288 };
5289
5290 /**
5291 * Create the menu for this widget. This is in a separate method so that
5292 * child classes can override this without polluting the constructor with
5293 * unnecessary extra objects that will be overidden.
5294 *
5295 * @param {Object} menuConfig Configuration options
5296 * @return {OO.ui.MenuSelectWidget} Menu widget
5297 */
5298 OO.ui.MenuTagMultiselectWidget.prototype.createMenuWidget = function ( menuConfig ) {
5299 return new OO.ui.MenuSelectWidget( menuConfig );
5300 };
5301
5302 /**
5303 * Add options to the menu
5304 *
5305 * @param {Object[]} menuOptions Object defining options
5306 */
5307 OO.ui.MenuTagMultiselectWidget.prototype.addOptions = function ( menuOptions ) {
5308 var widget = this,
5309 items = menuOptions.map( function ( obj ) {
5310 return widget.createMenuOptionWidget( obj.data, obj.label, obj.icon );
5311 } );
5312
5313 this.menu.addItems( items );
5314 };
5315
5316 /**
5317 * Create a menu option widget.
5318 *
5319 * @param {string} data Item data
5320 * @param {string} [label] Item label
5321 * @param {string} [icon] Symbolic icon name
5322 * @return {OO.ui.OptionWidget} Option widget
5323 */
5324 OO.ui.MenuTagMultiselectWidget.prototype.createMenuOptionWidget = function ( data, label, icon ) {
5325 return new OO.ui.MenuOptionWidget( {
5326 data: data,
5327 label: label || data,
5328 icon: icon
5329 } );
5330 };
5331
5332 /**
5333 * Get the menu
5334 *
5335 * @return {OO.ui.MenuSelectWidget} Menu
5336 */
5337 OO.ui.MenuTagMultiselectWidget.prototype.getMenu = function () {
5338 return this.menu;
5339 };
5340
5341 /**
5342 * Get the allowed values list
5343 *
5344 * @return {string[]} Allowed data values
5345 */
5346 OO.ui.MenuTagMultiselectWidget.prototype.getAllowedValues = function () {
5347 var menuDatas = [];
5348 if ( this.menu ) {
5349 // If the parent constructor is calling us, we're not ready yet, this.menu is not set up.
5350 menuDatas = this.menu.getItems().map( function ( menuItem ) {
5351 return menuItem.getData();
5352 } );
5353 }
5354 return this.allowedValues.concat( menuDatas );
5355 };
5356
5357 /**
5358 * SelectFileWidgets allow for selecting files, using the HTML5 File API. These
5359 * widgets can be configured with {@link OO.ui.mixin.IconElement icons} and {@link
5360 * OO.ui.mixin.IndicatorElement indicators}.
5361 * Please see the [OOUI documentation on MediaWiki] [1] for more information and examples.
5362 *
5363 * @example
5364 * // Example of a file select widget
5365 * var selectFile = new OO.ui.SelectFileWidget();
5366 * $( 'body' ).append( selectFile.$element );
5367 *
5368 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets
5369 *
5370 * @class
5371 * @extends OO.ui.Widget
5372 * @mixins OO.ui.mixin.IconElement
5373 * @mixins OO.ui.mixin.IndicatorElement
5374 * @mixins OO.ui.mixin.PendingElement
5375 * @mixins OO.ui.mixin.LabelElement
5376 *
5377 * @constructor
5378 * @param {Object} [config] Configuration options
5379 * @cfg {string[]|null} [accept=null] MIME types to accept. null accepts all types.
5380 * @cfg {string} [placeholder] Text to display when no file is selected.
5381 * @cfg {string} [notsupported] Text to display when file support is missing in the browser.
5382 * @cfg {boolean} [droppable=true] Whether to accept files by drag and drop.
5383 * @cfg {boolean} [showDropTarget=false] Whether to show a drop target. Requires droppable to be true.
5384 * @cfg {number} [thumbnailSizeLimit=20] File size limit in MiB above which to not try and show a
5385 * preview (for performance)
5386 */
5387 OO.ui.SelectFileWidget = function OoUiSelectFileWidget( config ) {
5388 var dragHandler;
5389
5390 // Configuration initialization
5391 config = $.extend( {
5392 accept: null,
5393 placeholder: OO.ui.msg( 'ooui-selectfile-placeholder' ),
5394 notsupported: OO.ui.msg( 'ooui-selectfile-not-supported' ),
5395 droppable: true,
5396 showDropTarget: false,
5397 thumbnailSizeLimit: 20
5398 }, config );
5399
5400 // Parent constructor
5401 OO.ui.SelectFileWidget.parent.call( this, config );
5402
5403 // Mixin constructors
5404 OO.ui.mixin.IconElement.call( this, config );
5405 OO.ui.mixin.IndicatorElement.call( this, config );
5406 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$info } ) );
5407 OO.ui.mixin.LabelElement.call( this, config );
5408
5409 // Properties
5410 this.$info = $( '<span>' );
5411 this.showDropTarget = config.showDropTarget;
5412 this.thumbnailSizeLimit = config.thumbnailSizeLimit;
5413 this.isSupported = this.constructor.static.isSupported();
5414 this.currentFile = null;
5415 if ( Array.isArray( config.accept ) ) {
5416 this.accept = config.accept;
5417 } else {
5418 this.accept = null;
5419 }
5420 this.placeholder = config.placeholder;
5421 this.notsupported = config.notsupported;
5422 this.onFileSelectedHandler = this.onFileSelected.bind( this );
5423
5424 this.selectButton = new OO.ui.ButtonWidget( {
5425 $element: $( '<label>' ),
5426 classes: [ 'oo-ui-selectFileWidget-selectButton' ],
5427 label: OO.ui.msg( 'ooui-selectfile-button-select' ),
5428 disabled: this.disabled || !this.isSupported
5429 } );
5430
5431 this.clearButton = new OO.ui.ButtonWidget( {
5432 classes: [ 'oo-ui-selectFileWidget-clearButton' ],
5433 framed: false,
5434 icon: 'close',
5435 disabled: this.disabled
5436 } );
5437
5438 // Events
5439 this.selectButton.$button.on( {
5440 keypress: this.onKeyPress.bind( this )
5441 } );
5442 this.clearButton.connect( this, {
5443 click: 'onClearClick'
5444 } );
5445 if ( config.droppable ) {
5446 dragHandler = this.onDragEnterOrOver.bind( this );
5447 this.$element.on( {
5448 dragenter: dragHandler,
5449 dragover: dragHandler,
5450 dragleave: this.onDragLeave.bind( this ),
5451 drop: this.onDrop.bind( this )
5452 } );
5453 }
5454
5455 // Initialization
5456 this.addInput();
5457 this.$label.addClass( 'oo-ui-selectFileWidget-label' );
5458 this.$info
5459 .addClass( 'oo-ui-selectFileWidget-info' )
5460 .append( this.$icon, this.$label, this.clearButton.$element, this.$indicator );
5461
5462 if ( config.droppable && config.showDropTarget ) {
5463 this.selectButton.setIcon( 'upload' );
5464 this.$thumbnail = $( '<div>' ).addClass( 'oo-ui-selectFileWidget-thumbnail' );
5465 this.setPendingElement( this.$thumbnail );
5466 this.$element
5467 .addClass( 'oo-ui-selectFileWidget-dropTarget oo-ui-selectFileWidget' )
5468 .on( {
5469 click: this.onDropTargetClick.bind( this )
5470 } )
5471 .append(
5472 this.$thumbnail,
5473 this.$info,
5474 this.selectButton.$element,
5475 $( '<span>' )
5476 .addClass( 'oo-ui-selectFileWidget-dropLabel' )
5477 .text( OO.ui.msg( 'ooui-selectfile-dragdrop-placeholder' ) )
5478 );
5479 } else {
5480 this.$element
5481 .addClass( 'oo-ui-selectFileWidget' )
5482 .append( this.$info, this.selectButton.$element );
5483 }
5484 this.updateUI();
5485 };
5486
5487 /* Setup */
5488
5489 OO.inheritClass( OO.ui.SelectFileWidget, OO.ui.Widget );
5490 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IconElement );
5491 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IndicatorElement );
5492 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.PendingElement );
5493 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.LabelElement );
5494
5495 /* Static Properties */
5496
5497 /**
5498 * Check if this widget is supported
5499 *
5500 * @static
5501 * @return {boolean}
5502 */
5503 OO.ui.SelectFileWidget.static.isSupported = function () {
5504 var $input;
5505 if ( OO.ui.SelectFileWidget.static.isSupportedCache === null ) {
5506 $input = $( '<input>' ).attr( 'type', 'file' );
5507 OO.ui.SelectFileWidget.static.isSupportedCache = $input[ 0 ].files !== undefined;
5508 }
5509 return OO.ui.SelectFileWidget.static.isSupportedCache;
5510 };
5511
5512 OO.ui.SelectFileWidget.static.isSupportedCache = null;
5513
5514 /* Events */
5515
5516 /**
5517 * @event change
5518 *
5519 * A change event is emitted when the on/off state of the toggle changes.
5520 *
5521 * @param {File|null} value New value
5522 */
5523
5524 /* Methods */
5525
5526 /**
5527 * Get the current value of the field
5528 *
5529 * @return {File|null}
5530 */
5531 OO.ui.SelectFileWidget.prototype.getValue = function () {
5532 return this.currentFile;
5533 };
5534
5535 /**
5536 * Set the current value of the field
5537 *
5538 * @param {File|null} file File to select
5539 */
5540 OO.ui.SelectFileWidget.prototype.setValue = function ( file ) {
5541 if ( this.currentFile !== file ) {
5542 this.currentFile = file;
5543 this.updateUI();
5544 this.emit( 'change', this.currentFile );
5545 }
5546 };
5547
5548 /**
5549 * Focus the widget.
5550 *
5551 * Focusses the select file button.
5552 *
5553 * @chainable
5554 * @return {OO.ui.Widget} The widget, for chaining
5555 */
5556 OO.ui.SelectFileWidget.prototype.focus = function () {
5557 this.selectButton.focus();
5558 return this;
5559 };
5560
5561 /**
5562 * Blur the widget.
5563 *
5564 * @chainable
5565 * @return {OO.ui.Widget} The widget, for chaining
5566 */
5567 OO.ui.SelectFileWidget.prototype.blur = function () {
5568 this.selectButton.blur();
5569 return this;
5570 };
5571
5572 /**
5573 * @inheritdoc
5574 */
5575 OO.ui.SelectFileWidget.prototype.simulateLabelClick = function () {
5576 this.focus();
5577 };
5578
5579 /**
5580 * Update the user interface when a file is selected or unselected
5581 *
5582 * @protected
5583 */
5584 OO.ui.SelectFileWidget.prototype.updateUI = function () {
5585 var $label;
5586 if ( !this.isSupported ) {
5587 this.$element.addClass( 'oo-ui-selectFileWidget-notsupported' );
5588 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
5589 this.setLabel( this.notsupported );
5590 } else {
5591 this.$element.addClass( 'oo-ui-selectFileWidget-supported' );
5592 if ( this.currentFile ) {
5593 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
5594 $label = $( [] );
5595 $label = $label.add(
5596 $( '<span>' )
5597 .addClass( 'oo-ui-selectFileWidget-fileName' )
5598 .text( this.currentFile.name )
5599 );
5600 this.setLabel( $label );
5601
5602 if ( this.showDropTarget ) {
5603 this.pushPending();
5604 this.loadAndGetImageUrl().done( function ( url ) {
5605 this.$thumbnail.css( 'background-image', 'url( ' + url + ' )' );
5606 }.bind( this ) ).fail( function () {
5607 this.$thumbnail.append(
5608 new OO.ui.IconWidget( {
5609 icon: 'attachment',
5610 classes: [ 'oo-ui-selectFileWidget-noThumbnail-icon' ]
5611 } ).$element
5612 );
5613 }.bind( this ) ).always( function () {
5614 this.popPending();
5615 }.bind( this ) );
5616 this.$element.off( 'click' );
5617 }
5618 } else {
5619 if ( this.showDropTarget ) {
5620 this.$element.off( 'click' );
5621 this.$element.on( {
5622 click: this.onDropTargetClick.bind( this )
5623 } );
5624 this.$thumbnail
5625 .empty()
5626 .css( 'background-image', '' );
5627 }
5628 this.$element.addClass( 'oo-ui-selectFileWidget-empty' );
5629 this.setLabel( this.placeholder );
5630 }
5631 }
5632 };
5633
5634 /**
5635 * If the selected file is an image, get its URL and load it.
5636 *
5637 * @return {jQuery.Promise} Promise resolves with the image URL after it has loaded
5638 */
5639 OO.ui.SelectFileWidget.prototype.loadAndGetImageUrl = function () {
5640 var deferred = $.Deferred(),
5641 file = this.currentFile,
5642 reader = new FileReader();
5643
5644 if (
5645 file &&
5646 ( OO.getProp( file, 'type' ) || '' ).indexOf( 'image/' ) === 0 &&
5647 file.size < this.thumbnailSizeLimit * 1024 * 1024
5648 ) {
5649 reader.onload = function ( event ) {
5650 var img = document.createElement( 'img' );
5651 img.addEventListener( 'load', function () {
5652 if (
5653 img.naturalWidth === 0 ||
5654 img.naturalHeight === 0 ||
5655 img.complete === false
5656 ) {
5657 deferred.reject();
5658 } else {
5659 deferred.resolve( event.target.result );
5660 }
5661 } );
5662 img.src = event.target.result;
5663 };
5664 reader.readAsDataURL( file );
5665 } else {
5666 deferred.reject();
5667 }
5668
5669 return deferred.promise();
5670 };
5671
5672 /**
5673 * Add the input to the widget
5674 *
5675 * @private
5676 */
5677 OO.ui.SelectFileWidget.prototype.addInput = function () {
5678 if ( this.$input ) {
5679 this.$input.remove();
5680 }
5681
5682 if ( !this.isSupported ) {
5683 this.$input = null;
5684 return;
5685 }
5686
5687 this.$input = $( '<input>' ).attr( 'type', 'file' );
5688 this.$input.on( 'change', this.onFileSelectedHandler );
5689 this.$input.on( 'click', function ( e ) {
5690 // Prevents dropTarget to get clicked which calls
5691 // a click on this input
5692 e.stopPropagation();
5693 } );
5694 this.$input.attr( {
5695 tabindex: -1
5696 } );
5697 if ( this.accept ) {
5698 this.$input.attr( 'accept', this.accept.join( ', ' ) );
5699 }
5700 this.selectButton.$button.append( this.$input );
5701 };
5702
5703 /**
5704 * Determine if we should accept this file
5705 *
5706 * @private
5707 * @param {string} mimeType File MIME type
5708 * @return {boolean}
5709 */
5710 OO.ui.SelectFileWidget.prototype.isAllowedType = function ( mimeType ) {
5711 var i, mimeTest;
5712
5713 if ( !this.accept || !mimeType ) {
5714 return true;
5715 }
5716
5717 for ( i = 0; i < this.accept.length; i++ ) {
5718 mimeTest = this.accept[ i ];
5719 if ( mimeTest === mimeType ) {
5720 return true;
5721 } else if ( mimeTest.substr( -2 ) === '/*' ) {
5722 mimeTest = mimeTest.substr( 0, mimeTest.length - 1 );
5723 if ( mimeType.substr( 0, mimeTest.length ) === mimeTest ) {
5724 return true;
5725 }
5726 }
5727 }
5728
5729 return false;
5730 };
5731
5732 /**
5733 * Handle file selection from the input
5734 *
5735 * @private
5736 * @param {jQuery.Event} e
5737 */
5738 OO.ui.SelectFileWidget.prototype.onFileSelected = function ( e ) {
5739 var file = OO.getProp( e.target, 'files', 0 ) || null;
5740
5741 if ( file && !this.isAllowedType( file.type ) ) {
5742 file = null;
5743 }
5744
5745 this.setValue( file );
5746 this.addInput();
5747 };
5748
5749 /**
5750 * Handle clear button click events.
5751 *
5752 * @private
5753 * @return {undefined/boolean} False to prevent default if event is handled
5754 */
5755 OO.ui.SelectFileWidget.prototype.onClearClick = function () {
5756 this.setValue( null );
5757 return false;
5758 };
5759
5760 /**
5761 * Handle key press events.
5762 *
5763 * @private
5764 * @param {jQuery.Event} e Key press event
5765 * @return {undefined/boolean} False to prevent default if event is handled
5766 */
5767 OO.ui.SelectFileWidget.prototype.onKeyPress = function ( e ) {
5768 if ( this.isSupported && !this.isDisabled() && this.$input &&
5769 ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
5770 ) {
5771 this.$input.click();
5772 return false;
5773 }
5774 };
5775
5776 /**
5777 * Handle drop target click events.
5778 *
5779 * @private
5780 * @param {jQuery.Event} e Key press event
5781 * @return {undefined/boolean} False to prevent default if event is handled
5782 */
5783 OO.ui.SelectFileWidget.prototype.onDropTargetClick = function () {
5784 if ( this.isSupported && !this.isDisabled() && this.$input ) {
5785 this.$input.click();
5786 return false;
5787 }
5788 };
5789
5790 /**
5791 * Handle drag enter and over events
5792 *
5793 * @private
5794 * @param {jQuery.Event} e Drag event
5795 * @return {undefined/boolean} False to prevent default if event is handled
5796 */
5797 OO.ui.SelectFileWidget.prototype.onDragEnterOrOver = function ( e ) {
5798 var itemOrFile,
5799 droppableFile = false,
5800 dt = e.originalEvent.dataTransfer;
5801
5802 e.preventDefault();
5803 e.stopPropagation();
5804
5805 if ( this.isDisabled() || !this.isSupported ) {
5806 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
5807 dt.dropEffect = 'none';
5808 return false;
5809 }
5810
5811 // DataTransferItem and File both have a type property, but in Chrome files
5812 // have no information at this point.
5813 itemOrFile = OO.getProp( dt, 'items', 0 ) || OO.getProp( dt, 'files', 0 );
5814 if ( itemOrFile ) {
5815 if ( this.isAllowedType( itemOrFile.type ) ) {
5816 droppableFile = true;
5817 }
5818 // dt.types is Array-like, but not an Array
5819 } else if ( Array.prototype.indexOf.call( OO.getProp( dt, 'types' ) || [], 'Files' ) !== -1 ) {
5820 // File information is not available at this point for security so just assume
5821 // it is acceptable for now.
5822 // https://bugzilla.mozilla.org/show_bug.cgi?id=640534
5823 droppableFile = true;
5824 }
5825
5826 this.$element.toggleClass( 'oo-ui-selectFileWidget-canDrop', droppableFile );
5827 if ( !droppableFile ) {
5828 dt.dropEffect = 'none';
5829 }
5830
5831 return false;
5832 };
5833
5834 /**
5835 * Handle drag leave events
5836 *
5837 * @private
5838 * @param {jQuery.Event} e Drag event
5839 */
5840 OO.ui.SelectFileWidget.prototype.onDragLeave = function () {
5841 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
5842 };
5843
5844 /**
5845 * Handle drop events
5846 *
5847 * @private
5848 * @param {jQuery.Event} e Drop event
5849 * @return {undefined/boolean} False to prevent default if event is handled
5850 */
5851 OO.ui.SelectFileWidget.prototype.onDrop = function ( e ) {
5852 var file = null,
5853 dt = e.originalEvent.dataTransfer;
5854
5855 e.preventDefault();
5856 e.stopPropagation();
5857 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
5858
5859 if ( this.isDisabled() || !this.isSupported ) {
5860 return false;
5861 }
5862
5863 file = OO.getProp( dt, 'files', 0 );
5864 if ( file && !this.isAllowedType( file.type ) ) {
5865 file = null;
5866 }
5867 if ( file ) {
5868 this.setValue( file );
5869 }
5870
5871 return false;
5872 };
5873
5874 /**
5875 * @inheritdoc
5876 */
5877 OO.ui.SelectFileWidget.prototype.setDisabled = function ( disabled ) {
5878 OO.ui.SelectFileWidget.parent.prototype.setDisabled.call( this, disabled );
5879 if ( this.selectButton ) {
5880 this.selectButton.setDisabled( disabled );
5881 }
5882 if ( this.clearButton ) {
5883 this.clearButton.setDisabled( disabled );
5884 }
5885 return this;
5886 };
5887
5888 /**
5889 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
5890 * and a menu of search results, which is displayed beneath the query
5891 * field. Unlike {@link OO.ui.mixin.LookupElement lookup menus}, search result menus are always visible to the user.
5892 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
5893 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
5894 *
5895 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
5896 * the [OOUI demos][1] for an example.
5897 *
5898 * [1]: https://doc.wikimedia.org/oojs-ui/master/demos/#SearchInputWidget-type-search
5899 *
5900 * @class
5901 * @extends OO.ui.Widget
5902 *
5903 * @constructor
5904 * @param {Object} [config] Configuration options
5905 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
5906 * @cfg {string} [value] Initial query value
5907 */
5908 OO.ui.SearchWidget = function OoUiSearchWidget( config ) {
5909 // Configuration initialization
5910 config = config || {};
5911
5912 // Parent constructor
5913 OO.ui.SearchWidget.parent.call( this, config );
5914
5915 // Properties
5916 this.query = new OO.ui.TextInputWidget( {
5917 icon: 'search',
5918 placeholder: config.placeholder,
5919 value: config.value
5920 } );
5921 this.results = new OO.ui.SelectWidget();
5922 this.$query = $( '<div>' );
5923 this.$results = $( '<div>' );
5924
5925 // Events
5926 this.query.connect( this, {
5927 change: 'onQueryChange',
5928 enter: 'onQueryEnter'
5929 } );
5930 this.query.$input.on( 'keydown', this.onQueryKeydown.bind( this ) );
5931
5932 // Initialization
5933 this.$query
5934 .addClass( 'oo-ui-searchWidget-query' )
5935 .append( this.query.$element );
5936 this.$results
5937 .addClass( 'oo-ui-searchWidget-results' )
5938 .append( this.results.$element );
5939 this.$element
5940 .addClass( 'oo-ui-searchWidget' )
5941 .append( this.$results, this.$query );
5942 };
5943
5944 /* Setup */
5945
5946 OO.inheritClass( OO.ui.SearchWidget, OO.ui.Widget );
5947
5948 /* Methods */
5949
5950 /**
5951 * Handle query key down events.
5952 *
5953 * @private
5954 * @param {jQuery.Event} e Key down event
5955 */
5956 OO.ui.SearchWidget.prototype.onQueryKeydown = function ( e ) {
5957 var highlightedItem, nextItem,
5958 dir = e.which === OO.ui.Keys.DOWN ? 1 : ( e.which === OO.ui.Keys.UP ? -1 : 0 );
5959
5960 if ( dir ) {
5961 highlightedItem = this.results.findHighlightedItem();
5962 if ( !highlightedItem ) {
5963 highlightedItem = this.results.findSelectedItem();
5964 }
5965 nextItem = this.results.findRelativeSelectableItem( highlightedItem, dir );
5966 this.results.highlightItem( nextItem );
5967 nextItem.scrollElementIntoView();
5968 }
5969 };
5970
5971 /**
5972 * Handle select widget select events.
5973 *
5974 * Clears existing results. Subclasses should repopulate items according to new query.
5975 *
5976 * @private
5977 * @param {string} value New value
5978 */
5979 OO.ui.SearchWidget.prototype.onQueryChange = function () {
5980 // Reset
5981 this.results.clearItems();
5982 };
5983
5984 /**
5985 * Handle select widget enter key events.
5986 *
5987 * Chooses highlighted item.
5988 *
5989 * @private
5990 * @param {string} value New value
5991 */
5992 OO.ui.SearchWidget.prototype.onQueryEnter = function () {
5993 var highlightedItem = this.results.findHighlightedItem();
5994 if ( highlightedItem ) {
5995 this.results.chooseItem( highlightedItem );
5996 }
5997 };
5998
5999 /**
6000 * Get the query input.
6001 *
6002 * @return {OO.ui.TextInputWidget} Query input
6003 */
6004 OO.ui.SearchWidget.prototype.getQuery = function () {
6005 return this.query;
6006 };
6007
6008 /**
6009 * Get the search results menu.
6010 *
6011 * @return {OO.ui.SelectWidget} Menu of search results
6012 */
6013 OO.ui.SearchWidget.prototype.getResults = function () {
6014 return this.results;
6015 };
6016
6017 }( OO ) );
6018
6019 //# sourceMappingURL=oojs-ui-widgets.js.map.json