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