3 * https://www.mediawiki.org/wiki/OOjs_UI
5 * Copyright 2011–2016 OOjs UI Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
9 * Date: 2016-07-12T20:26:03Z
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.
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
|| {};
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 )
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 )
49 this.$handle
.addClass( 'oo-ui-draggableElement-handle' );
52 OO
.initClass( OO
.ui
.mixin
.DraggableElement
);
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.
65 * A dragend event is emitted when the user drags an item and releases the mouse,
66 * thus terminating the drag operation.
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 */
78 * @inheritdoc OO.ui.mixin.ButtonElement
80 OO
.ui
.mixin
.DraggableElement
.static.cancelButtonMouseDownEvents
= false;
85 * Respond to mousedown event.
88 * @param {jQuery.Event} e jQuery event
90 OO
.ui
.mixin
.DraggableElement
.prototype.onDragMouseDown = function ( e
) {
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 );
99 * Respond to dragstart event.
102 * @param {jQuery.Event} e jQuery event
105 OO
.ui
.mixin
.DraggableElement
.prototype.onDragStart = function ( e
) {
107 dataTransfer
= e
.originalEvent
.dataTransfer
;
109 if ( !this.wasHandleUsed
) {
113 // Define drop effect
114 dataTransfer
.dropEffect
= 'none';
115 dataTransfer
.effectAllowed
= 'move';
117 // We must set up a dataTransfer data property or Firefox seems to
118 // ignore the fact the element is draggable.
120 dataTransfer
.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
122 // The above is only for Firefox. Move on if it fails.
124 // Briefly add a 'clone' class to style the browser's native drag image
125 this.$element
.addClass( 'oo-ui-draggableElement-clone' );
126 // Add placeholder class after the browser has rendered the clone
127 setTimeout( function () {
129 .removeClass( 'oo-ui-draggableElement-clone' )
130 .addClass( 'oo-ui-draggableElement-placeholder' );
133 this.emit( 'dragstart', this );
138 * Respond to dragend event.
143 OO
.ui
.mixin
.DraggableElement
.prototype.onDragEnd = function () {
144 this.$element
.removeClass( 'oo-ui-draggableElement-placeholder' );
145 this.emit( 'dragend' );
152 * @param {jQuery.Event} e jQuery event
155 OO
.ui
.mixin
.DraggableElement
.prototype.onDrop = function ( e
) {
157 this.emit( 'drop', e
);
161 * In order for drag/drop to work, the dragover event must
162 * return false and stop propogation.
166 OO
.ui
.mixin
.DraggableElement
.prototype.onDragOver = function ( e
) {
172 * Store it in the DOM so we can access from the widget drag event
175 * @param {number} index Item index
177 OO
.ui
.mixin
.DraggableElement
.prototype.setIndex = function ( index
) {
178 if ( this.index
!== index
) {
180 this.$element
.data( 'index', index
);
188 * @return {number} Item index
190 OO
.ui
.mixin
.DraggableElement
.prototype.getIndex = function () {
195 * DraggableGroupElement is a mixin class used to create a group element to
196 * contain draggable elements, which are items that can be clicked and dragged by a mouse.
197 * The class is used with OO.ui.mixin.DraggableElement.
201 * @mixins OO.ui.mixin.GroupElement
204 * @param {Object} [config] Configuration options
205 * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation
206 * should match the layout of the items. Items displayed in a single row
207 * or in several rows should use horizontal orientation. The vertical orientation should only be
208 * used when the items are displayed in a single column. Defaults to 'vertical'
210 OO
.ui
.mixin
.DraggableGroupElement
= function OoUiMixinDraggableGroupElement( config
) {
211 // Configuration initialization
212 config
= config
|| {};
214 // Parent constructor
215 OO
.ui
.mixin
.GroupElement
.call( this, config
);
218 this.orientation
= config
.orientation
|| 'vertical';
219 this.dragItem
= null;
222 this.itemsOrder
= null;
226 dragstart
: 'itemDragStart',
227 dragend
: 'itemDragEnd',
230 this.connect( this, {
231 itemDragStart
: 'onItemDragStart',
232 itemDrop
: 'onItemDropOrDragEnd',
233 itemDragEnd
: 'onItemDropOrDragEnd'
237 if ( Array
.isArray( config
.items
) ) {
238 this.addItems( config
.items
);
241 .addClass( 'oo-ui-draggableGroupElement' )
242 .append( this.$status
)
243 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation
=== 'horizontal' );
247 OO
.mixinClass( OO
.ui
.mixin
.DraggableGroupElement
, OO
.ui
.mixin
.GroupElement
);
252 * An item has been dragged to a new position, but not yet dropped.
255 * @param {OO.ui.mixin.DraggableElement} item Dragged item
256 * @param {number} [newIndex] New index for the item
260 * And item has been dropped at a new position.
263 * @param {OO.ui.mixin.DraggableElement} item Reordered item
264 * @param {number} [newIndex] New index for the item
270 * Respond to item drag start event
273 * @param {OO.ui.mixin.DraggableElement} item Dragged item
275 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onItemDragStart = function ( item
) {
276 // Make a shallow copy of this.items so we can re-order it during previews
277 // without affecting the original array.
278 this.itemsOrder
= this.items
.slice();
279 this.updateIndexes();
280 if ( this.orientation
=== 'horizontal' ) {
281 // Calculate and cache directionality on drag start - it's a little
282 // expensive and it shouldn't change while dragging.
283 this.dir
= this.$element
.css( 'direction' );
285 this.setDragItem( item
);
289 * Update the index properties of the items
291 OO
.ui
.mixin
.DraggableGroupElement
.prototype.updateIndexes = function () {
294 // Map the index of each object
295 for ( i
= 0, len
= this.itemsOrder
.length
; i
< len
; i
++ ) {
296 this.itemsOrder
[ i
].setIndex( i
);
301 * Handle drop or dragend event and switch the order of the items accordingly
304 * @param {OO.ui.mixin.DraggableElement} item Dropped item
306 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onItemDropOrDragEnd = function () {
307 var targetIndex
, originalIndex
,
308 item
= this.getDragItem();
310 // TODO: Figure out a way to configure a list of legally droppable
311 // elements even if they are not yet in the list
313 originalIndex
= this.items
.indexOf( item
);
314 // If the item has moved forward, add one to the index to account for the left shift
315 targetIndex
= item
.getIndex() + ( item
.getIndex() > originalIndex
? 1 : 0 );
316 if ( targetIndex
!== originalIndex
) {
317 this.reorder( this.getDragItem(), targetIndex
);
318 this.emit( 'reorder', this.getDragItem(), targetIndex
);
320 this.updateIndexes();
322 this.unsetDragItem();
323 // Return false to prevent propogation
328 * Respond to dragover event
331 * @param {jQuery.Event} e Dragover event
334 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onDragOver = function ( e
) {
335 var overIndex
, targetIndex
,
336 item
= this.getDragItem(),
337 dragItemIndex
= item
.getIndex();
339 // Get the OptionWidget item we are dragging over
340 overIndex
= $( e
.target
).closest( '.oo-ui-draggableElement' ).data( 'index' );
342 if ( overIndex
!== undefined && overIndex
!== dragItemIndex
) {
343 targetIndex
= overIndex
+ ( overIndex
> dragItemIndex
? 1 : 0 );
345 if ( targetIndex
> 0 ) {
346 this.$group
.children().eq( targetIndex
- 1 ).after( item
.$element
);
348 this.$group
.prepend( item
.$element
);
350 // Move item in itemsOrder array
351 this.itemsOrder
.splice( overIndex
, 0,
352 this.itemsOrder
.splice( dragItemIndex
, 1 )[ 0 ]
354 this.updateIndexes();
355 this.emit( 'drag', item
, targetIndex
);
362 * Reorder the items in the group
364 * @param {OO.ui.mixin.DraggableElement} item Reordered item
365 * @param {number} newIndex New index
367 OO
.ui
.mixin
.DraggableGroupElement
.prototype.reorder = function ( item
, newIndex
) {
368 this.addItems( [ item
], newIndex
);
374 * @param {OO.ui.mixin.DraggableElement} item Dragged item
376 OO
.ui
.mixin
.DraggableGroupElement
.prototype.setDragItem = function ( item
) {
377 if ( this.dragItem
!== item
) {
378 this.dragItem
= item
;
379 this.$element
.on( 'dragover', this.onDragOver
.bind( this ) );
380 this.$element
.addClass( 'oo-ui-draggableGroupElement-dragging' );
385 * Unset the current dragged item
387 OO
.ui
.mixin
.DraggableGroupElement
.prototype.unsetDragItem = function () {
388 if ( this.dragItem
) {
389 this.dragItem
= null;
390 this.$element
.off( 'dragover' );
391 this.$element
.removeClass( 'oo-ui-draggableGroupElement-dragging' );
396 * Get the item that is currently being dragged.
398 * @return {OO.ui.mixin.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged
400 OO
.ui
.mixin
.DraggableGroupElement
.prototype.getDragItem = function () {
401 return this.dragItem
;
405 * RequestManager is a mixin that manages the lifecycle of a promise-backed request for a widget, such as
406 * the {@link OO.ui.mixin.LookupElement}.
413 OO
.ui
.mixin
.RequestManager
= function OoUiMixinRequestManager() {
414 this.requestCache
= {};
415 this.requestQuery
= null;
416 this.requestRequest
= null;
421 OO
.initClass( OO
.ui
.mixin
.RequestManager
);
424 * Get request results for the current query.
426 * @return {jQuery.Promise} Promise object which will be passed response data as the first argument of
427 * the done event. If the request was aborted to make way for a subsequent request, this promise
428 * may not be rejected, depending on what jQuery feels like doing.
430 OO
.ui
.mixin
.RequestManager
.prototype.getRequestData = function () {
432 value
= this.getRequestQuery(),
433 deferred
= $.Deferred(),
437 if ( Object
.prototype.hasOwnProperty
.call( this.requestCache
, value
) ) {
438 deferred
.resolve( this.requestCache
[ value
] );
440 if ( this.pushPending
) {
443 this.requestQuery
= value
;
444 ourRequest
= this.requestRequest
= this.getRequest();
446 .always( function () {
447 // We need to pop pending even if this is an old request, otherwise
448 // the widget will remain pending forever.
449 // TODO: this assumes that an aborted request will fail or succeed soon after
450 // being aborted, or at least eventually. It would be nice if we could popPending()
451 // at abort time, but only if we knew that we hadn't already called popPending()
453 if ( widget
.popPending
) {
457 .done( function ( response
) {
458 // If this is an old request (and aborting it somehow caused it to still succeed),
459 // ignore its success completely
460 if ( ourRequest
=== widget
.requestRequest
) {
461 widget
.requestQuery
= null;
462 widget
.requestRequest
= null;
463 widget
.requestCache
[ value
] = widget
.getRequestCacheDataFromResponse( response
);
464 deferred
.resolve( widget
.requestCache
[ value
] );
468 // If this is an old request (or a request failing because it's being aborted),
469 // ignore its failure completely
470 if ( ourRequest
=== widget
.requestRequest
) {
471 widget
.requestQuery
= null;
472 widget
.requestRequest
= null;
477 return deferred
.promise();
481 * Abort the currently pending request, if any.
485 OO
.ui
.mixin
.RequestManager
.prototype.abortRequest = function () {
486 var oldRequest
= this.requestRequest
;
488 // First unset this.requestRequest to the fail handler will notice
489 // that the request is no longer current
490 this.requestRequest
= null;
491 this.requestQuery
= null;
497 * Get the query to be made.
502 * @return {string} query to be used
504 OO
.ui
.mixin
.RequestManager
.prototype.getRequestQuery
= null;
507 * Get a new request object of the current query value.
512 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
514 OO
.ui
.mixin
.RequestManager
.prototype.getRequest
= null;
517 * Pre-process data returned by the request from #getRequest.
519 * The return value of this function will be cached, and any further queries for the given value
520 * will use the cache rather than doing API requests.
525 * @param {Mixed} response Response from server
526 * @return {Mixed} Cached result data
528 OO
.ui
.mixin
.RequestManager
.prototype.getRequestCacheDataFromResponse
= null;
531 * LookupElement is a mixin that creates a {@link OO.ui.FloatingMenuSelectWidget menu} of suggested values for
532 * a {@link OO.ui.TextInputWidget text input widget}. Suggested values are based on the characters the user types
533 * into the text input field and, in general, the menu is only displayed when the user types. If a suggested value is chosen
534 * from the lookup menu, that value becomes the value of the input field.
536 * Note that a new menu of suggested items is displayed when a value is chosen from the lookup menu. If this is
537 * not the desired behavior, disable lookup menus with the #setLookupsDisabled method, then set the value, then
540 * See the [OOjs UI demos][1] for an example.
542 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/index.html#widgets-apex-vector-ltr
546 * @mixins OO.ui.mixin.RequestManager
549 * @param {Object} [config] Configuration options
550 * @cfg {jQuery} [$overlay] Overlay for the lookup menu; defaults to relative positioning
551 * @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element.
552 * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty.
553 * By default, the lookup menu is not generated and displayed until the user begins to type.
554 * @cfg {boolean} [highlightFirst=true] Whether the first lookup result should be highlighted (so, that the user can
555 * take it over into the input with simply pressing return) automatically or not.
557 OO
.ui
.mixin
.LookupElement
= function OoUiMixinLookupElement( config
) {
558 // Configuration initialization
559 config
= $.extend( { highlightFirst
: true }, config
);
561 // Mixin constructors
562 OO
.ui
.mixin
.RequestManager
.call( this, config
);
565 this.$overlay
= config
.$overlay
|| this.$element
;
566 this.lookupMenu
= new OO
.ui
.FloatingMenuSelectWidget( {
569 $container
: config
.$container
|| this.$element
572 this.allowSuggestionsWhenEmpty
= config
.allowSuggestionsWhenEmpty
|| false;
574 this.lookupsDisabled
= false;
575 this.lookupInputFocused
= false;
576 this.lookupHighlightFirstItem
= config
.highlightFirst
;
580 focus
: this.onLookupInputFocus
.bind( this ),
581 blur
: this.onLookupInputBlur
.bind( this ),
582 mousedown
: this.onLookupInputMouseDown
.bind( this )
584 this.connect( this, { change
: 'onLookupInputChange' } );
585 this.lookupMenu
.connect( this, {
586 toggle
: 'onLookupMenuToggle',
587 choose
: 'onLookupMenuItemChoose'
591 this.$element
.addClass( 'oo-ui-lookupElement' );
592 this.lookupMenu
.$element
.addClass( 'oo-ui-lookupElement-menu' );
593 this.$overlay
.append( this.lookupMenu
.$element
);
598 OO
.mixinClass( OO
.ui
.mixin
.LookupElement
, OO
.ui
.mixin
.RequestManager
);
603 * Handle input focus event.
606 * @param {jQuery.Event} e Input focus event
608 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputFocus = function () {
609 this.lookupInputFocused
= true;
610 this.populateLookupMenu();
614 * Handle input blur event.
617 * @param {jQuery.Event} e Input blur event
619 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputBlur = function () {
620 this.closeLookupMenu();
621 this.lookupInputFocused
= false;
625 * Handle input mouse down event.
628 * @param {jQuery.Event} e Input mouse down event
630 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputMouseDown = function () {
631 // Only open the menu if the input was already focused.
632 // This way we allow the user to open the menu again after closing it with Esc
633 // by clicking in the input. Opening (and populating) the menu when initially
634 // clicking into the input is handled by the focus handler.
635 if ( this.lookupInputFocused
&& !this.lookupMenu
.isVisible() ) {
636 this.populateLookupMenu();
641 * Handle input change event.
644 * @param {string} value New input value
646 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputChange = function () {
647 if ( this.lookupInputFocused
) {
648 this.populateLookupMenu();
653 * Handle the lookup menu being shown/hidden.
656 * @param {boolean} visible Whether the lookup menu is now visible.
658 OO
.ui
.mixin
.LookupElement
.prototype.onLookupMenuToggle = function ( visible
) {
660 // When the menu is hidden, abort any active request and clear the menu.
661 // This has to be done here in addition to closeLookupMenu(), because
662 // MenuSelectWidget will close itself when the user presses Esc.
663 this.abortLookupRequest();
664 this.lookupMenu
.clearItems();
669 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
672 * @param {OO.ui.MenuOptionWidget} item Selected item
674 OO
.ui
.mixin
.LookupElement
.prototype.onLookupMenuItemChoose = function ( item
) {
675 this.setValue( item
.getData() );
682 * @return {OO.ui.FloatingMenuSelectWidget}
684 OO
.ui
.mixin
.LookupElement
.prototype.getLookupMenu = function () {
685 return this.lookupMenu
;
689 * Disable or re-enable lookups.
691 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
693 * @param {boolean} disabled Disable lookups
695 OO
.ui
.mixin
.LookupElement
.prototype.setLookupsDisabled = function ( disabled
) {
696 this.lookupsDisabled
= !!disabled
;
700 * Open the menu. If there are no entries in the menu, this does nothing.
705 OO
.ui
.mixin
.LookupElement
.prototype.openLookupMenu = function () {
706 if ( !this.lookupMenu
.isEmpty() ) {
707 this.lookupMenu
.toggle( true );
713 * Close the menu, empty it, and abort any pending request.
718 OO
.ui
.mixin
.LookupElement
.prototype.closeLookupMenu = function () {
719 this.lookupMenu
.toggle( false );
720 this.abortLookupRequest();
721 this.lookupMenu
.clearItems();
726 * Request menu items based on the input's current value, and when they arrive,
727 * populate the menu with these items and show the menu.
729 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
734 OO
.ui
.mixin
.LookupElement
.prototype.populateLookupMenu = function () {
736 value
= this.getValue();
738 if ( this.lookupsDisabled
|| this.isReadOnly() ) {
742 // If the input is empty, clear the menu, unless suggestions when empty are allowed.
743 if ( !this.allowSuggestionsWhenEmpty
&& value
=== '' ) {
744 this.closeLookupMenu();
745 // Skip population if there is already a request pending for the current value
746 } else if ( value
!== this.lookupQuery
) {
747 this.getLookupMenuItems()
748 .done( function ( items
) {
749 widget
.lookupMenu
.clearItems();
750 if ( items
.length
) {
754 widget
.initializeLookupMenuSelection();
756 widget
.lookupMenu
.toggle( false );
760 widget
.lookupMenu
.clearItems();
768 * Highlight the first selectable item in the menu, if configured.
773 OO
.ui
.mixin
.LookupElement
.prototype.initializeLookupMenuSelection = function () {
774 if ( this.lookupHighlightFirstItem
&& !this.lookupMenu
.getSelectedItem() ) {
775 this.lookupMenu
.highlightItem( this.lookupMenu
.getFirstSelectableItem() );
780 * Get lookup menu items for the current query.
783 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
784 * the done event. If the request was aborted to make way for a subsequent request, this promise
785 * will not be rejected: it will remain pending forever.
787 OO
.ui
.mixin
.LookupElement
.prototype.getLookupMenuItems = function () {
788 return this.getRequestData().then( function ( data
) {
789 return this.getLookupMenuOptionsFromData( data
);
794 * Abort the currently pending lookup request, if any.
798 OO
.ui
.mixin
.LookupElement
.prototype.abortLookupRequest = function () {
803 * Get a new request object of the current lookup query value.
808 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
810 OO
.ui
.mixin
.LookupElement
.prototype.getLookupRequest
= null;
813 * Pre-process data returned by the request from #getLookupRequest.
815 * The return value of this function will be cached, and any further queries for the given value
816 * will use the cache rather than doing API requests.
821 * @param {Mixed} response Response from server
822 * @return {Mixed} Cached result data
824 OO
.ui
.mixin
.LookupElement
.prototype.getLookupCacheDataFromResponse
= null;
827 * Get a list of menu option widgets from the (possibly cached) data returned by
828 * #getLookupCacheDataFromResponse.
833 * @param {Mixed} data Cached result data, usually an array
834 * @return {OO.ui.MenuOptionWidget[]} Menu items
836 OO
.ui
.mixin
.LookupElement
.prototype.getLookupMenuOptionsFromData
= null;
839 * Set the read-only state of the widget.
841 * This will also disable/enable the lookups functionality.
843 * @param {boolean} readOnly Make input read-only
846 OO
.ui
.mixin
.LookupElement
.prototype.setReadOnly = function ( readOnly
) {
848 // Note: Calling #setReadOnly this way assumes this is mixed into an OO.ui.TextInputWidget
849 OO
.ui
.TextInputWidget
.prototype.setReadOnly
.call( this, readOnly
);
851 // During construction, #setReadOnly is called before the OO.ui.mixin.LookupElement constructor
852 if ( this.isReadOnly() && this.lookupMenu
) {
853 this.closeLookupMenu();
860 * @inheritdoc OO.ui.mixin.RequestManager
862 OO
.ui
.mixin
.LookupElement
.prototype.getRequestQuery = function () {
863 return this.getValue();
867 * @inheritdoc OO.ui.mixin.RequestManager
869 OO
.ui
.mixin
.LookupElement
.prototype.getRequest = function () {
870 return this.getLookupRequest();
874 * @inheritdoc OO.ui.mixin.RequestManager
876 OO
.ui
.mixin
.LookupElement
.prototype.getRequestCacheDataFromResponse = function ( response
) {
877 return this.getLookupCacheDataFromResponse( response
);
881 * CardLayouts are used within {@link OO.ui.IndexLayout index layouts} to create cards that users can select and display
882 * from the index's optional {@link OO.ui.TabSelectWidget tab} navigation. Cards are usually not instantiated directly,
883 * rather extended to include the required content and functionality.
885 * Each card must have a unique symbolic name, which is passed to the constructor. In addition, the card's tab
886 * item is customized (with a label) using the #setupTabItem method. See
887 * {@link OO.ui.IndexLayout IndexLayout} for an example.
890 * @extends OO.ui.PanelLayout
893 * @param {string} name Unique symbolic name of card
894 * @param {Object} [config] Configuration options
895 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] Label for card's tab
897 OO
.ui
.CardLayout
= function OoUiCardLayout( name
, config
) {
898 // Allow passing positional parameters inside the config object
899 if ( OO
.isPlainObject( name
) && config
=== undefined ) {
904 // Configuration initialization
905 config
= $.extend( { scrollable
: true }, config
);
907 // Parent constructor
908 OO
.ui
.CardLayout
.parent
.call( this, config
);
912 this.label
= config
.label
;
917 this.$element
.addClass( 'oo-ui-cardLayout' );
922 OO
.inheritClass( OO
.ui
.CardLayout
, OO
.ui
.PanelLayout
);
927 * An 'active' event is emitted when the card becomes active. Cards become active when they are
928 * shown in a index layout that is configured to display only one card at a time.
931 * @param {boolean} active Card is active
937 * Get the symbolic name of the card.
939 * @return {string} Symbolic name of card
941 OO
.ui
.CardLayout
.prototype.getName = function () {
946 * Check if card is active.
948 * Cards become active when they are shown in a {@link OO.ui.IndexLayout index layout} that is configured to display
949 * only one card at a time. Additional CSS is applied to the card's tab item to reflect the active state.
951 * @return {boolean} Card is active
953 OO
.ui
.CardLayout
.prototype.isActive = function () {
960 * The tab item allows users to access the card from the index's tab
961 * navigation. The tab item itself can be customized (with a label, level, etc.) using the #setupTabItem method.
963 * @return {OO.ui.TabOptionWidget|null} Tab option widget
965 OO
.ui
.CardLayout
.prototype.getTabItem = function () {
970 * Set or unset the tab item.
972 * Specify a {@link OO.ui.TabOptionWidget tab option} to set it,
973 * or `null` to clear the tab item. To customize the tab item itself (e.g., to set a label or tab
974 * level), use #setupTabItem instead of this method.
976 * @param {OO.ui.TabOptionWidget|null} tabItem Tab option widget, null to clear
979 OO
.ui
.CardLayout
.prototype.setTabItem = function ( tabItem
) {
980 this.tabItem
= tabItem
|| null;
988 * Set up the tab item.
990 * Use this method to customize the tab item (e.g., to add a label or tab level). To set or unset
991 * the tab item itself (with a {@link OO.ui.TabOptionWidget tab option} or `null`), use
992 * the #setTabItem method instead.
994 * @param {OO.ui.TabOptionWidget} tabItem Tab option widget to set up
997 OO
.ui
.CardLayout
.prototype.setupTabItem = function () {
999 this.tabItem
.setLabel( this.label
);
1005 * Set the card to its 'active' state.
1007 * Cards become active when they are shown in a index layout that is configured to display only one card at a time. Additional
1008 * CSS is applied to the tab item to reflect the card's active state. Outside of the index
1009 * context, setting the active state on a card does nothing.
1011 * @param {boolean} active Card is active
1014 OO
.ui
.CardLayout
.prototype.setActive = function ( active
) {
1017 if ( active
!== this.active
) {
1018 this.active
= active
;
1019 this.$element
.toggleClass( 'oo-ui-cardLayout-active', this.active
);
1020 this.emit( 'active', this.active
);
1025 * PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display
1026 * from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly,
1027 * rather extended to include the required content and functionality.
1029 * Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline
1030 * item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See
1031 * {@link OO.ui.BookletLayout BookletLayout} for an example.
1034 * @extends OO.ui.PanelLayout
1037 * @param {string} name Unique symbolic name of page
1038 * @param {Object} [config] Configuration options
1040 OO
.ui
.PageLayout
= function OoUiPageLayout( name
, config
) {
1041 // Allow passing positional parameters inside the config object
1042 if ( OO
.isPlainObject( name
) && config
=== undefined ) {
1047 // Configuration initialization
1048 config
= $.extend( { scrollable
: true }, config
);
1050 // Parent constructor
1051 OO
.ui
.PageLayout
.parent
.call( this, config
);
1055 this.outlineItem
= null;
1056 this.active
= false;
1059 this.$element
.addClass( 'oo-ui-pageLayout' );
1064 OO
.inheritClass( OO
.ui
.PageLayout
, OO
.ui
.PanelLayout
);
1069 * An 'active' event is emitted when the page becomes active. Pages become active when they are
1070 * shown in a booklet layout that is configured to display only one page at a time.
1073 * @param {boolean} active Page is active
1079 * Get the symbolic name of the page.
1081 * @return {string} Symbolic name of page
1083 OO
.ui
.PageLayout
.prototype.getName = function () {
1088 * Check if page is active.
1090 * Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display
1091 * only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state.
1093 * @return {boolean} Page is active
1095 OO
.ui
.PageLayout
.prototype.isActive = function () {
1102 * The outline item allows users to access the page from the booklet's outline
1103 * navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method.
1105 * @return {OO.ui.OutlineOptionWidget|null} Outline option widget
1107 OO
.ui
.PageLayout
.prototype.getOutlineItem = function () {
1108 return this.outlineItem
;
1112 * Set or unset the outline item.
1114 * Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it,
1115 * or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline
1116 * level), use #setupOutlineItem instead of this method.
1118 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear
1121 OO
.ui
.PageLayout
.prototype.setOutlineItem = function ( outlineItem
) {
1122 this.outlineItem
= outlineItem
|| null;
1123 if ( outlineItem
) {
1124 this.setupOutlineItem();
1130 * Set up the outline item.
1132 * Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset
1133 * the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use
1134 * the #setOutlineItem method instead.
1136 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up
1139 OO
.ui
.PageLayout
.prototype.setupOutlineItem = function () {
1144 * Set the page to its 'active' state.
1146 * Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional
1147 * CSS is applied to the outline item to reflect the page's active state. Outside of the booklet
1148 * context, setting the active state on a page does nothing.
1150 * @param {boolean} active Page is active
1153 OO
.ui
.PageLayout
.prototype.setActive = function ( active
) {
1156 if ( active
!== this.active
) {
1157 this.active
= active
;
1158 this.$element
.toggleClass( 'oo-ui-pageLayout-active', active
);
1159 this.emit( 'active', this.active
);
1164 * StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed
1165 * at a time, though the stack layout can also be configured to show all contained panels, one after another,
1166 * by setting the #continuous option to 'true'.
1169 * // A stack layout with two panels, configured to be displayed continously
1170 * var myStack = new OO.ui.StackLayout( {
1172 * new OO.ui.PanelLayout( {
1173 * $content: $( '<p>Panel One</p>' ),
1177 * new OO.ui.PanelLayout( {
1178 * $content: $( '<p>Panel Two</p>' ),
1185 * $( 'body' ).append( myStack.$element );
1188 * @extends OO.ui.PanelLayout
1189 * @mixins OO.ui.mixin.GroupElement
1192 * @param {Object} [config] Configuration options
1193 * @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time.
1194 * @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout.
1196 OO
.ui
.StackLayout
= function OoUiStackLayout( config
) {
1197 // Configuration initialization
1198 config
= $.extend( { scrollable
: true }, config
);
1200 // Parent constructor
1201 OO
.ui
.StackLayout
.parent
.call( this, config
);
1203 // Mixin constructors
1204 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
1207 this.currentItem
= null;
1208 this.continuous
= !!config
.continuous
;
1211 this.$element
.addClass( 'oo-ui-stackLayout' );
1212 if ( this.continuous
) {
1213 this.$element
.addClass( 'oo-ui-stackLayout-continuous' );
1214 this.$element
.on( 'scroll', OO
.ui
.debounce( this.onScroll
.bind( this ), 250 ) );
1216 if ( Array
.isArray( config
.items
) ) {
1217 this.addItems( config
.items
);
1223 OO
.inheritClass( OO
.ui
.StackLayout
, OO
.ui
.PanelLayout
);
1224 OO
.mixinClass( OO
.ui
.StackLayout
, OO
.ui
.mixin
.GroupElement
);
1229 * A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed},
1230 * {@link #clearItems cleared} or {@link #setItem displayed}.
1233 * @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown
1237 * When used in continuous mode, this event is emitted when the user scrolls down
1238 * far enough such that currentItem is no longer visible.
1240 * @event visibleItemChange
1241 * @param {OO.ui.PanelLayout} panel The next visible item in the layout
1247 * Handle scroll events from the layout element
1249 * @param {jQuery.Event} e
1250 * @fires visibleItemChange
1252 OO
.ui
.StackLayout
.prototype.onScroll = function () {
1254 len
= this.items
.length
,
1255 currentIndex
= this.items
.indexOf( this.currentItem
),
1256 newIndex
= currentIndex
,
1257 containerRect
= this.$element
[ 0 ].getBoundingClientRect();
1259 if ( !containerRect
|| ( !containerRect
.top
&& !containerRect
.bottom
) ) {
1260 // Can't get bounding rect, possibly not attached.
1264 function getRect( item
) {
1265 return item
.$element
[ 0 ].getBoundingClientRect();
1268 function isVisible( item
) {
1269 var rect
= getRect( item
);
1270 return rect
.bottom
> containerRect
.top
&& rect
.top
< containerRect
.bottom
;
1273 currentRect
= getRect( this.currentItem
);
1275 if ( currentRect
.bottom
< containerRect
.top
) {
1276 // Scrolled down past current item
1277 while ( ++newIndex
< len
) {
1278 if ( isVisible( this.items
[ newIndex
] ) ) {
1282 } else if ( currentRect
.top
> containerRect
.bottom
) {
1283 // Scrolled up past current item
1284 while ( --newIndex
>= 0 ) {
1285 if ( isVisible( this.items
[ newIndex
] ) ) {
1291 if ( newIndex
!== currentIndex
) {
1292 this.emit( 'visibleItemChange', this.items
[ newIndex
] );
1297 * Get the current panel.
1299 * @return {OO.ui.Layout|null}
1301 OO
.ui
.StackLayout
.prototype.getCurrentItem = function () {
1302 return this.currentItem
;
1306 * Unset the current item.
1309 * @param {OO.ui.StackLayout} layout
1312 OO
.ui
.StackLayout
.prototype.unsetCurrentItem = function () {
1313 var prevItem
= this.currentItem
;
1314 if ( prevItem
=== null ) {
1318 this.currentItem
= null;
1319 this.emit( 'set', null );
1323 * Add panel layouts to the stack layout.
1325 * Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different
1326 * 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 * @param {OO.ui.Layout[]} items Panels to add
1330 * @param {number} [index] Index of the insertion point
1333 OO
.ui
.StackLayout
.prototype.addItems = function ( items
, index
) {
1334 // Update the visibility
1335 this.updateHiddenState( items
, this.currentItem
);
1338 OO
.ui
.mixin
.GroupElement
.prototype.addItems
.call( this, items
, index
);
1340 if ( !this.currentItem
&& items
.length
) {
1341 this.setItem( items
[ 0 ] );
1348 * Remove the specified panels from the stack layout.
1350 * Removed panels are detached from the DOM, not removed, so that they may be reused. To remove all panels,
1351 * you may wish to use the #clearItems method instead.
1353 * @param {OO.ui.Layout[]} items Panels to remove
1357 OO
.ui
.StackLayout
.prototype.removeItems = function ( items
) {
1359 OO
.ui
.mixin
.GroupElement
.prototype.removeItems
.call( this, items
);
1361 if ( items
.indexOf( this.currentItem
) !== -1 ) {
1362 if ( this.items
.length
) {
1363 this.setItem( this.items
[ 0 ] );
1365 this.unsetCurrentItem();
1373 * Clear all panels from the stack layout.
1375 * Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only
1376 * a subset of panels, use the #removeItems method.
1381 OO
.ui
.StackLayout
.prototype.clearItems = function () {
1382 this.unsetCurrentItem();
1383 OO
.ui
.mixin
.GroupElement
.prototype.clearItems
.call( this );
1389 * Show the specified panel.
1391 * If another panel is currently displayed, it will be hidden.
1393 * @param {OO.ui.Layout} item Panel to show
1397 OO
.ui
.StackLayout
.prototype.setItem = function ( item
) {
1398 if ( item
!== this.currentItem
) {
1399 this.updateHiddenState( this.items
, item
);
1401 if ( this.items
.indexOf( item
) !== -1 ) {
1402 this.currentItem
= item
;
1403 this.emit( 'set', item
);
1405 this.unsetCurrentItem();
1413 * Update the visibility of all items in case of non-continuous view.
1415 * Ensure all items are hidden except for the selected one.
1416 * This method does nothing when the stack is continuous.
1419 * @param {OO.ui.Layout[]} items Item list iterate over
1420 * @param {OO.ui.Layout} [selectedItem] Selected item to show
1422 OO
.ui
.StackLayout
.prototype.updateHiddenState = function ( items
, selectedItem
) {
1425 if ( !this.continuous
) {
1426 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
1427 if ( !selectedItem
|| selectedItem
!== items
[ i
] ) {
1428 items
[ i
].$element
.addClass( 'oo-ui-element-hidden' );
1429 items
[ i
].$element
.attr( 'aria-hidden', 'true' );
1432 if ( selectedItem
) {
1433 selectedItem
.$element
.removeClass( 'oo-ui-element-hidden' );
1434 selectedItem
.$element
.removeAttr( 'aria-hidden' );
1440 * 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)
1441 * and its size is customized with the #menuSize config. The content area will fill all remaining space.
1444 * var menuLayout = new OO.ui.MenuLayout( {
1447 * menuPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
1448 * contentPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
1449 * select = new OO.ui.SelectWidget( {
1451 * new OO.ui.OptionWidget( {
1455 * new OO.ui.OptionWidget( {
1459 * new OO.ui.OptionWidget( {
1463 * new OO.ui.OptionWidget( {
1468 * } ).on( 'select', function ( item ) {
1469 * menuLayout.setMenuPosition( item.getData() );
1472 * menuLayout.$menu.append(
1473 * menuPanel.$element.append( '<b>Menu panel</b>', select.$element )
1475 * menuLayout.$content.append(
1476 * contentPanel.$element.append( '<b>Content panel</b>', '<p>Note that the menu is positioned relative to the content panel: top, bottom, after, before.</p>')
1478 * $( 'body' ).append( menuLayout.$element );
1480 * If menu size needs to be overridden, it can be accomplished using CSS similar to the snippet
1481 * below. MenuLayout's CSS will override the appropriate values with 'auto' or '0' to display the
1482 * menu correctly. If `menuPosition` is known beforehand, CSS rules corresponding to other positions
1485 * .oo-ui-menuLayout-menu {
1489 * .oo-ui-menuLayout-content {
1497 * @extends OO.ui.Layout
1500 * @param {Object} [config] Configuration options
1501 * @cfg {boolean} [showMenu=true] Show menu
1502 * @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before`
1504 OO
.ui
.MenuLayout
= function OoUiMenuLayout( config
) {
1505 // Configuration initialization
1506 config
= $.extend( {
1508 menuPosition
: 'before'
1511 // Parent constructor
1512 OO
.ui
.MenuLayout
.parent
.call( this, config
);
1517 * @property {jQuery}
1519 this.$menu
= $( '<div>' );
1523 * @property {jQuery}
1525 this.$content
= $( '<div>' );
1529 .addClass( 'oo-ui-menuLayout-menu' );
1530 this.$content
.addClass( 'oo-ui-menuLayout-content' );
1532 .addClass( 'oo-ui-menuLayout' )
1533 .append( this.$content
, this.$menu
);
1534 this.setMenuPosition( config
.menuPosition
);
1535 this.toggleMenu( config
.showMenu
);
1540 OO
.inheritClass( OO
.ui
.MenuLayout
, OO
.ui
.Layout
);
1547 * @param {boolean} showMenu Show menu, omit to toggle
1550 OO
.ui
.MenuLayout
.prototype.toggleMenu = function ( showMenu
) {
1551 showMenu
= showMenu
=== undefined ? !this.showMenu
: !!showMenu
;
1553 if ( this.showMenu
!== showMenu
) {
1554 this.showMenu
= showMenu
;
1556 .toggleClass( 'oo-ui-menuLayout-showMenu', this.showMenu
)
1557 .toggleClass( 'oo-ui-menuLayout-hideMenu', !this.showMenu
);
1558 this.$menu
.attr( 'aria-hidden', this.showMenu
? 'false' : 'true' );
1565 * Check if menu is visible
1567 * @return {boolean} Menu is visible
1569 OO
.ui
.MenuLayout
.prototype.isMenuVisible = function () {
1570 return this.showMenu
;
1574 * Set menu position.
1576 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
1577 * @throws {Error} If position value is not supported
1580 OO
.ui
.MenuLayout
.prototype.setMenuPosition = function ( position
) {
1581 this.$element
.removeClass( 'oo-ui-menuLayout-' + this.menuPosition
);
1582 this.menuPosition
= position
;
1583 this.$element
.addClass( 'oo-ui-menuLayout-' + position
);
1589 * Get menu position.
1591 * @return {string} Menu position
1593 OO
.ui
.MenuLayout
.prototype.getMenuPosition = function () {
1594 return this.menuPosition
;
1598 * BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as
1599 * an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate
1600 * through the pages and select which one to display. By default, only one page is
1601 * displayed at a time and the outline is hidden. When a user navigates to a new page,
1602 * the booklet layout automatically focuses on the first focusable element, unless the
1603 * default setting is changed. Optionally, booklets can be configured to show
1604 * {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items.
1607 * // Example of a BookletLayout that contains two PageLayouts.
1609 * function PageOneLayout( name, config ) {
1610 * PageOneLayout.parent.call( this, name, config );
1611 * this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' );
1613 * OO.inheritClass( PageOneLayout, OO.ui.PageLayout );
1614 * PageOneLayout.prototype.setupOutlineItem = function () {
1615 * this.outlineItem.setLabel( 'Page One' );
1618 * function PageTwoLayout( name, config ) {
1619 * PageTwoLayout.parent.call( this, name, config );
1620 * this.$element.append( '<p>Second page</p>' );
1622 * OO.inheritClass( PageTwoLayout, OO.ui.PageLayout );
1623 * PageTwoLayout.prototype.setupOutlineItem = function () {
1624 * this.outlineItem.setLabel( 'Page Two' );
1627 * var page1 = new PageOneLayout( 'one' ),
1628 * page2 = new PageTwoLayout( 'two' );
1630 * var booklet = new OO.ui.BookletLayout( {
1634 * booklet.addPages ( [ page1, page2 ] );
1635 * $( 'body' ).append( booklet.$element );
1638 * @extends OO.ui.MenuLayout
1641 * @param {Object} [config] Configuration options
1642 * @cfg {boolean} [continuous=false] Show all pages, one after another
1643 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed.
1644 * @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet.
1645 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
1647 OO
.ui
.BookletLayout
= function OoUiBookletLayout( config
) {
1648 // Configuration initialization
1649 config
= config
|| {};
1651 // Parent constructor
1652 OO
.ui
.BookletLayout
.parent
.call( this, config
);
1655 this.currentPageName
= null;
1657 this.ignoreFocus
= false;
1658 this.stackLayout
= new OO
.ui
.StackLayout( { continuous
: !!config
.continuous
} );
1659 this.$content
.append( this.stackLayout
.$element
);
1660 this.autoFocus
= config
.autoFocus
=== undefined || !!config
.autoFocus
;
1661 this.outlineVisible
= false;
1662 this.outlined
= !!config
.outlined
;
1663 if ( this.outlined
) {
1664 this.editable
= !!config
.editable
;
1665 this.outlineControlsWidget
= null;
1666 this.outlineSelectWidget
= new OO
.ui
.OutlineSelectWidget();
1667 this.outlinePanel
= new OO
.ui
.PanelLayout( { scrollable
: true } );
1668 this.$menu
.append( this.outlinePanel
.$element
);
1669 this.outlineVisible
= true;
1670 if ( this.editable
) {
1671 this.outlineControlsWidget
= new OO
.ui
.OutlineControlsWidget(
1672 this.outlineSelectWidget
1676 this.toggleMenu( this.outlined
);
1679 this.stackLayout
.connect( this, { set: 'onStackLayoutSet' } );
1680 if ( this.outlined
) {
1681 this.outlineSelectWidget
.connect( this, { select
: 'onOutlineSelectWidgetSelect' } );
1682 this.scrolling
= false;
1683 this.stackLayout
.connect( this, { visibleItemChange
: 'onStackLayoutVisibleItemChange' } );
1685 if ( this.autoFocus
) {
1686 // Event 'focus' does not bubble, but 'focusin' does
1687 this.stackLayout
.$element
.on( 'focusin', this.onStackLayoutFocus
.bind( this ) );
1691 this.$element
.addClass( 'oo-ui-bookletLayout' );
1692 this.stackLayout
.$element
.addClass( 'oo-ui-bookletLayout-stackLayout' );
1693 if ( this.outlined
) {
1694 this.outlinePanel
.$element
1695 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
1696 .append( this.outlineSelectWidget
.$element
);
1697 if ( this.editable
) {
1698 this.outlinePanel
.$element
1699 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
1700 .append( this.outlineControlsWidget
.$element
);
1707 OO
.inheritClass( OO
.ui
.BookletLayout
, OO
.ui
.MenuLayout
);
1712 * A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout.
1714 * @param {OO.ui.PageLayout} page Current page
1718 * An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout.
1721 * @param {OO.ui.PageLayout[]} page Added pages
1722 * @param {number} index Index pages were added at
1726 * A 'remove' event is emitted when pages are {@link #clearPages cleared} or
1727 * {@link #removePages removed} from the booklet.
1730 * @param {OO.ui.PageLayout[]} pages Removed pages
1736 * Handle stack layout focus.
1739 * @param {jQuery.Event} e Focusin event
1741 OO
.ui
.BookletLayout
.prototype.onStackLayoutFocus = function ( e
) {
1744 // Find the page that an element was focused within
1745 $target
= $( e
.target
).closest( '.oo-ui-pageLayout' );
1746 for ( name
in this.pages
) {
1747 // Check for page match, exclude current page to find only page changes
1748 if ( this.pages
[ name
].$element
[ 0 ] === $target
[ 0 ] && name
!== this.currentPageName
) {
1749 this.setPage( name
);
1756 * Handle visibleItemChange events from the stackLayout
1758 * The next visible page is set as the current page by selecting it
1761 * @param {OO.ui.PageLayout} page The next visible page in the layout
1763 OO
.ui
.BookletLayout
.prototype.onStackLayoutVisibleItemChange = function ( page
) {
1764 // Set a flag to so that the resulting call to #onStackLayoutSet doesn't
1765 // try and scroll the item into view again.
1766 this.scrolling
= true;
1767 this.outlineSelectWidget
.selectItemByData( page
.getName() );
1768 this.scrolling
= false;
1772 * Handle stack layout set events.
1775 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
1777 OO
.ui
.BookletLayout
.prototype.onStackLayoutSet = function ( page
) {
1779 if ( !this.scrolling
&& page
) {
1780 page
.scrollElementIntoView( {
1781 complete: function () {
1782 if ( layout
.autoFocus
) {
1791 * Focus the first input in the current page.
1793 * If no page is selected, the first selectable page will be selected.
1794 * If the focus is already in an element on the current page, nothing will happen.
1796 * @param {number} [itemIndex] A specific item to focus on
1798 OO
.ui
.BookletLayout
.prototype.focus = function ( itemIndex
) {
1800 items
= this.stackLayout
.getItems();
1802 if ( itemIndex
!== undefined && items
[ itemIndex
] ) {
1803 page
= items
[ itemIndex
];
1805 page
= this.stackLayout
.getCurrentItem();
1808 if ( !page
&& this.outlined
) {
1809 this.selectFirstSelectablePage();
1810 page
= this.stackLayout
.getCurrentItem();
1815 // Only change the focus if is not already in the current page
1816 if ( !OO
.ui
.contains( page
.$element
[ 0 ], this.getElementDocument().activeElement
, true ) ) {
1822 * Find the first focusable input in the booklet layout and focus
1825 OO
.ui
.BookletLayout
.prototype.focusFirstFocusable = function () {
1826 OO
.ui
.findFocusable( this.stackLayout
.$element
).focus();
1830 * Handle outline widget select events.
1833 * @param {OO.ui.OptionWidget|null} item Selected item
1835 OO
.ui
.BookletLayout
.prototype.onOutlineSelectWidgetSelect = function ( item
) {
1837 this.setPage( item
.getData() );
1842 * Check if booklet has an outline.
1844 * @return {boolean} Booklet has an outline
1846 OO
.ui
.BookletLayout
.prototype.isOutlined = function () {
1847 return this.outlined
;
1851 * Check if booklet has editing controls.
1853 * @return {boolean} Booklet is editable
1855 OO
.ui
.BookletLayout
.prototype.isEditable = function () {
1856 return this.editable
;
1860 * Check if booklet has a visible outline.
1862 * @return {boolean} Outline is visible
1864 OO
.ui
.BookletLayout
.prototype.isOutlineVisible = function () {
1865 return this.outlined
&& this.outlineVisible
;
1869 * Hide or show the outline.
1871 * @param {boolean} [show] Show outline, omit to invert current state
1874 OO
.ui
.BookletLayout
.prototype.toggleOutline = function ( show
) {
1875 if ( this.outlined
) {
1876 show
= show
=== undefined ? !this.outlineVisible
: !!show
;
1877 this.outlineVisible
= show
;
1878 this.toggleMenu( show
);
1885 * Get the page closest to the specified page.
1887 * @param {OO.ui.PageLayout} page Page to use as a reference point
1888 * @return {OO.ui.PageLayout|null} Page closest to the specified page
1890 OO
.ui
.BookletLayout
.prototype.getClosestPage = function ( page
) {
1891 var next
, prev
, level
,
1892 pages
= this.stackLayout
.getItems(),
1893 index
= pages
.indexOf( page
);
1895 if ( index
!== -1 ) {
1896 next
= pages
[ index
+ 1 ];
1897 prev
= pages
[ index
- 1 ];
1898 // Prefer adjacent pages at the same level
1899 if ( this.outlined
) {
1900 level
= this.outlineSelectWidget
.getItemFromData( page
.getName() ).getLevel();
1903 level
=== this.outlineSelectWidget
.getItemFromData( prev
.getName() ).getLevel()
1909 level
=== this.outlineSelectWidget
.getItemFromData( next
.getName() ).getLevel()
1915 return prev
|| next
|| null;
1919 * Get the outline widget.
1921 * If the booklet is not outlined, the method will return `null`.
1923 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
1925 OO
.ui
.BookletLayout
.prototype.getOutline = function () {
1926 return this.outlineSelectWidget
;
1930 * Get the outline controls widget.
1932 * If the outline is not editable, the method will return `null`.
1934 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
1936 OO
.ui
.BookletLayout
.prototype.getOutlineControls = function () {
1937 return this.outlineControlsWidget
;
1941 * Get a page by its symbolic name.
1943 * @param {string} name Symbolic name of page
1944 * @return {OO.ui.PageLayout|undefined} Page, if found
1946 OO
.ui
.BookletLayout
.prototype.getPage = function ( name
) {
1947 return this.pages
[ name
];
1951 * Get the current page.
1953 * @return {OO.ui.PageLayout|undefined} Current page, if found
1955 OO
.ui
.BookletLayout
.prototype.getCurrentPage = function () {
1956 var name
= this.getCurrentPageName();
1957 return name
? this.getPage( name
) : undefined;
1961 * Get the symbolic name of the current page.
1963 * @return {string|null} Symbolic name of the current page
1965 OO
.ui
.BookletLayout
.prototype.getCurrentPageName = function () {
1966 return this.currentPageName
;
1970 * Add pages to the booklet layout
1972 * When pages are added with the same names as existing pages, the existing pages will be
1973 * automatically removed before the new pages are added.
1975 * @param {OO.ui.PageLayout[]} pages Pages to add
1976 * @param {number} index Index of the insertion point
1980 OO
.ui
.BookletLayout
.prototype.addPages = function ( pages
, index
) {
1981 var i
, len
, name
, page
, item
, currentIndex
,
1982 stackLayoutPages
= this.stackLayout
.getItems(),
1986 // Remove pages with same names
1987 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
1989 name
= page
.getName();
1991 if ( Object
.prototype.hasOwnProperty
.call( this.pages
, name
) ) {
1992 // Correct the insertion index
1993 currentIndex
= stackLayoutPages
.indexOf( this.pages
[ name
] );
1994 if ( currentIndex
!== -1 && currentIndex
+ 1 < index
) {
1997 remove
.push( this.pages
[ name
] );
2000 if ( remove
.length
) {
2001 this.removePages( remove
);
2005 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
2007 name
= page
.getName();
2008 this.pages
[ page
.getName() ] = page
;
2009 if ( this.outlined
) {
2010 item
= new OO
.ui
.OutlineOptionWidget( { data
: name
} );
2011 page
.setOutlineItem( item
);
2016 if ( this.outlined
&& items
.length
) {
2017 this.outlineSelectWidget
.addItems( items
, index
);
2018 this.selectFirstSelectablePage();
2020 this.stackLayout
.addItems( pages
, index
);
2021 this.emit( 'add', pages
, index
);
2027 * Remove the specified pages from the booklet layout.
2029 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
2031 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
2035 OO
.ui
.BookletLayout
.prototype.removePages = function ( pages
) {
2036 var i
, len
, name
, page
,
2039 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
2041 name
= page
.getName();
2042 delete this.pages
[ name
];
2043 if ( this.outlined
) {
2044 items
.push( this.outlineSelectWidget
.getItemFromData( name
) );
2045 page
.setOutlineItem( null );
2048 if ( this.outlined
&& items
.length
) {
2049 this.outlineSelectWidget
.removeItems( items
);
2050 this.selectFirstSelectablePage();
2052 this.stackLayout
.removeItems( pages
);
2053 this.emit( 'remove', pages
);
2059 * Clear all pages from the booklet layout.
2061 * To remove only a subset of pages from the booklet, use the #removePages method.
2066 OO
.ui
.BookletLayout
.prototype.clearPages = function () {
2068 pages
= this.stackLayout
.getItems();
2071 this.currentPageName
= null;
2072 if ( this.outlined
) {
2073 this.outlineSelectWidget
.clearItems();
2074 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
2075 pages
[ i
].setOutlineItem( null );
2078 this.stackLayout
.clearItems();
2080 this.emit( 'remove', pages
);
2086 * Set the current page by symbolic name.
2089 * @param {string} name Symbolic name of page
2091 OO
.ui
.BookletLayout
.prototype.setPage = function ( name
) {
2094 page
= this.pages
[ name
],
2095 previousPage
= this.currentPageName
&& this.pages
[ this.currentPageName
];
2097 if ( name
!== this.currentPageName
) {
2098 if ( this.outlined
) {
2099 selectedItem
= this.outlineSelectWidget
.getSelectedItem();
2100 if ( selectedItem
&& selectedItem
.getData() !== name
) {
2101 this.outlineSelectWidget
.selectItemByData( name
);
2105 if ( previousPage
) {
2106 previousPage
.setActive( false );
2107 // Blur anything focused if the next page doesn't have anything focusable.
2108 // This is not needed if the next page has something focusable (because once it is focused
2109 // this blur happens automatically). If the layout is non-continuous, this check is
2110 // meaningless because the next page is not visible yet and thus can't hold focus.
2113 this.stackLayout
.continuous
&&
2114 OO
.ui
.findFocusable( page
.$element
).length
!== 0
2116 $focused
= previousPage
.$element
.find( ':focus' );
2117 if ( $focused
.length
) {
2118 $focused
[ 0 ].blur();
2122 this.currentPageName
= name
;
2123 page
.setActive( true );
2124 this.stackLayout
.setItem( page
);
2125 if ( !this.stackLayout
.continuous
&& previousPage
) {
2126 // This should not be necessary, since any inputs on the previous page should have been
2127 // blurred when it was hidden, but browsers are not very consistent about this.
2128 $focused
= previousPage
.$element
.find( ':focus' );
2129 if ( $focused
.length
) {
2130 $focused
[ 0 ].blur();
2133 this.emit( 'set', page
);
2139 * Select the first selectable page.
2143 OO
.ui
.BookletLayout
.prototype.selectFirstSelectablePage = function () {
2144 if ( !this.outlineSelectWidget
.getSelectedItem() ) {
2145 this.outlineSelectWidget
.selectItem( this.outlineSelectWidget
.getFirstSelectableItem() );
2152 * IndexLayouts contain {@link OO.ui.CardLayout card layouts} as well as
2153 * {@link OO.ui.TabSelectWidget tabs} that allow users to easily navigate through the cards and
2154 * select which one to display. By default, only one card is displayed at a time. When a user
2155 * navigates to a new card, the index layout automatically focuses on the first focusable element,
2156 * unless the default setting is changed.
2158 * TODO: This class is similar to BookletLayout, we may want to refactor to reduce duplication
2161 * // Example of a IndexLayout that contains two CardLayouts.
2163 * function CardOneLayout( name, config ) {
2164 * CardOneLayout.parent.call( this, name, config );
2165 * this.$element.append( '<p>First card</p>' );
2167 * OO.inheritClass( CardOneLayout, OO.ui.CardLayout );
2168 * CardOneLayout.prototype.setupTabItem = function () {
2169 * this.tabItem.setLabel( 'Card one' );
2172 * var card1 = new CardOneLayout( 'one' ),
2173 * card2 = new CardLayout( 'two', { label: 'Card two' } );
2175 * card2.$element.append( '<p>Second card</p>' );
2177 * var index = new OO.ui.IndexLayout();
2179 * index.addCards ( [ card1, card2 ] );
2180 * $( 'body' ).append( index.$element );
2183 * @extends OO.ui.MenuLayout
2186 * @param {Object} [config] Configuration options
2187 * @cfg {boolean} [continuous=false] Show all cards, one after another
2188 * @cfg {boolean} [expanded=true] Expand the content panel to fill the entire parent element.
2189 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new card is displayed.
2191 OO
.ui
.IndexLayout
= function OoUiIndexLayout( config
) {
2192 // Configuration initialization
2193 config
= $.extend( {}, config
, { menuPosition
: 'top' } );
2195 // Parent constructor
2196 OO
.ui
.IndexLayout
.parent
.call( this, config
);
2199 this.currentCardName
= null;
2201 this.ignoreFocus
= false;
2202 this.stackLayout
= new OO
.ui
.StackLayout( {
2203 continuous
: !!config
.continuous
,
2204 expanded
: config
.expanded
2206 this.$content
.append( this.stackLayout
.$element
);
2207 this.autoFocus
= config
.autoFocus
=== undefined || !!config
.autoFocus
;
2209 this.tabSelectWidget
= new OO
.ui
.TabSelectWidget();
2210 this.tabPanel
= new OO
.ui
.PanelLayout();
2211 this.$menu
.append( this.tabPanel
.$element
);
2213 this.toggleMenu( true );
2216 this.stackLayout
.connect( this, { set: 'onStackLayoutSet' } );
2217 this.tabSelectWidget
.connect( this, { select
: 'onTabSelectWidgetSelect' } );
2218 if ( this.autoFocus
) {
2219 // Event 'focus' does not bubble, but 'focusin' does
2220 this.stackLayout
.$element
.on( 'focusin', this.onStackLayoutFocus
.bind( this ) );
2224 this.$element
.addClass( 'oo-ui-indexLayout' );
2225 this.stackLayout
.$element
.addClass( 'oo-ui-indexLayout-stackLayout' );
2226 this.tabPanel
.$element
2227 .addClass( 'oo-ui-indexLayout-tabPanel' )
2228 .append( this.tabSelectWidget
.$element
);
2233 OO
.inheritClass( OO
.ui
.IndexLayout
, OO
.ui
.MenuLayout
);
2238 * A 'set' event is emitted when a card is {@link #setCard set} to be displayed by the index layout.
2240 * @param {OO.ui.CardLayout} card Current card
2244 * An 'add' event is emitted when cards are {@link #addCards added} to the index layout.
2247 * @param {OO.ui.CardLayout[]} card Added cards
2248 * @param {number} index Index cards were added at
2252 * A 'remove' event is emitted when cards are {@link #clearCards cleared} or
2253 * {@link #removeCards removed} from the index.
2256 * @param {OO.ui.CardLayout[]} cards Removed cards
2262 * Handle stack layout focus.
2265 * @param {jQuery.Event} e Focusin event
2267 OO
.ui
.IndexLayout
.prototype.onStackLayoutFocus = function ( e
) {
2270 // Find the card that an element was focused within
2271 $target
= $( e
.target
).closest( '.oo-ui-cardLayout' );
2272 for ( name
in this.cards
) {
2273 // Check for card match, exclude current card to find only card changes
2274 if ( this.cards
[ name
].$element
[ 0 ] === $target
[ 0 ] && name
!== this.currentCardName
) {
2275 this.setCard( name
);
2282 * Handle stack layout set events.
2285 * @param {OO.ui.PanelLayout|null} card The card panel that is now the current panel
2287 OO
.ui
.IndexLayout
.prototype.onStackLayoutSet = function ( card
) {
2290 card
.scrollElementIntoView( {
2291 complete: function () {
2292 if ( layout
.autoFocus
) {
2301 * Focus the first input in the current card.
2303 * If no card is selected, the first selectable card will be selected.
2304 * If the focus is already in an element on the current card, nothing will happen.
2306 * @param {number} [itemIndex] A specific item to focus on
2308 OO
.ui
.IndexLayout
.prototype.focus = function ( itemIndex
) {
2310 items
= this.stackLayout
.getItems();
2312 if ( itemIndex
!== undefined && items
[ itemIndex
] ) {
2313 card
= items
[ itemIndex
];
2315 card
= this.stackLayout
.getCurrentItem();
2319 this.selectFirstSelectableCard();
2320 card
= this.stackLayout
.getCurrentItem();
2325 // Only change the focus if is not already in the current page
2326 if ( !OO
.ui
.contains( card
.$element
[ 0 ], this.getElementDocument().activeElement
, true ) ) {
2332 * Find the first focusable input in the index layout and focus
2335 OO
.ui
.IndexLayout
.prototype.focusFirstFocusable = function () {
2336 OO
.ui
.findFocusable( this.stackLayout
.$element
).focus();
2340 * Handle tab widget select events.
2343 * @param {OO.ui.OptionWidget|null} item Selected item
2345 OO
.ui
.IndexLayout
.prototype.onTabSelectWidgetSelect = function ( item
) {
2347 this.setCard( item
.getData() );
2352 * Get the card closest to the specified card.
2354 * @param {OO.ui.CardLayout} card Card to use as a reference point
2355 * @return {OO.ui.CardLayout|null} Card closest to the specified card
2357 OO
.ui
.IndexLayout
.prototype.getClosestCard = function ( card
) {
2358 var next
, prev
, level
,
2359 cards
= this.stackLayout
.getItems(),
2360 index
= cards
.indexOf( card
);
2362 if ( index
!== -1 ) {
2363 next
= cards
[ index
+ 1 ];
2364 prev
= cards
[ index
- 1 ];
2365 // Prefer adjacent cards at the same level
2366 level
= this.tabSelectWidget
.getItemFromData( card
.getName() ).getLevel();
2369 level
=== this.tabSelectWidget
.getItemFromData( prev
.getName() ).getLevel()
2375 level
=== this.tabSelectWidget
.getItemFromData( next
.getName() ).getLevel()
2380 return prev
|| next
|| null;
2384 * Get the tabs widget.
2386 * @return {OO.ui.TabSelectWidget} Tabs widget
2388 OO
.ui
.IndexLayout
.prototype.getTabs = function () {
2389 return this.tabSelectWidget
;
2393 * Get a card by its symbolic name.
2395 * @param {string} name Symbolic name of card
2396 * @return {OO.ui.CardLayout|undefined} Card, if found
2398 OO
.ui
.IndexLayout
.prototype.getCard = function ( name
) {
2399 return this.cards
[ name
];
2403 * Get the current card.
2405 * @return {OO.ui.CardLayout|undefined} Current card, if found
2407 OO
.ui
.IndexLayout
.prototype.getCurrentCard = function () {
2408 var name
= this.getCurrentCardName();
2409 return name
? this.getCard( name
) : undefined;
2413 * Get the symbolic name of the current card.
2415 * @return {string|null} Symbolic name of the current card
2417 OO
.ui
.IndexLayout
.prototype.getCurrentCardName = function () {
2418 return this.currentCardName
;
2422 * Add cards to the index layout
2424 * When cards are added with the same names as existing cards, the existing cards will be
2425 * automatically removed before the new cards are added.
2427 * @param {OO.ui.CardLayout[]} cards Cards to add
2428 * @param {number} index Index of the insertion point
2432 OO
.ui
.IndexLayout
.prototype.addCards = function ( cards
, index
) {
2433 var i
, len
, name
, card
, item
, currentIndex
,
2434 stackLayoutCards
= this.stackLayout
.getItems(),
2438 // Remove cards with same names
2439 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
2441 name
= card
.getName();
2443 if ( Object
.prototype.hasOwnProperty
.call( this.cards
, name
) ) {
2444 // Correct the insertion index
2445 currentIndex
= stackLayoutCards
.indexOf( this.cards
[ name
] );
2446 if ( currentIndex
!== -1 && currentIndex
+ 1 < index
) {
2449 remove
.push( this.cards
[ name
] );
2452 if ( remove
.length
) {
2453 this.removeCards( remove
);
2457 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
2459 name
= card
.getName();
2460 this.cards
[ card
.getName() ] = card
;
2461 item
= new OO
.ui
.TabOptionWidget( { data
: name
} );
2462 card
.setTabItem( item
);
2466 if ( items
.length
) {
2467 this.tabSelectWidget
.addItems( items
, index
);
2468 this.selectFirstSelectableCard();
2470 this.stackLayout
.addItems( cards
, index
);
2471 this.emit( 'add', cards
, index
);
2477 * Remove the specified cards from the index layout.
2479 * To remove all cards from the index, you may wish to use the #clearCards method instead.
2481 * @param {OO.ui.CardLayout[]} cards An array of cards to remove
2485 OO
.ui
.IndexLayout
.prototype.removeCards = function ( cards
) {
2486 var i
, len
, name
, card
,
2489 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
2491 name
= card
.getName();
2492 delete this.cards
[ name
];
2493 items
.push( this.tabSelectWidget
.getItemFromData( name
) );
2494 card
.setTabItem( null );
2496 if ( items
.length
) {
2497 this.tabSelectWidget
.removeItems( items
);
2498 this.selectFirstSelectableCard();
2500 this.stackLayout
.removeItems( cards
);
2501 this.emit( 'remove', cards
);
2507 * Clear all cards from the index layout.
2509 * To remove only a subset of cards from the index, use the #removeCards method.
2514 OO
.ui
.IndexLayout
.prototype.clearCards = function () {
2516 cards
= this.stackLayout
.getItems();
2519 this.currentCardName
= null;
2520 this.tabSelectWidget
.clearItems();
2521 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
2522 cards
[ i
].setTabItem( null );
2524 this.stackLayout
.clearItems();
2526 this.emit( 'remove', cards
);
2532 * Set the current card by symbolic name.
2535 * @param {string} name Symbolic name of card
2537 OO
.ui
.IndexLayout
.prototype.setCard = function ( name
) {
2540 card
= this.cards
[ name
],
2541 previousCard
= this.currentCardName
&& this.cards
[ this.currentCardName
];
2543 if ( name
!== this.currentCardName
) {
2544 selectedItem
= this.tabSelectWidget
.getSelectedItem();
2545 if ( selectedItem
&& selectedItem
.getData() !== name
) {
2546 this.tabSelectWidget
.selectItemByData( name
);
2549 if ( previousCard
) {
2550 previousCard
.setActive( false );
2551 // Blur anything focused if the next card doesn't have anything focusable.
2552 // This is not needed if the next card has something focusable (because once it is focused
2553 // this blur happens automatically). If the layout is non-continuous, this check is
2554 // meaningless because the next card is not visible yet and thus can't hold focus.
2557 this.stackLayout
.continuous
&&
2558 OO
.ui
.findFocusable( card
.$element
).length
!== 0
2560 $focused
= previousCard
.$element
.find( ':focus' );
2561 if ( $focused
.length
) {
2562 $focused
[ 0 ].blur();
2566 this.currentCardName
= name
;
2567 card
.setActive( true );
2568 this.stackLayout
.setItem( card
);
2569 if ( !this.stackLayout
.continuous
&& previousCard
) {
2570 // This should not be necessary, since any inputs on the previous card should have been
2571 // blurred when it was hidden, but browsers are not very consistent about this.
2572 $focused
= previousCard
.$element
.find( ':focus' );
2573 if ( $focused
.length
) {
2574 $focused
[ 0 ].blur();
2577 this.emit( 'set', card
);
2583 * Select the first selectable card.
2587 OO
.ui
.IndexLayout
.prototype.selectFirstSelectableCard = function () {
2588 if ( !this.tabSelectWidget
.getSelectedItem() ) {
2589 this.tabSelectWidget
.selectItem( this.tabSelectWidget
.getFirstSelectableItem() );
2596 * ToggleWidget implements basic behavior of widgets with an on/off state.
2597 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
2601 * @extends OO.ui.Widget
2604 * @param {Object} [config] Configuration options
2605 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
2606 * By default, the toggle is in the 'off' state.
2608 OO
.ui
.ToggleWidget
= function OoUiToggleWidget( config
) {
2609 // Configuration initialization
2610 config
= config
|| {};
2612 // Parent constructor
2613 OO
.ui
.ToggleWidget
.parent
.call( this, config
);
2619 this.$element
.addClass( 'oo-ui-toggleWidget' );
2620 this.setValue( !!config
.value
);
2625 OO
.inheritClass( OO
.ui
.ToggleWidget
, OO
.ui
.Widget
);
2632 * A change event is emitted when the on/off state of the toggle changes.
2634 * @param {boolean} value Value representing the new state of the toggle
2640 * Get the value representing the toggle’s state.
2642 * @return {boolean} The on/off state of the toggle
2644 OO
.ui
.ToggleWidget
.prototype.getValue = function () {
2649 * Set the state of the toggle: `true` for 'on', `false' for 'off'.
2651 * @param {boolean} value The state of the toggle
2655 OO
.ui
.ToggleWidget
.prototype.setValue = function ( value
) {
2657 if ( this.value
!== value
) {
2659 this.emit( 'change', value
);
2660 this.$element
.toggleClass( 'oo-ui-toggleWidget-on', value
);
2661 this.$element
.toggleClass( 'oo-ui-toggleWidget-off', !value
);
2662 this.$element
.attr( 'aria-checked', value
.toString() );
2668 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
2669 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
2670 * configured with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators},
2671 * {@link OO.ui.mixin.TitledElement titles}, {@link OO.ui.mixin.FlaggedElement styling flags},
2672 * and {@link OO.ui.mixin.LabelElement labels}. Please see
2673 * the [OOjs UI documentation][1] on MediaWiki for more information.
2676 * // Toggle buttons in the 'off' and 'on' state.
2677 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
2678 * label: 'Toggle Button off'
2680 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
2681 * label: 'Toggle Button on',
2684 * // Append the buttons to the DOM.
2685 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
2687 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
2690 * @extends OO.ui.ToggleWidget
2691 * @mixins OO.ui.mixin.ButtonElement
2692 * @mixins OO.ui.mixin.IconElement
2693 * @mixins OO.ui.mixin.IndicatorElement
2694 * @mixins OO.ui.mixin.LabelElement
2695 * @mixins OO.ui.mixin.TitledElement
2696 * @mixins OO.ui.mixin.FlaggedElement
2697 * @mixins OO.ui.mixin.TabIndexedElement
2700 * @param {Object} [config] Configuration options
2701 * @cfg {boolean} [value=false] The toggle button’s initial on/off
2702 * state. By default, the button is in the 'off' state.
2704 OO
.ui
.ToggleButtonWidget
= function OoUiToggleButtonWidget( config
) {
2705 // Configuration initialization
2706 config
= config
|| {};
2708 // Parent constructor
2709 OO
.ui
.ToggleButtonWidget
.parent
.call( this, config
);
2711 // Mixin constructors
2712 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
2713 OO
.ui
.mixin
.IconElement
.call( this, config
);
2714 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
2715 OO
.ui
.mixin
.LabelElement
.call( this, config
);
2716 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
2717 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
2718 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
2721 this.connect( this, { click
: 'onAction' } );
2724 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
2726 .addClass( 'oo-ui-toggleButtonWidget' )
2727 .append( this.$button
);
2732 OO
.inheritClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.ToggleWidget
);
2733 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
2734 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.IconElement
);
2735 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
2736 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.LabelElement
);
2737 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.TitledElement
);
2738 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
2739 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
2744 * Handle the button action being triggered.
2748 OO
.ui
.ToggleButtonWidget
.prototype.onAction = function () {
2749 this.setValue( !this.value
);
2755 OO
.ui
.ToggleButtonWidget
.prototype.setValue = function ( value
) {
2757 if ( value
!== this.value
) {
2758 // Might be called from parent constructor before ButtonElement constructor
2759 if ( this.$button
) {
2760 this.$button
.attr( 'aria-pressed', value
.toString() );
2762 this.setActive( value
);
2766 OO
.ui
.ToggleButtonWidget
.parent
.prototype.setValue
.call( this, value
);
2774 OO
.ui
.ToggleButtonWidget
.prototype.setButtonElement = function ( $button
) {
2775 if ( this.$button
) {
2776 this.$button
.removeAttr( 'aria-pressed' );
2778 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement
.call( this, $button
);
2779 this.$button
.attr( 'aria-pressed', this.value
.toString() );
2783 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
2784 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
2785 * visually by a slider in the leftmost position.
2788 * // Toggle switches in the 'off' and 'on' position.
2789 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
2790 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
2794 * // Create a FieldsetLayout to layout and label switches
2795 * var fieldset = new OO.ui.FieldsetLayout( {
2796 * label: 'Toggle switches'
2798 * fieldset.addItems( [
2799 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
2800 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
2802 * $( 'body' ).append( fieldset.$element );
2805 * @extends OO.ui.ToggleWidget
2806 * @mixins OO.ui.mixin.TabIndexedElement
2809 * @param {Object} [config] Configuration options
2810 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
2811 * By default, the toggle switch is in the 'off' position.
2813 OO
.ui
.ToggleSwitchWidget
= function OoUiToggleSwitchWidget( config
) {
2814 // Parent constructor
2815 OO
.ui
.ToggleSwitchWidget
.parent
.call( this, config
);
2817 // Mixin constructors
2818 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
2821 this.dragging
= false;
2822 this.dragStart
= null;
2823 this.sliding
= false;
2824 this.$glow
= $( '<span>' );
2825 this.$grip
= $( '<span>' );
2829 click
: this.onClick
.bind( this ),
2830 keypress
: this.onKeyPress
.bind( this )
2834 this.$glow
.addClass( 'oo-ui-toggleSwitchWidget-glow' );
2835 this.$grip
.addClass( 'oo-ui-toggleSwitchWidget-grip' );
2837 .addClass( 'oo-ui-toggleSwitchWidget' )
2838 .attr( 'role', 'checkbox' )
2839 .append( this.$glow
, this.$grip
);
2844 OO
.inheritClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.ToggleWidget
);
2845 OO
.mixinClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.mixin
.TabIndexedElement
);
2850 * Handle mouse click events.
2853 * @param {jQuery.Event} e Mouse click event
2855 OO
.ui
.ToggleSwitchWidget
.prototype.onClick = function ( e
) {
2856 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
2857 this.setValue( !this.value
);
2863 * Handle key press events.
2866 * @param {jQuery.Event} e Key press event
2868 OO
.ui
.ToggleSwitchWidget
.prototype.onKeyPress = function ( e
) {
2869 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
2870 this.setValue( !this.value
);
2876 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
2877 * Controls include moving items up and down, removing items, and adding different kinds of items.
2879 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
2882 * @extends OO.ui.Widget
2883 * @mixins OO.ui.mixin.GroupElement
2884 * @mixins OO.ui.mixin.IconElement
2887 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
2888 * @param {Object} [config] Configuration options
2889 * @cfg {Object} [abilities] List of abilties
2890 * @cfg {boolean} [abilities.move=true] Allow moving movable items
2891 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
2893 OO
.ui
.OutlineControlsWidget
= function OoUiOutlineControlsWidget( outline
, config
) {
2894 // Allow passing positional parameters inside the config object
2895 if ( OO
.isPlainObject( outline
) && config
=== undefined ) {
2897 outline
= config
.outline
;
2900 // Configuration initialization
2901 config
= $.extend( { icon
: 'add' }, config
);
2903 // Parent constructor
2904 OO
.ui
.OutlineControlsWidget
.parent
.call( this, config
);
2906 // Mixin constructors
2907 OO
.ui
.mixin
.GroupElement
.call( this, config
);
2908 OO
.ui
.mixin
.IconElement
.call( this, config
);
2911 this.outline
= outline
;
2912 this.$movers
= $( '<div>' );
2913 this.upButton
= new OO
.ui
.ButtonWidget( {
2916 title
: OO
.ui
.msg( 'ooui-outline-control-move-up' )
2918 this.downButton
= new OO
.ui
.ButtonWidget( {
2921 title
: OO
.ui
.msg( 'ooui-outline-control-move-down' )
2923 this.removeButton
= new OO
.ui
.ButtonWidget( {
2926 title
: OO
.ui
.msg( 'ooui-outline-control-remove' )
2928 this.abilities
= { move: true, remove
: true };
2931 outline
.connect( this, {
2932 select
: 'onOutlineChange',
2933 add
: 'onOutlineChange',
2934 remove
: 'onOutlineChange'
2936 this.upButton
.connect( this, { click
: [ 'emit', 'move', -1 ] } );
2937 this.downButton
.connect( this, { click
: [ 'emit', 'move', 1 ] } );
2938 this.removeButton
.connect( this, { click
: [ 'emit', 'remove' ] } );
2941 this.$element
.addClass( 'oo-ui-outlineControlsWidget' );
2942 this.$group
.addClass( 'oo-ui-outlineControlsWidget-items' );
2944 .addClass( 'oo-ui-outlineControlsWidget-movers' )
2945 .append( this.removeButton
.$element
, this.upButton
.$element
, this.downButton
.$element
);
2946 this.$element
.append( this.$icon
, this.$group
, this.$movers
);
2947 this.setAbilities( config
.abilities
|| {} );
2952 OO
.inheritClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.Widget
);
2953 OO
.mixinClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.mixin
.GroupElement
);
2954 OO
.mixinClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.mixin
.IconElement
);
2960 * @param {number} places Number of places to move
2972 * @param {Object} abilities List of abilties
2973 * @param {boolean} [abilities.move] Allow moving movable items
2974 * @param {boolean} [abilities.remove] Allow removing removable items
2976 OO
.ui
.OutlineControlsWidget
.prototype.setAbilities = function ( abilities
) {
2979 for ( ability
in this.abilities
) {
2980 if ( abilities
[ ability
] !== undefined ) {
2981 this.abilities
[ ability
] = !!abilities
[ ability
];
2985 this.onOutlineChange();
2989 * Handle outline change events.
2993 OO
.ui
.OutlineControlsWidget
.prototype.onOutlineChange = function () {
2994 var i
, len
, firstMovable
, lastMovable
,
2995 items
= this.outline
.getItems(),
2996 selectedItem
= this.outline
.getSelectedItem(),
2997 movable
= this.abilities
.move && selectedItem
&& selectedItem
.isMovable(),
2998 removable
= this.abilities
.remove
&& selectedItem
&& selectedItem
.isRemovable();
3003 while ( ++i
< len
) {
3004 if ( items
[ i
].isMovable() ) {
3005 firstMovable
= items
[ i
];
3011 if ( items
[ i
].isMovable() ) {
3012 lastMovable
= items
[ i
];
3017 this.upButton
.setDisabled( !movable
|| selectedItem
=== firstMovable
);
3018 this.downButton
.setDisabled( !movable
|| selectedItem
=== lastMovable
);
3019 this.removeButton
.setDisabled( !removable
);
3023 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
3025 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
3026 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
3030 * @extends OO.ui.DecoratedOptionWidget
3033 * @param {Object} [config] Configuration options
3034 * @cfg {number} [level] Indentation level
3035 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
3037 OO
.ui
.OutlineOptionWidget
= function OoUiOutlineOptionWidget( config
) {
3038 // Configuration initialization
3039 config
= config
|| {};
3041 // Parent constructor
3042 OO
.ui
.OutlineOptionWidget
.parent
.call( this, config
);
3046 this.movable
= !!config
.movable
;
3047 this.removable
= !!config
.removable
;
3050 this.$element
.addClass( 'oo-ui-outlineOptionWidget' );
3051 this.setLevel( config
.level
);
3056 OO
.inheritClass( OO
.ui
.OutlineOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
3058 /* Static Properties */
3060 OO
.ui
.OutlineOptionWidget
.static.highlightable
= false;
3062 OO
.ui
.OutlineOptionWidget
.static.scrollIntoViewOnSelect
= true;
3064 OO
.ui
.OutlineOptionWidget
.static.levelClass
= 'oo-ui-outlineOptionWidget-level-';
3066 OO
.ui
.OutlineOptionWidget
.static.levels
= 3;
3071 * Check if item is movable.
3073 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
3075 * @return {boolean} Item is movable
3077 OO
.ui
.OutlineOptionWidget
.prototype.isMovable = function () {
3078 return this.movable
;
3082 * Check if item is removable.
3084 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
3086 * @return {boolean} Item is removable
3088 OO
.ui
.OutlineOptionWidget
.prototype.isRemovable = function () {
3089 return this.removable
;
3093 * Get indentation level.
3095 * @return {number} Indentation level
3097 OO
.ui
.OutlineOptionWidget
.prototype.getLevel = function () {
3104 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
3106 * @param {boolean} movable Item is movable
3109 OO
.ui
.OutlineOptionWidget
.prototype.setMovable = function ( movable
) {
3110 this.movable
= !!movable
;
3111 this.updateThemeClasses();
3118 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
3120 * @param {boolean} removable Item is removable
3123 OO
.ui
.OutlineOptionWidget
.prototype.setRemovable = function ( removable
) {
3124 this.removable
= !!removable
;
3125 this.updateThemeClasses();
3130 * Set indentation level.
3132 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
3135 OO
.ui
.OutlineOptionWidget
.prototype.setLevel = function ( level
) {
3136 var levels
= this.constructor.static.levels
,
3137 levelClass
= this.constructor.static.levelClass
,
3140 this.level
= level
? Math
.max( 0, Math
.min( levels
- 1, level
) ) : 0;
3142 if ( this.level
=== i
) {
3143 this.$element
.addClass( levelClass
+ i
);
3145 this.$element
.removeClass( levelClass
+ i
);
3148 this.updateThemeClasses();
3154 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
3155 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
3157 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
3160 * @extends OO.ui.SelectWidget
3161 * @mixins OO.ui.mixin.TabIndexedElement
3164 * @param {Object} [config] Configuration options
3166 OO
.ui
.OutlineSelectWidget
= function OoUiOutlineSelectWidget( config
) {
3167 // Parent constructor
3168 OO
.ui
.OutlineSelectWidget
.parent
.call( this, config
);
3170 // Mixin constructors
3171 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
3175 focus
: this.bindKeyDownListener
.bind( this ),
3176 blur
: this.unbindKeyDownListener
.bind( this )
3180 this.$element
.addClass( 'oo-ui-outlineSelectWidget' );
3185 OO
.inheritClass( OO
.ui
.OutlineSelectWidget
, OO
.ui
.SelectWidget
);
3186 OO
.mixinClass( OO
.ui
.OutlineSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
3189 * ButtonOptionWidget is a special type of {@link OO.ui.mixin.ButtonElement button element} that
3190 * can be selected and configured with data. The class is
3191 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
3192 * [OOjs UI documentation on MediaWiki] [1] for more information.
3194 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
3197 * @extends OO.ui.OptionWidget
3198 * @mixins OO.ui.mixin.ButtonElement
3199 * @mixins OO.ui.mixin.IconElement
3200 * @mixins OO.ui.mixin.IndicatorElement
3201 * @mixins OO.ui.mixin.TitledElement
3204 * @param {Object} [config] Configuration options
3206 OO
.ui
.ButtonOptionWidget
= function OoUiButtonOptionWidget( config
) {
3207 // Configuration initialization
3208 config
= config
|| {};
3210 // Parent constructor
3211 OO
.ui
.ButtonOptionWidget
.parent
.call( this, config
);
3213 // Mixin constructors
3214 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
3215 OO
.ui
.mixin
.IconElement
.call( this, config
);
3216 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
3217 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
3220 this.$element
.addClass( 'oo-ui-buttonOptionWidget' );
3221 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
3222 this.$element
.append( this.$button
);
3227 OO
.inheritClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.OptionWidget
);
3228 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.mixin
.ButtonElement
);
3229 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.mixin
.IconElement
);
3230 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.mixin
.IndicatorElement
);
3231 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.mixin
.TitledElement
);
3233 /* Static Properties */
3235 // Allow button mouse down events to pass through so they can be handled by the parent select widget
3236 OO
.ui
.ButtonOptionWidget
.static.cancelButtonMouseDownEvents
= false;
3238 OO
.ui
.ButtonOptionWidget
.static.highlightable
= false;
3245 OO
.ui
.ButtonOptionWidget
.prototype.setSelected = function ( state
) {
3246 OO
.ui
.ButtonOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
3248 if ( this.constructor.static.selectable
) {
3249 this.setActive( state
);
3256 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
3257 * button options and is used together with
3258 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
3259 * highlighting, choosing, and selecting mutually exclusive options. Please see
3260 * the [OOjs UI documentation on MediaWiki] [1] for more information.
3263 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
3264 * var option1 = new OO.ui.ButtonOptionWidget( {
3266 * label: 'Option 1',
3267 * title: 'Button option 1'
3270 * var option2 = new OO.ui.ButtonOptionWidget( {
3272 * label: 'Option 2',
3273 * title: 'Button option 2'
3276 * var option3 = new OO.ui.ButtonOptionWidget( {
3278 * label: 'Option 3',
3279 * title: 'Button option 3'
3282 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
3283 * items: [ option1, option2, option3 ]
3285 * $( 'body' ).append( buttonSelect.$element );
3287 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
3290 * @extends OO.ui.SelectWidget
3291 * @mixins OO.ui.mixin.TabIndexedElement
3294 * @param {Object} [config] Configuration options
3296 OO
.ui
.ButtonSelectWidget
= function OoUiButtonSelectWidget( config
) {
3297 // Parent constructor
3298 OO
.ui
.ButtonSelectWidget
.parent
.call( this, config
);
3300 // Mixin constructors
3301 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
3305 focus
: this.bindKeyDownListener
.bind( this ),
3306 blur
: this.unbindKeyDownListener
.bind( this )
3310 this.$element
.addClass( 'oo-ui-buttonSelectWidget' );
3315 OO
.inheritClass( OO
.ui
.ButtonSelectWidget
, OO
.ui
.SelectWidget
);
3316 OO
.mixinClass( OO
.ui
.ButtonSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
3319 * TabOptionWidget is an item in a {@link OO.ui.TabSelectWidget TabSelectWidget}.
3321 * Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}, which contain
3322 * {@link OO.ui.CardLayout card layouts}. See {@link OO.ui.IndexLayout IndexLayout}
3326 * @extends OO.ui.OptionWidget
3329 * @param {Object} [config] Configuration options
3331 OO
.ui
.TabOptionWidget
= function OoUiTabOptionWidget( config
) {
3332 // Configuration initialization
3333 config
= config
|| {};
3335 // Parent constructor
3336 OO
.ui
.TabOptionWidget
.parent
.call( this, config
);
3339 this.$element
.addClass( 'oo-ui-tabOptionWidget' );
3344 OO
.inheritClass( OO
.ui
.TabOptionWidget
, OO
.ui
.OptionWidget
);
3346 /* Static Properties */
3348 OO
.ui
.TabOptionWidget
.static.highlightable
= false;
3351 * TabSelectWidget is a list that contains {@link OO.ui.TabOptionWidget tab options}
3353 * **Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}.**
3356 * @extends OO.ui.SelectWidget
3357 * @mixins OO.ui.mixin.TabIndexedElement
3360 * @param {Object} [config] Configuration options
3362 OO
.ui
.TabSelectWidget
= function OoUiTabSelectWidget( config
) {
3363 // Parent constructor
3364 OO
.ui
.TabSelectWidget
.parent
.call( this, config
);
3366 // Mixin constructors
3367 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
3371 focus
: this.bindKeyDownListener
.bind( this ),
3372 blur
: this.unbindKeyDownListener
.bind( this )
3376 this.$element
.addClass( 'oo-ui-tabSelectWidget' );
3381 OO
.inheritClass( OO
.ui
.TabSelectWidget
, OO
.ui
.SelectWidget
);
3382 OO
.mixinClass( OO
.ui
.TabSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
3385 * CapsuleItemWidgets are used within a {@link OO.ui.CapsuleMultiselectWidget
3386 * CapsuleMultiselectWidget} to display the selected items.
3389 * @extends OO.ui.Widget
3390 * @mixins OO.ui.mixin.ItemWidget
3391 * @mixins OO.ui.mixin.LabelElement
3392 * @mixins OO.ui.mixin.FlaggedElement
3393 * @mixins OO.ui.mixin.TabIndexedElement
3396 * @param {Object} [config] Configuration options
3398 OO
.ui
.CapsuleItemWidget
= function OoUiCapsuleItemWidget( config
) {
3399 // Configuration initialization
3400 config
= config
|| {};
3402 // Parent constructor
3403 OO
.ui
.CapsuleItemWidget
.parent
.call( this, config
);
3405 // Mixin constructors
3406 OO
.ui
.mixin
.ItemWidget
.call( this );
3407 OO
.ui
.mixin
.LabelElement
.call( this, config
);
3408 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
3409 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
3412 this.closeButton
= new OO
.ui
.ButtonWidget( {
3416 } ).on( 'click', this.onCloseClick
.bind( this ) );
3418 this.on( 'disable', function ( disabled
) {
3419 this.closeButton
.setDisabled( disabled
);
3425 click
: this.onClick
.bind( this ),
3426 keydown
: this.onKeyDown
.bind( this )
3428 .addClass( 'oo-ui-capsuleItemWidget' )
3429 .append( this.$label
, this.closeButton
.$element
);
3434 OO
.inheritClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.Widget
);
3435 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.ItemWidget
);
3436 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.LabelElement
);
3437 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.FlaggedElement
);
3438 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.TabIndexedElement
);
3443 * Handle close icon clicks
3445 OO
.ui
.CapsuleItemWidget
.prototype.onCloseClick = function () {
3446 var element
= this.getElementGroup();
3448 if ( element
&& $.isFunction( element
.removeItems
) ) {
3449 element
.removeItems( [ this ] );
3455 * Handle click event for the entire capsule
3457 OO
.ui
.CapsuleItemWidget
.prototype.onClick = function () {
3458 var element
= this.getElementGroup();
3460 if ( !this.isDisabled() && element
&& $.isFunction( element
.editItem
) ) {
3461 element
.editItem( this );
3466 * Handle keyDown event for the entire capsule
3468 OO
.ui
.CapsuleItemWidget
.prototype.onKeyDown = function ( e
) {
3469 var element
= this.getElementGroup();
3471 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
|| e
.keyCode
=== OO
.ui
.Keys
.DELETE
) {
3472 element
.removeItems( [ this ] );
3475 } else if ( e
.keyCode
=== OO
.ui
.Keys
.ENTER
) {
3476 element
.editItem( this );
3478 } else if ( e
.keyCode
=== OO
.ui
.Keys
.LEFT
) {
3479 element
.getPreviousItem( this ).focus();
3480 } else if ( e
.keyCode
=== OO
.ui
.Keys
.RIGHT
) {
3481 element
.getNextItem( this ).focus();
3486 * Focuses the capsule
3488 OO
.ui
.CapsuleItemWidget
.prototype.focus = function () {
3489 this.$element
.focus();
3493 * CapsuleMultiselectWidgets are something like a {@link OO.ui.ComboBoxInputWidget combo box widget}
3494 * that allows for selecting multiple values.
3496 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
3499 * // Example: A CapsuleMultiselectWidget.
3500 * var capsule = new OO.ui.CapsuleMultiselectWidget( {
3501 * label: 'CapsuleMultiselectWidget',
3502 * selected: [ 'Option 1', 'Option 3' ],
3505 * new OO.ui.MenuOptionWidget( {
3507 * label: 'Option One'
3509 * new OO.ui.MenuOptionWidget( {
3511 * label: 'Option Two'
3513 * new OO.ui.MenuOptionWidget( {
3515 * label: 'Option Three'
3517 * new OO.ui.MenuOptionWidget( {
3519 * label: 'Option Four'
3521 * new OO.ui.MenuOptionWidget( {
3523 * label: 'Option Five'
3528 * $( 'body' ).append( capsule.$element );
3530 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
3533 * @extends OO.ui.Widget
3534 * @mixins OO.ui.mixin.GroupElement
3535 * @mixins OO.ui.mixin.PopupElement
3536 * @mixins OO.ui.mixin.TabIndexedElement
3537 * @mixins OO.ui.mixin.IndicatorElement
3538 * @mixins OO.ui.mixin.IconElement
3539 * @uses OO.ui.CapsuleItemWidget
3540 * @uses OO.ui.FloatingMenuSelectWidget
3543 * @param {Object} [config] Configuration options
3544 * @cfg {boolean} [allowArbitrary=false] Allow data items to be added even if not present in the menu.
3545 * @cfg {Object} [menu] (required) Configuration options to pass to the
3546 * {@link OO.ui.MenuSelectWidget menu select widget}.
3547 * @cfg {Object} [popup] Configuration options to pass to the {@link OO.ui.PopupWidget popup widget}.
3548 * If specified, this popup will be shown instead of the menu (but the menu
3549 * will still be used for item labels and allowArbitrary=false). The widgets
3550 * in the popup should use {@link #addItemsFromData} or {@link #addItems} as necessary.
3551 * @cfg {jQuery} [$overlay=this.$element] Render the menu or popup into a separate layer.
3552 * This configuration is useful in cases where the expanded menu is larger than
3553 * its containing `<div>`. The specified overlay layer is usually on top of
3554 * the containing `<div>` and has a larger area. By default, the menu uses
3555 * relative positioning.
3557 OO
.ui
.CapsuleMultiselectWidget
= function OoUiCapsuleMultiselectWidget( config
) {
3560 // Parent constructor
3561 OO
.ui
.CapsuleMultiselectWidget
.parent
.call( this, config
);
3563 // Configuration initialization
3564 config
= $.extend( {
3565 allowArbitrary
: false,
3566 $overlay
: this.$element
3569 // Properties (must be set before mixin constructor calls)
3570 this.$input
= config
.popup
? null : $( '<input>' );
3571 this.$handle
= $( '<div>' );
3573 // Mixin constructors
3574 OO
.ui
.mixin
.GroupElement
.call( this, config
);
3575 if ( config
.popup
) {
3576 config
.popup
= $.extend( {}, config
.popup
, {
3580 OO
.ui
.mixin
.PopupElement
.call( this, config
);
3581 $tabFocus
= $( '<span>' );
3582 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: $tabFocus
} ) );
3586 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
3588 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
3589 OO
.ui
.mixin
.IconElement
.call( this, config
);
3592 this.$content
= $( '<div>' );
3593 this.allowArbitrary
= config
.allowArbitrary
;
3594 this.$overlay
= config
.$overlay
;
3595 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend(
3598 $input
: this.$input
,
3599 $container
: this.$element
,
3600 filterFromInput
: true,
3601 disabled
: this.isDisabled()
3609 focus
: this.onFocusForPopup
.bind( this )
3611 this.popup
.$element
.on( 'focusout', this.onPopupFocusOut
.bind( this ) );
3612 if ( this.popup
.$autoCloseIgnore
) {
3613 this.popup
.$autoCloseIgnore
.on( 'focusout', this.onPopupFocusOut
.bind( this ) );
3615 this.popup
.connect( this, {
3616 toggle: function ( visible
) {
3617 $tabFocus
.toggle( !visible
);
3622 focus
: this.onInputFocus
.bind( this ),
3623 blur
: this.onInputBlur
.bind( this ),
3624 'propertychange change click mouseup keydown keyup input cut paste select focus':
3625 OO
.ui
.debounce( this.updateInputSize
.bind( this ) ),
3626 keydown
: this.onKeyDown
.bind( this ),
3627 keypress
: this.onKeyPress
.bind( this )
3630 this.menu
.connect( this, {
3631 choose
: 'onMenuChoose',
3632 add
: 'onMenuItemsChange',
3633 remove
: 'onMenuItemsChange'
3636 mousedown
: this.onMouseDown
.bind( this )
3640 if ( this.$input
) {
3641 this.$input
.prop( 'disabled', this.isDisabled() );
3644 'aria-autocomplete': 'list'
3646 this.updateInputSize();
3648 if ( config
.data
) {
3649 this.setItemsFromData( config
.data
);
3651 this.$content
.addClass( 'oo-ui-capsuleMultiselectWidget-content' )
3652 .append( this.$group
);
3653 this.$group
.addClass( 'oo-ui-capsuleMultiselectWidget-group' );
3654 this.$handle
.addClass( 'oo-ui-capsuleMultiselectWidget-handle' )
3655 .append( this.$indicator
, this.$icon
, this.$content
);
3656 this.$element
.addClass( 'oo-ui-capsuleMultiselectWidget' )
3657 .append( this.$handle
);
3659 this.$content
.append( $tabFocus
);
3660 this.$overlay
.append( this.popup
.$element
);
3662 this.$content
.append( this.$input
);
3663 this.$overlay
.append( this.menu
.$element
);
3665 this.onMenuItemsChange();
3670 OO
.inheritClass( OO
.ui
.CapsuleMultiselectWidget
, OO
.ui
.Widget
);
3671 OO
.mixinClass( OO
.ui
.CapsuleMultiselectWidget
, OO
.ui
.mixin
.GroupElement
);
3672 OO
.mixinClass( OO
.ui
.CapsuleMultiselectWidget
, OO
.ui
.mixin
.PopupElement
);
3673 OO
.mixinClass( OO
.ui
.CapsuleMultiselectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
3674 OO
.mixinClass( OO
.ui
.CapsuleMultiselectWidget
, OO
.ui
.mixin
.IndicatorElement
);
3675 OO
.mixinClass( OO
.ui
.CapsuleMultiselectWidget
, OO
.ui
.mixin
.IconElement
);
3682 * A change event is emitted when the set of selected items changes.
3684 * @param {Mixed[]} datas Data of the now-selected items
3690 * A resize event is emitted when the widget's dimensions change to accomodate newly added items or
3691 * current user input.
3697 * Construct a OO.ui.CapsuleItemWidget (or a subclass thereof) from given label and data.
3698 * May return `null` if the given label and data are not valid.
3701 * @param {Mixed} data Custom data of any type.
3702 * @param {string} label The label text.
3703 * @return {OO.ui.CapsuleItemWidget|null}
3705 OO
.ui
.CapsuleMultiselectWidget
.prototype.createItemWidget = function ( data
, label
) {
3706 if ( label
=== '' ) {
3709 return new OO
.ui
.CapsuleItemWidget( { data
: data
, label
: label
} );
3713 * Get the data of the items in the capsule
3717 OO
.ui
.CapsuleMultiselectWidget
.prototype.getItemsData = function () {
3718 return this.getItems().map( function ( item
) {
3724 * Set the items in the capsule by providing data
3727 * @param {Mixed[]} datas
3728 * @return {OO.ui.CapsuleMultiselectWidget}
3730 OO
.ui
.CapsuleMultiselectWidget
.prototype.setItemsFromData = function ( datas
) {
3733 items
= this.getItems();
3735 $.each( datas
, function ( i
, data
) {
3737 item
= menu
.getItemFromData( data
);
3741 } else if ( widget
.allowArbitrary
) {
3742 label
= String( data
);
3748 for ( j
= 0; j
< items
.length
; j
++ ) {
3749 if ( items
[ j
].data
=== data
&& items
[ j
].label
=== label
) {
3751 items
.splice( j
, 1 );
3756 item
= widget
.createItemWidget( data
, label
);
3759 widget
.addItems( [ item
], i
);
3763 if ( items
.length
) {
3764 widget
.removeItems( items
);
3771 * Add items to the capsule by providing their data
3774 * @param {Mixed[]} datas
3775 * @return {OO.ui.CapsuleMultiselectWidget}
3777 OO
.ui
.CapsuleMultiselectWidget
.prototype.addItemsFromData = function ( datas
) {
3782 $.each( datas
, function ( i
, data
) {
3785 if ( !widget
.getItemFromData( data
) ) {
3786 item
= menu
.getItemFromData( data
);
3788 item
= widget
.createItemWidget( data
, item
.label
);
3789 } else if ( widget
.allowArbitrary
) {
3790 item
= widget
.createItemWidget( data
, String( data
) );
3798 if ( items
.length
) {
3799 this.addItems( items
);
3806 * Add items to the capsule by providing a label
3808 * @param {string} label
3809 * @return {boolean} Whether the item was added or not
3811 OO
.ui
.CapsuleMultiselectWidget
.prototype.addItemFromLabel = function ( label
) {
3813 item
= this.menu
.getItemFromLabel( label
, true );
3815 this.addItemsFromData( [ item
.data
] );
3817 } else if ( this.allowArbitrary
) {
3818 items
= this.getItems();
3819 this.addItemsFromData( [ label
] );
3820 return !OO
.compare( this.getItems(), items
);
3826 * Remove items by data
3829 * @param {Mixed[]} datas
3830 * @return {OO.ui.CapsuleMultiselectWidget}
3832 OO
.ui
.CapsuleMultiselectWidget
.prototype.removeItemsFromData = function ( datas
) {
3836 $.each( datas
, function ( i
, data
) {
3837 var item
= widget
.getItemFromData( data
);
3843 if ( items
.length
) {
3844 this.removeItems( items
);
3853 OO
.ui
.CapsuleMultiselectWidget
.prototype.addItems = function ( items
) {
3855 oldItems
= this.items
.slice();
3857 OO
.ui
.mixin
.GroupElement
.prototype.addItems
.call( this, items
);
3859 if ( this.items
.length
!== oldItems
.length
) {
3863 for ( i
= 0, l
= oldItems
.length
; same
&& i
< l
; i
++ ) {
3864 same
= same
&& this.items
[ i
] === oldItems
[ i
];
3868 this.emit( 'change', this.getItemsData() );
3869 this.updateIfHeightChanged();
3876 * Removes the item from the list and copies its label to `this.$input`.
3878 * @param {Object} item
3880 OO
.ui
.CapsuleMultiselectWidget
.prototype.editItem = function ( item
) {
3881 this.$input
.val( item
.label
);
3882 this.updateInputSize();
3884 this.removeItems( [ item
] );
3890 OO
.ui
.CapsuleMultiselectWidget
.prototype.removeItems = function ( items
) {
3892 oldItems
= this.items
.slice();
3894 OO
.ui
.mixin
.GroupElement
.prototype.removeItems
.call( this, items
);
3896 if ( this.items
.length
!== oldItems
.length
) {
3900 for ( i
= 0, l
= oldItems
.length
; same
&& i
< l
; i
++ ) {
3901 same
= same
&& this.items
[ i
] === oldItems
[ i
];
3905 this.emit( 'change', this.getItemsData() );
3906 this.updateIfHeightChanged();
3915 OO
.ui
.CapsuleMultiselectWidget
.prototype.clearItems = function () {
3916 if ( this.items
.length
) {
3917 OO
.ui
.mixin
.GroupElement
.prototype.clearItems
.call( this );
3918 this.emit( 'change', this.getItemsData() );
3919 this.updateIfHeightChanged();
3925 * Given an item, returns the item after it. If its the last item,
3926 * returns `this.$input`. If no item is passed, returns the very first
3929 * @param {OO.ui.CapsuleItemWidget} [item]
3930 * @return {OO.ui.CapsuleItemWidget|jQuery|boolean}
3932 OO
.ui
.CapsuleMultiselectWidget
.prototype.getNextItem = function ( item
) {
3935 if ( item
=== undefined ) {
3936 return this.items
[ 0 ];
3939 itemIndex
= this.items
.indexOf( item
);
3940 if ( itemIndex
< 0 ) { // Item not in list
3942 } else if ( itemIndex
=== this.items
.length
- 1 ) { // Last item
3945 return this.items
[ itemIndex
+ 1 ];
3950 * Given an item, returns the item before it. If its the first item,
3951 * returns `this.$input`. If no item is passed, returns the very last
3954 * @param {OO.ui.CapsuleItemWidget} [item]
3955 * @return {OO.ui.CapsuleItemWidget|jQuery|boolean}
3957 OO
.ui
.CapsuleMultiselectWidget
.prototype.getPreviousItem = function ( item
) {
3960 if ( item
=== undefined ) {
3961 return this.items
[ this.items
.length
- 1 ];
3964 itemIndex
= this.items
.indexOf( item
);
3965 if ( itemIndex
< 0 ) { // Item not in list
3967 } else if ( itemIndex
=== 0 ) { // First item
3970 return this.items
[ itemIndex
- 1 ];
3975 * Get the capsule widget's menu.
3977 * @return {OO.ui.MenuSelectWidget} Menu widget
3979 OO
.ui
.CapsuleMultiselectWidget
.prototype.getMenu = function () {
3984 * Handle focus events
3987 * @param {jQuery.Event} event
3989 OO
.ui
.CapsuleMultiselectWidget
.prototype.onInputFocus = function () {
3990 if ( !this.isDisabled() ) {
3991 this.menu
.toggle( true );
3996 * Handle blur events
3999 * @param {jQuery.Event} event
4001 OO
.ui
.CapsuleMultiselectWidget
.prototype.onInputBlur = function () {
4002 this.addItemFromLabel( this.$input
.val() );
4007 * Handle focus events
4010 * @param {jQuery.Event} event
4012 OO
.ui
.CapsuleMultiselectWidget
.prototype.onFocusForPopup = function () {
4013 if ( !this.isDisabled() ) {
4014 this.popup
.setSize( this.$handle
.width() );
4015 this.popup
.toggle( true );
4016 OO
.ui
.findFocusable( this.popup
.$element
).focus();
4021 * Handles popup focus out events.
4024 * @param {jQuery.Event} e Focus out event
4026 OO
.ui
.CapsuleMultiselectWidget
.prototype.onPopupFocusOut = function () {
4027 var widget
= this.popup
;
4029 setTimeout( function () {
4031 widget
.isVisible() &&
4032 !OO
.ui
.contains( widget
.$element
[ 0 ], document
.activeElement
, true ) &&
4033 ( !widget
.$autoCloseIgnore
|| !widget
.$autoCloseIgnore
.has( document
.activeElement
).length
)
4035 widget
.toggle( false );
4041 * Handle mouse down events.
4044 * @param {jQuery.Event} e Mouse down event
4046 OO
.ui
.CapsuleMultiselectWidget
.prototype.onMouseDown = function ( e
) {
4047 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
4051 this.updateInputSize();
4056 * Handle key press events.
4059 * @param {jQuery.Event} e Key press event
4061 OO
.ui
.CapsuleMultiselectWidget
.prototype.onKeyPress = function ( e
) {
4062 if ( !this.isDisabled() ) {
4063 if ( e
.which
=== OO
.ui
.Keys
.ESCAPE
) {
4068 if ( !this.popup
) {
4069 this.menu
.toggle( true );
4070 if ( e
.which
=== OO
.ui
.Keys
.ENTER
) {
4071 if ( this.addItemFromLabel( this.$input
.val() ) ) {
4077 // Make sure the input gets resized.
4078 setTimeout( this.updateInputSize
.bind( this ), 0 );
4084 * Handle key down events.
4087 * @param {jQuery.Event} e Key down event
4089 OO
.ui
.CapsuleMultiselectWidget
.prototype.onKeyDown = function ( e
) {
4091 !this.isDisabled() &&
4092 this.$input
.val() === '' &&
4095 // 'keypress' event is not triggered for Backspace
4096 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
) {
4097 if ( e
.metaKey
|| e
.ctrlKey
) {
4098 this.removeItems( this.items
.slice( -1 ) );
4100 this.editItem( this.items
[ this.items
.length
- 1 ] );
4103 } else if ( e
.keyCode
=== OO
.ui
.Keys
.LEFT
) {
4104 this.getPreviousItem().focus();
4105 } else if ( e
.keyCode
=== OO
.ui
.Keys
.RIGHT
) {
4106 this.getNextItem().focus();
4112 * Update the dimensions of the text input field to encompass all available area.
4115 * @param {jQuery.Event} e Event of some sort
4117 OO
.ui
.CapsuleMultiselectWidget
.prototype.updateInputSize = function () {
4118 var $lastItem
, direction
, contentWidth
, currentWidth
, bestWidth
;
4119 if ( !this.isDisabled() ) {
4120 this.$input
.css( 'width', '1em' );
4121 $lastItem
= this.$group
.children().last();
4122 direction
= OO
.ui
.Element
.static.getDir( this.$handle
);
4123 contentWidth
= this.$input
[ 0 ].scrollWidth
;
4124 currentWidth
= this.$input
.width();
4126 if ( contentWidth
< currentWidth
) {
4127 // All is fine, don't perform expensive calculations
4131 if ( !$lastItem
.length
) {
4132 bestWidth
= this.$content
.innerWidth();
4134 bestWidth
= direction
=== 'ltr' ?
4135 this.$content
.innerWidth() - $lastItem
.position().left
- $lastItem
.outerWidth() :
4136 $lastItem
.position().left
;
4138 // Some safety margin for sanity, because I *really* don't feel like finding out where the few
4139 // pixels this is off by are coming from.
4141 if ( contentWidth
> bestWidth
) {
4142 // This will result in the input getting shifted to the next line
4143 bestWidth
= this.$content
.innerWidth() - 10;
4145 this.$input
.width( Math
.floor( bestWidth
) );
4146 this.updateIfHeightChanged();
4151 * Determine if widget height changed, and if so, update menu position and emit 'resize' event.
4155 OO
.ui
.CapsuleMultiselectWidget
.prototype.updateIfHeightChanged = function () {
4156 var height
= this.$element
.height();
4157 if ( height
!== this.height
) {
4158 this.height
= height
;
4159 this.menu
.position();
4160 this.emit( 'resize' );
4165 * Handle menu choose events.
4168 * @param {OO.ui.OptionWidget} item Chosen item
4170 OO
.ui
.CapsuleMultiselectWidget
.prototype.onMenuChoose = function ( item
) {
4171 if ( item
&& item
.isVisible() ) {
4172 this.addItemsFromData( [ item
.getData() ] );
4178 * Handle menu item change events.
4182 OO
.ui
.CapsuleMultiselectWidget
.prototype.onMenuItemsChange = function () {
4183 this.setItemsFromData( this.getItemsData() );
4184 this.$element
.toggleClass( 'oo-ui-capsuleMultiselectWidget-empty', this.menu
.isEmpty() );
4188 * Clear the input field
4192 OO
.ui
.CapsuleMultiselectWidget
.prototype.clearInput = function () {
4193 if ( this.$input
) {
4194 this.$input
.val( '' );
4195 this.updateInputSize();
4198 this.popup
.toggle( false );
4200 this.menu
.toggle( false );
4201 this.menu
.selectItem();
4202 this.menu
.highlightItem();
4208 OO
.ui
.CapsuleMultiselectWidget
.prototype.setDisabled = function ( disabled
) {
4212 OO
.ui
.CapsuleMultiselectWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
4214 if ( this.$input
) {
4215 this.$input
.prop( 'disabled', this.isDisabled() );
4218 this.menu
.setDisabled( this.isDisabled() );
4221 this.popup
.setDisabled( this.isDisabled() );
4225 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4226 this.items
[ i
].updateDisabled();
4237 * @return {OO.ui.CapsuleMultiselectWidget}
4239 OO
.ui
.CapsuleMultiselectWidget
.prototype.focus = function () {
4240 if ( !this.isDisabled() ) {
4242 this.popup
.setSize( this.$handle
.width() );
4243 this.popup
.toggle( true );
4244 OO
.ui
.findFocusable( this.popup
.$element
).focus();
4246 this.updateInputSize();
4247 this.menu
.toggle( true );
4248 this.$input
.focus();
4256 * @deprecated since 0.17.3; use OO.ui.CapsuleMultiselectWidget instead
4258 OO
.ui
.CapsuleMultiSelectWidget
= OO
.ui
.CapsuleMultiselectWidget
;
4261 * SelectFileWidgets allow for selecting files, using the HTML5 File API. These
4262 * widgets can be configured with {@link OO.ui.mixin.IconElement icons} and {@link
4263 * OO.ui.mixin.IndicatorElement indicators}.
4264 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
4267 * // Example of a file select widget
4268 * var selectFile = new OO.ui.SelectFileWidget();
4269 * $( 'body' ).append( selectFile.$element );
4271 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets
4274 * @extends OO.ui.Widget
4275 * @mixins OO.ui.mixin.IconElement
4276 * @mixins OO.ui.mixin.IndicatorElement
4277 * @mixins OO.ui.mixin.PendingElement
4278 * @mixins OO.ui.mixin.LabelElement
4281 * @param {Object} [config] Configuration options
4282 * @cfg {string[]|null} [accept=null] MIME types to accept. null accepts all types.
4283 * @cfg {string} [placeholder] Text to display when no file is selected.
4284 * @cfg {string} [notsupported] Text to display when file support is missing in the browser.
4285 * @cfg {boolean} [droppable=true] Whether to accept files by drag and drop.
4286 * @cfg {boolean} [showDropTarget=false] Whether to show a drop target. Requires droppable to be true.
4287 * @cfg {number} [thumbnailSizeLimit=20] File size limit in MiB above which to not try and show a
4288 * preview (for performance)
4290 OO
.ui
.SelectFileWidget
= function OoUiSelectFileWidget( config
) {
4293 // Configuration initialization
4294 config
= $.extend( {
4296 placeholder
: OO
.ui
.msg( 'ooui-selectfile-placeholder' ),
4297 notsupported
: OO
.ui
.msg( 'ooui-selectfile-not-supported' ),
4299 showDropTarget
: false,
4300 thumbnailSizeLimit
: 20
4303 // Parent constructor
4304 OO
.ui
.SelectFileWidget
.parent
.call( this, config
);
4306 // Mixin constructors
4307 OO
.ui
.mixin
.IconElement
.call( this, config
);
4308 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
4309 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$info
} ) );
4310 OO
.ui
.mixin
.LabelElement
.call( this, config
);
4313 this.$info
= $( '<span>' );
4314 this.showDropTarget
= config
.showDropTarget
;
4315 this.thumbnailSizeLimit
= config
.thumbnailSizeLimit
;
4316 this.isSupported
= this.constructor.static.isSupported();
4317 this.currentFile
= null;
4318 if ( Array
.isArray( config
.accept
) ) {
4319 this.accept
= config
.accept
;
4323 this.placeholder
= config
.placeholder
;
4324 this.notsupported
= config
.notsupported
;
4325 this.onFileSelectedHandler
= this.onFileSelected
.bind( this );
4327 this.selectButton
= new OO
.ui
.ButtonWidget( {
4328 classes
: [ 'oo-ui-selectFileWidget-selectButton' ],
4329 label
: OO
.ui
.msg( 'ooui-selectfile-button-select' ),
4330 disabled
: this.disabled
|| !this.isSupported
4333 this.clearButton
= new OO
.ui
.ButtonWidget( {
4334 classes
: [ 'oo-ui-selectFileWidget-clearButton' ],
4337 disabled
: this.disabled
4341 this.selectButton
.$button
.on( {
4342 keypress
: this.onKeyPress
.bind( this )
4344 this.clearButton
.connect( this, {
4345 click
: 'onClearClick'
4347 if ( config
.droppable
) {
4348 dragHandler
= this.onDragEnterOrOver
.bind( this );
4350 dragenter
: dragHandler
,
4351 dragover
: dragHandler
,
4352 dragleave
: this.onDragLeave
.bind( this ),
4353 drop
: this.onDrop
.bind( this )
4359 this.$label
.addClass( 'oo-ui-selectFileWidget-label' );
4361 .addClass( 'oo-ui-selectFileWidget-info' )
4362 .append( this.$icon
, this.$label
, this.clearButton
.$element
, this.$indicator
);
4364 if ( config
.droppable
&& config
.showDropTarget
) {
4365 this.selectButton
.setIcon( 'upload' );
4366 this.$thumbnail
= $( '<div>' ).addClass( 'oo-ui-selectFileWidget-thumbnail' );
4367 this.setPendingElement( this.$thumbnail
);
4368 this.$dropTarget
= $( '<div>' )
4369 .addClass( 'oo-ui-selectFileWidget-dropTarget' )
4371 click
: this.onDropTargetClick
.bind( this )
4376 this.selectButton
.$element
,
4378 .addClass( 'oo-ui-selectFileWidget-dropLabel' )
4379 .text( OO
.ui
.msg( 'ooui-selectfile-dragdrop-placeholder' ) )
4381 this.$element
.append( this.$dropTarget
);
4384 .addClass( 'oo-ui-selectFileWidget' )
4385 .append( this.$info
, this.selectButton
.$element
);
4392 OO
.inheritClass( OO
.ui
.SelectFileWidget
, OO
.ui
.Widget
);
4393 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.IconElement
);
4394 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.IndicatorElement
);
4395 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.PendingElement
);
4396 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.LabelElement
);
4398 /* Static Properties */
4401 * Check if this widget is supported
4406 OO
.ui
.SelectFileWidget
.static.isSupported = function () {
4408 if ( OO
.ui
.SelectFileWidget
.static.isSupportedCache
=== null ) {
4409 $input
= $( '<input>' ).attr( 'type', 'file' );
4410 OO
.ui
.SelectFileWidget
.static.isSupportedCache
= $input
[ 0 ].files
!== undefined;
4412 return OO
.ui
.SelectFileWidget
.static.isSupportedCache
;
4415 OO
.ui
.SelectFileWidget
.static.isSupportedCache
= null;
4422 * A change event is emitted when the on/off state of the toggle changes.
4424 * @param {File|null} value New value
4430 * Get the current value of the field
4432 * @return {File|null}
4434 OO
.ui
.SelectFileWidget
.prototype.getValue = function () {
4435 return this.currentFile
;
4439 * Set the current value of the field
4441 * @param {File|null} file File to select
4443 OO
.ui
.SelectFileWidget
.prototype.setValue = function ( file
) {
4444 if ( this.currentFile
!== file
) {
4445 this.currentFile
= file
;
4447 this.emit( 'change', this.currentFile
);
4454 * Focusses the select file button.
4458 OO
.ui
.SelectFileWidget
.prototype.focus = function () {
4459 this.selectButton
.$button
[ 0 ].focus();
4464 * Update the user interface when a file is selected or unselected
4468 OO
.ui
.SelectFileWidget
.prototype.updateUI = function () {
4470 if ( !this.isSupported
) {
4471 this.$element
.addClass( 'oo-ui-selectFileWidget-notsupported' );
4472 this.$element
.removeClass( 'oo-ui-selectFileWidget-empty' );
4473 this.setLabel( this.notsupported
);
4475 this.$element
.addClass( 'oo-ui-selectFileWidget-supported' );
4476 if ( this.currentFile
) {
4477 this.$element
.removeClass( 'oo-ui-selectFileWidget-empty' );
4479 $label
= $label
.add(
4481 .addClass( 'oo-ui-selectFileWidget-fileName' )
4482 .text( this.currentFile
.name
)
4484 if ( this.currentFile
.type
!== '' ) {
4485 $label
= $label
.add(
4487 .addClass( 'oo-ui-selectFileWidget-fileType' )
4488 .text( this.currentFile
.type
)
4491 this.setLabel( $label
);
4493 if ( this.showDropTarget
) {
4495 this.loadAndGetImageUrl().done( function ( url
) {
4496 this.$thumbnail
.css( 'background-image', 'url( ' + url
+ ' )' );
4497 }.bind( this ) ).fail( function () {
4498 this.$thumbnail
.append(
4499 new OO
.ui
.IconWidget( {
4501 classes
: [ 'oo-ui-selectFileWidget-noThumbnail-icon' ]
4504 }.bind( this ) ).always( function () {
4507 this.$dropTarget
.off( 'click' );
4510 if ( this.showDropTarget
) {
4511 this.$dropTarget
.off( 'click' );
4512 this.$dropTarget
.on( {
4513 click
: this.onDropTargetClick
.bind( this )
4517 .css( 'background-image', '' );
4519 this.$element
.addClass( 'oo-ui-selectFileWidget-empty' );
4520 this.setLabel( this.placeholder
);
4526 * If the selected file is an image, get its URL and load it.
4528 * @return {jQuery.Promise} Promise resolves with the image URL after it has loaded
4530 OO
.ui
.SelectFileWidget
.prototype.loadAndGetImageUrl = function () {
4531 var deferred
= $.Deferred(),
4532 file
= this.currentFile
,
4533 reader
= new FileReader();
4537 ( OO
.getProp( file
, 'type' ) || '' ).indexOf( 'image/' ) === 0 &&
4538 file
.size
< this.thumbnailSizeLimit
* 1024 * 1024
4540 reader
.onload = function ( event
) {
4541 var img
= document
.createElement( 'img' );
4542 img
.addEventListener( 'load', function () {
4544 img
.naturalWidth
=== 0 ||
4545 img
.naturalHeight
=== 0 ||
4546 img
.complete
=== false
4550 deferred
.resolve( event
.target
.result
);
4553 img
.src
= event
.target
.result
;
4555 reader
.readAsDataURL( file
);
4560 return deferred
.promise();
4564 * Add the input to the widget
4568 OO
.ui
.SelectFileWidget
.prototype.addInput = function () {
4569 if ( this.$input
) {
4570 this.$input
.remove();
4573 if ( !this.isSupported
) {
4578 this.$input
= $( '<input>' ).attr( 'type', 'file' );
4579 this.$input
.on( 'change', this.onFileSelectedHandler
);
4580 this.$input
.on( 'click', function ( e
) {
4581 // Prevents dropTarget to get clicked which calls
4582 // a click on this input
4583 e
.stopPropagation();
4588 if ( this.accept
) {
4589 this.$input
.attr( 'accept', this.accept
.join( ', ' ) );
4591 this.selectButton
.$button
.append( this.$input
);
4595 * Determine if we should accept this file
4598 * @param {string} mimeType File MIME type
4601 OO
.ui
.SelectFileWidget
.prototype.isAllowedType = function ( mimeType
) {
4604 if ( !this.accept
|| !mimeType
) {
4608 for ( i
= 0; i
< this.accept
.length
; i
++ ) {
4609 mimeTest
= this.accept
[ i
];
4610 if ( mimeTest
=== mimeType
) {
4612 } else if ( mimeTest
.substr( -2 ) === '/*' ) {
4613 mimeTest
= mimeTest
.substr( 0, mimeTest
.length
- 1 );
4614 if ( mimeType
.substr( 0, mimeTest
.length
) === mimeTest
) {
4624 * Handle file selection from the input
4627 * @param {jQuery.Event} e
4629 OO
.ui
.SelectFileWidget
.prototype.onFileSelected = function ( e
) {
4630 var file
= OO
.getProp( e
.target
, 'files', 0 ) || null;
4632 if ( file
&& !this.isAllowedType( file
.type
) ) {
4636 this.setValue( file
);
4641 * Handle clear button click events.
4645 OO
.ui
.SelectFileWidget
.prototype.onClearClick = function () {
4646 this.setValue( null );
4651 * Handle key press events.
4654 * @param {jQuery.Event} e Key press event
4656 OO
.ui
.SelectFileWidget
.prototype.onKeyPress = function ( e
) {
4657 if ( this.isSupported
&& !this.isDisabled() && this.$input
&&
4658 ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
4660 this.$input
.click();
4666 * Handle drop target click events.
4669 * @param {jQuery.Event} e Key press event
4671 OO
.ui
.SelectFileWidget
.prototype.onDropTargetClick = function () {
4672 if ( this.isSupported
&& !this.isDisabled() && this.$input
) {
4673 this.$input
.click();
4679 * Handle drag enter and over events
4682 * @param {jQuery.Event} e Drag event
4684 OO
.ui
.SelectFileWidget
.prototype.onDragEnterOrOver = function ( e
) {
4686 droppableFile
= false,
4687 dt
= e
.originalEvent
.dataTransfer
;
4690 e
.stopPropagation();
4692 if ( this.isDisabled() || !this.isSupported
) {
4693 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
4694 dt
.dropEffect
= 'none';
4698 // DataTransferItem and File both have a type property, but in Chrome files
4699 // have no information at this point.
4700 itemOrFile
= OO
.getProp( dt
, 'items', 0 ) || OO
.getProp( dt
, 'files', 0 );
4702 if ( this.isAllowedType( itemOrFile
.type
) ) {
4703 droppableFile
= true;
4705 // dt.types is Array-like, but not an Array
4706 } else if ( Array
.prototype.indexOf
.call( OO
.getProp( dt
, 'types' ) || [], 'Files' ) !== -1 ) {
4707 // File information is not available at this point for security so just assume
4708 // it is acceptable for now.
4709 // https://bugzilla.mozilla.org/show_bug.cgi?id=640534
4710 droppableFile
= true;
4713 this.$element
.toggleClass( 'oo-ui-selectFileWidget-canDrop', droppableFile
);
4714 if ( !droppableFile
) {
4715 dt
.dropEffect
= 'none';
4722 * Handle drag leave events
4725 * @param {jQuery.Event} e Drag event
4727 OO
.ui
.SelectFileWidget
.prototype.onDragLeave = function () {
4728 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
4732 * Handle drop events
4735 * @param {jQuery.Event} e Drop event
4737 OO
.ui
.SelectFileWidget
.prototype.onDrop = function ( e
) {
4739 dt
= e
.originalEvent
.dataTransfer
;
4742 e
.stopPropagation();
4743 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
4745 if ( this.isDisabled() || !this.isSupported
) {
4749 file
= OO
.getProp( dt
, 'files', 0 );
4750 if ( file
&& !this.isAllowedType( file
.type
) ) {
4754 this.setValue( file
);
4763 OO
.ui
.SelectFileWidget
.prototype.setDisabled = function ( disabled
) {
4764 OO
.ui
.SelectFileWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
4765 if ( this.selectButton
) {
4766 this.selectButton
.setDisabled( disabled
);
4768 if ( this.clearButton
) {
4769 this.clearButton
.setDisabled( disabled
);
4775 * Progress bars visually display the status of an operation, such as a download,
4776 * and can be either determinate or indeterminate:
4778 * - **determinate** process bars show the percent of an operation that is complete.
4780 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
4781 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
4782 * not use percentages.
4784 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
4787 * // Examples of determinate and indeterminate progress bars.
4788 * var progressBar1 = new OO.ui.ProgressBarWidget( {
4791 * var progressBar2 = new OO.ui.ProgressBarWidget();
4793 * // Create a FieldsetLayout to layout progress bars
4794 * var fieldset = new OO.ui.FieldsetLayout;
4795 * fieldset.addItems( [
4796 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
4797 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
4799 * $( 'body' ).append( fieldset.$element );
4802 * @extends OO.ui.Widget
4805 * @param {Object} [config] Configuration options
4806 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
4807 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
4808 * By default, the progress bar is indeterminate.
4810 OO
.ui
.ProgressBarWidget
= function OoUiProgressBarWidget( config
) {
4811 // Configuration initialization
4812 config
= config
|| {};
4814 // Parent constructor
4815 OO
.ui
.ProgressBarWidget
.parent
.call( this, config
);
4818 this.$bar
= $( '<div>' );
4819 this.progress
= null;
4822 this.setProgress( config
.progress
!== undefined ? config
.progress
: false );
4823 this.$bar
.addClass( 'oo-ui-progressBarWidget-bar' );
4826 role
: 'progressbar',
4828 'aria-valuemax': 100
4830 .addClass( 'oo-ui-progressBarWidget' )
4831 .append( this.$bar
);
4836 OO
.inheritClass( OO
.ui
.ProgressBarWidget
, OO
.ui
.Widget
);
4838 /* Static Properties */
4840 OO
.ui
.ProgressBarWidget
.static.tagName
= 'div';
4845 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
4847 * @return {number|boolean} Progress percent
4849 OO
.ui
.ProgressBarWidget
.prototype.getProgress = function () {
4850 return this.progress
;
4854 * Set the percent of the process completed or `false` for an indeterminate process.
4856 * @param {number|boolean} progress Progress percent or `false` for indeterminate
4858 OO
.ui
.ProgressBarWidget
.prototype.setProgress = function ( progress
) {
4859 this.progress
= progress
;
4861 if ( progress
!== false ) {
4862 this.$bar
.css( 'width', this.progress
+ '%' );
4863 this.$element
.attr( 'aria-valuenow', this.progress
);
4865 this.$bar
.css( 'width', '' );
4866 this.$element
.removeAttr( 'aria-valuenow' );
4868 this.$element
.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress
);
4872 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
4873 * and a menu of search results, which is displayed beneath the query
4874 * field. Unlike {@link OO.ui.mixin.LookupElement lookup menus}, search result menus are always visible to the user.
4875 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
4876 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
4878 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
4879 * the [OOjs UI demos][1] for an example.
4881 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
4884 * @extends OO.ui.Widget
4887 * @param {Object} [config] Configuration options
4888 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
4889 * @cfg {string} [value] Initial query value
4891 OO
.ui
.SearchWidget
= function OoUiSearchWidget( config
) {
4892 // Configuration initialization
4893 config
= config
|| {};
4895 // Parent constructor
4896 OO
.ui
.SearchWidget
.parent
.call( this, config
);
4899 this.query
= new OO
.ui
.TextInputWidget( {
4901 placeholder
: config
.placeholder
,
4904 this.results
= new OO
.ui
.SelectWidget();
4905 this.$query
= $( '<div>' );
4906 this.$results
= $( '<div>' );
4909 this.query
.connect( this, {
4910 change
: 'onQueryChange',
4911 enter
: 'onQueryEnter'
4913 this.query
.$input
.on( 'keydown', this.onQueryKeydown
.bind( this ) );
4917 .addClass( 'oo-ui-searchWidget-query' )
4918 .append( this.query
.$element
);
4920 .addClass( 'oo-ui-searchWidget-results' )
4921 .append( this.results
.$element
);
4923 .addClass( 'oo-ui-searchWidget' )
4924 .append( this.$results
, this.$query
);
4929 OO
.inheritClass( OO
.ui
.SearchWidget
, OO
.ui
.Widget
);
4934 * Handle query key down events.
4937 * @param {jQuery.Event} e Key down event
4939 OO
.ui
.SearchWidget
.prototype.onQueryKeydown = function ( e
) {
4940 var highlightedItem
, nextItem
,
4941 dir
= e
.which
=== OO
.ui
.Keys
.DOWN
? 1 : ( e
.which
=== OO
.ui
.Keys
.UP
? -1 : 0 );
4944 highlightedItem
= this.results
.getHighlightedItem();
4945 if ( !highlightedItem
) {
4946 highlightedItem
= this.results
.getSelectedItem();
4948 nextItem
= this.results
.getRelativeSelectableItem( highlightedItem
, dir
);
4949 this.results
.highlightItem( nextItem
);
4950 nextItem
.scrollElementIntoView();
4955 * Handle select widget select events.
4957 * Clears existing results. Subclasses should repopulate items according to new query.
4960 * @param {string} value New value
4962 OO
.ui
.SearchWidget
.prototype.onQueryChange = function () {
4964 this.results
.clearItems();
4968 * Handle select widget enter key events.
4970 * Chooses highlighted item.
4973 * @param {string} value New value
4975 OO
.ui
.SearchWidget
.prototype.onQueryEnter = function () {
4976 var highlightedItem
= this.results
.getHighlightedItem();
4977 if ( highlightedItem
) {
4978 this.results
.chooseItem( highlightedItem
);
4983 * Get the query input.
4985 * @return {OO.ui.TextInputWidget} Query input
4987 OO
.ui
.SearchWidget
.prototype.getQuery = function () {
4992 * Get the search results menu.
4994 * @return {OO.ui.SelectWidget} Menu of search results
4996 OO
.ui
.SearchWidget
.prototype.getResults = function () {
4997 return this.results
;
5001 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
5002 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
5003 * (to adjust the value in increments) to allow the user to enter a number.
5006 * // Example: A NumberInputWidget.
5007 * var numberInput = new OO.ui.NumberInputWidget( {
5008 * label: 'NumberInputWidget',
5009 * input: { value: 5 },
5013 * $( 'body' ).append( numberInput.$element );
5016 * @extends OO.ui.Widget
5019 * @param {Object} [config] Configuration options
5020 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
5021 * @cfg {Object} [minusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget decrementing button widget}.
5022 * @cfg {Object} [plusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget incrementing button widget}.
5023 * @cfg {boolean} [isInteger=false] Whether the field accepts only integer values.
5024 * @cfg {number} [min=-Infinity] Minimum allowed value
5025 * @cfg {number} [max=Infinity] Maximum allowed value
5026 * @cfg {number} [step=1] Delta when using the buttons or up/down arrow keys
5027 * @cfg {number|null} [pageStep] Delta when using the page-up/page-down keys. Defaults to 10 times #step.
5028 * @cfg {boolean} [showButtons=true] Whether to show the plus and minus buttons.
5030 OO
.ui
.NumberInputWidget
= function OoUiNumberInputWidget( config
) {
5031 // Configuration initialization
5032 config
= $.extend( {
5041 // Parent constructor
5042 OO
.ui
.NumberInputWidget
.parent
.call( this, config
);
5045 this.input
= new OO
.ui
.TextInputWidget( $.extend(
5047 disabled
: this.isDisabled(),
5052 if ( config
.showButtons
) {
5053 this.minusButton
= new OO
.ui
.ButtonWidget( $.extend(
5055 disabled
: this.isDisabled(),
5060 classes
: [ 'oo-ui-numberInputWidget-minusButton' ],
5064 this.plusButton
= new OO
.ui
.ButtonWidget( $.extend(
5066 disabled
: this.isDisabled(),
5071 classes
: [ 'oo-ui-numberInputWidget-plusButton' ],
5078 this.input
.connect( this, {
5079 change
: this.emit
.bind( this, 'change' ),
5080 enter
: this.emit
.bind( this, 'enter' )
5082 this.input
.$input
.on( {
5083 keydown
: this.onKeyDown
.bind( this ),
5084 'wheel mousewheel DOMMouseScroll': this.onWheel
.bind( this )
5086 if ( config
.showButtons
) {
5087 this.plusButton
.connect( this, {
5088 click
: [ 'onButtonClick', +1 ]
5090 this.minusButton
.connect( this, {
5091 click
: [ 'onButtonClick', -1 ]
5096 this.setIsInteger( !!config
.isInteger
);
5097 this.setRange( config
.min
, config
.max
);
5098 this.setStep( config
.step
, config
.pageStep
);
5100 this.$field
= $( '<div>' ).addClass( 'oo-ui-numberInputWidget-field' )
5101 .append( this.input
.$element
);
5102 this.$element
.addClass( 'oo-ui-numberInputWidget' ).append( this.$field
);
5103 if ( config
.showButtons
) {
5105 .prepend( this.minusButton
.$element
)
5106 .append( this.plusButton
.$element
);
5107 this.$element
.addClass( 'oo-ui-numberInputWidget-buttoned' );
5109 this.input
.setValidation( this.validateNumber
.bind( this ) );
5114 OO
.inheritClass( OO
.ui
.NumberInputWidget
, OO
.ui
.Widget
);
5119 * A `change` event is emitted when the value of the input changes.
5125 * An `enter` event is emitted when the user presses 'enter' inside the text box.
5133 * Set whether only integers are allowed
5135 * @param {boolean} flag
5137 OO
.ui
.NumberInputWidget
.prototype.setIsInteger = function ( flag
) {
5138 this.isInteger
= !!flag
;
5139 this.input
.setValidityFlag();
5143 * Get whether only integers are allowed
5145 * @return {boolean} Flag value
5147 OO
.ui
.NumberInputWidget
.prototype.getIsInteger = function () {
5148 return this.isInteger
;
5152 * Set the range of allowed values
5154 * @param {number} min Minimum allowed value
5155 * @param {number} max Maximum allowed value
5157 OO
.ui
.NumberInputWidget
.prototype.setRange = function ( min
, max
) {
5159 throw new Error( 'Minimum (' + min
+ ') must not be greater than maximum (' + max
+ ')' );
5163 this.input
.setValidityFlag();
5167 * Get the current range
5169 * @return {number[]} Minimum and maximum values
5171 OO
.ui
.NumberInputWidget
.prototype.getRange = function () {
5172 return [ this.min
, this.max
];
5176 * Set the stepping deltas
5178 * @param {number} step Normal step
5179 * @param {number|null} pageStep Page step. If null, 10 * step will be used.
5181 OO
.ui
.NumberInputWidget
.prototype.setStep = function ( step
, pageStep
) {
5183 throw new Error( 'Step value must be positive' );
5185 if ( pageStep
=== null ) {
5186 pageStep
= step
* 10;
5187 } else if ( pageStep
<= 0 ) {
5188 throw new Error( 'Page step value must be positive' );
5191 this.pageStep
= pageStep
;
5195 * Get the current stepping values
5197 * @return {number[]} Step and page step
5199 OO
.ui
.NumberInputWidget
.prototype.getStep = function () {
5200 return [ this.step
, this.pageStep
];
5204 * Get the current value of the widget
5208 OO
.ui
.NumberInputWidget
.prototype.getValue = function () {
5209 return this.input
.getValue();
5213 * Get the current value of the widget as a number
5215 * @return {number} May be NaN, or an invalid number
5217 OO
.ui
.NumberInputWidget
.prototype.getNumericValue = function () {
5218 return +this.input
.getValue();
5222 * Set the value of the widget
5224 * @param {string} value Invalid values are allowed
5226 OO
.ui
.NumberInputWidget
.prototype.setValue = function ( value
) {
5227 this.input
.setValue( value
);
5231 * Adjust the value of the widget
5233 * @param {number} delta Adjustment amount
5235 OO
.ui
.NumberInputWidget
.prototype.adjustValue = function ( delta
) {
5236 var n
, v
= this.getNumericValue();
5239 if ( isNaN( delta
) || !isFinite( delta
) ) {
5240 throw new Error( 'Delta must be a finite number' );
5247 n
= Math
.max( Math
.min( n
, this.max
), this.min
);
5248 if ( this.isInteger
) {
5249 n
= Math
.round( n
);
5262 * @param {string} value Field value
5265 OO
.ui
.NumberInputWidget
.prototype.validateNumber = function ( value
) {
5267 if ( isNaN( n
) || !isFinite( n
) ) {
5271 /*jshint bitwise: false */
5272 if ( this.isInteger
&& ( n
| 0 ) !== n
) {
5275 /*jshint bitwise: true */
5277 if ( n
< this.min
|| n
> this.max
) {
5285 * Handle mouse click events.
5288 * @param {number} dir +1 or -1
5290 OO
.ui
.NumberInputWidget
.prototype.onButtonClick = function ( dir
) {
5291 this.adjustValue( dir
* this.step
);
5295 * Handle mouse wheel events.
5298 * @param {jQuery.Event} event
5300 OO
.ui
.NumberInputWidget
.prototype.onWheel = function ( event
) {
5303 if ( !this.isDisabled() && this.input
.$input
.is( ':focus' ) ) {
5304 // Standard 'wheel' event
5305 if ( event
.originalEvent
.deltaMode
!== undefined ) {
5306 this.sawWheelEvent
= true;
5308 if ( event
.originalEvent
.deltaY
) {
5309 delta
= -event
.originalEvent
.deltaY
;
5310 } else if ( event
.originalEvent
.deltaX
) {
5311 delta
= event
.originalEvent
.deltaX
;
5314 // Non-standard events
5315 if ( !this.sawWheelEvent
) {
5316 if ( event
.originalEvent
.wheelDeltaX
) {
5317 delta
= -event
.originalEvent
.wheelDeltaX
;
5318 } else if ( event
.originalEvent
.wheelDeltaY
) {
5319 delta
= event
.originalEvent
.wheelDeltaY
;
5320 } else if ( event
.originalEvent
.wheelDelta
) {
5321 delta
= event
.originalEvent
.wheelDelta
;
5322 } else if ( event
.originalEvent
.detail
) {
5323 delta
= -event
.originalEvent
.detail
;
5328 delta
= delta
< 0 ? -1 : 1;
5329 this.adjustValue( delta
* this.step
);
5337 * Handle key down events.
5340 * @param {jQuery.Event} e Key down event
5342 OO
.ui
.NumberInputWidget
.prototype.onKeyDown = function ( e
) {
5343 if ( !this.isDisabled() ) {
5344 switch ( e
.which
) {
5346 this.adjustValue( this.step
);
5348 case OO
.ui
.Keys
.DOWN
:
5349 this.adjustValue( -this.step
);
5351 case OO
.ui
.Keys
.PAGEUP
:
5352 this.adjustValue( this.pageStep
);
5354 case OO
.ui
.Keys
.PAGEDOWN
:
5355 this.adjustValue( -this.pageStep
);
5364 OO
.ui
.NumberInputWidget
.prototype.setDisabled = function ( disabled
) {
5366 OO
.ui
.NumberInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
5369 this.input
.setDisabled( this.isDisabled() );
5371 if ( this.minusButton
) {
5372 this.minusButton
.setDisabled( this.isDisabled() );
5374 if ( this.plusButton
) {
5375 this.plusButton
.setDisabled( this.isDisabled() );