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