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