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