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