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