Merge "Add more $wgPoolCounterConf comments"
[mediawiki.git] / resources / lib / oojs-ui / oojs-ui-widgets.js
blobe26e203188a306f91896f3ec4402ae9e40bd92eb
1 /*!
2 * OOjs UI v0.18.4
3 * https://www.mediawiki.org/wiki/OOjs_UI
5 * Copyright 2011–2017 OOjs UI Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
9 * Date: 2017-01-18T00:07:07Z
11 ( function ( OO ) {
13 'use strict';
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.
21 * @abstract
22 * @class
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
28 OO.ui.mixin.DraggableElement = function OoUiMixinDraggableElement( config ) {
29 config = config || {};
31 // Properties
32 this.index = null;
33 this.$handle = config.$handle || this.$element;
34 this.wasHandleUsed = null;
36 // Initialize and events
37 this.$element.addClass( 'oo-ui-draggableElement' )
38 // We make the entire element draggable, not just the handle, so that
39 // the whole element appears to move. wasHandleUsed prevents drags from
40 // starting outside the handle
41 .attr( 'draggable', true )
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' );
52 OO.initClass( OO.ui.mixin.DraggableElement );
54 /* Events */
56 /**
57 * @event dragstart
59 * A dragstart event is emitted when the user clicks and begins dragging an item.
60 * @param {OO.ui.mixin.DraggableElement} item The item the user has clicked and is dragging with the mouse.
63 /**
64 * @event dragend
65 * A dragend event is emitted when the user drags an item and releases the mouse,
66 * thus terminating the drag operation.
69 /**
70 * @event drop
71 * A drop event is emitted when the user drags an item and then releases the mouse button
72 * over a valid target.
75 /* Static Properties */
77 /**
78 * @inheritdoc OO.ui.mixin.ButtonElement
80 OO.ui.mixin.DraggableElement.static.cancelButtonMouseDownEvents = false;
82 /* Methods */
84 /**
85 * Respond to mousedown event.
87 * @private
88 * @param {jQuery.Event} e Drag event
90 OO.ui.mixin.DraggableElement.prototype.onDragMouseDown = function ( e ) {
91 this.wasHandleUsed =
92 // Optimization: if the handle is the whole element this is always true
93 this.$handle[ 0 ] === this.$element[ 0 ] ||
94 // Check the mousedown occurred inside the handle
95 OO.ui.contains( this.$handle[ 0 ], e.target, true );
98 /**
99 * Respond to dragstart event.
101 * @private
102 * @param {jQuery.Event} e Drag event
103 * @return {boolean} False if the event is cancelled
104 * @fires dragstart
106 OO.ui.mixin.DraggableElement.prototype.onDragStart = function ( e ) {
107 var element = this,
108 dataTransfer = e.originalEvent.dataTransfer;
110 if ( !this.wasHandleUsed ) {
111 return false;
114 // Define drop effect
115 dataTransfer.dropEffect = 'none';
116 dataTransfer.effectAllowed = 'move';
117 // Support: Firefox
118 // We must set up a dataTransfer data property or Firefox seems to
119 // ignore the fact the element is draggable.
120 try {
121 dataTransfer.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
122 } catch ( err ) {
123 // The above is only for Firefox. Move on if it fails.
125 // Briefly add a 'clone' class to style the browser's native drag image
126 this.$element.addClass( 'oo-ui-draggableElement-clone' );
127 // Add placeholder class after the browser has rendered the clone
128 setTimeout( function () {
129 element.$element
130 .removeClass( 'oo-ui-draggableElement-clone' )
131 .addClass( 'oo-ui-draggableElement-placeholder' );
132 } );
133 // Emit event
134 this.emit( 'dragstart', this );
135 return true;
139 * Respond to dragend event.
141 * @private
142 * @fires dragend
144 OO.ui.mixin.DraggableElement.prototype.onDragEnd = function () {
145 this.$element.removeClass( 'oo-ui-draggableElement-placeholder' );
146 this.emit( 'dragend' );
150 * Handle drop event.
152 * @private
153 * @param {jQuery.Event} e Drop event
154 * @fires drop
156 OO.ui.mixin.DraggableElement.prototype.onDrop = function ( e ) {
157 e.preventDefault();
158 this.emit( 'drop', e );
162 * In order for drag/drop to work, the dragover event must
163 * return false and stop propogation.
165 * @param {jQuery.Event} e Drag event
166 * @private
168 OO.ui.mixin.DraggableElement.prototype.onDragOver = function ( e ) {
169 e.preventDefault();
173 * Set item index.
174 * Store it in the DOM so we can access from the widget drag event
176 * @private
177 * @param {number} index Item index
179 OO.ui.mixin.DraggableElement.prototype.setIndex = function ( index ) {
180 if ( this.index !== index ) {
181 this.index = index;
182 this.$element.data( 'index', index );
187 * Get item index
189 * @private
190 * @return {number} Item index
192 OO.ui.mixin.DraggableElement.prototype.getIndex = function () {
193 return this.index;
197 * DraggableGroupElement is a mixin class used to create a group element to
198 * contain draggable elements, which are items that can be clicked and dragged by a mouse.
199 * The class is used with OO.ui.mixin.DraggableElement.
201 * @abstract
202 * @class
203 * @mixins OO.ui.mixin.GroupElement
205 * @constructor
206 * @param {Object} [config] Configuration options
207 * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation
208 * should match the layout of the items. Items displayed in a single row
209 * or in several rows should use horizontal orientation. The vertical orientation should only be
210 * used when the items are displayed in a single column. Defaults to 'vertical'
212 OO.ui.mixin.DraggableGroupElement = function OoUiMixinDraggableGroupElement( config ) {
213 // Configuration initialization
214 config = config || {};
216 // Parent constructor
217 OO.ui.mixin.GroupElement.call( this, config );
219 // Properties
220 this.orientation = config.orientation || 'vertical';
221 this.dragItem = null;
222 this.itemKeys = {};
223 this.dir = null;
224 this.itemsOrder = null;
226 // Events
227 this.aggregate( {
228 dragstart: 'itemDragStart',
229 dragend: 'itemDragEnd',
230 drop: 'itemDrop'
231 } );
232 this.connect( this, {
233 itemDragStart: 'onItemDragStart',
234 itemDrop: 'onItemDropOrDragEnd',
235 itemDragEnd: 'onItemDropOrDragEnd'
236 } );
238 // Initialize
239 if ( Array.isArray( config.items ) ) {
240 this.addItems( config.items );
242 this.$element
243 .addClass( 'oo-ui-draggableGroupElement' )
244 .append( this.$status )
245 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation === 'horizontal' );
248 /* Setup */
249 OO.mixinClass( OO.ui.mixin.DraggableGroupElement, OO.ui.mixin.GroupElement );
251 /* Events */
254 * An item has been dragged to a new position, but not yet dropped.
256 * @event drag
257 * @param {OO.ui.mixin.DraggableElement} item Dragged item
258 * @param {number} [newIndex] New index for the item
262 * And item has been dropped at a new position.
264 * @event reorder
265 * @param {OO.ui.mixin.DraggableElement} item Reordered item
266 * @param {number} [newIndex] New index for the item
269 /* Methods */
272 * Respond to item drag start event
274 * @private
275 * @param {OO.ui.mixin.DraggableElement} item Dragged item
277 OO.ui.mixin.DraggableGroupElement.prototype.onItemDragStart = function ( item ) {
278 // Make a shallow copy of this.items so we can re-order it during previews
279 // without affecting the original array.
280 this.itemsOrder = this.items.slice();
281 this.updateIndexes();
282 if ( this.orientation === 'horizontal' ) {
283 // Calculate and cache directionality on drag start - it's a little
284 // expensive and it shouldn't change while dragging.
285 this.dir = this.$element.css( 'direction' );
287 this.setDragItem( item );
291 * Update the index properties of the items
293 OO.ui.mixin.DraggableGroupElement.prototype.updateIndexes = function () {
294 var i, len;
296 // Map the index of each object
297 for ( i = 0, len = this.itemsOrder.length; i < len; i++ ) {
298 this.itemsOrder[ i ].setIndex( i );
303 * Handle drop or dragend event and switch the order of the items accordingly
305 * @private
306 * @param {OO.ui.mixin.DraggableElement} item Dropped item
308 OO.ui.mixin.DraggableGroupElement.prototype.onItemDropOrDragEnd = function () {
309 var targetIndex, originalIndex,
310 item = this.getDragItem();
312 // TODO: Figure out a way to configure a list of legally droppable
313 // elements even if they are not yet in the list
314 if ( item ) {
315 originalIndex = this.items.indexOf( item );
316 // If the item has moved forward, add one to the index to account for the left shift
317 targetIndex = item.getIndex() + ( item.getIndex() > originalIndex ? 1 : 0 );
318 if ( targetIndex !== originalIndex ) {
319 this.reorder( this.getDragItem(), targetIndex );
320 this.emit( 'reorder', this.getDragItem(), targetIndex );
322 this.updateIndexes();
324 this.unsetDragItem();
325 // Return false to prevent propogation
326 return false;
330 * Respond to dragover event
332 * @private
333 * @param {jQuery.Event} e Dragover event
334 * @fires reorder
336 OO.ui.mixin.DraggableGroupElement.prototype.onDragOver = function ( e ) {
337 var overIndex, targetIndex,
338 item = this.getDragItem(),
339 dragItemIndex = item.getIndex();
341 // Get the OptionWidget item we are dragging over
342 overIndex = $( e.target ).closest( '.oo-ui-draggableElement' ).data( 'index' );
344 if ( overIndex !== undefined && overIndex !== dragItemIndex ) {
345 targetIndex = overIndex + ( overIndex > dragItemIndex ? 1 : 0 );
347 if ( targetIndex > 0 ) {
348 this.$group.children().eq( targetIndex - 1 ).after( item.$element );
349 } else {
350 this.$group.prepend( item.$element );
352 // Move item in itemsOrder array
353 this.itemsOrder.splice( overIndex, 0,
354 this.itemsOrder.splice( dragItemIndex, 1 )[ 0 ]
356 this.updateIndexes();
357 this.emit( 'drag', item, targetIndex );
359 // Prevent default
360 e.preventDefault();
364 * Reorder the items in the group
366 * @param {OO.ui.mixin.DraggableElement} item Reordered item
367 * @param {number} newIndex New index
369 OO.ui.mixin.DraggableGroupElement.prototype.reorder = function ( item, newIndex ) {
370 this.addItems( [ item ], newIndex );
374 * Set a dragged item
376 * @param {OO.ui.mixin.DraggableElement} item Dragged item
378 OO.ui.mixin.DraggableGroupElement.prototype.setDragItem = function ( item ) {
379 if ( this.dragItem !== item ) {
380 this.dragItem = item;
381 this.$element.on( 'dragover', this.onDragOver.bind( this ) );
382 this.$element.addClass( 'oo-ui-draggableGroupElement-dragging' );
387 * Unset the current dragged item
389 OO.ui.mixin.DraggableGroupElement.prototype.unsetDragItem = function () {
390 if ( this.dragItem ) {
391 this.dragItem = null;
392 this.$element.off( 'dragover' );
393 this.$element.removeClass( 'oo-ui-draggableGroupElement-dragging' );
398 * Get the item that is currently being dragged.
400 * @return {OO.ui.mixin.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged
402 OO.ui.mixin.DraggableGroupElement.prototype.getDragItem = function () {
403 return this.dragItem;
407 * RequestManager is a mixin that manages the lifecycle of a promise-backed request for a widget, such as
408 * the {@link OO.ui.mixin.LookupElement}.
410 * @class
411 * @abstract
413 * @constructor
415 OO.ui.mixin.RequestManager = function OoUiMixinRequestManager() {
416 this.requestCache = {};
417 this.requestQuery = null;
418 this.requestRequest = null;
421 /* Setup */
423 OO.initClass( OO.ui.mixin.RequestManager );
426 * Get request results for the current query.
428 * @return {jQuery.Promise} Promise object which will be passed response data as the first argument of
429 * the done event. If the request was aborted to make way for a subsequent request, this promise
430 * may not be rejected, depending on what jQuery feels like doing.
432 OO.ui.mixin.RequestManager.prototype.getRequestData = function () {
433 var widget = this,
434 value = this.getRequestQuery(),
435 deferred = $.Deferred(),
436 ourRequest;
438 this.abortRequest();
439 if ( Object.prototype.hasOwnProperty.call( this.requestCache, value ) ) {
440 deferred.resolve( this.requestCache[ value ] );
441 } else {
442 if ( this.pushPending ) {
443 this.pushPending();
445 this.requestQuery = value;
446 ourRequest = this.requestRequest = this.getRequest();
447 ourRequest
448 .always( function () {
449 // We need to pop pending even if this is an old request, otherwise
450 // the widget will remain pending forever.
451 // TODO: this assumes that an aborted request will fail or succeed soon after
452 // being aborted, or at least eventually. It would be nice if we could popPending()
453 // at abort time, but only if we knew that we hadn't already called popPending()
454 // for that request.
455 if ( widget.popPending ) {
456 widget.popPending();
459 .done( function ( response ) {
460 // If this is an old request (and aborting it somehow caused it to still succeed),
461 // ignore its success completely
462 if ( ourRequest === widget.requestRequest ) {
463 widget.requestQuery = null;
464 widget.requestRequest = null;
465 widget.requestCache[ value ] = widget.getRequestCacheDataFromResponse( response );
466 deferred.resolve( widget.requestCache[ value ] );
469 .fail( function () {
470 // If this is an old request (or a request failing because it's being aborted),
471 // ignore its failure completely
472 if ( ourRequest === widget.requestRequest ) {
473 widget.requestQuery = null;
474 widget.requestRequest = null;
475 deferred.reject();
477 } );
479 return deferred.promise();
483 * Abort the currently pending request, if any.
485 * @private
487 OO.ui.mixin.RequestManager.prototype.abortRequest = function () {
488 var oldRequest = this.requestRequest;
489 if ( oldRequest ) {
490 // First unset this.requestRequest to the fail handler will notice
491 // that the request is no longer current
492 this.requestRequest = null;
493 this.requestQuery = null;
494 oldRequest.abort();
499 * Get the query to be made.
501 * @protected
502 * @method
503 * @abstract
504 * @return {string} query to be used
506 OO.ui.mixin.RequestManager.prototype.getRequestQuery = null;
509 * Get a new request object of the current query value.
511 * @protected
512 * @method
513 * @abstract
514 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
516 OO.ui.mixin.RequestManager.prototype.getRequest = null;
519 * Pre-process data returned by the request from #getRequest.
521 * The return value of this function will be cached, and any further queries for the given value
522 * will use the cache rather than doing API requests.
524 * @protected
525 * @method
526 * @abstract
527 * @param {Mixed} response Response from server
528 * @return {Mixed} Cached result data
530 OO.ui.mixin.RequestManager.prototype.getRequestCacheDataFromResponse = null;
533 * LookupElement is a mixin that creates a {@link OO.ui.FloatingMenuSelectWidget menu} of suggested values for
534 * a {@link OO.ui.TextInputWidget text input widget}. Suggested values are based on the characters the user types
535 * into the text input field and, in general, the menu is only displayed when the user types. If a suggested value is chosen
536 * from the lookup menu, that value becomes the value of the input field.
538 * Note that a new menu of suggested items is displayed when a value is chosen from the lookup menu. If this is
539 * not the desired behavior, disable lookup menus with the #setLookupsDisabled method, then set the value, then
540 * re-enable lookups.
542 * See the [OOjs UI demos][1] for an example.
544 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/index.html#widgets-apex-vector-ltr
546 * @class
547 * @abstract
548 * @mixins OO.ui.mixin.RequestManager
550 * @constructor
551 * @param {Object} [config] Configuration options
552 * @cfg {jQuery} [$overlay] Overlay for the lookup menu; defaults to relative positioning
553 * @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element.
554 * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty.
555 * By default, the lookup menu is not generated and displayed until the user begins to type.
556 * @cfg {boolean} [highlightFirst=true] Whether the first lookup result should be highlighted (so, that the user can
557 * take it over into the input with simply pressing return) automatically or not.
559 OO.ui.mixin.LookupElement = function OoUiMixinLookupElement( config ) {
560 // Configuration initialization
561 config = $.extend( { highlightFirst: true }, config );
563 // Mixin constructors
564 OO.ui.mixin.RequestManager.call( this, config );
566 // Properties
567 this.$overlay = config.$overlay || this.$element;
568 this.lookupMenu = new OO.ui.FloatingMenuSelectWidget( {
569 widget: this,
570 input: this,
571 $container: config.$container || this.$element
572 } );
574 this.allowSuggestionsWhenEmpty = config.allowSuggestionsWhenEmpty || false;
576 this.lookupsDisabled = false;
577 this.lookupInputFocused = false;
578 this.lookupHighlightFirstItem = config.highlightFirst;
580 // Events
581 this.$input.on( {
582 focus: this.onLookupInputFocus.bind( this ),
583 blur: this.onLookupInputBlur.bind( this ),
584 mousedown: this.onLookupInputMouseDown.bind( this )
585 } );
586 this.connect( this, { change: 'onLookupInputChange' } );
587 this.lookupMenu.connect( this, {
588 toggle: 'onLookupMenuToggle',
589 choose: 'onLookupMenuItemChoose'
590 } );
592 // Initialization
593 this.$element.addClass( 'oo-ui-lookupElement' );
594 this.lookupMenu.$element.addClass( 'oo-ui-lookupElement-menu' );
595 this.$overlay.append( this.lookupMenu.$element );
598 /* Setup */
600 OO.mixinClass( OO.ui.mixin.LookupElement, OO.ui.mixin.RequestManager );
602 /* Methods */
605 * Handle input focus event.
607 * @protected
608 * @param {jQuery.Event} e Input focus event
610 OO.ui.mixin.LookupElement.prototype.onLookupInputFocus = function () {
611 this.lookupInputFocused = true;
612 this.populateLookupMenu();
616 * Handle input blur event.
618 * @protected
619 * @param {jQuery.Event} e Input blur event
621 OO.ui.mixin.LookupElement.prototype.onLookupInputBlur = function () {
622 this.closeLookupMenu();
623 this.lookupInputFocused = false;
627 * Handle input mouse down event.
629 * @protected
630 * @param {jQuery.Event} e Input mouse down event
632 OO.ui.mixin.LookupElement.prototype.onLookupInputMouseDown = function () {
633 // Only open the menu if the input was already focused.
634 // This way we allow the user to open the menu again after closing it with Esc
635 // by clicking in the input. Opening (and populating) the menu when initially
636 // clicking into the input is handled by the focus handler.
637 if ( this.lookupInputFocused && !this.lookupMenu.isVisible() ) {
638 this.populateLookupMenu();
643 * Handle input change event.
645 * @protected
646 * @param {string} value New input value
648 OO.ui.mixin.LookupElement.prototype.onLookupInputChange = function () {
649 if ( this.lookupInputFocused ) {
650 this.populateLookupMenu();
655 * Handle the lookup menu being shown/hidden.
657 * @protected
658 * @param {boolean} visible Whether the lookup menu is now visible.
660 OO.ui.mixin.LookupElement.prototype.onLookupMenuToggle = function ( visible ) {
661 if ( !visible ) {
662 // When the menu is hidden, abort any active request and clear the menu.
663 // This has to be done here in addition to closeLookupMenu(), because
664 // MenuSelectWidget will close itself when the user presses Esc.
665 this.abortLookupRequest();
666 this.lookupMenu.clearItems();
671 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
673 * @protected
674 * @param {OO.ui.MenuOptionWidget} item Selected item
676 OO.ui.mixin.LookupElement.prototype.onLookupMenuItemChoose = function ( item ) {
677 this.setValue( item.getData() );
681 * Get lookup menu.
683 * @private
684 * @return {OO.ui.FloatingMenuSelectWidget}
686 OO.ui.mixin.LookupElement.prototype.getLookupMenu = function () {
687 return this.lookupMenu;
691 * Disable or re-enable lookups.
693 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
695 * @param {boolean} disabled Disable lookups
697 OO.ui.mixin.LookupElement.prototype.setLookupsDisabled = function ( disabled ) {
698 this.lookupsDisabled = !!disabled;
702 * Open the menu. If there are no entries in the menu, this does nothing.
704 * @private
705 * @chainable
707 OO.ui.mixin.LookupElement.prototype.openLookupMenu = function () {
708 if ( !this.lookupMenu.isEmpty() ) {
709 this.lookupMenu.toggle( true );
711 return this;
715 * Close the menu, empty it, and abort any pending request.
717 * @private
718 * @chainable
720 OO.ui.mixin.LookupElement.prototype.closeLookupMenu = function () {
721 this.lookupMenu.toggle( false );
722 this.abortLookupRequest();
723 this.lookupMenu.clearItems();
724 return this;
728 * Request menu items based on the input's current value, and when they arrive,
729 * populate the menu with these items and show the menu.
731 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
733 * @private
734 * @chainable
736 OO.ui.mixin.LookupElement.prototype.populateLookupMenu = function () {
737 var widget = this,
738 value = this.getValue();
740 if ( this.lookupsDisabled || this.isReadOnly() ) {
741 return;
744 // If the input is empty, clear the menu, unless suggestions when empty are allowed.
745 if ( !this.allowSuggestionsWhenEmpty && value === '' ) {
746 this.closeLookupMenu();
747 // Skip population if there is already a request pending for the current value
748 } else if ( value !== this.lookupQuery ) {
749 this.getLookupMenuItems()
750 .done( function ( items ) {
751 widget.lookupMenu.clearItems();
752 if ( items.length ) {
753 widget.lookupMenu
754 .addItems( items )
755 .toggle( true );
756 widget.initializeLookupMenuSelection();
757 } else {
758 widget.lookupMenu.toggle( false );
761 .fail( function () {
762 widget.lookupMenu.clearItems();
763 } );
766 return this;
770 * Highlight the first selectable item in the menu, if configured.
772 * @private
773 * @chainable
775 OO.ui.mixin.LookupElement.prototype.initializeLookupMenuSelection = function () {
776 if ( this.lookupHighlightFirstItem && !this.lookupMenu.getSelectedItem() ) {
777 this.lookupMenu.highlightItem( this.lookupMenu.getFirstSelectableItem() );
782 * Get lookup menu items for the current query.
784 * @private
785 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
786 * the done event. If the request was aborted to make way for a subsequent request, this promise
787 * will not be rejected: it will remain pending forever.
789 OO.ui.mixin.LookupElement.prototype.getLookupMenuItems = function () {
790 return this.getRequestData().then( function ( data ) {
791 return this.getLookupMenuOptionsFromData( data );
792 }.bind( this ) );
796 * Abort the currently pending lookup request, if any.
798 * @private
800 OO.ui.mixin.LookupElement.prototype.abortLookupRequest = function () {
801 this.abortRequest();
805 * Get a new request object of the current lookup query value.
807 * @protected
808 * @method
809 * @abstract
810 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
812 OO.ui.mixin.LookupElement.prototype.getLookupRequest = null;
815 * Pre-process data returned by the request from #getLookupRequest.
817 * The return value of this function will be cached, and any further queries for the given value
818 * will use the cache rather than doing API requests.
820 * @protected
821 * @method
822 * @abstract
823 * @param {Mixed} response Response from server
824 * @return {Mixed} Cached result data
826 OO.ui.mixin.LookupElement.prototype.getLookupCacheDataFromResponse = null;
829 * Get a list of menu option widgets from the (possibly cached) data returned by
830 * #getLookupCacheDataFromResponse.
832 * @protected
833 * @method
834 * @abstract
835 * @param {Mixed} data Cached result data, usually an array
836 * @return {OO.ui.MenuOptionWidget[]} Menu items
838 OO.ui.mixin.LookupElement.prototype.getLookupMenuOptionsFromData = null;
841 * Set the read-only state of the widget.
843 * This will also disable/enable the lookups functionality.
845 * @param {boolean} readOnly Make input read-only
846 * @chainable
848 OO.ui.mixin.LookupElement.prototype.setReadOnly = function ( readOnly ) {
849 // Parent method
850 // Note: Calling #setReadOnly this way assumes this is mixed into an OO.ui.TextInputWidget
851 OO.ui.TextInputWidget.prototype.setReadOnly.call( this, readOnly );
853 // During construction, #setReadOnly is called before the OO.ui.mixin.LookupElement constructor
854 if ( this.isReadOnly() && this.lookupMenu ) {
855 this.closeLookupMenu();
858 return this;
862 * @inheritdoc OO.ui.mixin.RequestManager
864 OO.ui.mixin.LookupElement.prototype.getRequestQuery = function () {
865 return this.getValue();
869 * @inheritdoc OO.ui.mixin.RequestManager
871 OO.ui.mixin.LookupElement.prototype.getRequest = function () {
872 return this.getLookupRequest();
876 * @inheritdoc OO.ui.mixin.RequestManager
878 OO.ui.mixin.LookupElement.prototype.getRequestCacheDataFromResponse = function ( response ) {
879 return this.getLookupCacheDataFromResponse( response );
883 * CardLayouts are used within {@link OO.ui.IndexLayout index layouts} to create cards that users can select and display
884 * from the index's optional {@link OO.ui.TabSelectWidget tab} navigation. Cards are usually not instantiated directly,
885 * rather extended to include the required content and functionality.
887 * Each card must have a unique symbolic name, which is passed to the constructor. In addition, the card's tab
888 * item is customized (with a label) using the #setupTabItem method. See
889 * {@link OO.ui.IndexLayout IndexLayout} for an example.
891 * @class
892 * @extends OO.ui.PanelLayout
894 * @constructor
895 * @param {string} name Unique symbolic name of card
896 * @param {Object} [config] Configuration options
897 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] Label for card's tab
899 OO.ui.CardLayout = function OoUiCardLayout( name, config ) {
900 // Allow passing positional parameters inside the config object
901 if ( OO.isPlainObject( name ) && config === undefined ) {
902 config = name;
903 name = config.name;
906 // Configuration initialization
907 config = $.extend( { scrollable: true }, config );
909 // Parent constructor
910 OO.ui.CardLayout.parent.call( this, config );
912 // Properties
913 this.name = name;
914 this.label = config.label;
915 this.tabItem = null;
916 this.active = false;
918 // Initialization
919 this.$element.addClass( 'oo-ui-cardLayout' );
922 /* Setup */
924 OO.inheritClass( OO.ui.CardLayout, OO.ui.PanelLayout );
926 /* Events */
929 * An 'active' event is emitted when the card becomes active. Cards become active when they are
930 * shown in a index layout that is configured to display only one card at a time.
932 * @event active
933 * @param {boolean} active Card is active
936 /* Methods */
939 * Get the symbolic name of the card.
941 * @return {string} Symbolic name of card
943 OO.ui.CardLayout.prototype.getName = function () {
944 return this.name;
948 * Check if card is active.
950 * Cards become active when they are shown in a {@link OO.ui.IndexLayout index layout} that is configured to display
951 * only one card at a time. Additional CSS is applied to the card's tab item to reflect the active state.
953 * @return {boolean} Card is active
955 OO.ui.CardLayout.prototype.isActive = function () {
956 return this.active;
960 * Get tab item.
962 * The tab item allows users to access the card from the index's tab
963 * navigation. The tab item itself can be customized (with a label, level, etc.) using the #setupTabItem method.
965 * @return {OO.ui.TabOptionWidget|null} Tab option widget
967 OO.ui.CardLayout.prototype.getTabItem = function () {
968 return this.tabItem;
972 * Set or unset the tab item.
974 * Specify a {@link OO.ui.TabOptionWidget tab option} to set it,
975 * or `null` to clear the tab item. To customize the tab item itself (e.g., to set a label or tab
976 * level), use #setupTabItem instead of this method.
978 * @param {OO.ui.TabOptionWidget|null} tabItem Tab option widget, null to clear
979 * @chainable
981 OO.ui.CardLayout.prototype.setTabItem = function ( tabItem ) {
982 this.tabItem = tabItem || null;
983 if ( tabItem ) {
984 this.setupTabItem();
986 return this;
990 * Set up the tab item.
992 * Use this method to customize the tab item (e.g., to add a label or tab level). To set or unset
993 * the tab item itself (with a {@link OO.ui.TabOptionWidget tab option} or `null`), use
994 * the #setTabItem method instead.
996 * @param {OO.ui.TabOptionWidget} tabItem Tab option widget to set up
997 * @chainable
999 OO.ui.CardLayout.prototype.setupTabItem = function () {
1000 if ( this.label ) {
1001 this.tabItem.setLabel( this.label );
1003 return this;
1007 * Set the card to its 'active' state.
1009 * Cards become active when they are shown in a index layout that is configured to display only one card at a time. Additional
1010 * CSS is applied to the tab item to reflect the card's active state. Outside of the index
1011 * context, setting the active state on a card does nothing.
1013 * @param {boolean} active Card is active
1014 * @fires active
1016 OO.ui.CardLayout.prototype.setActive = function ( active ) {
1017 active = !!active;
1019 if ( active !== this.active ) {
1020 this.active = active;
1021 this.$element.toggleClass( 'oo-ui-cardLayout-active', this.active );
1022 this.emit( 'active', this.active );
1027 * PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display
1028 * from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly,
1029 * rather extended to include the required content and functionality.
1031 * Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline
1032 * item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See
1033 * {@link OO.ui.BookletLayout BookletLayout} for an example.
1035 * @class
1036 * @extends OO.ui.PanelLayout
1038 * @constructor
1039 * @param {string} name Unique symbolic name of page
1040 * @param {Object} [config] Configuration options
1042 OO.ui.PageLayout = function OoUiPageLayout( name, config ) {
1043 // Allow passing positional parameters inside the config object
1044 if ( OO.isPlainObject( name ) && config === undefined ) {
1045 config = name;
1046 name = config.name;
1049 // Configuration initialization
1050 config = $.extend( { scrollable: true }, config );
1052 // Parent constructor
1053 OO.ui.PageLayout.parent.call( this, config );
1055 // Properties
1056 this.name = name;
1057 this.outlineItem = null;
1058 this.active = false;
1060 // Initialization
1061 this.$element.addClass( 'oo-ui-pageLayout' );
1064 /* Setup */
1066 OO.inheritClass( OO.ui.PageLayout, OO.ui.PanelLayout );
1068 /* Events */
1071 * An 'active' event is emitted when the page becomes active. Pages become active when they are
1072 * shown in a booklet layout that is configured to display only one page at a time.
1074 * @event active
1075 * @param {boolean} active Page is active
1078 /* Methods */
1081 * Get the symbolic name of the page.
1083 * @return {string} Symbolic name of page
1085 OO.ui.PageLayout.prototype.getName = function () {
1086 return this.name;
1090 * Check if page is active.
1092 * Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display
1093 * only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state.
1095 * @return {boolean} Page is active
1097 OO.ui.PageLayout.prototype.isActive = function () {
1098 return this.active;
1102 * Get outline item.
1104 * The outline item allows users to access the page from the booklet's outline
1105 * navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method.
1107 * @return {OO.ui.OutlineOptionWidget|null} Outline option widget
1109 OO.ui.PageLayout.prototype.getOutlineItem = function () {
1110 return this.outlineItem;
1114 * Set or unset the outline item.
1116 * Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it,
1117 * or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline
1118 * level), use #setupOutlineItem instead of this method.
1120 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear
1121 * @chainable
1123 OO.ui.PageLayout.prototype.setOutlineItem = function ( outlineItem ) {
1124 this.outlineItem = outlineItem || null;
1125 if ( outlineItem ) {
1126 this.setupOutlineItem();
1128 return this;
1132 * Set up the outline item.
1134 * Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset
1135 * the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use
1136 * the #setOutlineItem method instead.
1138 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up
1139 * @chainable
1141 OO.ui.PageLayout.prototype.setupOutlineItem = function () {
1142 return this;
1146 * Set the page to its 'active' state.
1148 * Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional
1149 * CSS is applied to the outline item to reflect the page's active state. Outside of the booklet
1150 * context, setting the active state on a page does nothing.
1152 * @param {boolean} active Page is active
1153 * @fires active
1155 OO.ui.PageLayout.prototype.setActive = function ( active ) {
1156 active = !!active;
1158 if ( active !== this.active ) {
1159 this.active = active;
1160 this.$element.toggleClass( 'oo-ui-pageLayout-active', active );
1161 this.emit( 'active', this.active );
1166 * StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed
1167 * at a time, though the stack layout can also be configured to show all contained panels, one after another,
1168 * by setting the #continuous option to 'true'.
1170 * @example
1171 * // A stack layout with two panels, configured to be displayed continously
1172 * var myStack = new OO.ui.StackLayout( {
1173 * items: [
1174 * new OO.ui.PanelLayout( {
1175 * $content: $( '<p>Panel One</p>' ),
1176 * padded: true,
1177 * framed: true
1178 * } ),
1179 * new OO.ui.PanelLayout( {
1180 * $content: $( '<p>Panel Two</p>' ),
1181 * padded: true,
1182 * framed: true
1183 * } )
1184 * ],
1185 * continuous: true
1186 * } );
1187 * $( 'body' ).append( myStack.$element );
1189 * @class
1190 * @extends OO.ui.PanelLayout
1191 * @mixins OO.ui.mixin.GroupElement
1193 * @constructor
1194 * @param {Object} [config] Configuration options
1195 * @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time.
1196 * @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout.
1198 OO.ui.StackLayout = function OoUiStackLayout( config ) {
1199 // Configuration initialization
1200 config = $.extend( { scrollable: true }, config );
1202 // Parent constructor
1203 OO.ui.StackLayout.parent.call( this, config );
1205 // Mixin constructors
1206 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
1208 // Properties
1209 this.currentItem = null;
1210 this.continuous = !!config.continuous;
1212 // Initialization
1213 this.$element.addClass( 'oo-ui-stackLayout' );
1214 if ( this.continuous ) {
1215 this.$element.addClass( 'oo-ui-stackLayout-continuous' );
1216 this.$element.on( 'scroll', OO.ui.debounce( this.onScroll.bind( this ), 250 ) );
1218 if ( Array.isArray( config.items ) ) {
1219 this.addItems( config.items );
1223 /* Setup */
1225 OO.inheritClass( OO.ui.StackLayout, OO.ui.PanelLayout );
1226 OO.mixinClass( OO.ui.StackLayout, OO.ui.mixin.GroupElement );
1228 /* Events */
1231 * A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed},
1232 * {@link #clearItems cleared} or {@link #setItem displayed}.
1234 * @event set
1235 * @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown
1239 * When used in continuous mode, this event is emitted when the user scrolls down
1240 * far enough such that currentItem is no longer visible.
1242 * @event visibleItemChange
1243 * @param {OO.ui.PanelLayout} panel The next visible item in the layout
1246 /* Methods */
1249 * Handle scroll events from the layout element
1251 * @param {jQuery.Event} e
1252 * @fires visibleItemChange
1254 OO.ui.StackLayout.prototype.onScroll = function () {
1255 var currentRect,
1256 len = this.items.length,
1257 currentIndex = this.items.indexOf( this.currentItem ),
1258 newIndex = currentIndex,
1259 containerRect = this.$element[ 0 ].getBoundingClientRect();
1261 if ( !containerRect || ( !containerRect.top && !containerRect.bottom ) ) {
1262 // Can't get bounding rect, possibly not attached.
1263 return;
1266 function getRect( item ) {
1267 return item.$element[ 0 ].getBoundingClientRect();
1270 function isVisible( item ) {
1271 var rect = getRect( item );
1272 return rect.bottom > containerRect.top && rect.top < containerRect.bottom;
1275 currentRect = getRect( this.currentItem );
1277 if ( currentRect.bottom < containerRect.top ) {
1278 // Scrolled down past current item
1279 while ( ++newIndex < len ) {
1280 if ( isVisible( this.items[ newIndex ] ) ) {
1281 break;
1284 } else if ( currentRect.top > containerRect.bottom ) {
1285 // Scrolled up past current item
1286 while ( --newIndex >= 0 ) {
1287 if ( isVisible( this.items[ newIndex ] ) ) {
1288 break;
1293 if ( newIndex !== currentIndex ) {
1294 this.emit( 'visibleItemChange', this.items[ newIndex ] );
1299 * Get the current panel.
1301 * @return {OO.ui.Layout|null}
1303 OO.ui.StackLayout.prototype.getCurrentItem = function () {
1304 return this.currentItem;
1308 * Unset the current item.
1310 * @private
1311 * @param {OO.ui.StackLayout} layout
1312 * @fires set
1314 OO.ui.StackLayout.prototype.unsetCurrentItem = function () {
1315 var prevItem = this.currentItem;
1316 if ( prevItem === null ) {
1317 return;
1320 this.currentItem = null;
1321 this.emit( 'set', null );
1325 * Add panel layouts to the stack layout.
1327 * Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different
1328 * insertion point. Adding a panel that is already in the stack will move it to the end of the array or the point specified
1329 * by the index.
1331 * @param {OO.ui.Layout[]} items Panels to add
1332 * @param {number} [index] Index of the insertion point
1333 * @chainable
1335 OO.ui.StackLayout.prototype.addItems = function ( items, index ) {
1336 // Update the visibility
1337 this.updateHiddenState( items, this.currentItem );
1339 // Mixin method
1340 OO.ui.mixin.GroupElement.prototype.addItems.call( this, items, index );
1342 if ( !this.currentItem && items.length ) {
1343 this.setItem( items[ 0 ] );
1346 return this;
1350 * Remove the specified panels from the stack layout.
1352 * Removed panels are detached from the DOM, not removed, so that they may be reused. To remove all panels,
1353 * you may wish to use the #clearItems method instead.
1355 * @param {OO.ui.Layout[]} items Panels to remove
1356 * @chainable
1357 * @fires set
1359 OO.ui.StackLayout.prototype.removeItems = function ( items ) {
1360 // Mixin method
1361 OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items );
1363 if ( items.indexOf( this.currentItem ) !== -1 ) {
1364 if ( this.items.length ) {
1365 this.setItem( this.items[ 0 ] );
1366 } else {
1367 this.unsetCurrentItem();
1371 return this;
1375 * Clear all panels from the stack layout.
1377 * Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only
1378 * a subset of panels, use the #removeItems method.
1380 * @chainable
1381 * @fires set
1383 OO.ui.StackLayout.prototype.clearItems = function () {
1384 this.unsetCurrentItem();
1385 OO.ui.mixin.GroupElement.prototype.clearItems.call( this );
1387 return this;
1391 * Show the specified panel.
1393 * If another panel is currently displayed, it will be hidden.
1395 * @param {OO.ui.Layout} item Panel to show
1396 * @chainable
1397 * @fires set
1399 OO.ui.StackLayout.prototype.setItem = function ( item ) {
1400 if ( item !== this.currentItem ) {
1401 this.updateHiddenState( this.items, item );
1403 if ( this.items.indexOf( item ) !== -1 ) {
1404 this.currentItem = item;
1405 this.emit( 'set', item );
1406 } else {
1407 this.unsetCurrentItem();
1411 return this;
1415 * Update the visibility of all items in case of non-continuous view.
1417 * Ensure all items are hidden except for the selected one.
1418 * This method does nothing when the stack is continuous.
1420 * @private
1421 * @param {OO.ui.Layout[]} items Item list iterate over
1422 * @param {OO.ui.Layout} [selectedItem] Selected item to show
1424 OO.ui.StackLayout.prototype.updateHiddenState = function ( items, selectedItem ) {
1425 var i, len;
1427 if ( !this.continuous ) {
1428 for ( i = 0, len = items.length; i < len; i++ ) {
1429 if ( !selectedItem || selectedItem !== items[ i ] ) {
1430 items[ i ].$element.addClass( 'oo-ui-element-hidden' );
1431 items[ i ].$element.attr( 'aria-hidden', 'true' );
1434 if ( selectedItem ) {
1435 selectedItem.$element.removeClass( 'oo-ui-element-hidden' );
1436 selectedItem.$element.removeAttr( 'aria-hidden' );
1442 * 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)
1443 * and its size is customized with the #menuSize config. The content area will fill all remaining space.
1445 * @example
1446 * var menuLayout = new OO.ui.MenuLayout( {
1447 * position: 'top'
1448 * } ),
1449 * menuPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
1450 * contentPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
1451 * select = new OO.ui.SelectWidget( {
1452 * items: [
1453 * new OO.ui.OptionWidget( {
1454 * data: 'before',
1455 * label: 'Before',
1456 * } ),
1457 * new OO.ui.OptionWidget( {
1458 * data: 'after',
1459 * label: 'After',
1460 * } ),
1461 * new OO.ui.OptionWidget( {
1462 * data: 'top',
1463 * label: 'Top',
1464 * } ),
1465 * new OO.ui.OptionWidget( {
1466 * data: 'bottom',
1467 * label: 'Bottom',
1468 * } )
1470 * } ).on( 'select', function ( item ) {
1471 * menuLayout.setMenuPosition( item.getData() );
1472 * } );
1474 * menuLayout.$menu.append(
1475 * menuPanel.$element.append( '<b>Menu panel</b>', select.$element )
1476 * );
1477 * menuLayout.$content.append(
1478 * contentPanel.$element.append( '<b>Content panel</b>', '<p>Note that the menu is positioned relative to the content panel: top, bottom, after, before.</p>')
1479 * );
1480 * $( 'body' ).append( menuLayout.$element );
1482 * If menu size needs to be overridden, it can be accomplished using CSS similar to the snippet
1483 * below. MenuLayout's CSS will override the appropriate values with 'auto' or '0' to display the
1484 * menu correctly. If `menuPosition` is known beforehand, CSS rules corresponding to other positions
1485 * may be omitted.
1487 * .oo-ui-menuLayout-menu {
1488 * height: 200px;
1489 * width: 200px;
1491 * .oo-ui-menuLayout-content {
1492 * top: 200px;
1493 * left: 200px;
1494 * right: 200px;
1495 * bottom: 200px;
1498 * @class
1499 * @extends OO.ui.Layout
1501 * @constructor
1502 * @param {Object} [config] Configuration options
1503 * @cfg {boolean} [showMenu=true] Show menu
1504 * @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before`
1506 OO.ui.MenuLayout = function OoUiMenuLayout( config ) {
1507 // Configuration initialization
1508 config = $.extend( {
1509 showMenu: true,
1510 menuPosition: 'before'
1511 }, config );
1513 // Parent constructor
1514 OO.ui.MenuLayout.parent.call( this, config );
1517 * Menu DOM node
1519 * @property {jQuery}
1521 this.$menu = $( '<div>' );
1523 * Content DOM node
1525 * @property {jQuery}
1527 this.$content = $( '<div>' );
1529 // Initialization
1530 this.$menu
1531 .addClass( 'oo-ui-menuLayout-menu' );
1532 this.$content.addClass( 'oo-ui-menuLayout-content' );
1533 this.$element
1534 .addClass( 'oo-ui-menuLayout' )
1535 .append( this.$content, this.$menu );
1536 this.setMenuPosition( config.menuPosition );
1537 this.toggleMenu( config.showMenu );
1540 /* Setup */
1542 OO.inheritClass( OO.ui.MenuLayout, OO.ui.Layout );
1544 /* Methods */
1547 * Toggle menu.
1549 * @param {boolean} showMenu Show menu, omit to toggle
1550 * @chainable
1552 OO.ui.MenuLayout.prototype.toggleMenu = function ( showMenu ) {
1553 showMenu = showMenu === undefined ? !this.showMenu : !!showMenu;
1555 if ( this.showMenu !== showMenu ) {
1556 this.showMenu = showMenu;
1557 this.$element
1558 .toggleClass( 'oo-ui-menuLayout-showMenu', this.showMenu )
1559 .toggleClass( 'oo-ui-menuLayout-hideMenu', !this.showMenu );
1560 this.$menu.attr( 'aria-hidden', this.showMenu ? 'false' : 'true' );
1563 return this;
1567 * Check if menu is visible
1569 * @return {boolean} Menu is visible
1571 OO.ui.MenuLayout.prototype.isMenuVisible = function () {
1572 return this.showMenu;
1576 * Set menu position.
1578 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
1579 * @throws {Error} If position value is not supported
1580 * @chainable
1582 OO.ui.MenuLayout.prototype.setMenuPosition = function ( position ) {
1583 this.$element.removeClass( 'oo-ui-menuLayout-' + this.menuPosition );
1584 this.menuPosition = position;
1585 this.$element.addClass( 'oo-ui-menuLayout-' + position );
1587 return this;
1591 * Get menu position.
1593 * @return {string} Menu position
1595 OO.ui.MenuLayout.prototype.getMenuPosition = function () {
1596 return this.menuPosition;
1600 * BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as
1601 * an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate
1602 * through the pages and select which one to display. By default, only one page is
1603 * displayed at a time and the outline is hidden. When a user navigates to a new page,
1604 * the booklet layout automatically focuses on the first focusable element, unless the
1605 * default setting is changed. Optionally, booklets can be configured to show
1606 * {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items.
1608 * @example
1609 * // Example of a BookletLayout that contains two PageLayouts.
1611 * function PageOneLayout( name, config ) {
1612 * PageOneLayout.parent.call( this, name, config );
1613 * this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' );
1615 * OO.inheritClass( PageOneLayout, OO.ui.PageLayout );
1616 * PageOneLayout.prototype.setupOutlineItem = function () {
1617 * this.outlineItem.setLabel( 'Page One' );
1618 * };
1620 * function PageTwoLayout( name, config ) {
1621 * PageTwoLayout.parent.call( this, name, config );
1622 * this.$element.append( '<p>Second page</p>' );
1624 * OO.inheritClass( PageTwoLayout, OO.ui.PageLayout );
1625 * PageTwoLayout.prototype.setupOutlineItem = function () {
1626 * this.outlineItem.setLabel( 'Page Two' );
1627 * };
1629 * var page1 = new PageOneLayout( 'one' ),
1630 * page2 = new PageTwoLayout( 'two' );
1632 * var booklet = new OO.ui.BookletLayout( {
1633 * outlined: true
1634 * } );
1636 * booklet.addPages ( [ page1, page2 ] );
1637 * $( 'body' ).append( booklet.$element );
1639 * @class
1640 * @extends OO.ui.MenuLayout
1642 * @constructor
1643 * @param {Object} [config] Configuration options
1644 * @cfg {boolean} [continuous=false] Show all pages, one after another
1645 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed. Disabled on mobile.
1646 * @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet.
1647 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
1649 OO.ui.BookletLayout = function OoUiBookletLayout( config ) {
1650 // Configuration initialization
1651 config = config || {};
1653 // Parent constructor
1654 OO.ui.BookletLayout.parent.call( this, config );
1656 // Properties
1657 this.currentPageName = null;
1658 this.pages = {};
1659 this.ignoreFocus = false;
1660 this.stackLayout = new OO.ui.StackLayout( { continuous: !!config.continuous } );
1661 this.$content.append( this.stackLayout.$element );
1662 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
1663 this.outlineVisible = false;
1664 this.outlined = !!config.outlined;
1665 if ( this.outlined ) {
1666 this.editable = !!config.editable;
1667 this.outlineControlsWidget = null;
1668 this.outlineSelectWidget = new OO.ui.OutlineSelectWidget();
1669 this.outlinePanel = new OO.ui.PanelLayout( { scrollable: true } );
1670 this.$menu.append( this.outlinePanel.$element );
1671 this.outlineVisible = true;
1672 if ( this.editable ) {
1673 this.outlineControlsWidget = new OO.ui.OutlineControlsWidget(
1674 this.outlineSelectWidget
1678 this.toggleMenu( this.outlined );
1680 // Events
1681 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
1682 if ( this.outlined ) {
1683 this.outlineSelectWidget.connect( this, { select: 'onOutlineSelectWidgetSelect' } );
1684 this.scrolling = false;
1685 this.stackLayout.connect( this, { visibleItemChange: 'onStackLayoutVisibleItemChange' } );
1687 if ( this.autoFocus ) {
1688 // Event 'focus' does not bubble, but 'focusin' does
1689 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
1692 // Initialization
1693 this.$element.addClass( 'oo-ui-bookletLayout' );
1694 this.stackLayout.$element.addClass( 'oo-ui-bookletLayout-stackLayout' );
1695 if ( this.outlined ) {
1696 this.outlinePanel.$element
1697 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
1698 .append( this.outlineSelectWidget.$element );
1699 if ( this.editable ) {
1700 this.outlinePanel.$element
1701 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
1702 .append( this.outlineControlsWidget.$element );
1707 /* Setup */
1709 OO.inheritClass( OO.ui.BookletLayout, OO.ui.MenuLayout );
1711 /* Events */
1714 * A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout.
1715 * @event set
1716 * @param {OO.ui.PageLayout} page Current page
1720 * An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout.
1722 * @event add
1723 * @param {OO.ui.PageLayout[]} page Added pages
1724 * @param {number} index Index pages were added at
1728 * A 'remove' event is emitted when pages are {@link #clearPages cleared} or
1729 * {@link #removePages removed} from the booklet.
1731 * @event remove
1732 * @param {OO.ui.PageLayout[]} pages Removed pages
1735 /* Methods */
1738 * Handle stack layout focus.
1740 * @private
1741 * @param {jQuery.Event} e Focusin event
1743 OO.ui.BookletLayout.prototype.onStackLayoutFocus = function ( e ) {
1744 var name, $target;
1746 // Find the page that an element was focused within
1747 $target = $( e.target ).closest( '.oo-ui-pageLayout' );
1748 for ( name in this.pages ) {
1749 // Check for page match, exclude current page to find only page changes
1750 if ( this.pages[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentPageName ) {
1751 this.setPage( name );
1752 break;
1758 * Handle visibleItemChange events from the stackLayout
1760 * The next visible page is set as the current page by selecting it
1761 * in the outline
1763 * @param {OO.ui.PageLayout} page The next visible page in the layout
1765 OO.ui.BookletLayout.prototype.onStackLayoutVisibleItemChange = function ( page ) {
1766 // Set a flag to so that the resulting call to #onStackLayoutSet doesn't
1767 // try and scroll the item into view again.
1768 this.scrolling = true;
1769 this.outlineSelectWidget.selectItemByData( page.getName() );
1770 this.scrolling = false;
1774 * Handle stack layout set events.
1776 * @private
1777 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
1779 OO.ui.BookletLayout.prototype.onStackLayoutSet = function ( page ) {
1780 var layout = this;
1781 if ( !this.scrolling && page ) {
1782 page.scrollElementIntoView( {
1783 complete: function () {
1784 if ( layout.autoFocus && !OO.ui.isMobile() ) {
1785 layout.focus();
1788 } );
1793 * Focus the first input in the current page.
1795 * If no page is selected, the first selectable page will be selected.
1796 * If the focus is already in an element on the current page, nothing will happen.
1798 * @param {number} [itemIndex] A specific item to focus on
1800 OO.ui.BookletLayout.prototype.focus = function ( itemIndex ) {
1801 var page,
1802 items = this.stackLayout.getItems();
1804 if ( itemIndex !== undefined && items[ itemIndex ] ) {
1805 page = items[ itemIndex ];
1806 } else {
1807 page = this.stackLayout.getCurrentItem();
1810 if ( !page && this.outlined ) {
1811 this.selectFirstSelectablePage();
1812 page = this.stackLayout.getCurrentItem();
1814 if ( !page ) {
1815 return;
1817 // Only change the focus if is not already in the current page
1818 if ( !OO.ui.contains( page.$element[ 0 ], this.getElementDocument().activeElement, true ) ) {
1819 page.focus();
1824 * Find the first focusable input in the booklet layout and focus
1825 * on it.
1827 OO.ui.BookletLayout.prototype.focusFirstFocusable = function () {
1828 OO.ui.findFocusable( this.stackLayout.$element ).focus();
1832 * Handle outline widget select events.
1834 * @private
1835 * @param {OO.ui.OptionWidget|null} item Selected item
1837 OO.ui.BookletLayout.prototype.onOutlineSelectWidgetSelect = function ( item ) {
1838 if ( item ) {
1839 this.setPage( item.getData() );
1844 * Check if booklet has an outline.
1846 * @return {boolean} Booklet has an outline
1848 OO.ui.BookletLayout.prototype.isOutlined = function () {
1849 return this.outlined;
1853 * Check if booklet has editing controls.
1855 * @return {boolean} Booklet is editable
1857 OO.ui.BookletLayout.prototype.isEditable = function () {
1858 return this.editable;
1862 * Check if booklet has a visible outline.
1864 * @return {boolean} Outline is visible
1866 OO.ui.BookletLayout.prototype.isOutlineVisible = function () {
1867 return this.outlined && this.outlineVisible;
1871 * Hide or show the outline.
1873 * @param {boolean} [show] Show outline, omit to invert current state
1874 * @chainable
1876 OO.ui.BookletLayout.prototype.toggleOutline = function ( show ) {
1877 if ( this.outlined ) {
1878 show = show === undefined ? !this.outlineVisible : !!show;
1879 this.outlineVisible = show;
1880 this.toggleMenu( show );
1883 return this;
1887 * Get the page closest to the specified page.
1889 * @param {OO.ui.PageLayout} page Page to use as a reference point
1890 * @return {OO.ui.PageLayout|null} Page closest to the specified page
1892 OO.ui.BookletLayout.prototype.getClosestPage = function ( page ) {
1893 var next, prev, level,
1894 pages = this.stackLayout.getItems(),
1895 index = pages.indexOf( page );
1897 if ( index !== -1 ) {
1898 next = pages[ index + 1 ];
1899 prev = pages[ index - 1 ];
1900 // Prefer adjacent pages at the same level
1901 if ( this.outlined ) {
1902 level = this.outlineSelectWidget.getItemFromData( page.getName() ).getLevel();
1903 if (
1904 prev &&
1905 level === this.outlineSelectWidget.getItemFromData( prev.getName() ).getLevel()
1907 return prev;
1909 if (
1910 next &&
1911 level === this.outlineSelectWidget.getItemFromData( next.getName() ).getLevel()
1913 return next;
1917 return prev || next || null;
1921 * Get the outline widget.
1923 * If the booklet is not outlined, the method will return `null`.
1925 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
1927 OO.ui.BookletLayout.prototype.getOutline = function () {
1928 return this.outlineSelectWidget;
1932 * Get the outline controls widget.
1934 * If the outline is not editable, the method will return `null`.
1936 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
1938 OO.ui.BookletLayout.prototype.getOutlineControls = function () {
1939 return this.outlineControlsWidget;
1943 * Get a page by its symbolic name.
1945 * @param {string} name Symbolic name of page
1946 * @return {OO.ui.PageLayout|undefined} Page, if found
1948 OO.ui.BookletLayout.prototype.getPage = function ( name ) {
1949 return this.pages[ name ];
1953 * Get the current page.
1955 * @return {OO.ui.PageLayout|undefined} Current page, if found
1957 OO.ui.BookletLayout.prototype.getCurrentPage = function () {
1958 var name = this.getCurrentPageName();
1959 return name ? this.getPage( name ) : undefined;
1963 * Get the symbolic name of the current page.
1965 * @return {string|null} Symbolic name of the current page
1967 OO.ui.BookletLayout.prototype.getCurrentPageName = function () {
1968 return this.currentPageName;
1972 * Add pages to the booklet layout
1974 * When pages are added with the same names as existing pages, the existing pages will be
1975 * automatically removed before the new pages are added.
1977 * @param {OO.ui.PageLayout[]} pages Pages to add
1978 * @param {number} index Index of the insertion point
1979 * @fires add
1980 * @chainable
1982 OO.ui.BookletLayout.prototype.addPages = function ( pages, index ) {
1983 var i, len, name, page, item, currentIndex,
1984 stackLayoutPages = this.stackLayout.getItems(),
1985 remove = [],
1986 items = [];
1988 // Remove pages with same names
1989 for ( i = 0, len = pages.length; i < len; i++ ) {
1990 page = pages[ i ];
1991 name = page.getName();
1993 if ( Object.prototype.hasOwnProperty.call( this.pages, name ) ) {
1994 // Correct the insertion index
1995 currentIndex = stackLayoutPages.indexOf( this.pages[ name ] );
1996 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
1997 index--;
1999 remove.push( this.pages[ name ] );
2002 if ( remove.length ) {
2003 this.removePages( remove );
2006 // Add new pages
2007 for ( i = 0, len = pages.length; i < len; i++ ) {
2008 page = pages[ i ];
2009 name = page.getName();
2010 this.pages[ page.getName() ] = page;
2011 if ( this.outlined ) {
2012 item = new OO.ui.OutlineOptionWidget( { data: name } );
2013 page.setOutlineItem( item );
2014 items.push( item );
2018 if ( this.outlined && items.length ) {
2019 this.outlineSelectWidget.addItems( items, index );
2020 this.selectFirstSelectablePage();
2022 this.stackLayout.addItems( pages, index );
2023 this.emit( 'add', pages, index );
2025 return this;
2029 * Remove the specified pages from the booklet layout.
2031 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
2033 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
2034 * @fires remove
2035 * @chainable
2037 OO.ui.BookletLayout.prototype.removePages = function ( pages ) {
2038 var i, len, name, page,
2039 items = [];
2041 for ( i = 0, len = pages.length; i < len; i++ ) {
2042 page = pages[ i ];
2043 name = page.getName();
2044 delete this.pages[ name ];
2045 if ( this.outlined ) {
2046 items.push( this.outlineSelectWidget.getItemFromData( name ) );
2047 page.setOutlineItem( null );
2050 if ( this.outlined && items.length ) {
2051 this.outlineSelectWidget.removeItems( items );
2052 this.selectFirstSelectablePage();
2054 this.stackLayout.removeItems( pages );
2055 this.emit( 'remove', pages );
2057 return this;
2061 * Clear all pages from the booklet layout.
2063 * To remove only a subset of pages from the booklet, use the #removePages method.
2065 * @fires remove
2066 * @chainable
2068 OO.ui.BookletLayout.prototype.clearPages = function () {
2069 var i, len,
2070 pages = this.stackLayout.getItems();
2072 this.pages = {};
2073 this.currentPageName = null;
2074 if ( this.outlined ) {
2075 this.outlineSelectWidget.clearItems();
2076 for ( i = 0, len = pages.length; i < len; i++ ) {
2077 pages[ i ].setOutlineItem( null );
2080 this.stackLayout.clearItems();
2082 this.emit( 'remove', pages );
2084 return this;
2088 * Set the current page by symbolic name.
2090 * @fires set
2091 * @param {string} name Symbolic name of page
2093 OO.ui.BookletLayout.prototype.setPage = function ( name ) {
2094 var selectedItem,
2095 $focused,
2096 page = this.pages[ name ],
2097 previousPage = this.currentPageName && this.pages[ this.currentPageName ];
2099 if ( name !== this.currentPageName ) {
2100 if ( this.outlined ) {
2101 selectedItem = this.outlineSelectWidget.getSelectedItem();
2102 if ( selectedItem && selectedItem.getData() !== name ) {
2103 this.outlineSelectWidget.selectItemByData( name );
2106 if ( page ) {
2107 if ( previousPage ) {
2108 previousPage.setActive( false );
2109 // Blur anything focused if the next page doesn't have anything focusable.
2110 // This is not needed if the next page has something focusable (because once it is focused
2111 // this blur happens automatically). If the layout is non-continuous, this check is
2112 // meaningless because the next page is not visible yet and thus can't hold focus.
2113 if (
2114 this.autoFocus &&
2115 !OO.ui.isMobile() &&
2116 this.stackLayout.continuous &&
2117 OO.ui.findFocusable( page.$element ).length !== 0
2119 $focused = previousPage.$element.find( ':focus' );
2120 if ( $focused.length ) {
2121 $focused[ 0 ].blur();
2125 this.currentPageName = name;
2126 page.setActive( true );
2127 this.stackLayout.setItem( page );
2128 if ( !this.stackLayout.continuous && previousPage ) {
2129 // This should not be necessary, since any inputs on the previous page should have been
2130 // blurred when it was hidden, but browsers are not very consistent about this.
2131 $focused = previousPage.$element.find( ':focus' );
2132 if ( $focused.length ) {
2133 $focused[ 0 ].blur();
2136 this.emit( 'set', page );
2142 * Select the first selectable page.
2144 * @chainable
2146 OO.ui.BookletLayout.prototype.selectFirstSelectablePage = function () {
2147 if ( !this.outlineSelectWidget.getSelectedItem() ) {
2148 this.outlineSelectWidget.selectItem( this.outlineSelectWidget.getFirstSelectableItem() );
2151 return this;
2155 * IndexLayouts contain {@link OO.ui.CardLayout card layouts} as well as
2156 * {@link OO.ui.TabSelectWidget tabs} that allow users to easily navigate through the cards and
2157 * select which one to display. By default, only one card is displayed at a time. When a user
2158 * navigates to a new card, the index layout automatically focuses on the first focusable element,
2159 * unless the default setting is changed.
2161 * TODO: This class is similar to BookletLayout, we may want to refactor to reduce duplication
2163 * @example
2164 * // Example of a IndexLayout that contains two CardLayouts.
2166 * function CardOneLayout( name, config ) {
2167 * CardOneLayout.parent.call( this, name, config );
2168 * this.$element.append( '<p>First card</p>' );
2170 * OO.inheritClass( CardOneLayout, OO.ui.CardLayout );
2171 * CardOneLayout.prototype.setupTabItem = function () {
2172 * this.tabItem.setLabel( 'Card one' );
2173 * };
2175 * var card1 = new CardOneLayout( 'one' ),
2176 * card2 = new OO.ui.CardLayout( 'two', { label: 'Card two' } );
2178 * card2.$element.append( '<p>Second card</p>' );
2180 * var index = new OO.ui.IndexLayout();
2182 * index.addCards ( [ card1, card2 ] );
2183 * $( 'body' ).append( index.$element );
2185 * @class
2186 * @extends OO.ui.MenuLayout
2188 * @constructor
2189 * @param {Object} [config] Configuration options
2190 * @cfg {boolean} [continuous=false] Show all cards, one after another
2191 * @cfg {boolean} [expanded=true] Expand the content panel to fill the entire parent element.
2192 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new card is displayed. Disabled on mobile.
2194 OO.ui.IndexLayout = function OoUiIndexLayout( config ) {
2195 // Configuration initialization
2196 config = $.extend( {}, config, { menuPosition: 'top' } );
2198 // Parent constructor
2199 OO.ui.IndexLayout.parent.call( this, config );
2201 // Properties
2202 this.currentCardName = null;
2203 this.cards = {};
2204 this.ignoreFocus = false;
2205 this.stackLayout = new OO.ui.StackLayout( {
2206 continuous: !!config.continuous,
2207 expanded: config.expanded
2208 } );
2209 this.$content.append( this.stackLayout.$element );
2210 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
2212 this.tabSelectWidget = new OO.ui.TabSelectWidget();
2213 this.tabPanel = new OO.ui.PanelLayout();
2214 this.$menu.append( this.tabPanel.$element );
2216 this.toggleMenu( true );
2218 // Events
2219 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
2220 this.tabSelectWidget.connect( this, { select: 'onTabSelectWidgetSelect' } );
2221 if ( this.autoFocus ) {
2222 // Event 'focus' does not bubble, but 'focusin' does
2223 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
2226 // Initialization
2227 this.$element.addClass( 'oo-ui-indexLayout' );
2228 this.stackLayout.$element.addClass( 'oo-ui-indexLayout-stackLayout' );
2229 this.tabPanel.$element
2230 .addClass( 'oo-ui-indexLayout-tabPanel' )
2231 .append( this.tabSelectWidget.$element );
2234 /* Setup */
2236 OO.inheritClass( OO.ui.IndexLayout, OO.ui.MenuLayout );
2238 /* Events */
2241 * A 'set' event is emitted when a card is {@link #setCard set} to be displayed by the index layout.
2242 * @event set
2243 * @param {OO.ui.CardLayout} card Current card
2247 * An 'add' event is emitted when cards are {@link #addCards added} to the index layout.
2249 * @event add
2250 * @param {OO.ui.CardLayout[]} card Added cards
2251 * @param {number} index Index cards were added at
2255 * A 'remove' event is emitted when cards are {@link #clearCards cleared} or
2256 * {@link #removeCards removed} from the index.
2258 * @event remove
2259 * @param {OO.ui.CardLayout[]} cards Removed cards
2262 /* Methods */
2265 * Handle stack layout focus.
2267 * @private
2268 * @param {jQuery.Event} e Focusin event
2270 OO.ui.IndexLayout.prototype.onStackLayoutFocus = function ( e ) {
2271 var name, $target;
2273 // Find the card that an element was focused within
2274 $target = $( e.target ).closest( '.oo-ui-cardLayout' );
2275 for ( name in this.cards ) {
2276 // Check for card match, exclude current card to find only card changes
2277 if ( this.cards[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentCardName ) {
2278 this.setCard( name );
2279 break;
2285 * Handle stack layout set events.
2287 * @private
2288 * @param {OO.ui.PanelLayout|null} card The card panel that is now the current panel
2290 OO.ui.IndexLayout.prototype.onStackLayoutSet = function ( card ) {
2291 var layout = this;
2292 if ( card ) {
2293 card.scrollElementIntoView( {
2294 complete: function () {
2295 if ( layout.autoFocus && !OO.ui.isMobile() ) {
2296 layout.focus();
2299 } );
2304 * Focus the first input in the current card.
2306 * If no card is selected, the first selectable card will be selected.
2307 * If the focus is already in an element on the current card, nothing will happen.
2309 * @param {number} [itemIndex] A specific item to focus on
2311 OO.ui.IndexLayout.prototype.focus = function ( itemIndex ) {
2312 var card,
2313 items = this.stackLayout.getItems();
2315 if ( itemIndex !== undefined && items[ itemIndex ] ) {
2316 card = items[ itemIndex ];
2317 } else {
2318 card = this.stackLayout.getCurrentItem();
2321 if ( !card ) {
2322 this.selectFirstSelectableCard();
2323 card = this.stackLayout.getCurrentItem();
2325 if ( !card ) {
2326 return;
2328 // Only change the focus if is not already in the current page
2329 if ( !OO.ui.contains( card.$element[ 0 ], this.getElementDocument().activeElement, true ) ) {
2330 card.focus();
2335 * Find the first focusable input in the index layout and focus
2336 * on it.
2338 OO.ui.IndexLayout.prototype.focusFirstFocusable = function () {
2339 OO.ui.findFocusable( this.stackLayout.$element ).focus();
2343 * Handle tab widget select events.
2345 * @private
2346 * @param {OO.ui.OptionWidget|null} item Selected item
2348 OO.ui.IndexLayout.prototype.onTabSelectWidgetSelect = function ( item ) {
2349 if ( item ) {
2350 this.setCard( item.getData() );
2355 * Get the card closest to the specified card.
2357 * @param {OO.ui.CardLayout} card Card to use as a reference point
2358 * @return {OO.ui.CardLayout|null} Card closest to the specified card
2360 OO.ui.IndexLayout.prototype.getClosestCard = function ( card ) {
2361 var next, prev, level,
2362 cards = this.stackLayout.getItems(),
2363 index = cards.indexOf( card );
2365 if ( index !== -1 ) {
2366 next = cards[ index + 1 ];
2367 prev = cards[ index - 1 ];
2368 // Prefer adjacent cards at the same level
2369 level = this.tabSelectWidget.getItemFromData( card.getName() ).getLevel();
2370 if (
2371 prev &&
2372 level === this.tabSelectWidget.getItemFromData( prev.getName() ).getLevel()
2374 return prev;
2376 if (
2377 next &&
2378 level === this.tabSelectWidget.getItemFromData( next.getName() ).getLevel()
2380 return next;
2383 return prev || next || null;
2387 * Get the tabs widget.
2389 * @return {OO.ui.TabSelectWidget} Tabs widget
2391 OO.ui.IndexLayout.prototype.getTabs = function () {
2392 return this.tabSelectWidget;
2396 * Get a card by its symbolic name.
2398 * @param {string} name Symbolic name of card
2399 * @return {OO.ui.CardLayout|undefined} Card, if found
2401 OO.ui.IndexLayout.prototype.getCard = function ( name ) {
2402 return this.cards[ name ];
2406 * Get the current card.
2408 * @return {OO.ui.CardLayout|undefined} Current card, if found
2410 OO.ui.IndexLayout.prototype.getCurrentCard = function () {
2411 var name = this.getCurrentCardName();
2412 return name ? this.getCard( name ) : undefined;
2416 * Get the symbolic name of the current card.
2418 * @return {string|null} Symbolic name of the current card
2420 OO.ui.IndexLayout.prototype.getCurrentCardName = function () {
2421 return this.currentCardName;
2425 * Add cards to the index layout
2427 * When cards are added with the same names as existing cards, the existing cards will be
2428 * automatically removed before the new cards are added.
2430 * @param {OO.ui.CardLayout[]} cards Cards to add
2431 * @param {number} index Index of the insertion point
2432 * @fires add
2433 * @chainable
2435 OO.ui.IndexLayout.prototype.addCards = function ( cards, index ) {
2436 var i, len, name, card, item, currentIndex,
2437 stackLayoutCards = this.stackLayout.getItems(),
2438 remove = [],
2439 items = [];
2441 // Remove cards with same names
2442 for ( i = 0, len = cards.length; i < len; i++ ) {
2443 card = cards[ i ];
2444 name = card.getName();
2446 if ( Object.prototype.hasOwnProperty.call( this.cards, name ) ) {
2447 // Correct the insertion index
2448 currentIndex = stackLayoutCards.indexOf( this.cards[ name ] );
2449 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
2450 index--;
2452 remove.push( this.cards[ name ] );
2455 if ( remove.length ) {
2456 this.removeCards( remove );
2459 // Add new cards
2460 for ( i = 0, len = cards.length; i < len; i++ ) {
2461 card = cards[ i ];
2462 name = card.getName();
2463 this.cards[ card.getName() ] = card;
2464 item = new OO.ui.TabOptionWidget( { data: name } );
2465 card.setTabItem( item );
2466 items.push( item );
2469 if ( items.length ) {
2470 this.tabSelectWidget.addItems( items, index );
2471 this.selectFirstSelectableCard();
2473 this.stackLayout.addItems( cards, index );
2474 this.emit( 'add', cards, index );
2476 return this;
2480 * Remove the specified cards from the index layout.
2482 * To remove all cards from the index, you may wish to use the #clearCards method instead.
2484 * @param {OO.ui.CardLayout[]} cards An array of cards to remove
2485 * @fires remove
2486 * @chainable
2488 OO.ui.IndexLayout.prototype.removeCards = function ( cards ) {
2489 var i, len, name, card,
2490 items = [];
2492 for ( i = 0, len = cards.length; i < len; i++ ) {
2493 card = cards[ i ];
2494 name = card.getName();
2495 delete this.cards[ name ];
2496 items.push( this.tabSelectWidget.getItemFromData( name ) );
2497 card.setTabItem( null );
2499 if ( items.length ) {
2500 this.tabSelectWidget.removeItems( items );
2501 this.selectFirstSelectableCard();
2503 this.stackLayout.removeItems( cards );
2504 this.emit( 'remove', cards );
2506 return this;
2510 * Clear all cards from the index layout.
2512 * To remove only a subset of cards from the index, use the #removeCards method.
2514 * @fires remove
2515 * @chainable
2517 OO.ui.IndexLayout.prototype.clearCards = function () {
2518 var i, len,
2519 cards = this.stackLayout.getItems();
2521 this.cards = {};
2522 this.currentCardName = null;
2523 this.tabSelectWidget.clearItems();
2524 for ( i = 0, len = cards.length; i < len; i++ ) {
2525 cards[ i ].setTabItem( null );
2527 this.stackLayout.clearItems();
2529 this.emit( 'remove', cards );
2531 return this;
2535 * Set the current card by symbolic name.
2537 * @fires set
2538 * @param {string} name Symbolic name of card
2540 OO.ui.IndexLayout.prototype.setCard = function ( name ) {
2541 var selectedItem,
2542 $focused,
2543 card = this.cards[ name ],
2544 previousCard = this.currentCardName && this.cards[ this.currentCardName ];
2546 if ( name !== this.currentCardName ) {
2547 selectedItem = this.tabSelectWidget.getSelectedItem();
2548 if ( selectedItem && selectedItem.getData() !== name ) {
2549 this.tabSelectWidget.selectItemByData( name );
2551 if ( card ) {
2552 if ( previousCard ) {
2553 previousCard.setActive( false );
2554 // Blur anything focused if the next card doesn't have anything focusable.
2555 // This is not needed if the next card has something focusable (because once it is focused
2556 // this blur happens automatically). If the layout is non-continuous, this check is
2557 // meaningless because the next card is not visible yet and thus can't hold focus.
2558 if (
2559 this.autoFocus &&
2560 !OO.ui.isMobile() &&
2561 this.stackLayout.continuous &&
2562 OO.ui.findFocusable( card.$element ).length !== 0
2564 $focused = previousCard.$element.find( ':focus' );
2565 if ( $focused.length ) {
2566 $focused[ 0 ].blur();
2570 this.currentCardName = name;
2571 card.setActive( true );
2572 this.stackLayout.setItem( card );
2573 if ( !this.stackLayout.continuous && previousCard ) {
2574 // This should not be necessary, since any inputs on the previous card should have been
2575 // blurred when it was hidden, but browsers are not very consistent about this.
2576 $focused = previousCard.$element.find( ':focus' );
2577 if ( $focused.length ) {
2578 $focused[ 0 ].blur();
2581 this.emit( 'set', card );
2587 * Select the first selectable card.
2589 * @chainable
2591 OO.ui.IndexLayout.prototype.selectFirstSelectableCard = function () {
2592 if ( !this.tabSelectWidget.getSelectedItem() ) {
2593 this.tabSelectWidget.selectItem( this.tabSelectWidget.getFirstSelectableItem() );
2596 return this;
2600 * ToggleWidget implements basic behavior of widgets with an on/off state.
2601 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
2603 * @abstract
2604 * @class
2605 * @extends OO.ui.Widget
2607 * @constructor
2608 * @param {Object} [config] Configuration options
2609 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
2610 * By default, the toggle is in the 'off' state.
2612 OO.ui.ToggleWidget = function OoUiToggleWidget( config ) {
2613 // Configuration initialization
2614 config = config || {};
2616 // Parent constructor
2617 OO.ui.ToggleWidget.parent.call( this, config );
2619 // Properties
2620 this.value = null;
2622 // Initialization
2623 this.$element.addClass( 'oo-ui-toggleWidget' );
2624 this.setValue( !!config.value );
2627 /* Setup */
2629 OO.inheritClass( OO.ui.ToggleWidget, OO.ui.Widget );
2631 /* Events */
2634 * @event change
2636 * A change event is emitted when the on/off state of the toggle changes.
2638 * @param {boolean} value Value representing the new state of the toggle
2641 /* Methods */
2644 * Get the value representing the toggle’s state.
2646 * @return {boolean} The on/off state of the toggle
2648 OO.ui.ToggleWidget.prototype.getValue = function () {
2649 return this.value;
2653 * Set the state of the toggle: `true` for 'on', `false' for 'off'.
2655 * @param {boolean} value The state of the toggle
2656 * @fires change
2657 * @chainable
2659 OO.ui.ToggleWidget.prototype.setValue = function ( value ) {
2660 value = !!value;
2661 if ( this.value !== value ) {
2662 this.value = value;
2663 this.emit( 'change', value );
2664 this.$element.toggleClass( 'oo-ui-toggleWidget-on', value );
2665 this.$element.toggleClass( 'oo-ui-toggleWidget-off', !value );
2666 this.$element.attr( 'aria-checked', value.toString() );
2668 return this;
2672 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
2673 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
2674 * configured with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators},
2675 * {@link OO.ui.mixin.TitledElement titles}, {@link OO.ui.mixin.FlaggedElement styling flags},
2676 * and {@link OO.ui.mixin.LabelElement labels}. Please see
2677 * the [OOjs UI documentation][1] on MediaWiki for more information.
2679 * @example
2680 * // Toggle buttons in the 'off' and 'on' state.
2681 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
2682 * label: 'Toggle Button off'
2683 * } );
2684 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
2685 * label: 'Toggle Button on',
2686 * value: true
2687 * } );
2688 * // Append the buttons to the DOM.
2689 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
2691 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
2693 * @class
2694 * @extends OO.ui.ToggleWidget
2695 * @mixins OO.ui.mixin.ButtonElement
2696 * @mixins OO.ui.mixin.IconElement
2697 * @mixins OO.ui.mixin.IndicatorElement
2698 * @mixins OO.ui.mixin.LabelElement
2699 * @mixins OO.ui.mixin.TitledElement
2700 * @mixins OO.ui.mixin.FlaggedElement
2701 * @mixins OO.ui.mixin.TabIndexedElement
2703 * @constructor
2704 * @param {Object} [config] Configuration options
2705 * @cfg {boolean} [value=false] The toggle button’s initial on/off
2706 * state. By default, the button is in the 'off' state.
2708 OO.ui.ToggleButtonWidget = function OoUiToggleButtonWidget( config ) {
2709 // Configuration initialization
2710 config = config || {};
2712 // Parent constructor
2713 OO.ui.ToggleButtonWidget.parent.call( this, config );
2715 // Mixin constructors
2716 OO.ui.mixin.ButtonElement.call( this, $.extend( {}, config, { active: this.active } ) );
2717 OO.ui.mixin.IconElement.call( this, config );
2718 OO.ui.mixin.IndicatorElement.call( this, config );
2719 OO.ui.mixin.LabelElement.call( this, config );
2720 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
2721 OO.ui.mixin.FlaggedElement.call( this, config );
2722 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
2724 // Events
2725 this.connect( this, { click: 'onAction' } );
2727 // Initialization
2728 this.$button.append( this.$icon, this.$label, this.$indicator );
2729 this.$element
2730 .addClass( 'oo-ui-toggleButtonWidget' )
2731 .append( this.$button );
2734 /* Setup */
2736 OO.inheritClass( OO.ui.ToggleButtonWidget, OO.ui.ToggleWidget );
2737 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.ButtonElement );
2738 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IconElement );
2739 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IndicatorElement );
2740 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.LabelElement );
2741 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TitledElement );
2742 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.FlaggedElement );
2743 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TabIndexedElement );
2745 /* Methods */
2748 * Handle the button action being triggered.
2750 * @private
2752 OO.ui.ToggleButtonWidget.prototype.onAction = function () {
2753 this.setValue( !this.value );
2757 * @inheritdoc
2759 OO.ui.ToggleButtonWidget.prototype.setValue = function ( value ) {
2760 value = !!value;
2761 if ( value !== this.value ) {
2762 // Might be called from parent constructor before ButtonElement constructor
2763 if ( this.$button ) {
2764 this.$button.attr( 'aria-pressed', value.toString() );
2766 this.setActive( value );
2769 // Parent method
2770 OO.ui.ToggleButtonWidget.parent.prototype.setValue.call( this, value );
2772 return this;
2776 * @inheritdoc
2778 OO.ui.ToggleButtonWidget.prototype.setButtonElement = function ( $button ) {
2779 if ( this.$button ) {
2780 this.$button.removeAttr( 'aria-pressed' );
2782 OO.ui.mixin.ButtonElement.prototype.setButtonElement.call( this, $button );
2783 this.$button.attr( 'aria-pressed', this.value.toString() );
2787 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
2788 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
2789 * visually by a slider in the leftmost position.
2791 * @example
2792 * // Toggle switches in the 'off' and 'on' position.
2793 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
2794 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
2795 * value: true
2796 * } );
2798 * // Create a FieldsetLayout to layout and label switches
2799 * var fieldset = new OO.ui.FieldsetLayout( {
2800 * label: 'Toggle switches'
2801 * } );
2802 * fieldset.addItems( [
2803 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
2804 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
2805 * ] );
2806 * $( 'body' ).append( fieldset.$element );
2808 * @class
2809 * @extends OO.ui.ToggleWidget
2810 * @mixins OO.ui.mixin.TabIndexedElement
2812 * @constructor
2813 * @param {Object} [config] Configuration options
2814 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
2815 * By default, the toggle switch is in the 'off' position.
2817 OO.ui.ToggleSwitchWidget = function OoUiToggleSwitchWidget( config ) {
2818 // Parent constructor
2819 OO.ui.ToggleSwitchWidget.parent.call( this, config );
2821 // Mixin constructors
2822 OO.ui.mixin.TabIndexedElement.call( this, config );
2824 // Properties
2825 this.dragging = false;
2826 this.dragStart = null;
2827 this.sliding = false;
2828 this.$glow = $( '<span>' );
2829 this.$grip = $( '<span>' );
2831 // Events
2832 this.$element.on( {
2833 click: this.onClick.bind( this ),
2834 keypress: this.onKeyPress.bind( this )
2835 } );
2837 // Initialization
2838 this.$glow.addClass( 'oo-ui-toggleSwitchWidget-glow' );
2839 this.$grip.addClass( 'oo-ui-toggleSwitchWidget-grip' );
2840 this.$element
2841 .addClass( 'oo-ui-toggleSwitchWidget' )
2842 .attr( 'role', 'checkbox' )
2843 .append( this.$glow, this.$grip );
2846 /* Setup */
2848 OO.inheritClass( OO.ui.ToggleSwitchWidget, OO.ui.ToggleWidget );
2849 OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.mixin.TabIndexedElement );
2851 /* Methods */
2854 * Handle mouse click events.
2856 * @private
2857 * @param {jQuery.Event} e Mouse click event
2859 OO.ui.ToggleSwitchWidget.prototype.onClick = function ( e ) {
2860 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
2861 this.setValue( !this.value );
2863 return false;
2867 * Handle key press events.
2869 * @private
2870 * @param {jQuery.Event} e Key press event
2872 OO.ui.ToggleSwitchWidget.prototype.onKeyPress = function ( e ) {
2873 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
2874 this.setValue( !this.value );
2875 return false;
2880 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
2881 * Controls include moving items up and down, removing items, and adding different kinds of items.
2883 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
2885 * @class
2886 * @extends OO.ui.Widget
2887 * @mixins OO.ui.mixin.GroupElement
2888 * @mixins OO.ui.mixin.IconElement
2890 * @constructor
2891 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
2892 * @param {Object} [config] Configuration options
2893 * @cfg {Object} [abilities] List of abilties
2894 * @cfg {boolean} [abilities.move=true] Allow moving movable items
2895 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
2897 OO.ui.OutlineControlsWidget = function OoUiOutlineControlsWidget( outline, config ) {
2898 // Allow passing positional parameters inside the config object
2899 if ( OO.isPlainObject( outline ) && config === undefined ) {
2900 config = outline;
2901 outline = config.outline;
2904 // Configuration initialization
2905 config = $.extend( { icon: 'add' }, config );
2907 // Parent constructor
2908 OO.ui.OutlineControlsWidget.parent.call( this, config );
2910 // Mixin constructors
2911 OO.ui.mixin.GroupElement.call( this, config );
2912 OO.ui.mixin.IconElement.call( this, config );
2914 // Properties
2915 this.outline = outline;
2916 this.$movers = $( '<div>' );
2917 this.upButton = new OO.ui.ButtonWidget( {
2918 framed: false,
2919 icon: 'collapse',
2920 title: OO.ui.msg( 'ooui-outline-control-move-up' )
2921 } );
2922 this.downButton = new OO.ui.ButtonWidget( {
2923 framed: false,
2924 icon: 'expand',
2925 title: OO.ui.msg( 'ooui-outline-control-move-down' )
2926 } );
2927 this.removeButton = new OO.ui.ButtonWidget( {
2928 framed: false,
2929 icon: 'remove',
2930 title: OO.ui.msg( 'ooui-outline-control-remove' )
2931 } );
2932 this.abilities = { move: true, remove: true };
2934 // Events
2935 outline.connect( this, {
2936 select: 'onOutlineChange',
2937 add: 'onOutlineChange',
2938 remove: 'onOutlineChange'
2939 } );
2940 this.upButton.connect( this, { click: [ 'emit', 'move', -1 ] } );
2941 this.downButton.connect( this, { click: [ 'emit', 'move', 1 ] } );
2942 this.removeButton.connect( this, { click: [ 'emit', 'remove' ] } );
2944 // Initialization
2945 this.$element.addClass( 'oo-ui-outlineControlsWidget' );
2946 this.$group.addClass( 'oo-ui-outlineControlsWidget-items' );
2947 this.$movers
2948 .addClass( 'oo-ui-outlineControlsWidget-movers' )
2949 .append( this.removeButton.$element, this.upButton.$element, this.downButton.$element );
2950 this.$element.append( this.$icon, this.$group, this.$movers );
2951 this.setAbilities( config.abilities || {} );
2954 /* Setup */
2956 OO.inheritClass( OO.ui.OutlineControlsWidget, OO.ui.Widget );
2957 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.GroupElement );
2958 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.IconElement );
2960 /* Events */
2963 * @event move
2964 * @param {number} places Number of places to move
2968 * @event remove
2971 /* Methods */
2974 * Set abilities.
2976 * @param {Object} abilities List of abilties
2977 * @param {boolean} [abilities.move] Allow moving movable items
2978 * @param {boolean} [abilities.remove] Allow removing removable items
2980 OO.ui.OutlineControlsWidget.prototype.setAbilities = function ( abilities ) {
2981 var ability;
2983 for ( ability in this.abilities ) {
2984 if ( abilities[ ability ] !== undefined ) {
2985 this.abilities[ ability ] = !!abilities[ ability ];
2989 this.onOutlineChange();
2993 * Handle outline change events.
2995 * @private
2997 OO.ui.OutlineControlsWidget.prototype.onOutlineChange = function () {
2998 var i, len, firstMovable, lastMovable,
2999 items = this.outline.getItems(),
3000 selectedItem = this.outline.getSelectedItem(),
3001 movable = this.abilities.move && selectedItem && selectedItem.isMovable(),
3002 removable = this.abilities.remove && selectedItem && selectedItem.isRemovable();
3004 if ( movable ) {
3005 i = -1;
3006 len = items.length;
3007 while ( ++i < len ) {
3008 if ( items[ i ].isMovable() ) {
3009 firstMovable = items[ i ];
3010 break;
3013 i = len;
3014 while ( i-- ) {
3015 if ( items[ i ].isMovable() ) {
3016 lastMovable = items[ i ];
3017 break;
3021 this.upButton.setDisabled( !movable || selectedItem === firstMovable );
3022 this.downButton.setDisabled( !movable || selectedItem === lastMovable );
3023 this.removeButton.setDisabled( !removable );
3027 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
3029 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
3030 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
3031 * for an example.
3033 * @class
3034 * @extends OO.ui.DecoratedOptionWidget
3036 * @constructor
3037 * @param {Object} [config] Configuration options
3038 * @cfg {number} [level] Indentation level
3039 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
3041 OO.ui.OutlineOptionWidget = function OoUiOutlineOptionWidget( config ) {
3042 // Configuration initialization
3043 config = config || {};
3045 // Parent constructor
3046 OO.ui.OutlineOptionWidget.parent.call( this, config );
3048 // Properties
3049 this.level = 0;
3050 this.movable = !!config.movable;
3051 this.removable = !!config.removable;
3053 // Initialization
3054 this.$element.addClass( 'oo-ui-outlineOptionWidget' );
3055 this.setLevel( config.level );
3058 /* Setup */
3060 OO.inheritClass( OO.ui.OutlineOptionWidget, OO.ui.DecoratedOptionWidget );
3062 /* Static Properties */
3064 OO.ui.OutlineOptionWidget.static.highlightable = true;
3066 OO.ui.OutlineOptionWidget.static.scrollIntoViewOnSelect = true;
3068 OO.ui.OutlineOptionWidget.static.levelClass = 'oo-ui-outlineOptionWidget-level-';
3070 OO.ui.OutlineOptionWidget.static.levels = 3;
3072 /* Methods */
3075 * Check if item is movable.
3077 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
3079 * @return {boolean} Item is movable
3081 OO.ui.OutlineOptionWidget.prototype.isMovable = function () {
3082 return this.movable;
3086 * Check if item is removable.
3088 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
3090 * @return {boolean} Item is removable
3092 OO.ui.OutlineOptionWidget.prototype.isRemovable = function () {
3093 return this.removable;
3097 * Get indentation level.
3099 * @return {number} Indentation level
3101 OO.ui.OutlineOptionWidget.prototype.getLevel = function () {
3102 return this.level;
3106 * @inheritdoc
3108 OO.ui.OutlineOptionWidget.prototype.setPressed = function ( state ) {
3109 OO.ui.OutlineOptionWidget.parent.prototype.setPressed.call( this, state );
3110 if ( this.pressed ) {
3111 this.setFlags( 'progressive' );
3112 } else if ( !this.selected ) {
3113 this.clearFlags();
3115 return this;
3119 * Set movability.
3121 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
3123 * @param {boolean} movable Item is movable
3124 * @chainable
3126 OO.ui.OutlineOptionWidget.prototype.setMovable = function ( movable ) {
3127 this.movable = !!movable;
3128 this.updateThemeClasses();
3129 return this;
3133 * Set removability.
3135 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
3137 * @param {boolean} removable Item is removable
3138 * @chainable
3140 OO.ui.OutlineOptionWidget.prototype.setRemovable = function ( removable ) {
3141 this.removable = !!removable;
3142 this.updateThemeClasses();
3143 return this;
3147 * @inheritdoc
3149 OO.ui.OutlineOptionWidget.prototype.setSelected = function ( state ) {
3150 OO.ui.OutlineOptionWidget.parent.prototype.setSelected.call( this, state );
3151 if ( this.selected ) {
3152 this.setFlags( 'progressive' );
3153 } else {
3154 this.clearFlags();
3156 return this;
3160 * Set indentation level.
3162 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
3163 * @chainable
3165 OO.ui.OutlineOptionWidget.prototype.setLevel = function ( level ) {
3166 var levels = this.constructor.static.levels,
3167 levelClass = this.constructor.static.levelClass,
3168 i = levels;
3170 this.level = level ? Math.max( 0, Math.min( levels - 1, level ) ) : 0;
3171 while ( i-- ) {
3172 if ( this.level === i ) {
3173 this.$element.addClass( levelClass + i );
3174 } else {
3175 this.$element.removeClass( levelClass + i );
3178 this.updateThemeClasses();
3180 return this;
3184 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
3185 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
3187 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
3189 * @class
3190 * @extends OO.ui.SelectWidget
3191 * @mixins OO.ui.mixin.TabIndexedElement
3193 * @constructor
3194 * @param {Object} [config] Configuration options
3196 OO.ui.OutlineSelectWidget = function OoUiOutlineSelectWidget( config ) {
3197 // Parent constructor
3198 OO.ui.OutlineSelectWidget.parent.call( this, config );
3200 // Mixin constructors
3201 OO.ui.mixin.TabIndexedElement.call( this, config );
3203 // Events
3204 this.$element.on( {
3205 focus: this.bindKeyDownListener.bind( this ),
3206 blur: this.unbindKeyDownListener.bind( this )
3207 } );
3209 // Initialization
3210 this.$element.addClass( 'oo-ui-outlineSelectWidget' );
3213 /* Setup */
3215 OO.inheritClass( OO.ui.OutlineSelectWidget, OO.ui.SelectWidget );
3216 OO.mixinClass( OO.ui.OutlineSelectWidget, OO.ui.mixin.TabIndexedElement );
3219 * ButtonOptionWidget is a special type of {@link OO.ui.mixin.ButtonElement button element} that
3220 * can be selected and configured with data. The class is
3221 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
3222 * [OOjs UI documentation on MediaWiki] [1] for more information.
3224 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
3226 * @class
3227 * @extends OO.ui.OptionWidget
3228 * @mixins OO.ui.mixin.ButtonElement
3229 * @mixins OO.ui.mixin.IconElement
3230 * @mixins OO.ui.mixin.IndicatorElement
3231 * @mixins OO.ui.mixin.TitledElement
3233 * @constructor
3234 * @param {Object} [config] Configuration options
3236 OO.ui.ButtonOptionWidget = function OoUiButtonOptionWidget( config ) {
3237 // Configuration initialization
3238 config = config || {};
3240 // Parent constructor
3241 OO.ui.ButtonOptionWidget.parent.call( this, config );
3243 // Mixin constructors
3244 OO.ui.mixin.ButtonElement.call( this, config );
3245 OO.ui.mixin.IconElement.call( this, config );
3246 OO.ui.mixin.IndicatorElement.call( this, config );
3247 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
3249 // Initialization
3250 this.$element.addClass( 'oo-ui-buttonOptionWidget' );
3251 this.$button.append( this.$icon, this.$label, this.$indicator );
3252 this.$element.append( this.$button );
3255 /* Setup */
3257 OO.inheritClass( OO.ui.ButtonOptionWidget, OO.ui.OptionWidget );
3258 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.ButtonElement );
3259 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.IconElement );
3260 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.IndicatorElement );
3261 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.TitledElement );
3263 /* Static Properties */
3265 // Allow button mouse down events to pass through so they can be handled by the parent select widget
3266 OO.ui.ButtonOptionWidget.static.cancelButtonMouseDownEvents = false;
3268 OO.ui.ButtonOptionWidget.static.highlightable = false;
3270 /* Methods */
3273 * @inheritdoc
3275 OO.ui.ButtonOptionWidget.prototype.setSelected = function ( state ) {
3276 OO.ui.ButtonOptionWidget.parent.prototype.setSelected.call( this, state );
3278 if ( this.constructor.static.selectable ) {
3279 this.setActive( state );
3282 return this;
3286 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
3287 * button options and is used together with
3288 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
3289 * highlighting, choosing, and selecting mutually exclusive options. Please see
3290 * the [OOjs UI documentation on MediaWiki] [1] for more information.
3292 * @example
3293 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
3294 * var option1 = new OO.ui.ButtonOptionWidget( {
3295 * data: 1,
3296 * label: 'Option 1',
3297 * title: 'Button option 1'
3298 * } );
3300 * var option2 = new OO.ui.ButtonOptionWidget( {
3301 * data: 2,
3302 * label: 'Option 2',
3303 * title: 'Button option 2'
3304 * } );
3306 * var option3 = new OO.ui.ButtonOptionWidget( {
3307 * data: 3,
3308 * label: 'Option 3',
3309 * title: 'Button option 3'
3310 * } );
3312 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
3313 * items: [ option1, option2, option3 ]
3314 * } );
3315 * $( 'body' ).append( buttonSelect.$element );
3317 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
3319 * @class
3320 * @extends OO.ui.SelectWidget
3321 * @mixins OO.ui.mixin.TabIndexedElement
3323 * @constructor
3324 * @param {Object} [config] Configuration options
3326 OO.ui.ButtonSelectWidget = function OoUiButtonSelectWidget( config ) {
3327 // Parent constructor
3328 OO.ui.ButtonSelectWidget.parent.call( this, config );
3330 // Mixin constructors
3331 OO.ui.mixin.TabIndexedElement.call( this, config );
3333 // Events
3334 this.$element.on( {
3335 focus: this.bindKeyDownListener.bind( this ),
3336 blur: this.unbindKeyDownListener.bind( this )
3337 } );
3339 // Initialization
3340 this.$element.addClass( 'oo-ui-buttonSelectWidget' );
3343 /* Setup */
3345 OO.inheritClass( OO.ui.ButtonSelectWidget, OO.ui.SelectWidget );
3346 OO.mixinClass( OO.ui.ButtonSelectWidget, OO.ui.mixin.TabIndexedElement );
3349 * TabOptionWidget is an item in a {@link OO.ui.TabSelectWidget TabSelectWidget}.
3351 * Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}, which contain
3352 * {@link OO.ui.CardLayout card layouts}. See {@link OO.ui.IndexLayout IndexLayout}
3353 * for an example.
3355 * @class
3356 * @extends OO.ui.OptionWidget
3358 * @constructor
3359 * @param {Object} [config] Configuration options
3361 OO.ui.TabOptionWidget = function OoUiTabOptionWidget( config ) {
3362 // Configuration initialization
3363 config = config || {};
3365 // Parent constructor
3366 OO.ui.TabOptionWidget.parent.call( this, config );
3368 // Initialization
3369 this.$element.addClass( 'oo-ui-tabOptionWidget' );
3372 /* Setup */
3374 OO.inheritClass( OO.ui.TabOptionWidget, OO.ui.OptionWidget );
3376 /* Static Properties */
3378 OO.ui.TabOptionWidget.static.highlightable = false;
3381 * TabSelectWidget is a list that contains {@link OO.ui.TabOptionWidget tab options}
3383 * **Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}.**
3385 * @class
3386 * @extends OO.ui.SelectWidget
3387 * @mixins OO.ui.mixin.TabIndexedElement
3389 * @constructor
3390 * @param {Object} [config] Configuration options
3392 OO.ui.TabSelectWidget = function OoUiTabSelectWidget( config ) {
3393 // Parent constructor
3394 OO.ui.TabSelectWidget.parent.call( this, config );
3396 // Mixin constructors
3397 OO.ui.mixin.TabIndexedElement.call( this, config );
3399 // Events
3400 this.$element.on( {
3401 focus: this.bindKeyDownListener.bind( this ),
3402 blur: this.unbindKeyDownListener.bind( this )
3403 } );
3405 // Initialization
3406 this.$element.addClass( 'oo-ui-tabSelectWidget' );
3409 /* Setup */
3411 OO.inheritClass( OO.ui.TabSelectWidget, OO.ui.SelectWidget );
3412 OO.mixinClass( OO.ui.TabSelectWidget, OO.ui.mixin.TabIndexedElement );
3415 * CapsuleItemWidgets are used within a {@link OO.ui.CapsuleMultiselectWidget
3416 * CapsuleMultiselectWidget} to display the selected items.
3418 * @class
3419 * @extends OO.ui.Widget
3420 * @mixins OO.ui.mixin.ItemWidget
3421 * @mixins OO.ui.mixin.LabelElement
3422 * @mixins OO.ui.mixin.FlaggedElement
3423 * @mixins OO.ui.mixin.TabIndexedElement
3425 * @constructor
3426 * @param {Object} [config] Configuration options
3428 OO.ui.CapsuleItemWidget = function OoUiCapsuleItemWidget( config ) {
3429 // Configuration initialization
3430 config = config || {};
3432 // Parent constructor
3433 OO.ui.CapsuleItemWidget.parent.call( this, config );
3435 // Mixin constructors
3436 OO.ui.mixin.ItemWidget.call( this );
3437 OO.ui.mixin.LabelElement.call( this, config );
3438 OO.ui.mixin.FlaggedElement.call( this, config );
3439 OO.ui.mixin.TabIndexedElement.call( this, config );
3441 // Events
3442 this.closeButton = new OO.ui.ButtonWidget( {
3443 framed: false,
3444 indicator: 'clear',
3445 tabIndex: -1
3446 } ).on( 'click', this.onCloseClick.bind( this ) );
3448 this.on( 'disable', function ( disabled ) {
3449 this.closeButton.setDisabled( disabled );
3450 }.bind( this ) );
3452 // Initialization
3453 this.$element
3454 .on( {
3455 click: this.onClick.bind( this ),
3456 keydown: this.onKeyDown.bind( this )
3458 .addClass( 'oo-ui-capsuleItemWidget' )
3459 .append( this.$label, this.closeButton.$element );
3462 /* Setup */
3464 OO.inheritClass( OO.ui.CapsuleItemWidget, OO.ui.Widget );
3465 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.ItemWidget );
3466 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.LabelElement );
3467 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.FlaggedElement );
3468 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.TabIndexedElement );
3470 /* Methods */
3473 * Handle close icon clicks
3475 OO.ui.CapsuleItemWidget.prototype.onCloseClick = function () {
3476 var element = this.getElementGroup();
3478 if ( element && $.isFunction( element.removeItems ) ) {
3479 element.removeItems( [ this ] );
3480 element.focus();
3485 * Handle click event for the entire capsule
3487 OO.ui.CapsuleItemWidget.prototype.onClick = function () {
3488 var element = this.getElementGroup();
3490 if ( !this.isDisabled() && element && $.isFunction( element.editItem ) ) {
3491 element.editItem( this );
3496 * Handle keyDown event for the entire capsule
3498 * @param {jQuery.Event} e Key down event
3500 OO.ui.CapsuleItemWidget.prototype.onKeyDown = function ( e ) {
3501 var element = this.getElementGroup();
3503 if ( e.keyCode === OO.ui.Keys.BACKSPACE || e.keyCode === OO.ui.Keys.DELETE ) {
3504 element.removeItems( [ this ] );
3505 element.focus();
3506 return false;
3507 } else if ( e.keyCode === OO.ui.Keys.ENTER ) {
3508 element.editItem( this );
3509 return false;
3510 } else if ( e.keyCode === OO.ui.Keys.LEFT ) {
3511 element.getPreviousItem( this ).focus();
3512 } else if ( e.keyCode === OO.ui.Keys.RIGHT ) {
3513 element.getNextItem( this ).focus();
3518 * Focuses the capsule
3520 OO.ui.CapsuleItemWidget.prototype.focus = function () {
3521 this.$element.focus();
3525 * CapsuleMultiselectWidgets are something like a {@link OO.ui.ComboBoxInputWidget combo box widget}
3526 * that allows for selecting multiple values.
3528 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
3530 * @example
3531 * // Example: A CapsuleMultiselectWidget.
3532 * var capsule = new OO.ui.CapsuleMultiselectWidget( {
3533 * label: 'CapsuleMultiselectWidget',
3534 * selected: [ 'Option 1', 'Option 3' ],
3535 * menu: {
3536 * items: [
3537 * new OO.ui.MenuOptionWidget( {
3538 * data: 'Option 1',
3539 * label: 'Option One'
3540 * } ),
3541 * new OO.ui.MenuOptionWidget( {
3542 * data: 'Option 2',
3543 * label: 'Option Two'
3544 * } ),
3545 * new OO.ui.MenuOptionWidget( {
3546 * data: 'Option 3',
3547 * label: 'Option Three'
3548 * } ),
3549 * new OO.ui.MenuOptionWidget( {
3550 * data: 'Option 4',
3551 * label: 'Option Four'
3552 * } ),
3553 * new OO.ui.MenuOptionWidget( {
3554 * data: 'Option 5',
3555 * label: 'Option Five'
3556 * } )
3559 * } );
3560 * $( 'body' ).append( capsule.$element );
3562 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
3564 * @class
3565 * @extends OO.ui.Widget
3566 * @mixins OO.ui.mixin.GroupElement
3567 * @mixins OO.ui.mixin.PopupElement
3568 * @mixins OO.ui.mixin.TabIndexedElement
3569 * @mixins OO.ui.mixin.IndicatorElement
3570 * @mixins OO.ui.mixin.IconElement
3571 * @uses OO.ui.CapsuleItemWidget
3572 * @uses OO.ui.FloatingMenuSelectWidget
3574 * @constructor
3575 * @param {Object} [config] Configuration options
3576 * @cfg {string} [placeholder] Placeholder text
3577 * @cfg {boolean} [allowArbitrary=false] Allow data items to be added even if not present in the menu.
3578 * @cfg {boolean} [allowDuplicates=false] Allow duplicate items to be added.
3579 * @cfg {Object} [menu] (required) Configuration options to pass to the
3580 * {@link OO.ui.MenuSelectWidget menu select widget}.
3581 * @cfg {Object} [popup] Configuration options to pass to the {@link OO.ui.PopupWidget popup widget}.
3582 * If specified, this popup will be shown instead of the menu (but the menu
3583 * will still be used for item labels and allowArbitrary=false). The widgets
3584 * in the popup should use {@link #addItemsFromData} or {@link #addItems} as necessary.
3585 * @cfg {jQuery} [$overlay=this.$element] Render the menu or popup into a separate layer.
3586 * This configuration is useful in cases where the expanded menu is larger than
3587 * its containing `<div>`. The specified overlay layer is usually on top of
3588 * the containing `<div>` and has a larger area. By default, the menu uses
3589 * relative positioning.
3591 OO.ui.CapsuleMultiselectWidget = function OoUiCapsuleMultiselectWidget( config ) {
3592 var $tabFocus;
3594 // Parent constructor
3595 OO.ui.CapsuleMultiselectWidget.parent.call( this, config );
3597 // Configuration initialization
3598 config = $.extend( {
3599 allowArbitrary: false,
3600 allowDuplicates: false,
3601 $overlay: this.$element
3602 }, config );
3604 // Properties (must be set before mixin constructor calls)
3605 this.$handle = $( '<div>' );
3606 this.$input = config.popup ? null : $( '<input>' );
3607 if ( config.placeholder !== undefined && config.placeholder !== '' ) {
3608 this.$input.attr( 'placeholder', config.placeholder );
3611 // Mixin constructors
3612 OO.ui.mixin.GroupElement.call( this, config );
3613 if ( config.popup ) {
3614 config.popup = $.extend( {}, config.popup, {
3615 align: 'forwards',
3616 anchor: false
3617 } );
3618 OO.ui.mixin.PopupElement.call( this, config );
3619 $tabFocus = $( '<span>' );
3620 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: $tabFocus } ) );
3621 } else {
3622 this.popup = null;
3623 $tabFocus = null;
3624 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
3626 OO.ui.mixin.IndicatorElement.call( this, config );
3627 OO.ui.mixin.IconElement.call( this, config );
3629 // Properties
3630 this.$content = $( '<div>' );
3631 this.allowArbitrary = config.allowArbitrary;
3632 this.allowDuplicates = config.allowDuplicates;
3633 this.$overlay = config.$overlay;
3634 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend(
3636 widget: this,
3637 $input: this.$input,
3638 $container: this.$element,
3639 filterFromInput: true,
3640 disabled: this.isDisabled()
3642 config.menu
3643 ) );
3645 // Events
3646 if ( this.popup ) {
3647 $tabFocus.on( {
3648 focus: this.focus.bind( this )
3649 } );
3650 this.popup.$element.on( 'focusout', this.onPopupFocusOut.bind( this ) );
3651 if ( this.popup.$autoCloseIgnore ) {
3652 this.popup.$autoCloseIgnore.on( 'focusout', this.onPopupFocusOut.bind( this ) );
3654 this.popup.connect( this, {
3655 toggle: function ( visible ) {
3656 $tabFocus.toggle( !visible );
3658 } );
3659 } else {
3660 this.$input.on( {
3661 focus: this.onInputFocus.bind( this ),
3662 blur: this.onInputBlur.bind( this ),
3663 'propertychange change click mouseup keydown keyup input cut paste select focus':
3664 OO.ui.debounce( this.updateInputSize.bind( this ) ),
3665 keydown: this.onKeyDown.bind( this ),
3666 keypress: this.onKeyPress.bind( this )
3667 } );
3669 this.menu.connect( this, {
3670 choose: 'onMenuChoose',
3671 toggle: 'onMenuToggle',
3672 add: 'onMenuItemsChange',
3673 remove: 'onMenuItemsChange'
3674 } );
3675 this.$handle.on( {
3676 mousedown: this.onMouseDown.bind( this )
3677 } );
3679 // Initialization
3680 if ( this.$input ) {
3681 this.$input.prop( 'disabled', this.isDisabled() );
3682 this.$input.attr( {
3683 role: 'combobox',
3684 'aria-autocomplete': 'list'
3685 } );
3687 if ( config.data ) {
3688 this.setItemsFromData( config.data );
3690 this.$content.addClass( 'oo-ui-capsuleMultiselectWidget-content' )
3691 .append( this.$group );
3692 this.$group.addClass( 'oo-ui-capsuleMultiselectWidget-group' );
3693 this.$handle.addClass( 'oo-ui-capsuleMultiselectWidget-handle' )
3694 .append( this.$indicator, this.$icon, this.$content );
3695 this.$element.addClass( 'oo-ui-capsuleMultiselectWidget' )
3696 .append( this.$handle );
3697 if ( this.popup ) {
3698 this.$content.append( $tabFocus );
3699 this.$overlay.append( this.popup.$element );
3700 } else {
3701 this.$content.append( this.$input );
3702 this.$overlay.append( this.menu.$element );
3705 // Input size needs to be calculated after everything else is rendered
3706 setTimeout( function () {
3707 if ( this.$input ) {
3708 this.updateInputSize();
3710 }.bind( this ) );
3712 this.onMenuItemsChange();
3715 /* Setup */
3717 OO.inheritClass( OO.ui.CapsuleMultiselectWidget, OO.ui.Widget );
3718 OO.mixinClass( OO.ui.CapsuleMultiselectWidget, OO.ui.mixin.GroupElement );
3719 OO.mixinClass( OO.ui.CapsuleMultiselectWidget, OO.ui.mixin.PopupElement );
3720 OO.mixinClass( OO.ui.CapsuleMultiselectWidget, OO.ui.mixin.TabIndexedElement );
3721 OO.mixinClass( OO.ui.CapsuleMultiselectWidget, OO.ui.mixin.IndicatorElement );
3722 OO.mixinClass( OO.ui.CapsuleMultiselectWidget, OO.ui.mixin.IconElement );
3724 /* Events */
3727 * @event change
3729 * A change event is emitted when the set of selected items changes.
3731 * @param {Mixed[]} datas Data of the now-selected items
3735 * @event resize
3737 * A resize event is emitted when the widget's dimensions change to accomodate newly added items or
3738 * current user input.
3741 /* Methods */
3744 * Construct a OO.ui.CapsuleItemWidget (or a subclass thereof) from given label and data.
3745 * May return `null` if the given label and data are not valid.
3747 * @protected
3748 * @param {Mixed} data Custom data of any type.
3749 * @param {string} label The label text.
3750 * @return {OO.ui.CapsuleItemWidget|null}
3752 OO.ui.CapsuleMultiselectWidget.prototype.createItemWidget = function ( data, label ) {
3753 if ( label === '' ) {
3754 return null;
3756 return new OO.ui.CapsuleItemWidget( { data: data, label: label } );
3760 * Get the data of the items in the capsule
3762 * @return {Mixed[]}
3764 OO.ui.CapsuleMultiselectWidget.prototype.getItemsData = function () {
3765 return this.getItems().map( function ( item ) {
3766 return item.data;
3767 } );
3771 * Set the items in the capsule by providing data
3773 * @chainable
3774 * @param {Mixed[]} datas
3775 * @return {OO.ui.CapsuleMultiselectWidget}
3777 OO.ui.CapsuleMultiselectWidget.prototype.setItemsFromData = function ( datas ) {
3778 var widget = this,
3779 menu = this.menu,
3780 items = this.getItems();
3782 $.each( datas, function ( i, data ) {
3783 var j, label,
3784 item = menu.getItemFromData( data );
3786 if ( item ) {
3787 label = item.label;
3788 } else if ( widget.allowArbitrary ) {
3789 label = String( data );
3790 } else {
3791 return;
3794 item = null;
3795 for ( j = 0; j < items.length; j++ ) {
3796 if ( items[ j ].data === data && items[ j ].label === label ) {
3797 item = items[ j ];
3798 items.splice( j, 1 );
3799 break;
3802 if ( !item ) {
3803 item = widget.createItemWidget( data, label );
3805 if ( item ) {
3806 widget.addItems( [ item ], i );
3808 } );
3810 if ( items.length ) {
3811 widget.removeItems( items );
3814 return this;
3818 * Add items to the capsule by providing their data
3820 * @chainable
3821 * @param {Mixed[]} datas
3822 * @return {OO.ui.CapsuleMultiselectWidget}
3824 OO.ui.CapsuleMultiselectWidget.prototype.addItemsFromData = function ( datas ) {
3825 var widget = this,
3826 menu = this.menu,
3827 items = [];
3829 $.each( datas, function ( i, data ) {
3830 var item;
3832 if ( !widget.getItemFromData( data ) || widget.allowDuplicates ) {
3833 item = menu.getItemFromData( data );
3834 if ( item ) {
3835 item = widget.createItemWidget( data, item.label );
3836 } else if ( widget.allowArbitrary ) {
3837 item = widget.createItemWidget( data, String( data ) );
3839 if ( item ) {
3840 items.push( item );
3843 } );
3845 if ( items.length ) {
3846 this.addItems( items );
3849 return this;
3853 * Add items to the capsule by providing a label
3855 * @param {string} label
3856 * @return {boolean} Whether the item was added or not
3858 OO.ui.CapsuleMultiselectWidget.prototype.addItemFromLabel = function ( label ) {
3859 var item, items;
3860 item = this.menu.getItemFromLabel( label, true );
3861 if ( item ) {
3862 this.addItemsFromData( [ item.data ] );
3863 return true;
3864 } else if ( this.allowArbitrary ) {
3865 items = this.getItems();
3866 this.addItemsFromData( [ label ] );
3867 return !OO.compare( this.getItems(), items );
3869 return false;
3873 * Remove items by data
3875 * @chainable
3876 * @param {Mixed[]} datas
3877 * @return {OO.ui.CapsuleMultiselectWidget}
3879 OO.ui.CapsuleMultiselectWidget.prototype.removeItemsFromData = function ( datas ) {
3880 var widget = this,
3881 items = [];
3883 $.each( datas, function ( i, data ) {
3884 var item = widget.getItemFromData( data );
3885 if ( item ) {
3886 items.push( item );
3888 } );
3890 if ( items.length ) {
3891 this.removeItems( items );
3894 return this;
3898 * @inheritdoc
3900 OO.ui.CapsuleMultiselectWidget.prototype.addItems = function ( items ) {
3901 var same, i, l,
3902 oldItems = this.items.slice();
3904 OO.ui.mixin.GroupElement.prototype.addItems.call( this, items );
3906 if ( this.items.length !== oldItems.length ) {
3907 same = false;
3908 } else {
3909 same = true;
3910 for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
3911 same = same && this.items[ i ] === oldItems[ i ];
3914 if ( !same ) {
3915 this.emit( 'change', this.getItemsData() );
3916 this.updateIfHeightChanged();
3919 return this;
3923 * Removes the item from the list and copies its label to `this.$input`.
3925 * @param {Object} item
3927 OO.ui.CapsuleMultiselectWidget.prototype.editItem = function ( item ) {
3928 this.addItemFromLabel( this.$input.val() );
3929 this.clearInput();
3930 this.$input.val( item.label );
3931 this.updateInputSize();
3932 this.focus();
3933 this.menu.updateItemVisibility(); // Hack, we shouldn't be calling this method directly
3934 this.removeItems( [ item ] );
3938 * @inheritdoc
3940 OO.ui.CapsuleMultiselectWidget.prototype.removeItems = function ( items ) {
3941 var same, i, l,
3942 oldItems = this.items.slice();
3944 OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items );
3946 if ( this.items.length !== oldItems.length ) {
3947 same = false;
3948 } else {
3949 same = true;
3950 for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
3951 same = same && this.items[ i ] === oldItems[ i ];
3954 if ( !same ) {
3955 this.emit( 'change', this.getItemsData() );
3956 this.updateIfHeightChanged();
3959 return this;
3963 * @inheritdoc
3965 OO.ui.CapsuleMultiselectWidget.prototype.clearItems = function () {
3966 if ( this.items.length ) {
3967 OO.ui.mixin.GroupElement.prototype.clearItems.call( this );
3968 this.emit( 'change', this.getItemsData() );
3969 this.updateIfHeightChanged();
3971 return this;
3975 * Given an item, returns the item after it. If its the last item,
3976 * returns `this.$input`. If no item is passed, returns the very first
3977 * item.
3979 * @param {OO.ui.CapsuleItemWidget} [item]
3980 * @return {OO.ui.CapsuleItemWidget|jQuery|boolean}
3982 OO.ui.CapsuleMultiselectWidget.prototype.getNextItem = function ( item ) {
3983 var itemIndex;
3985 if ( item === undefined ) {
3986 return this.items[ 0 ];
3989 itemIndex = this.items.indexOf( item );
3990 if ( itemIndex < 0 ) { // Item not in list
3991 return false;
3992 } else if ( itemIndex === this.items.length - 1 ) { // Last item
3993 return this.$input;
3994 } else {
3995 return this.items[ itemIndex + 1 ];
4000 * Given an item, returns the item before it. If its the first item,
4001 * returns `this.$input`. If no item is passed, returns the very last
4002 * item.
4004 * @param {OO.ui.CapsuleItemWidget} [item]
4005 * @return {OO.ui.CapsuleItemWidget|jQuery|boolean}
4007 OO.ui.CapsuleMultiselectWidget.prototype.getPreviousItem = function ( item ) {
4008 var itemIndex;
4010 if ( item === undefined ) {
4011 return this.items[ this.items.length - 1 ];
4014 itemIndex = this.items.indexOf( item );
4015 if ( itemIndex < 0 ) { // Item not in list
4016 return false;
4017 } else if ( itemIndex === 0 ) { // First item
4018 return this.$input;
4019 } else {
4020 return this.items[ itemIndex - 1 ];
4025 * Get the capsule widget's menu.
4027 * @return {OO.ui.MenuSelectWidget} Menu widget
4029 OO.ui.CapsuleMultiselectWidget.prototype.getMenu = function () {
4030 return this.menu;
4034 * Handle focus events
4036 * @private
4037 * @param {jQuery.Event} event
4039 OO.ui.CapsuleMultiselectWidget.prototype.onInputFocus = function () {
4040 if ( !this.isDisabled() ) {
4041 this.menu.toggle( true );
4046 * Handle blur events
4048 * @private
4049 * @param {jQuery.Event} event
4051 OO.ui.CapsuleMultiselectWidget.prototype.onInputBlur = function () {
4052 this.addItemFromLabel( this.$input.val() );
4053 this.clearInput();
4057 * Handles popup focus out events.
4059 * @private
4060 * @param {jQuery.Event} e Focus out event
4062 OO.ui.CapsuleMultiselectWidget.prototype.onPopupFocusOut = function () {
4063 var widget = this.popup;
4065 setTimeout( function () {
4066 if (
4067 widget.isVisible() &&
4068 !OO.ui.contains( widget.$element.add( widget.$autoCloseIgnore ).get(), document.activeElement, true )
4070 widget.toggle( false );
4072 } );
4076 * Handle mouse down events.
4078 * @private
4079 * @param {jQuery.Event} e Mouse down event
4081 OO.ui.CapsuleMultiselectWidget.prototype.onMouseDown = function ( e ) {
4082 if ( e.which === OO.ui.MouseButtons.LEFT ) {
4083 this.focus();
4084 return false;
4085 } else {
4086 this.updateInputSize();
4091 * Handle key press events.
4093 * @private
4094 * @param {jQuery.Event} e Key press event
4096 OO.ui.CapsuleMultiselectWidget.prototype.onKeyPress = function ( e ) {
4097 if ( !this.isDisabled() ) {
4098 if ( e.which === OO.ui.Keys.ESCAPE ) {
4099 this.clearInput();
4100 return false;
4103 if ( !this.popup ) {
4104 this.menu.toggle( true );
4105 if ( e.which === OO.ui.Keys.ENTER ) {
4106 if ( this.addItemFromLabel( this.$input.val() ) ) {
4107 this.clearInput();
4109 return false;
4112 // Make sure the input gets resized.
4113 setTimeout( this.updateInputSize.bind( this ), 0 );
4119 * Handle key down events.
4121 * @private
4122 * @param {jQuery.Event} e Key down event
4124 OO.ui.CapsuleMultiselectWidget.prototype.onKeyDown = function ( e ) {
4125 if (
4126 !this.isDisabled() &&
4127 this.$input.val() === '' &&
4128 this.items.length
4130 // 'keypress' event is not triggered for Backspace
4131 if ( e.keyCode === OO.ui.Keys.BACKSPACE ) {
4132 if ( e.metaKey || e.ctrlKey ) {
4133 this.removeItems( this.items.slice( -1 ) );
4134 } else {
4135 this.editItem( this.items[ this.items.length - 1 ] );
4137 return false;
4138 } else if ( e.keyCode === OO.ui.Keys.LEFT ) {
4139 this.getPreviousItem().focus();
4140 } else if ( e.keyCode === OO.ui.Keys.RIGHT ) {
4141 this.getNextItem().focus();
4147 * Update the dimensions of the text input field to encompass all available area.
4149 * @private
4150 * @param {jQuery.Event} e Event of some sort
4152 OO.ui.CapsuleMultiselectWidget.prototype.updateInputSize = function () {
4153 var $lastItem, direction, contentWidth, currentWidth, bestWidth;
4154 if ( this.$input && !this.isDisabled() ) {
4155 this.$input.css( 'width', '1em' );
4156 $lastItem = this.$group.children().last();
4157 direction = OO.ui.Element.static.getDir( this.$handle );
4159 // Get the width of the input with the placeholder text as
4160 // the value and save it so that we don't keep recalculating
4161 if (
4162 this.contentWidthWithPlaceholder === undefined &&
4163 this.$input.val() === '' &&
4164 this.$input.attr( 'placeholder' ) !== undefined
4166 this.$input.val( this.$input.attr( 'placeholder' ) );
4167 this.contentWidthWithPlaceholder = this.$input[ 0 ].scrollWidth;
4168 this.$input.val( '' );
4172 // Always keep the input wide enough for the placeholder text
4173 contentWidth = Math.max(
4174 this.$input[ 0 ].scrollWidth,
4175 // undefined arguments in Math.max lead to NaN
4176 ( this.contentWidthWithPlaceholder === undefined ) ?
4177 0 : this.contentWidthWithPlaceholder
4179 currentWidth = this.$input.width();
4181 if ( contentWidth < currentWidth ) {
4182 // All is fine, don't perform expensive calculations
4183 return;
4186 if ( $lastItem.length === 0 ) {
4187 bestWidth = this.$content.innerWidth();
4188 } else {
4189 bestWidth = direction === 'ltr' ?
4190 this.$content.innerWidth() - $lastItem.position().left - $lastItem.outerWidth() :
4191 $lastItem.position().left;
4194 // Some safety margin for sanity, because I *really* don't feel like finding out where the few
4195 // pixels this is off by are coming from.
4196 bestWidth -= 10;
4197 if ( contentWidth > bestWidth ) {
4198 // This will result in the input getting shifted to the next line
4199 bestWidth = this.$content.innerWidth() - 10;
4201 this.$input.width( Math.floor( bestWidth ) );
4202 this.updateIfHeightChanged();
4207 * Determine if widget height changed, and if so, update menu position and emit 'resize' event.
4209 * @private
4211 OO.ui.CapsuleMultiselectWidget.prototype.updateIfHeightChanged = function () {
4212 var height = this.$element.height();
4213 if ( height !== this.height ) {
4214 this.height = height;
4215 this.menu.position();
4216 this.emit( 'resize' );
4221 * Handle menu choose events.
4223 * @private
4224 * @param {OO.ui.OptionWidget} item Chosen item
4226 OO.ui.CapsuleMultiselectWidget.prototype.onMenuChoose = function ( item ) {
4227 if ( item && item.isVisible() ) {
4228 this.addItemsFromData( [ item.getData() ] );
4229 this.clearInput();
4234 * Handle menu toggle events.
4236 * @private
4237 * @param {boolean} isVisible Menu toggle event
4239 OO.ui.CapsuleMultiselectWidget.prototype.onMenuToggle = function ( isVisible ) {
4240 this.$element.toggleClass( 'oo-ui-capsuleMultiselectWidget-open', isVisible );
4244 * Handle menu item change events.
4246 * @private
4248 OO.ui.CapsuleMultiselectWidget.prototype.onMenuItemsChange = function () {
4249 this.setItemsFromData( this.getItemsData() );
4250 this.$element.toggleClass( 'oo-ui-capsuleMultiselectWidget-empty', this.menu.isEmpty() );
4254 * Clear the input field
4256 * @private
4258 OO.ui.CapsuleMultiselectWidget.prototype.clearInput = function () {
4259 if ( this.$input ) {
4260 this.$input.val( '' );
4261 this.updateInputSize();
4263 if ( this.popup ) {
4264 this.popup.toggle( false );
4266 this.menu.toggle( false );
4267 this.menu.selectItem();
4268 this.menu.highlightItem();
4272 * @inheritdoc
4274 OO.ui.CapsuleMultiselectWidget.prototype.setDisabled = function ( disabled ) {
4275 var i, len;
4277 // Parent method
4278 OO.ui.CapsuleMultiselectWidget.parent.prototype.setDisabled.call( this, disabled );
4280 if ( this.$input ) {
4281 this.$input.prop( 'disabled', this.isDisabled() );
4283 if ( this.menu ) {
4284 this.menu.setDisabled( this.isDisabled() );
4286 if ( this.popup ) {
4287 this.popup.setDisabled( this.isDisabled() );
4290 if ( this.items ) {
4291 for ( i = 0, len = this.items.length; i < len; i++ ) {
4292 this.items[ i ].updateDisabled();
4296 return this;
4300 * Focus the widget
4302 * @chainable
4303 * @return {OO.ui.CapsuleMultiselectWidget}
4305 OO.ui.CapsuleMultiselectWidget.prototype.focus = function () {
4306 if ( !this.isDisabled() ) {
4307 if ( this.popup ) {
4308 this.popup.setSize( this.$handle.width() );
4309 this.popup.toggle( true );
4310 OO.ui.findFocusable( this.popup.$element ).focus();
4311 } else {
4312 this.updateInputSize();
4313 this.menu.toggle( true );
4314 this.$input.focus();
4317 return this;
4321 * The old name for the CapsuleMultiselectWidget widget, provided for backwards-compatibility.
4323 * @class
4324 * @extends OO.ui.CapsuleMultiselectWidget
4326 * @constructor
4327 * @deprecated since 0.17.3; use OO.ui.CapsuleMultiselectWidget instead
4329 OO.ui.CapsuleMultiSelectWidget = function OoUiCapsuleMultiSelectWidget() {
4330 OO.ui.warnDeprecation( 'CapsuleMultiSelectWidget is deprecated. Use the CapsuleMultiselectWidget instead.' );
4331 // Parent constructor
4332 OO.ui.TextInputMenuSelectWidget.parent.apply( this, arguments );
4335 OO.inheritClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.CapsuleMultiselectWidget );
4338 * SelectFileWidgets allow for selecting files, using the HTML5 File API. These
4339 * widgets can be configured with {@link OO.ui.mixin.IconElement icons} and {@link
4340 * OO.ui.mixin.IndicatorElement indicators}.
4341 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
4343 * @example
4344 * // Example of a file select widget
4345 * var selectFile = new OO.ui.SelectFileWidget();
4346 * $( 'body' ).append( selectFile.$element );
4348 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets
4350 * @class
4351 * @extends OO.ui.Widget
4352 * @mixins OO.ui.mixin.IconElement
4353 * @mixins OO.ui.mixin.IndicatorElement
4354 * @mixins OO.ui.mixin.PendingElement
4355 * @mixins OO.ui.mixin.LabelElement
4357 * @constructor
4358 * @param {Object} [config] Configuration options
4359 * @cfg {string[]|null} [accept=null] MIME types to accept. null accepts all types.
4360 * @cfg {string} [placeholder] Text to display when no file is selected.
4361 * @cfg {string} [notsupported] Text to display when file support is missing in the browser.
4362 * @cfg {boolean} [droppable=true] Whether to accept files by drag and drop.
4363 * @cfg {boolean} [showDropTarget=false] Whether to show a drop target. Requires droppable to be true.
4364 * @cfg {number} [thumbnailSizeLimit=20] File size limit in MiB above which to not try and show a
4365 * preview (for performance)
4367 OO.ui.SelectFileWidget = function OoUiSelectFileWidget( config ) {
4368 var dragHandler;
4370 // Configuration initialization
4371 config = $.extend( {
4372 accept: null,
4373 placeholder: OO.ui.msg( 'ooui-selectfile-placeholder' ),
4374 notsupported: OO.ui.msg( 'ooui-selectfile-not-supported' ),
4375 droppable: true,
4376 showDropTarget: false,
4377 thumbnailSizeLimit: 20
4378 }, config );
4380 // Parent constructor
4381 OO.ui.SelectFileWidget.parent.call( this, config );
4383 // Mixin constructors
4384 OO.ui.mixin.IconElement.call( this, config );
4385 OO.ui.mixin.IndicatorElement.call( this, config );
4386 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$info } ) );
4387 OO.ui.mixin.LabelElement.call( this, config );
4389 // Properties
4390 this.$info = $( '<span>' );
4391 this.showDropTarget = config.showDropTarget;
4392 this.thumbnailSizeLimit = config.thumbnailSizeLimit;
4393 this.isSupported = this.constructor.static.isSupported();
4394 this.currentFile = null;
4395 if ( Array.isArray( config.accept ) ) {
4396 this.accept = config.accept;
4397 } else {
4398 this.accept = null;
4400 this.placeholder = config.placeholder;
4401 this.notsupported = config.notsupported;
4402 this.onFileSelectedHandler = this.onFileSelected.bind( this );
4404 this.selectButton = new OO.ui.ButtonWidget( {
4405 classes: [ 'oo-ui-selectFileWidget-selectButton' ],
4406 label: OO.ui.msg( 'ooui-selectfile-button-select' ),
4407 disabled: this.disabled || !this.isSupported
4408 } );
4410 this.clearButton = new OO.ui.ButtonWidget( {
4411 classes: [ 'oo-ui-selectFileWidget-clearButton' ],
4412 framed: false,
4413 icon: 'close',
4414 disabled: this.disabled
4415 } );
4417 // Events
4418 this.selectButton.$button.on( {
4419 keypress: this.onKeyPress.bind( this )
4420 } );
4421 this.clearButton.connect( this, {
4422 click: 'onClearClick'
4423 } );
4424 if ( config.droppable ) {
4425 dragHandler = this.onDragEnterOrOver.bind( this );
4426 this.$element.on( {
4427 dragenter: dragHandler,
4428 dragover: dragHandler,
4429 dragleave: this.onDragLeave.bind( this ),
4430 drop: this.onDrop.bind( this )
4431 } );
4434 // Initialization
4435 this.addInput();
4436 this.$label.addClass( 'oo-ui-selectFileWidget-label' );
4437 this.$info
4438 .addClass( 'oo-ui-selectFileWidget-info' )
4439 .append( this.$icon, this.$label, this.clearButton.$element, this.$indicator );
4441 if ( config.droppable && config.showDropTarget ) {
4442 this.selectButton.setIcon( 'upload' );
4443 this.$thumbnail = $( '<div>' ).addClass( 'oo-ui-selectFileWidget-thumbnail' );
4444 this.setPendingElement( this.$thumbnail );
4445 this.$element
4446 .addClass( 'oo-ui-selectFileWidget-dropTarget oo-ui-selectFileWidget' )
4447 .on( {
4448 click: this.onDropTargetClick.bind( this )
4450 .append(
4451 this.$thumbnail,
4452 this.$info,
4453 this.selectButton.$element,
4454 $( '<span>' )
4455 .addClass( 'oo-ui-selectFileWidget-dropLabel' )
4456 .text( OO.ui.msg( 'ooui-selectfile-dragdrop-placeholder' ) )
4458 } else {
4459 this.$element
4460 .addClass( 'oo-ui-selectFileWidget' )
4461 .append( this.$info, this.selectButton.$element );
4463 this.updateUI();
4466 /* Setup */
4468 OO.inheritClass( OO.ui.SelectFileWidget, OO.ui.Widget );
4469 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IconElement );
4470 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IndicatorElement );
4471 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.PendingElement );
4472 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.LabelElement );
4474 /* Static Properties */
4477 * Check if this widget is supported
4479 * @static
4480 * @return {boolean}
4482 OO.ui.SelectFileWidget.static.isSupported = function () {
4483 var $input;
4484 if ( OO.ui.SelectFileWidget.static.isSupportedCache === null ) {
4485 $input = $( '<input>' ).attr( 'type', 'file' );
4486 OO.ui.SelectFileWidget.static.isSupportedCache = $input[ 0 ].files !== undefined;
4488 return OO.ui.SelectFileWidget.static.isSupportedCache;
4491 OO.ui.SelectFileWidget.static.isSupportedCache = null;
4493 /* Events */
4496 * @event change
4498 * A change event is emitted when the on/off state of the toggle changes.
4500 * @param {File|null} value New value
4503 /* Methods */
4506 * Get the current value of the field
4508 * @return {File|null}
4510 OO.ui.SelectFileWidget.prototype.getValue = function () {
4511 return this.currentFile;
4515 * Set the current value of the field
4517 * @param {File|null} file File to select
4519 OO.ui.SelectFileWidget.prototype.setValue = function ( file ) {
4520 if ( this.currentFile !== file ) {
4521 this.currentFile = file;
4522 this.updateUI();
4523 this.emit( 'change', this.currentFile );
4528 * Focus the widget.
4530 * Focusses the select file button.
4532 * @chainable
4534 OO.ui.SelectFileWidget.prototype.focus = function () {
4535 this.selectButton.$button[ 0 ].focus();
4536 return this;
4540 * Update the user interface when a file is selected or unselected
4542 * @protected
4544 OO.ui.SelectFileWidget.prototype.updateUI = function () {
4545 var $label;
4546 if ( !this.isSupported ) {
4547 this.$element.addClass( 'oo-ui-selectFileWidget-notsupported' );
4548 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
4549 this.setLabel( this.notsupported );
4550 } else {
4551 this.$element.addClass( 'oo-ui-selectFileWidget-supported' );
4552 if ( this.currentFile ) {
4553 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
4554 $label = $( [] );
4555 $label = $label.add(
4556 $( '<span>' )
4557 .addClass( 'oo-ui-selectFileWidget-fileName' )
4558 .text( this.currentFile.name )
4560 this.setLabel( $label );
4562 if ( this.showDropTarget ) {
4563 this.pushPending();
4564 this.loadAndGetImageUrl().done( function ( url ) {
4565 this.$thumbnail.css( 'background-image', 'url( ' + url + ' )' );
4566 }.bind( this ) ).fail( function () {
4567 this.$thumbnail.append(
4568 new OO.ui.IconWidget( {
4569 icon: 'attachment',
4570 classes: [ 'oo-ui-selectFileWidget-noThumbnail-icon' ]
4571 } ).$element
4573 }.bind( this ) ).always( function () {
4574 this.popPending();
4575 }.bind( this ) );
4576 this.$element.off( 'click' );
4578 } else {
4579 if ( this.showDropTarget ) {
4580 this.$element.off( 'click' );
4581 this.$element.on( {
4582 click: this.onDropTargetClick.bind( this )
4583 } );
4584 this.$thumbnail
4585 .empty()
4586 .css( 'background-image', '' );
4588 this.$element.addClass( 'oo-ui-selectFileWidget-empty' );
4589 this.setLabel( this.placeholder );
4595 * If the selected file is an image, get its URL and load it.
4597 * @return {jQuery.Promise} Promise resolves with the image URL after it has loaded
4599 OO.ui.SelectFileWidget.prototype.loadAndGetImageUrl = function () {
4600 var deferred = $.Deferred(),
4601 file = this.currentFile,
4602 reader = new FileReader();
4604 if (
4605 file &&
4606 ( OO.getProp( file, 'type' ) || '' ).indexOf( 'image/' ) === 0 &&
4607 file.size < this.thumbnailSizeLimit * 1024 * 1024
4609 reader.onload = function ( event ) {
4610 var img = document.createElement( 'img' );
4611 img.addEventListener( 'load', function () {
4612 if (
4613 img.naturalWidth === 0 ||
4614 img.naturalHeight === 0 ||
4615 img.complete === false
4617 deferred.reject();
4618 } else {
4619 deferred.resolve( event.target.result );
4621 } );
4622 img.src = event.target.result;
4624 reader.readAsDataURL( file );
4625 } else {
4626 deferred.reject();
4629 return deferred.promise();
4633 * Add the input to the widget
4635 * @private
4637 OO.ui.SelectFileWidget.prototype.addInput = function () {
4638 if ( this.$input ) {
4639 this.$input.remove();
4642 if ( !this.isSupported ) {
4643 this.$input = null;
4644 return;
4647 this.$input = $( '<input>' ).attr( 'type', 'file' );
4648 this.$input.on( 'change', this.onFileSelectedHandler );
4649 this.$input.on( 'click', function ( e ) {
4650 // Prevents dropTarget to get clicked which calls
4651 // a click on this input
4652 e.stopPropagation();
4653 } );
4654 this.$input.attr( {
4655 tabindex: -1
4656 } );
4657 if ( this.accept ) {
4658 this.$input.attr( 'accept', this.accept.join( ', ' ) );
4660 this.selectButton.$button.append( this.$input );
4664 * Determine if we should accept this file
4666 * @private
4667 * @param {string} mimeType File MIME type
4668 * @return {boolean}
4670 OO.ui.SelectFileWidget.prototype.isAllowedType = function ( mimeType ) {
4671 var i, mimeTest;
4673 if ( !this.accept || !mimeType ) {
4674 return true;
4677 for ( i = 0; i < this.accept.length; i++ ) {
4678 mimeTest = this.accept[ i ];
4679 if ( mimeTest === mimeType ) {
4680 return true;
4681 } else if ( mimeTest.substr( -2 ) === '/*' ) {
4682 mimeTest = mimeTest.substr( 0, mimeTest.length - 1 );
4683 if ( mimeType.substr( 0, mimeTest.length ) === mimeTest ) {
4684 return true;
4689 return false;
4693 * Handle file selection from the input
4695 * @private
4696 * @param {jQuery.Event} e
4698 OO.ui.SelectFileWidget.prototype.onFileSelected = function ( e ) {
4699 var file = OO.getProp( e.target, 'files', 0 ) || null;
4701 if ( file && !this.isAllowedType( file.type ) ) {
4702 file = null;
4705 this.setValue( file );
4706 this.addInput();
4710 * Handle clear button click events.
4712 * @private
4714 OO.ui.SelectFileWidget.prototype.onClearClick = function () {
4715 this.setValue( null );
4716 return false;
4720 * Handle key press events.
4722 * @private
4723 * @param {jQuery.Event} e Key press event
4725 OO.ui.SelectFileWidget.prototype.onKeyPress = function ( e ) {
4726 if ( this.isSupported && !this.isDisabled() && this.$input &&
4727 ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
4729 this.$input.click();
4730 return false;
4735 * Handle drop target click events.
4737 * @private
4738 * @param {jQuery.Event} e Key press event
4740 OO.ui.SelectFileWidget.prototype.onDropTargetClick = function () {
4741 if ( this.isSupported && !this.isDisabled() && this.$input ) {
4742 this.$input.click();
4743 return false;
4748 * Handle drag enter and over events
4750 * @private
4751 * @param {jQuery.Event} e Drag event
4753 OO.ui.SelectFileWidget.prototype.onDragEnterOrOver = function ( e ) {
4754 var itemOrFile,
4755 droppableFile = false,
4756 dt = e.originalEvent.dataTransfer;
4758 e.preventDefault();
4759 e.stopPropagation();
4761 if ( this.isDisabled() || !this.isSupported ) {
4762 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
4763 dt.dropEffect = 'none';
4764 return false;
4767 // DataTransferItem and File both have a type property, but in Chrome files
4768 // have no information at this point.
4769 itemOrFile = OO.getProp( dt, 'items', 0 ) || OO.getProp( dt, 'files', 0 );
4770 if ( itemOrFile ) {
4771 if ( this.isAllowedType( itemOrFile.type ) ) {
4772 droppableFile = true;
4774 // dt.types is Array-like, but not an Array
4775 } else if ( Array.prototype.indexOf.call( OO.getProp( dt, 'types' ) || [], 'Files' ) !== -1 ) {
4776 // File information is not available at this point for security so just assume
4777 // it is acceptable for now.
4778 // https://bugzilla.mozilla.org/show_bug.cgi?id=640534
4779 droppableFile = true;
4782 this.$element.toggleClass( 'oo-ui-selectFileWidget-canDrop', droppableFile );
4783 if ( !droppableFile ) {
4784 dt.dropEffect = 'none';
4787 return false;
4791 * Handle drag leave events
4793 * @private
4794 * @param {jQuery.Event} e Drag event
4796 OO.ui.SelectFileWidget.prototype.onDragLeave = function () {
4797 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
4801 * Handle drop events
4803 * @private
4804 * @param {jQuery.Event} e Drop event
4806 OO.ui.SelectFileWidget.prototype.onDrop = function ( e ) {
4807 var file = null,
4808 dt = e.originalEvent.dataTransfer;
4810 e.preventDefault();
4811 e.stopPropagation();
4812 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
4814 if ( this.isDisabled() || !this.isSupported ) {
4815 return false;
4818 file = OO.getProp( dt, 'files', 0 );
4819 if ( file && !this.isAllowedType( file.type ) ) {
4820 file = null;
4822 if ( file ) {
4823 this.setValue( file );
4826 return false;
4830 * @inheritdoc
4832 OO.ui.SelectFileWidget.prototype.setDisabled = function ( disabled ) {
4833 OO.ui.SelectFileWidget.parent.prototype.setDisabled.call( this, disabled );
4834 if ( this.selectButton ) {
4835 this.selectButton.setDisabled( disabled );
4837 if ( this.clearButton ) {
4838 this.clearButton.setDisabled( disabled );
4840 return this;
4844 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
4845 * and a menu of search results, which is displayed beneath the query
4846 * field. Unlike {@link OO.ui.mixin.LookupElement lookup menus}, search result menus are always visible to the user.
4847 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
4848 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
4850 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
4851 * the [OOjs UI demos][1] for an example.
4853 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
4855 * @class
4856 * @extends OO.ui.Widget
4858 * @constructor
4859 * @param {Object} [config] Configuration options
4860 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
4861 * @cfg {string} [value] Initial query value
4863 OO.ui.SearchWidget = function OoUiSearchWidget( config ) {
4864 // Configuration initialization
4865 config = config || {};
4867 // Parent constructor
4868 OO.ui.SearchWidget.parent.call( this, config );
4870 // Properties
4871 this.query = new OO.ui.TextInputWidget( {
4872 icon: 'search',
4873 placeholder: config.placeholder,
4874 value: config.value
4875 } );
4876 this.results = new OO.ui.SelectWidget();
4877 this.$query = $( '<div>' );
4878 this.$results = $( '<div>' );
4880 // Events
4881 this.query.connect( this, {
4882 change: 'onQueryChange',
4883 enter: 'onQueryEnter'
4884 } );
4885 this.query.$input.on( 'keydown', this.onQueryKeydown.bind( this ) );
4887 // Initialization
4888 this.$query
4889 .addClass( 'oo-ui-searchWidget-query' )
4890 .append( this.query.$element );
4891 this.$results
4892 .addClass( 'oo-ui-searchWidget-results' )
4893 .append( this.results.$element );
4894 this.$element
4895 .addClass( 'oo-ui-searchWidget' )
4896 .append( this.$results, this.$query );
4899 /* Setup */
4901 OO.inheritClass( OO.ui.SearchWidget, OO.ui.Widget );
4903 /* Methods */
4906 * Handle query key down events.
4908 * @private
4909 * @param {jQuery.Event} e Key down event
4911 OO.ui.SearchWidget.prototype.onQueryKeydown = function ( e ) {
4912 var highlightedItem, nextItem,
4913 dir = e.which === OO.ui.Keys.DOWN ? 1 : ( e.which === OO.ui.Keys.UP ? -1 : 0 );
4915 if ( dir ) {
4916 highlightedItem = this.results.getHighlightedItem();
4917 if ( !highlightedItem ) {
4918 highlightedItem = this.results.getSelectedItem();
4920 nextItem = this.results.getRelativeSelectableItem( highlightedItem, dir );
4921 this.results.highlightItem( nextItem );
4922 nextItem.scrollElementIntoView();
4927 * Handle select widget select events.
4929 * Clears existing results. Subclasses should repopulate items according to new query.
4931 * @private
4932 * @param {string} value New value
4934 OO.ui.SearchWidget.prototype.onQueryChange = function () {
4935 // Reset
4936 this.results.clearItems();
4940 * Handle select widget enter key events.
4942 * Chooses highlighted item.
4944 * @private
4945 * @param {string} value New value
4947 OO.ui.SearchWidget.prototype.onQueryEnter = function () {
4948 var highlightedItem = this.results.getHighlightedItem();
4949 if ( highlightedItem ) {
4950 this.results.chooseItem( highlightedItem );
4955 * Get the query input.
4957 * @return {OO.ui.TextInputWidget} Query input
4959 OO.ui.SearchWidget.prototype.getQuery = function () {
4960 return this.query;
4964 * Get the search results menu.
4966 * @return {OO.ui.SelectWidget} Menu of search results
4968 OO.ui.SearchWidget.prototype.getResults = function () {
4969 return this.results;
4973 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
4974 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
4975 * (to adjust the value in increments) to allow the user to enter a number.
4977 * @example
4978 * // Example: A NumberInputWidget.
4979 * var numberInput = new OO.ui.NumberInputWidget( {
4980 * label: 'NumberInputWidget',
4981 * input: { value: 5 },
4982 * min: 1,
4983 * max: 10
4984 * } );
4985 * $( 'body' ).append( numberInput.$element );
4987 * @class
4988 * @extends OO.ui.Widget
4990 * @constructor
4991 * @param {Object} [config] Configuration options
4992 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
4993 * @cfg {Object} [minusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget decrementing button widget}.
4994 * @cfg {Object} [plusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget incrementing button widget}.
4995 * @cfg {boolean} [isInteger=false] Whether the field accepts only integer values.
4996 * @cfg {number} [min=-Infinity] Minimum allowed value
4997 * @cfg {number} [max=Infinity] Maximum allowed value
4998 * @cfg {number} [step=1] Delta when using the buttons or up/down arrow keys
4999 * @cfg {number|null} [pageStep] Delta when using the page-up/page-down keys. Defaults to 10 times #step.
5000 * @cfg {boolean} [showButtons=true] Whether to show the plus and minus buttons.
5002 OO.ui.NumberInputWidget = function OoUiNumberInputWidget( config ) {
5003 // Configuration initialization
5004 config = $.extend( {
5005 isInteger: false,
5006 min: -Infinity,
5007 max: Infinity,
5008 step: 1,
5009 pageStep: null,
5010 showButtons: true
5011 }, config );
5013 // Parent constructor
5014 OO.ui.NumberInputWidget.parent.call( this, config );
5016 // Properties
5017 this.input = new OO.ui.TextInputWidget( $.extend(
5019 disabled: this.isDisabled(),
5020 type: 'number'
5022 config.input
5023 ) );
5024 if ( config.showButtons ) {
5025 this.minusButton = new OO.ui.ButtonWidget( $.extend(
5027 disabled: this.isDisabled(),
5028 tabIndex: -1,
5029 classes: [ 'oo-ui-numberInputWidget-minusButton' ],
5030 label: '−'
5032 config.minusButton
5033 ) );
5034 this.plusButton = new OO.ui.ButtonWidget( $.extend(
5036 disabled: this.isDisabled(),
5037 tabIndex: -1,
5038 classes: [ 'oo-ui-numberInputWidget-plusButton' ],
5039 label: '+'
5041 config.plusButton
5042 ) );
5045 // Events
5046 this.input.connect( this, {
5047 change: this.emit.bind( this, 'change' ),
5048 enter: this.emit.bind( this, 'enter' )
5049 } );
5050 this.input.$input.on( {
5051 keydown: this.onKeyDown.bind( this ),
5052 'wheel mousewheel DOMMouseScroll': this.onWheel.bind( this )
5053 } );
5054 if ( config.showButtons ) {
5055 this.plusButton.connect( this, {
5056 click: [ 'onButtonClick', +1 ]
5057 } );
5058 this.minusButton.connect( this, {
5059 click: [ 'onButtonClick', -1 ]
5060 } );
5063 // Initialization
5064 this.setIsInteger( !!config.isInteger );
5065 this.setRange( config.min, config.max );
5066 this.setStep( config.step, config.pageStep );
5068 this.$field = $( '<div>' ).addClass( 'oo-ui-numberInputWidget-field' )
5069 .append( this.input.$element );
5070 this.$element.addClass( 'oo-ui-numberInputWidget' ).append( this.$field );
5071 if ( config.showButtons ) {
5072 this.$field
5073 .prepend( this.minusButton.$element )
5074 .append( this.plusButton.$element );
5075 this.$element.addClass( 'oo-ui-numberInputWidget-buttoned' );
5077 this.input.setValidation( this.validateNumber.bind( this ) );
5080 /* Setup */
5082 OO.inheritClass( OO.ui.NumberInputWidget, OO.ui.Widget );
5084 /* Events */
5087 * A `change` event is emitted when the value of the input changes.
5089 * @event change
5093 * An `enter` event is emitted when the user presses 'enter' inside the text box.
5095 * @event enter
5098 /* Methods */
5101 * Set whether only integers are allowed
5103 * @param {boolean} flag
5105 OO.ui.NumberInputWidget.prototype.setIsInteger = function ( flag ) {
5106 this.isInteger = !!flag;
5107 this.input.setValidityFlag();
5111 * Get whether only integers are allowed
5113 * @return {boolean} Flag value
5115 OO.ui.NumberInputWidget.prototype.getIsInteger = function () {
5116 return this.isInteger;
5120 * Set the range of allowed values
5122 * @param {number} min Minimum allowed value
5123 * @param {number} max Maximum allowed value
5125 OO.ui.NumberInputWidget.prototype.setRange = function ( min, max ) {
5126 if ( min > max ) {
5127 throw new Error( 'Minimum (' + min + ') must not be greater than maximum (' + max + ')' );
5129 this.min = min;
5130 this.max = max;
5131 this.input.setValidityFlag();
5135 * Get the current range
5137 * @return {number[]} Minimum and maximum values
5139 OO.ui.NumberInputWidget.prototype.getRange = function () {
5140 return [ this.min, this.max ];
5144 * Set the stepping deltas
5146 * @param {number} step Normal step
5147 * @param {number|null} pageStep Page step. If null, 10 * step will be used.
5149 OO.ui.NumberInputWidget.prototype.setStep = function ( step, pageStep ) {
5150 if ( step <= 0 ) {
5151 throw new Error( 'Step value must be positive' );
5153 if ( pageStep === null ) {
5154 pageStep = step * 10;
5155 } else if ( pageStep <= 0 ) {
5156 throw new Error( 'Page step value must be positive' );
5158 this.step = step;
5159 this.pageStep = pageStep;
5163 * Get the current stepping values
5165 * @return {number[]} Step and page step
5167 OO.ui.NumberInputWidget.prototype.getStep = function () {
5168 return [ this.step, this.pageStep ];
5172 * Get the current value of the widget
5174 * @return {string}
5176 OO.ui.NumberInputWidget.prototype.getValue = function () {
5177 return this.input.getValue();
5181 * Get the current value of the widget as a number
5183 * @return {number} May be NaN, or an invalid number
5185 OO.ui.NumberInputWidget.prototype.getNumericValue = function () {
5186 return +this.input.getValue();
5190 * Set the value of the widget
5192 * @param {string} value Invalid values are allowed
5194 OO.ui.NumberInputWidget.prototype.setValue = function ( value ) {
5195 this.input.setValue( value );
5199 * Adjust the value of the widget
5201 * @param {number} delta Adjustment amount
5203 OO.ui.NumberInputWidget.prototype.adjustValue = function ( delta ) {
5204 var n, v = this.getNumericValue();
5206 delta = +delta;
5207 if ( isNaN( delta ) || !isFinite( delta ) ) {
5208 throw new Error( 'Delta must be a finite number' );
5211 if ( isNaN( v ) ) {
5212 n = 0;
5213 } else {
5214 n = v + delta;
5215 n = Math.max( Math.min( n, this.max ), this.min );
5216 if ( this.isInteger ) {
5217 n = Math.round( n );
5221 if ( n !== v ) {
5222 this.setValue( n );
5227 * Validate input
5229 * @private
5230 * @param {string} value Field value
5231 * @return {boolean}
5233 OO.ui.NumberInputWidget.prototype.validateNumber = function ( value ) {
5234 var n = +value;
5235 if ( isNaN( n ) || !isFinite( n ) ) {
5236 return false;
5239 if ( this.isInteger && Math.floor( n ) !== n ) {
5240 return false;
5243 if ( n < this.min || n > this.max ) {
5244 return false;
5247 return true;
5251 * Handle mouse click events.
5253 * @private
5254 * @param {number} dir +1 or -1
5256 OO.ui.NumberInputWidget.prototype.onButtonClick = function ( dir ) {
5257 this.adjustValue( dir * this.step );
5261 * Handle mouse wheel events.
5263 * @private
5264 * @param {jQuery.Event} event
5266 OO.ui.NumberInputWidget.prototype.onWheel = function ( event ) {
5267 var delta = 0;
5269 if ( !this.isDisabled() && this.input.$input.is( ':focus' ) ) {
5270 // Standard 'wheel' event
5271 if ( event.originalEvent.deltaMode !== undefined ) {
5272 this.sawWheelEvent = true;
5274 if ( event.originalEvent.deltaY ) {
5275 delta = -event.originalEvent.deltaY;
5276 } else if ( event.originalEvent.deltaX ) {
5277 delta = event.originalEvent.deltaX;
5280 // Non-standard events
5281 if ( !this.sawWheelEvent ) {
5282 if ( event.originalEvent.wheelDeltaX ) {
5283 delta = -event.originalEvent.wheelDeltaX;
5284 } else if ( event.originalEvent.wheelDeltaY ) {
5285 delta = event.originalEvent.wheelDeltaY;
5286 } else if ( event.originalEvent.wheelDelta ) {
5287 delta = event.originalEvent.wheelDelta;
5288 } else if ( event.originalEvent.detail ) {
5289 delta = -event.originalEvent.detail;
5293 if ( delta ) {
5294 delta = delta < 0 ? -1 : 1;
5295 this.adjustValue( delta * this.step );
5298 return false;
5303 * Handle key down events.
5305 * @private
5306 * @param {jQuery.Event} e Key down event
5308 OO.ui.NumberInputWidget.prototype.onKeyDown = function ( e ) {
5309 if ( !this.isDisabled() ) {
5310 switch ( e.which ) {
5311 case OO.ui.Keys.UP:
5312 this.adjustValue( this.step );
5313 return false;
5314 case OO.ui.Keys.DOWN:
5315 this.adjustValue( -this.step );
5316 return false;
5317 case OO.ui.Keys.PAGEUP:
5318 this.adjustValue( this.pageStep );
5319 return false;
5320 case OO.ui.Keys.PAGEDOWN:
5321 this.adjustValue( -this.pageStep );
5322 return false;
5328 * @inheritdoc
5330 OO.ui.NumberInputWidget.prototype.setDisabled = function ( disabled ) {
5331 // Parent method
5332 OO.ui.NumberInputWidget.parent.prototype.setDisabled.call( this, disabled );
5334 if ( this.input ) {
5335 this.input.setDisabled( this.isDisabled() );
5337 if ( this.minusButton ) {
5338 this.minusButton.setDisabled( this.isDisabled() );
5340 if ( this.plusButton ) {
5341 this.plusButton.setDisabled( this.isDisabled() );
5344 return this;
5347 }( OO ) );