3 * https://www.mediawiki.org/wiki/OOjs_UI
5 * Copyright 2011–2017 OOjs UI Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
9 * Date: 2017-04-26T01:05:10Z
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
27 * @cfg {boolean} [draggable] The items are draggable. This can change with #toggleDraggable
28 * but the draggable state should be called from the DraggableGroupElement, which updates
31 OO
.ui
.mixin
.DraggableElement
= function OoUiMixinDraggableElement( config
) {
32 config
= config
|| {};
36 this.$handle
= config
.$handle
|| this.$element
;
37 this.wasHandleUsed
= null;
38 this.draggable
= config
.draggable
=== undefined ? true : !!config
.draggable
;
40 // Initialize and events
41 this.$element
.addClass( 'oo-ui-draggableElement' )
42 // We make the entire element draggable, not just the handle, so that
43 // the whole element appears to move. wasHandleUsed prevents drags from
44 // starting outside the handle
45 .attr( 'draggable', true )
47 mousedown
: this.onDragMouseDown
.bind( this ),
48 dragstart
: this.onDragStart
.bind( this ),
49 dragover
: this.onDragOver
.bind( this ),
50 dragend
: this.onDragEnd
.bind( this ),
51 drop
: this.onDrop
.bind( this )
53 this.$handle
.addClass( 'oo-ui-draggableElement-handle' );
56 OO
.initClass( OO
.ui
.mixin
.DraggableElement
);
63 * A dragstart event is emitted when the user clicks and begins dragging an item.
64 * @param {OO.ui.mixin.DraggableElement} item The item the user has clicked and is dragging with the mouse.
69 * A dragend event is emitted when the user drags an item and releases the mouse,
70 * thus terminating the drag operation.
75 * A drop event is emitted when the user drags an item and then releases the mouse button
76 * over a valid target.
79 /* Static Properties */
82 * @inheritdoc OO.ui.mixin.ButtonElement
84 OO
.ui
.mixin
.DraggableElement
.static.cancelButtonMouseDownEvents
= false;
89 * Change the draggable state of this widget.
90 * This allows users to temporarily halt the dragging operations.
92 * @param {boolean} isDraggable Widget supports draggable operations
95 OO
.ui
.mixin
.DraggableElement
.prototype.toggleDraggable = function ( isDraggable
) {
96 isDraggable
= isDraggable
!== undefined ? !!isDraggable
: !this.draggable
;
98 if ( this.draggable
!== isDraggable
) {
99 this.draggable
= isDraggable
;
101 this.$handle
.toggleClass( 'oo-ui-draggableElement-undraggable', !this.draggable
);
106 * Check the draggable state of this widget
108 * @return {boolean} Widget supports draggable operations
110 OO
.ui
.mixin
.DraggableElement
.prototype.isDraggable = function () {
111 return this.draggable
;
115 * Respond to mousedown event.
118 * @param {jQuery.Event} e Drag event
120 OO
.ui
.mixin
.DraggableElement
.prototype.onDragMouseDown = function ( e
) {
121 if ( !this.isDraggable() ) {
126 // Optimization: if the handle is the whole element this is always true
127 this.$handle
[ 0 ] === this.$element
[ 0 ] ||
128 // Check the mousedown occurred inside the handle
129 OO
.ui
.contains( this.$handle
[ 0 ], e
.target
, true );
133 * Respond to dragstart event.
136 * @param {jQuery.Event} e Drag event
137 * @return {boolean} False if the event is cancelled
140 OO
.ui
.mixin
.DraggableElement
.prototype.onDragStart = function ( e
) {
142 dataTransfer
= e
.originalEvent
.dataTransfer
;
144 if ( !this.wasHandleUsed
|| !this.isDraggable() ) {
148 // Define drop effect
149 dataTransfer
.dropEffect
= 'none';
150 dataTransfer
.effectAllowed
= 'move';
152 // We must set up a dataTransfer data property or Firefox seems to
153 // ignore the fact the element is draggable.
155 dataTransfer
.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
157 // The above is only for Firefox. Move on if it fails.
159 // Briefly add a 'clone' class to style the browser's native drag image
160 this.$element
.addClass( 'oo-ui-draggableElement-clone' );
161 // Add placeholder class after the browser has rendered the clone
162 setTimeout( function () {
164 .removeClass( 'oo-ui-draggableElement-clone' )
165 .addClass( 'oo-ui-draggableElement-placeholder' );
168 this.emit( 'dragstart', this );
173 * Respond to dragend event.
178 OO
.ui
.mixin
.DraggableElement
.prototype.onDragEnd = function () {
179 this.$element
.removeClass( 'oo-ui-draggableElement-placeholder' );
180 this.emit( 'dragend' );
187 * @param {jQuery.Event} e Drop event
190 OO
.ui
.mixin
.DraggableElement
.prototype.onDrop = function ( e
) {
192 this.emit( 'drop', e
);
196 * In order for drag/drop to work, the dragover event must
197 * return false and stop propogation.
199 * @param {jQuery.Event} e Drag event
202 OO
.ui
.mixin
.DraggableElement
.prototype.onDragOver = function ( e
) {
208 * Store it in the DOM so we can access from the widget drag event
211 * @param {number} index Item index
213 OO
.ui
.mixin
.DraggableElement
.prototype.setIndex = function ( index
) {
214 if ( this.index
!== index
) {
216 this.$element
.data( 'index', index
);
224 * @return {number} Item index
226 OO
.ui
.mixin
.DraggableElement
.prototype.getIndex = function () {
231 * DraggableGroupElement is a mixin class used to create a group element to
232 * contain draggable elements, which are items that can be clicked and dragged by a mouse.
233 * The class is used with OO.ui.mixin.DraggableElement.
237 * @mixins OO.ui.mixin.GroupElement
240 * @param {Object} [config] Configuration options
241 * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation
242 * should match the layout of the items. Items displayed in a single row
243 * or in several rows should use horizontal orientation. The vertical orientation should only be
244 * used when the items are displayed in a single column. Defaults to 'vertical'
245 * @cfg {boolean} [draggable] The items are draggable. This can change with #toggleDraggable
247 OO
.ui
.mixin
.DraggableGroupElement
= function OoUiMixinDraggableGroupElement( config
) {
248 // Configuration initialization
249 config
= config
|| {};
251 // Parent constructor
252 OO
.ui
.mixin
.GroupElement
.call( this, config
);
255 this.orientation
= config
.orientation
|| 'vertical';
256 this.dragItem
= null;
259 this.itemsOrder
= null;
260 this.draggable
= config
.draggable
=== undefined ? true : !!config
.draggable
;
264 dragstart
: 'itemDragStart',
265 dragend
: 'itemDragEnd',
268 this.connect( this, {
269 itemDragStart
: 'onItemDragStart',
270 itemDrop
: 'onItemDropOrDragEnd',
271 itemDragEnd
: 'onItemDropOrDragEnd'
275 if ( Array
.isArray( config
.items
) ) {
276 this.addItems( config
.items
);
279 .addClass( 'oo-ui-draggableGroupElement' )
280 .attr( 'role', 'listbox' )
281 .append( this.$status
)
282 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation
=== 'horizontal' );
286 OO
.mixinClass( OO
.ui
.mixin
.DraggableGroupElement
, OO
.ui
.mixin
.GroupElement
);
291 * An item has been dragged to a new position, but not yet dropped.
294 * @param {OO.ui.mixin.DraggableElement} item Dragged item
295 * @param {number} [newIndex] New index for the item
299 * An item has been dropped at a new position.
302 * @param {OO.ui.mixin.DraggableElement} item Reordered item
303 * @param {number} [newIndex] New index for the item
307 * Draggable state of this widget has changed.
310 * @param {boolean} [draggable] Widget is draggable
316 * Change the draggable state of this widget.
317 * This allows users to temporarily halt the dragging operations.
319 * @param {boolean} isDraggable Widget supports draggable operations
322 OO
.ui
.mixin
.DraggableGroupElement
.prototype.toggleDraggable = function ( isDraggable
) {
323 isDraggable
= isDraggable
!== undefined ? !!isDraggable
: !this.draggable
;
325 if ( this.draggable
!== isDraggable
) {
326 this.draggable
= isDraggable
;
328 // Tell the items their draggable state changed
329 this.getItems().forEach( function ( item
) {
330 item
.toggleDraggable( this.draggable
);
334 this.emit( 'draggable', this.draggable
);
339 * Check the draggable state of this widget
341 * @return {boolean} Widget supports draggable operations
343 OO
.ui
.mixin
.DraggableGroupElement
.prototype.isDraggable = function () {
344 return this.draggable
;
348 * Respond to item drag start event
351 * @param {OO.ui.mixin.DraggableElement} item Dragged item
353 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onItemDragStart = function ( item
) {
354 if ( !this.isDraggable() ) {
357 // Make a shallow copy of this.items so we can re-order it during previews
358 // without affecting the original array.
359 this.itemsOrder
= this.items
.slice();
360 this.updateIndexes();
361 if ( this.orientation
=== 'horizontal' ) {
362 // Calculate and cache directionality on drag start - it's a little
363 // expensive and it shouldn't change while dragging.
364 this.dir
= this.$element
.css( 'direction' );
366 this.setDragItem( item
);
370 * Update the index properties of the items
372 OO
.ui
.mixin
.DraggableGroupElement
.prototype.updateIndexes = function () {
375 // Map the index of each object
376 for ( i
= 0, len
= this.itemsOrder
.length
; i
< len
; i
++ ) {
377 this.itemsOrder
[ i
].setIndex( i
);
382 * Handle drop or dragend event and switch the order of the items accordingly
385 * @param {OO.ui.mixin.DraggableElement} item Dropped item
387 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onItemDropOrDragEnd = function () {
388 var targetIndex
, originalIndex
,
389 item
= this.getDragItem();
391 // TODO: Figure out a way to configure a list of legally droppable
392 // elements even if they are not yet in the list
394 originalIndex
= this.items
.indexOf( item
);
395 // If the item has moved forward, add one to the index to account for the left shift
396 targetIndex
= item
.getIndex() + ( item
.getIndex() > originalIndex
? 1 : 0 );
397 if ( targetIndex
!== originalIndex
) {
398 this.reorder( this.getDragItem(), targetIndex
);
399 this.emit( 'reorder', this.getDragItem(), targetIndex
);
401 this.updateIndexes();
403 this.unsetDragItem();
404 // Return false to prevent propogation
409 * Respond to dragover event
412 * @param {jQuery.Event} e Dragover event
415 OO
.ui
.mixin
.DraggableGroupElement
.prototype.onDragOver = function ( e
) {
416 var overIndex
, targetIndex
,
417 item
= this.getDragItem(),
418 dragItemIndex
= item
.getIndex();
420 // Get the OptionWidget item we are dragging over
421 overIndex
= $( e
.target
).closest( '.oo-ui-draggableElement' ).data( 'index' );
423 if ( overIndex
!== undefined && overIndex
!== dragItemIndex
) {
424 targetIndex
= overIndex
+ ( overIndex
> dragItemIndex
? 1 : 0 );
426 if ( targetIndex
> 0 ) {
427 this.$group
.children().eq( targetIndex
- 1 ).after( item
.$element
);
429 this.$group
.prepend( item
.$element
);
431 // Move item in itemsOrder array
432 this.itemsOrder
.splice( overIndex
, 0,
433 this.itemsOrder
.splice( dragItemIndex
, 1 )[ 0 ]
435 this.updateIndexes();
436 this.emit( 'drag', item
, targetIndex
);
443 * Reorder the items in the group
445 * @param {OO.ui.mixin.DraggableElement} item Reordered item
446 * @param {number} newIndex New index
448 OO
.ui
.mixin
.DraggableGroupElement
.prototype.reorder = function ( item
, newIndex
) {
449 this.addItems( [ item
], newIndex
);
455 * @param {OO.ui.mixin.DraggableElement} item Dragged item
457 OO
.ui
.mixin
.DraggableGroupElement
.prototype.setDragItem = function ( item
) {
458 if ( this.dragItem
!== item
) {
459 this.dragItem
= item
;
460 this.$element
.on( 'dragover', this.onDragOver
.bind( this ) );
461 this.$element
.addClass( 'oo-ui-draggableGroupElement-dragging' );
466 * Unset the current dragged item
468 OO
.ui
.mixin
.DraggableGroupElement
.prototype.unsetDragItem = function () {
469 if ( this.dragItem
) {
470 this.dragItem
= null;
471 this.$element
.off( 'dragover' );
472 this.$element
.removeClass( 'oo-ui-draggableGroupElement-dragging' );
477 * Get the item that is currently being dragged.
479 * @return {OO.ui.mixin.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged
481 OO
.ui
.mixin
.DraggableGroupElement
.prototype.getDragItem = function () {
482 return this.dragItem
;
486 * RequestManager is a mixin that manages the lifecycle of a promise-backed request for a widget, such as
487 * the {@link OO.ui.mixin.LookupElement}.
494 OO
.ui
.mixin
.RequestManager
= function OoUiMixinRequestManager() {
495 this.requestCache
= {};
496 this.requestQuery
= null;
497 this.requestRequest
= null;
502 OO
.initClass( OO
.ui
.mixin
.RequestManager
);
505 * Get request results for the current query.
507 * @return {jQuery.Promise} Promise object which will be passed response data as the first argument of
508 * the done event. If the request was aborted to make way for a subsequent request, this promise
509 * may not be rejected, depending on what jQuery feels like doing.
511 OO
.ui
.mixin
.RequestManager
.prototype.getRequestData = function () {
513 value
= this.getRequestQuery(),
514 deferred
= $.Deferred(),
518 if ( Object
.prototype.hasOwnProperty
.call( this.requestCache
, value
) ) {
519 deferred
.resolve( this.requestCache
[ value
] );
521 if ( this.pushPending
) {
524 this.requestQuery
= value
;
525 ourRequest
= this.requestRequest
= this.getRequest();
527 .always( function () {
528 // We need to pop pending even if this is an old request, otherwise
529 // the widget will remain pending forever.
530 // TODO: this assumes that an aborted request will fail or succeed soon after
531 // being aborted, or at least eventually. It would be nice if we could popPending()
532 // at abort time, but only if we knew that we hadn't already called popPending()
534 if ( widget
.popPending
) {
538 .done( function ( response
) {
539 // If this is an old request (and aborting it somehow caused it to still succeed),
540 // ignore its success completely
541 if ( ourRequest
=== widget
.requestRequest
) {
542 widget
.requestQuery
= null;
543 widget
.requestRequest
= null;
544 widget
.requestCache
[ value
] = widget
.getRequestCacheDataFromResponse( response
);
545 deferred
.resolve( widget
.requestCache
[ value
] );
549 // If this is an old request (or a request failing because it's being aborted),
550 // ignore its failure completely
551 if ( ourRequest
=== widget
.requestRequest
) {
552 widget
.requestQuery
= null;
553 widget
.requestRequest
= null;
558 return deferred
.promise();
562 * Abort the currently pending request, if any.
566 OO
.ui
.mixin
.RequestManager
.prototype.abortRequest = function () {
567 var oldRequest
= this.requestRequest
;
569 // First unset this.requestRequest to the fail handler will notice
570 // that the request is no longer current
571 this.requestRequest
= null;
572 this.requestQuery
= null;
578 * Get the query to be made.
583 * @return {string} query to be used
585 OO
.ui
.mixin
.RequestManager
.prototype.getRequestQuery
= null;
588 * Get a new request object of the current query value.
593 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
595 OO
.ui
.mixin
.RequestManager
.prototype.getRequest
= null;
598 * Pre-process data returned by the request from #getRequest.
600 * The return value of this function will be cached, and any further queries for the given value
601 * will use the cache rather than doing API requests.
606 * @param {Mixed} response Response from server
607 * @return {Mixed} Cached result data
609 OO
.ui
.mixin
.RequestManager
.prototype.getRequestCacheDataFromResponse
= null;
612 * LookupElement is a mixin that creates a {@link OO.ui.FloatingMenuSelectWidget menu} of suggested values for
613 * a {@link OO.ui.TextInputWidget text input widget}. Suggested values are based on the characters the user types
614 * into the text input field and, in general, the menu is only displayed when the user types. If a suggested value is chosen
615 * from the lookup menu, that value becomes the value of the input field.
617 * Note that a new menu of suggested items is displayed when a value is chosen from the lookup menu. If this is
618 * not the desired behavior, disable lookup menus with the #setLookupsDisabled method, then set the value, then
621 * See the [OOjs UI demos][1] for an example.
623 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/index.html#widgets-apex-vector-ltr
627 * @mixins OO.ui.mixin.RequestManager
630 * @param {Object} [config] Configuration options
631 * @cfg {jQuery} [$overlay] Overlay for the lookup menu; defaults to relative positioning.
632 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
633 * @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element.
634 * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty.
635 * By default, the lookup menu is not generated and displayed until the user begins to type.
636 * @cfg {boolean} [highlightFirst=true] Whether the first lookup result should be highlighted (so, that the user can
637 * take it over into the input with simply pressing return) automatically or not.
639 OO
.ui
.mixin
.LookupElement
= function OoUiMixinLookupElement( config
) {
640 // Configuration initialization
641 config
= $.extend( { highlightFirst
: true }, config
);
643 // Mixin constructors
644 OO
.ui
.mixin
.RequestManager
.call( this, config
);
647 this.$overlay
= config
.$overlay
|| this.$element
;
648 this.lookupMenu
= new OO
.ui
.FloatingMenuSelectWidget( {
651 $container
: config
.$container
|| this.$element
654 this.allowSuggestionsWhenEmpty
= config
.allowSuggestionsWhenEmpty
|| false;
656 this.lookupsDisabled
= false;
657 this.lookupInputFocused
= false;
658 this.lookupHighlightFirstItem
= config
.highlightFirst
;
662 focus
: this.onLookupInputFocus
.bind( this ),
663 blur
: this.onLookupInputBlur
.bind( this ),
664 mousedown
: this.onLookupInputMouseDown
.bind( this )
666 this.connect( this, { change
: 'onLookupInputChange' } );
667 this.lookupMenu
.connect( this, {
668 toggle
: 'onLookupMenuToggle',
669 choose
: 'onLookupMenuItemChoose'
675 'aria-owns': this.lookupMenu
.getElementId(),
676 'aria-autocomplete': 'list'
678 this.$element
.addClass( 'oo-ui-lookupElement' );
679 this.lookupMenu
.$element
.addClass( 'oo-ui-lookupElement-menu' );
680 this.$overlay
.append( this.lookupMenu
.$element
);
685 OO
.mixinClass( OO
.ui
.mixin
.LookupElement
, OO
.ui
.mixin
.RequestManager
);
690 * Handle input focus event.
693 * @param {jQuery.Event} e Input focus event
695 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputFocus = function () {
696 this.lookupInputFocused
= true;
697 this.populateLookupMenu();
701 * Handle input blur event.
704 * @param {jQuery.Event} e Input blur event
706 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputBlur = function () {
707 this.closeLookupMenu();
708 this.lookupInputFocused
= false;
712 * Handle input mouse down event.
715 * @param {jQuery.Event} e Input mouse down event
717 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputMouseDown = function () {
718 // Only open the menu if the input was already focused.
719 // This way we allow the user to open the menu again after closing it with Esc
720 // by clicking in the input. Opening (and populating) the menu when initially
721 // clicking into the input is handled by the focus handler.
722 if ( this.lookupInputFocused
&& !this.lookupMenu
.isVisible() ) {
723 this.populateLookupMenu();
728 * Handle input change event.
731 * @param {string} value New input value
733 OO
.ui
.mixin
.LookupElement
.prototype.onLookupInputChange = function () {
734 if ( this.lookupInputFocused
) {
735 this.populateLookupMenu();
740 * Handle the lookup menu being shown/hidden.
743 * @param {boolean} visible Whether the lookup menu is now visible.
745 OO
.ui
.mixin
.LookupElement
.prototype.onLookupMenuToggle = function ( visible
) {
747 // When the menu is hidden, abort any active request and clear the menu.
748 // This has to be done here in addition to closeLookupMenu(), because
749 // MenuSelectWidget will close itself when the user presses Esc.
750 this.abortLookupRequest();
751 this.lookupMenu
.clearItems();
756 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
759 * @param {OO.ui.MenuOptionWidget} item Selected item
761 OO
.ui
.mixin
.LookupElement
.prototype.onLookupMenuItemChoose = function ( item
) {
762 this.setValue( item
.getData() );
769 * @return {OO.ui.FloatingMenuSelectWidget}
771 OO
.ui
.mixin
.LookupElement
.prototype.getLookupMenu = function () {
772 return this.lookupMenu
;
776 * Disable or re-enable lookups.
778 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
780 * @param {boolean} disabled Disable lookups
782 OO
.ui
.mixin
.LookupElement
.prototype.setLookupsDisabled = function ( disabled
) {
783 this.lookupsDisabled
= !!disabled
;
787 * Open the menu. If there are no entries in the menu, this does nothing.
792 OO
.ui
.mixin
.LookupElement
.prototype.openLookupMenu = function () {
793 if ( !this.lookupMenu
.isEmpty() ) {
794 this.lookupMenu
.toggle( true );
800 * Close the menu, empty it, and abort any pending request.
805 OO
.ui
.mixin
.LookupElement
.prototype.closeLookupMenu = function () {
806 this.lookupMenu
.toggle( false );
807 this.abortLookupRequest();
808 this.lookupMenu
.clearItems();
813 * Request menu items based on the input's current value, and when they arrive,
814 * populate the menu with these items and show the menu.
816 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
821 OO
.ui
.mixin
.LookupElement
.prototype.populateLookupMenu = function () {
823 value
= this.getValue();
825 if ( this.lookupsDisabled
|| this.isReadOnly() ) {
829 // If the input is empty, clear the menu, unless suggestions when empty are allowed.
830 if ( !this.allowSuggestionsWhenEmpty
&& value
=== '' ) {
831 this.closeLookupMenu();
832 // Skip population if there is already a request pending for the current value
833 } else if ( value
!== this.lookupQuery
) {
834 this.getLookupMenuItems()
835 .done( function ( items
) {
836 widget
.lookupMenu
.clearItems();
837 if ( items
.length
) {
841 widget
.initializeLookupMenuSelection();
843 widget
.lookupMenu
.toggle( false );
847 widget
.lookupMenu
.clearItems();
855 * Highlight the first selectable item in the menu, if configured.
860 OO
.ui
.mixin
.LookupElement
.prototype.initializeLookupMenuSelection = function () {
861 if ( this.lookupHighlightFirstItem
&& !this.lookupMenu
.getSelectedItem() ) {
862 this.lookupMenu
.highlightItem( this.lookupMenu
.getFirstSelectableItem() );
867 * Get lookup menu items for the current query.
870 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
871 * the done event. If the request was aborted to make way for a subsequent request, this promise
872 * will not be rejected: it will remain pending forever.
874 OO
.ui
.mixin
.LookupElement
.prototype.getLookupMenuItems = function () {
875 return this.getRequestData().then( function ( data
) {
876 return this.getLookupMenuOptionsFromData( data
);
881 * Abort the currently pending lookup request, if any.
885 OO
.ui
.mixin
.LookupElement
.prototype.abortLookupRequest = function () {
890 * Get a new request object of the current lookup query value.
895 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
897 OO
.ui
.mixin
.LookupElement
.prototype.getLookupRequest
= null;
900 * Pre-process data returned by the request from #getLookupRequest.
902 * The return value of this function will be cached, and any further queries for the given value
903 * will use the cache rather than doing API requests.
908 * @param {Mixed} response Response from server
909 * @return {Mixed} Cached result data
911 OO
.ui
.mixin
.LookupElement
.prototype.getLookupCacheDataFromResponse
= null;
914 * Get a list of menu option widgets from the (possibly cached) data returned by
915 * #getLookupCacheDataFromResponse.
920 * @param {Mixed} data Cached result data, usually an array
921 * @return {OO.ui.MenuOptionWidget[]} Menu items
923 OO
.ui
.mixin
.LookupElement
.prototype.getLookupMenuOptionsFromData
= null;
926 * Set the read-only state of the widget.
928 * This will also disable/enable the lookups functionality.
930 * @param {boolean} readOnly Make input read-only
933 OO
.ui
.mixin
.LookupElement
.prototype.setReadOnly = function ( readOnly
) {
935 // Note: Calling #setReadOnly this way assumes this is mixed into an OO.ui.TextInputWidget
936 OO
.ui
.TextInputWidget
.prototype.setReadOnly
.call( this, readOnly
);
938 // During construction, #setReadOnly is called before the OO.ui.mixin.LookupElement constructor
939 if ( this.isReadOnly() && this.lookupMenu
) {
940 this.closeLookupMenu();
947 * @inheritdoc OO.ui.mixin.RequestManager
949 OO
.ui
.mixin
.LookupElement
.prototype.getRequestQuery = function () {
950 return this.getValue();
954 * @inheritdoc OO.ui.mixin.RequestManager
956 OO
.ui
.mixin
.LookupElement
.prototype.getRequest = function () {
957 return this.getLookupRequest();
961 * @inheritdoc OO.ui.mixin.RequestManager
963 OO
.ui
.mixin
.LookupElement
.prototype.getRequestCacheDataFromResponse = function ( response
) {
964 return this.getLookupCacheDataFromResponse( response
);
968 * CardLayouts are used within {@link OO.ui.IndexLayout index layouts} to create cards that users can select and display
969 * from the index's optional {@link OO.ui.TabSelectWidget tab} navigation. Cards are usually not instantiated directly,
970 * rather extended to include the required content and functionality.
972 * Each card must have a unique symbolic name, which is passed to the constructor. In addition, the card's tab
973 * item is customized (with a label) using the #setupTabItem method. See
974 * {@link OO.ui.IndexLayout IndexLayout} for an example.
977 * @extends OO.ui.PanelLayout
980 * @param {string} name Unique symbolic name of card
981 * @param {Object} [config] Configuration options
982 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] Label for card's tab
984 OO
.ui
.CardLayout
= function OoUiCardLayout( name
, config
) {
985 // Allow passing positional parameters inside the config object
986 if ( OO
.isPlainObject( name
) && config
=== undefined ) {
991 // Configuration initialization
992 config
= $.extend( { scrollable
: true }, config
);
994 // Parent constructor
995 OO
.ui
.CardLayout
.parent
.call( this, config
);
999 this.label
= config
.label
;
1000 this.tabItem
= null;
1001 this.active
= false;
1004 this.$element
.addClass( 'oo-ui-cardLayout' );
1009 OO
.inheritClass( OO
.ui
.CardLayout
, OO
.ui
.PanelLayout
);
1014 * An 'active' event is emitted when the card becomes active. Cards become active when they are
1015 * shown in a index layout that is configured to display only one card at a time.
1018 * @param {boolean} active Card is active
1024 * Get the symbolic name of the card.
1026 * @return {string} Symbolic name of card
1028 OO
.ui
.CardLayout
.prototype.getName = function () {
1033 * Check if card is active.
1035 * Cards become active when they are shown in a {@link OO.ui.IndexLayout index layout} that is configured to display
1036 * only one card at a time. Additional CSS is applied to the card's tab item to reflect the active state.
1038 * @return {boolean} Card is active
1040 OO
.ui
.CardLayout
.prototype.isActive = function () {
1047 * The tab item allows users to access the card from the index's tab
1048 * navigation. The tab item itself can be customized (with a label, level, etc.) using the #setupTabItem method.
1050 * @return {OO.ui.TabOptionWidget|null} Tab option widget
1052 OO
.ui
.CardLayout
.prototype.getTabItem = function () {
1053 return this.tabItem
;
1057 * Set or unset the tab item.
1059 * Specify a {@link OO.ui.TabOptionWidget tab option} to set it,
1060 * or `null` to clear the tab item. To customize the tab item itself (e.g., to set a label or tab
1061 * level), use #setupTabItem instead of this method.
1063 * @param {OO.ui.TabOptionWidget|null} tabItem Tab option widget, null to clear
1066 OO
.ui
.CardLayout
.prototype.setTabItem = function ( tabItem
) {
1067 this.tabItem
= tabItem
|| null;
1069 this.setupTabItem();
1075 * Set up the tab item.
1077 * Use this method to customize the tab item (e.g., to add a label or tab level). To set or unset
1078 * the tab item itself (with a {@link OO.ui.TabOptionWidget tab option} or `null`), use
1079 * the #setTabItem method instead.
1081 * @param {OO.ui.TabOptionWidget} tabItem Tab option widget to set up
1084 OO
.ui
.CardLayout
.prototype.setupTabItem = function () {
1086 this.tabItem
.setLabel( this.label
);
1092 * Set the card to its 'active' state.
1094 * Cards become active when they are shown in a index layout that is configured to display only one card at a time. Additional
1095 * CSS is applied to the tab item to reflect the card's active state. Outside of the index
1096 * context, setting the active state on a card does nothing.
1098 * @param {boolean} active Card is active
1101 OO
.ui
.CardLayout
.prototype.setActive = function ( active
) {
1104 if ( active
!== this.active
) {
1105 this.active
= active
;
1106 this.$element
.toggleClass( 'oo-ui-cardLayout-active', this.active
);
1107 this.emit( 'active', this.active
);
1112 * PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display
1113 * from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly,
1114 * rather extended to include the required content and functionality.
1116 * Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline
1117 * item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See
1118 * {@link OO.ui.BookletLayout BookletLayout} for an example.
1121 * @extends OO.ui.PanelLayout
1124 * @param {string} name Unique symbolic name of page
1125 * @param {Object} [config] Configuration options
1127 OO
.ui
.PageLayout
= function OoUiPageLayout( name
, config
) {
1128 // Allow passing positional parameters inside the config object
1129 if ( OO
.isPlainObject( name
) && config
=== undefined ) {
1134 // Configuration initialization
1135 config
= $.extend( { scrollable
: true }, config
);
1137 // Parent constructor
1138 OO
.ui
.PageLayout
.parent
.call( this, config
);
1142 this.outlineItem
= null;
1143 this.active
= false;
1146 this.$element
.addClass( 'oo-ui-pageLayout' );
1151 OO
.inheritClass( OO
.ui
.PageLayout
, OO
.ui
.PanelLayout
);
1156 * An 'active' event is emitted when the page becomes active. Pages become active when they are
1157 * shown in a booklet layout that is configured to display only one page at a time.
1160 * @param {boolean} active Page is active
1166 * Get the symbolic name of the page.
1168 * @return {string} Symbolic name of page
1170 OO
.ui
.PageLayout
.prototype.getName = function () {
1175 * Check if page is active.
1177 * Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display
1178 * only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state.
1180 * @return {boolean} Page is active
1182 OO
.ui
.PageLayout
.prototype.isActive = function () {
1189 * The outline item allows users to access the page from the booklet's outline
1190 * navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method.
1192 * @return {OO.ui.OutlineOptionWidget|null} Outline option widget
1194 OO
.ui
.PageLayout
.prototype.getOutlineItem = function () {
1195 return this.outlineItem
;
1199 * Set or unset the outline item.
1201 * Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it,
1202 * or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline
1203 * level), use #setupOutlineItem instead of this method.
1205 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear
1208 OO
.ui
.PageLayout
.prototype.setOutlineItem = function ( outlineItem
) {
1209 this.outlineItem
= outlineItem
|| null;
1210 if ( outlineItem
) {
1211 this.setupOutlineItem();
1217 * Set up the outline item.
1219 * Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset
1220 * the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use
1221 * the #setOutlineItem method instead.
1223 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up
1226 OO
.ui
.PageLayout
.prototype.setupOutlineItem = function () {
1231 * Set the page to its 'active' state.
1233 * Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional
1234 * CSS is applied to the outline item to reflect the page's active state. Outside of the booklet
1235 * context, setting the active state on a page does nothing.
1237 * @param {boolean} active Page is active
1240 OO
.ui
.PageLayout
.prototype.setActive = function ( active
) {
1243 if ( active
!== this.active
) {
1244 this.active
= active
;
1245 this.$element
.toggleClass( 'oo-ui-pageLayout-active', active
);
1246 this.emit( 'active', this.active
);
1251 * StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed
1252 * at a time, though the stack layout can also be configured to show all contained panels, one after another,
1253 * by setting the #continuous option to 'true'.
1256 * // A stack layout with two panels, configured to be displayed continously
1257 * var myStack = new OO.ui.StackLayout( {
1259 * new OO.ui.PanelLayout( {
1260 * $content: $( '<p>Panel One</p>' ),
1264 * new OO.ui.PanelLayout( {
1265 * $content: $( '<p>Panel Two</p>' ),
1272 * $( 'body' ).append( myStack.$element );
1275 * @extends OO.ui.PanelLayout
1276 * @mixins OO.ui.mixin.GroupElement
1279 * @param {Object} [config] Configuration options
1280 * @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time.
1281 * @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout.
1283 OO
.ui
.StackLayout
= function OoUiStackLayout( config
) {
1284 // Configuration initialization
1285 config
= $.extend( { scrollable
: true }, config
);
1287 // Parent constructor
1288 OO
.ui
.StackLayout
.parent
.call( this, config
);
1290 // Mixin constructors
1291 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
1294 this.currentItem
= null;
1295 this.continuous
= !!config
.continuous
;
1298 this.$element
.addClass( 'oo-ui-stackLayout' );
1299 if ( this.continuous
) {
1300 this.$element
.addClass( 'oo-ui-stackLayout-continuous' );
1301 this.$element
.on( 'scroll', OO
.ui
.debounce( this.onScroll
.bind( this ), 250 ) );
1303 if ( Array
.isArray( config
.items
) ) {
1304 this.addItems( config
.items
);
1310 OO
.inheritClass( OO
.ui
.StackLayout
, OO
.ui
.PanelLayout
);
1311 OO
.mixinClass( OO
.ui
.StackLayout
, OO
.ui
.mixin
.GroupElement
);
1316 * A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed},
1317 * {@link #clearItems cleared} or {@link #setItem displayed}.
1320 * @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown
1324 * When used in continuous mode, this event is emitted when the user scrolls down
1325 * far enough such that currentItem is no longer visible.
1327 * @event visibleItemChange
1328 * @param {OO.ui.PanelLayout} panel The next visible item in the layout
1334 * Handle scroll events from the layout element
1336 * @param {jQuery.Event} e
1337 * @fires visibleItemChange
1339 OO
.ui
.StackLayout
.prototype.onScroll = function () {
1341 len
= this.items
.length
,
1342 currentIndex
= this.items
.indexOf( this.currentItem
),
1343 newIndex
= currentIndex
,
1344 containerRect
= this.$element
[ 0 ].getBoundingClientRect();
1346 if ( !containerRect
|| ( !containerRect
.top
&& !containerRect
.bottom
) ) {
1347 // Can't get bounding rect, possibly not attached.
1351 function getRect( item
) {
1352 return item
.$element
[ 0 ].getBoundingClientRect();
1355 function isVisible( item
) {
1356 var rect
= getRect( item
);
1357 return rect
.bottom
> containerRect
.top
&& rect
.top
< containerRect
.bottom
;
1360 currentRect
= getRect( this.currentItem
);
1362 if ( currentRect
.bottom
< containerRect
.top
) {
1363 // Scrolled down past current item
1364 while ( ++newIndex
< len
) {
1365 if ( isVisible( this.items
[ newIndex
] ) ) {
1369 } else if ( currentRect
.top
> containerRect
.bottom
) {
1370 // Scrolled up past current item
1371 while ( --newIndex
>= 0 ) {
1372 if ( isVisible( this.items
[ newIndex
] ) ) {
1378 if ( newIndex
!== currentIndex
) {
1379 this.emit( 'visibleItemChange', this.items
[ newIndex
] );
1384 * Get the current panel.
1386 * @return {OO.ui.Layout|null}
1388 OO
.ui
.StackLayout
.prototype.getCurrentItem = function () {
1389 return this.currentItem
;
1393 * Unset the current item.
1396 * @param {OO.ui.StackLayout} layout
1399 OO
.ui
.StackLayout
.prototype.unsetCurrentItem = function () {
1400 var prevItem
= this.currentItem
;
1401 if ( prevItem
=== null ) {
1405 this.currentItem
= null;
1406 this.emit( 'set', null );
1410 * Add panel layouts to the stack layout.
1412 * Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different
1413 * insertion point. Adding a panel that is already in the stack will move it to the end of the array or the point specified
1416 * @param {OO.ui.Layout[]} items Panels to add
1417 * @param {number} [index] Index of the insertion point
1420 OO
.ui
.StackLayout
.prototype.addItems = function ( items
, index
) {
1421 // Update the visibility
1422 this.updateHiddenState( items
, this.currentItem
);
1425 OO
.ui
.mixin
.GroupElement
.prototype.addItems
.call( this, items
, index
);
1427 if ( !this.currentItem
&& items
.length
) {
1428 this.setItem( items
[ 0 ] );
1435 * Remove the specified panels from the stack layout.
1437 * Removed panels are detached from the DOM, not removed, so that they may be reused. To remove all panels,
1438 * you may wish to use the #clearItems method instead.
1440 * @param {OO.ui.Layout[]} items Panels to remove
1444 OO
.ui
.StackLayout
.prototype.removeItems = function ( items
) {
1446 OO
.ui
.mixin
.GroupElement
.prototype.removeItems
.call( this, items
);
1448 if ( items
.indexOf( this.currentItem
) !== -1 ) {
1449 if ( this.items
.length
) {
1450 this.setItem( this.items
[ 0 ] );
1452 this.unsetCurrentItem();
1460 * Clear all panels from the stack layout.
1462 * Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only
1463 * a subset of panels, use the #removeItems method.
1468 OO
.ui
.StackLayout
.prototype.clearItems = function () {
1469 this.unsetCurrentItem();
1470 OO
.ui
.mixin
.GroupElement
.prototype.clearItems
.call( this );
1476 * Show the specified panel.
1478 * If another panel is currently displayed, it will be hidden.
1480 * @param {OO.ui.Layout} item Panel to show
1484 OO
.ui
.StackLayout
.prototype.setItem = function ( item
) {
1485 if ( item
!== this.currentItem
) {
1486 this.updateHiddenState( this.items
, item
);
1488 if ( this.items
.indexOf( item
) !== -1 ) {
1489 this.currentItem
= item
;
1490 this.emit( 'set', item
);
1492 this.unsetCurrentItem();
1500 * Update the visibility of all items in case of non-continuous view.
1502 * Ensure all items are hidden except for the selected one.
1503 * This method does nothing when the stack is continuous.
1506 * @param {OO.ui.Layout[]} items Item list iterate over
1507 * @param {OO.ui.Layout} [selectedItem] Selected item to show
1509 OO
.ui
.StackLayout
.prototype.updateHiddenState = function ( items
, selectedItem
) {
1512 if ( !this.continuous
) {
1513 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
1514 if ( !selectedItem
|| selectedItem
!== items
[ i
] ) {
1515 items
[ i
].$element
.addClass( 'oo-ui-element-hidden' );
1516 items
[ i
].$element
.attr( 'aria-hidden', 'true' );
1519 if ( selectedItem
) {
1520 selectedItem
.$element
.removeClass( 'oo-ui-element-hidden' );
1521 selectedItem
.$element
.removeAttr( 'aria-hidden' );
1527 * 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)
1528 * and its size is customized with the #menuSize config. The content area will fill all remaining space.
1531 * var menuLayout = new OO.ui.MenuLayout( {
1534 * menuPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
1535 * contentPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
1536 * select = new OO.ui.SelectWidget( {
1538 * new OO.ui.OptionWidget( {
1542 * new OO.ui.OptionWidget( {
1546 * new OO.ui.OptionWidget( {
1550 * new OO.ui.OptionWidget( {
1555 * } ).on( 'select', function ( item ) {
1556 * menuLayout.setMenuPosition( item.getData() );
1559 * menuLayout.$menu.append(
1560 * menuPanel.$element.append( '<b>Menu panel</b>', select.$element )
1562 * menuLayout.$content.append(
1563 * contentPanel.$element.append( '<b>Content panel</b>', '<p>Note that the menu is positioned relative to the content panel: top, bottom, after, before.</p>')
1565 * $( 'body' ).append( menuLayout.$element );
1567 * If menu size needs to be overridden, it can be accomplished using CSS similar to the snippet
1568 * below. MenuLayout's CSS will override the appropriate values with 'auto' or '0' to display the
1569 * menu correctly. If `menuPosition` is known beforehand, CSS rules corresponding to other positions
1572 * .oo-ui-menuLayout-menu {
1576 * .oo-ui-menuLayout-content {
1584 * @extends OO.ui.Layout
1587 * @param {Object} [config] Configuration options
1588 * @cfg {boolean} [showMenu=true] Show menu
1589 * @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before`
1591 OO
.ui
.MenuLayout
= function OoUiMenuLayout( config
) {
1592 // Configuration initialization
1593 config
= $.extend( {
1595 menuPosition
: 'before'
1598 // Parent constructor
1599 OO
.ui
.MenuLayout
.parent
.call( this, config
);
1604 * @property {jQuery}
1606 this.$menu
= $( '<div>' );
1610 * @property {jQuery}
1612 this.$content
= $( '<div>' );
1616 .addClass( 'oo-ui-menuLayout-menu' );
1617 this.$content
.addClass( 'oo-ui-menuLayout-content' );
1619 .addClass( 'oo-ui-menuLayout' )
1620 .append( this.$content
, this.$menu
);
1621 this.setMenuPosition( config
.menuPosition
);
1622 this.toggleMenu( config
.showMenu
);
1627 OO
.inheritClass( OO
.ui
.MenuLayout
, OO
.ui
.Layout
);
1634 * @param {boolean} showMenu Show menu, omit to toggle
1637 OO
.ui
.MenuLayout
.prototype.toggleMenu = function ( showMenu
) {
1638 showMenu
= showMenu
=== undefined ? !this.showMenu
: !!showMenu
;
1640 if ( this.showMenu
!== showMenu
) {
1641 this.showMenu
= showMenu
;
1643 .toggleClass( 'oo-ui-menuLayout-showMenu', this.showMenu
)
1644 .toggleClass( 'oo-ui-menuLayout-hideMenu', !this.showMenu
);
1645 this.$menu
.attr( 'aria-hidden', this.showMenu
? 'false' : 'true' );
1652 * Check if menu is visible
1654 * @return {boolean} Menu is visible
1656 OO
.ui
.MenuLayout
.prototype.isMenuVisible = function () {
1657 return this.showMenu
;
1661 * Set menu position.
1663 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
1664 * @throws {Error} If position value is not supported
1667 OO
.ui
.MenuLayout
.prototype.setMenuPosition = function ( position
) {
1668 this.$element
.removeClass( 'oo-ui-menuLayout-' + this.menuPosition
);
1669 this.menuPosition
= position
;
1670 this.$element
.addClass( 'oo-ui-menuLayout-' + position
);
1676 * Get menu position.
1678 * @return {string} Menu position
1680 OO
.ui
.MenuLayout
.prototype.getMenuPosition = function () {
1681 return this.menuPosition
;
1685 * BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as
1686 * an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate
1687 * through the pages and select which one to display. By default, only one page is
1688 * displayed at a time and the outline is hidden. When a user navigates to a new page,
1689 * the booklet layout automatically focuses on the first focusable element, unless the
1690 * default setting is changed. Optionally, booklets can be configured to show
1691 * {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items.
1694 * // Example of a BookletLayout that contains two PageLayouts.
1696 * function PageOneLayout( name, config ) {
1697 * PageOneLayout.parent.call( this, name, config );
1698 * this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' );
1700 * OO.inheritClass( PageOneLayout, OO.ui.PageLayout );
1701 * PageOneLayout.prototype.setupOutlineItem = function () {
1702 * this.outlineItem.setLabel( 'Page One' );
1705 * function PageTwoLayout( name, config ) {
1706 * PageTwoLayout.parent.call( this, name, config );
1707 * this.$element.append( '<p>Second page</p>' );
1709 * OO.inheritClass( PageTwoLayout, OO.ui.PageLayout );
1710 * PageTwoLayout.prototype.setupOutlineItem = function () {
1711 * this.outlineItem.setLabel( 'Page Two' );
1714 * var page1 = new PageOneLayout( 'one' ),
1715 * page2 = new PageTwoLayout( 'two' );
1717 * var booklet = new OO.ui.BookletLayout( {
1721 * booklet.addPages ( [ page1, page2 ] );
1722 * $( 'body' ).append( booklet.$element );
1725 * @extends OO.ui.MenuLayout
1728 * @param {Object} [config] Configuration options
1729 * @cfg {boolean} [continuous=false] Show all pages, one after another
1730 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed. Disabled on mobile.
1731 * @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet.
1732 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
1734 OO
.ui
.BookletLayout
= function OoUiBookletLayout( config
) {
1735 // Configuration initialization
1736 config
= config
|| {};
1738 // Parent constructor
1739 OO
.ui
.BookletLayout
.parent
.call( this, config
);
1742 this.currentPageName
= null;
1744 this.ignoreFocus
= false;
1745 this.stackLayout
= new OO
.ui
.StackLayout( { continuous
: !!config
.continuous
} );
1746 this.$content
.append( this.stackLayout
.$element
);
1747 this.autoFocus
= config
.autoFocus
=== undefined || !!config
.autoFocus
;
1748 this.outlineVisible
= false;
1749 this.outlined
= !!config
.outlined
;
1750 if ( this.outlined
) {
1751 this.editable
= !!config
.editable
;
1752 this.outlineControlsWidget
= null;
1753 this.outlineSelectWidget
= new OO
.ui
.OutlineSelectWidget();
1754 this.outlinePanel
= new OO
.ui
.PanelLayout( { scrollable
: true } );
1755 this.$menu
.append( this.outlinePanel
.$element
);
1756 this.outlineVisible
= true;
1757 if ( this.editable
) {
1758 this.outlineControlsWidget
= new OO
.ui
.OutlineControlsWidget(
1759 this.outlineSelectWidget
1763 this.toggleMenu( this.outlined
);
1766 this.stackLayout
.connect( this, { set: 'onStackLayoutSet' } );
1767 if ( this.outlined
) {
1768 this.outlineSelectWidget
.connect( this, { select
: 'onOutlineSelectWidgetSelect' } );
1769 this.scrolling
= false;
1770 this.stackLayout
.connect( this, { visibleItemChange
: 'onStackLayoutVisibleItemChange' } );
1772 if ( this.autoFocus
) {
1773 // Event 'focus' does not bubble, but 'focusin' does
1774 this.stackLayout
.$element
.on( 'focusin', this.onStackLayoutFocus
.bind( this ) );
1778 this.$element
.addClass( 'oo-ui-bookletLayout' );
1779 this.stackLayout
.$element
.addClass( 'oo-ui-bookletLayout-stackLayout' );
1780 if ( this.outlined
) {
1781 this.outlinePanel
.$element
1782 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
1783 .append( this.outlineSelectWidget
.$element
);
1784 if ( this.editable
) {
1785 this.outlinePanel
.$element
1786 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
1787 .append( this.outlineControlsWidget
.$element
);
1794 OO
.inheritClass( OO
.ui
.BookletLayout
, OO
.ui
.MenuLayout
);
1799 * A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout.
1801 * @param {OO.ui.PageLayout} page Current page
1805 * An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout.
1808 * @param {OO.ui.PageLayout[]} page Added pages
1809 * @param {number} index Index pages were added at
1813 * A 'remove' event is emitted when pages are {@link #clearPages cleared} or
1814 * {@link #removePages removed} from the booklet.
1817 * @param {OO.ui.PageLayout[]} pages Removed pages
1823 * Handle stack layout focus.
1826 * @param {jQuery.Event} e Focusin event
1828 OO
.ui
.BookletLayout
.prototype.onStackLayoutFocus = function ( e
) {
1831 // Find the page that an element was focused within
1832 $target
= $( e
.target
).closest( '.oo-ui-pageLayout' );
1833 for ( name
in this.pages
) {
1834 // Check for page match, exclude current page to find only page changes
1835 if ( this.pages
[ name
].$element
[ 0 ] === $target
[ 0 ] && name
!== this.currentPageName
) {
1836 this.setPage( name
);
1843 * Handle visibleItemChange events from the stackLayout
1845 * The next visible page is set as the current page by selecting it
1848 * @param {OO.ui.PageLayout} page The next visible page in the layout
1850 OO
.ui
.BookletLayout
.prototype.onStackLayoutVisibleItemChange = function ( page
) {
1851 // Set a flag to so that the resulting call to #onStackLayoutSet doesn't
1852 // try and scroll the item into view again.
1853 this.scrolling
= true;
1854 this.outlineSelectWidget
.selectItemByData( page
.getName() );
1855 this.scrolling
= false;
1859 * Handle stack layout set events.
1862 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
1864 OO
.ui
.BookletLayout
.prototype.onStackLayoutSet = function ( page
) {
1866 if ( !this.scrolling
&& page
) {
1867 page
.scrollElementIntoView().done( function () {
1868 if ( layout
.autoFocus
&& !OO
.ui
.isMobile() ) {
1876 * Focus the first input in the current page.
1878 * If no page is selected, the first selectable page will be selected.
1879 * If the focus is already in an element on the current page, nothing will happen.
1881 * @param {number} [itemIndex] A specific item to focus on
1883 OO
.ui
.BookletLayout
.prototype.focus = function ( itemIndex
) {
1885 items
= this.stackLayout
.getItems();
1887 if ( itemIndex
!== undefined && items
[ itemIndex
] ) {
1888 page
= items
[ itemIndex
];
1890 page
= this.stackLayout
.getCurrentItem();
1893 if ( !page
&& this.outlined
) {
1894 this.selectFirstSelectablePage();
1895 page
= this.stackLayout
.getCurrentItem();
1900 // Only change the focus if is not already in the current page
1901 if ( !OO
.ui
.contains( page
.$element
[ 0 ], this.getElementDocument().activeElement
, true ) ) {
1907 * Find the first focusable input in the booklet layout and focus
1910 OO
.ui
.BookletLayout
.prototype.focusFirstFocusable = function () {
1911 OO
.ui
.findFocusable( this.stackLayout
.$element
).focus();
1915 * Handle outline widget select events.
1918 * @param {OO.ui.OptionWidget|null} item Selected item
1920 OO
.ui
.BookletLayout
.prototype.onOutlineSelectWidgetSelect = function ( item
) {
1922 this.setPage( item
.getData() );
1927 * Check if booklet has an outline.
1929 * @return {boolean} Booklet has an outline
1931 OO
.ui
.BookletLayout
.prototype.isOutlined = function () {
1932 return this.outlined
;
1936 * Check if booklet has editing controls.
1938 * @return {boolean} Booklet is editable
1940 OO
.ui
.BookletLayout
.prototype.isEditable = function () {
1941 return this.editable
;
1945 * Check if booklet has a visible outline.
1947 * @return {boolean} Outline is visible
1949 OO
.ui
.BookletLayout
.prototype.isOutlineVisible = function () {
1950 return this.outlined
&& this.outlineVisible
;
1954 * Hide or show the outline.
1956 * @param {boolean} [show] Show outline, omit to invert current state
1959 OO
.ui
.BookletLayout
.prototype.toggleOutline = function ( show
) {
1960 if ( this.outlined
) {
1961 show
= show
=== undefined ? !this.outlineVisible
: !!show
;
1962 this.outlineVisible
= show
;
1963 this.toggleMenu( show
);
1970 * Get the page closest to the specified page.
1972 * @param {OO.ui.PageLayout} page Page to use as a reference point
1973 * @return {OO.ui.PageLayout|null} Page closest to the specified page
1975 OO
.ui
.BookletLayout
.prototype.getClosestPage = function ( page
) {
1976 var next
, prev
, level
,
1977 pages
= this.stackLayout
.getItems(),
1978 index
= pages
.indexOf( page
);
1980 if ( index
!== -1 ) {
1981 next
= pages
[ index
+ 1 ];
1982 prev
= pages
[ index
- 1 ];
1983 // Prefer adjacent pages at the same level
1984 if ( this.outlined
) {
1985 level
= this.outlineSelectWidget
.getItemFromData( page
.getName() ).getLevel();
1988 level
=== this.outlineSelectWidget
.getItemFromData( prev
.getName() ).getLevel()
1994 level
=== this.outlineSelectWidget
.getItemFromData( next
.getName() ).getLevel()
2000 return prev
|| next
|| null;
2004 * Get the outline widget.
2006 * If the booklet is not outlined, the method will return `null`.
2008 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
2010 OO
.ui
.BookletLayout
.prototype.getOutline = function () {
2011 return this.outlineSelectWidget
;
2015 * Get the outline controls widget.
2017 * If the outline is not editable, the method will return `null`.
2019 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
2021 OO
.ui
.BookletLayout
.prototype.getOutlineControls = function () {
2022 return this.outlineControlsWidget
;
2026 * Get a page by its symbolic name.
2028 * @param {string} name Symbolic name of page
2029 * @return {OO.ui.PageLayout|undefined} Page, if found
2031 OO
.ui
.BookletLayout
.prototype.getPage = function ( name
) {
2032 return this.pages
[ name
];
2036 * Get the current page.
2038 * @return {OO.ui.PageLayout|undefined} Current page, if found
2040 OO
.ui
.BookletLayout
.prototype.getCurrentPage = function () {
2041 var name
= this.getCurrentPageName();
2042 return name
? this.getPage( name
) : undefined;
2046 * Get the symbolic name of the current page.
2048 * @return {string|null} Symbolic name of the current page
2050 OO
.ui
.BookletLayout
.prototype.getCurrentPageName = function () {
2051 return this.currentPageName
;
2055 * Add pages to the booklet layout
2057 * When pages are added with the same names as existing pages, the existing pages will be
2058 * automatically removed before the new pages are added.
2060 * @param {OO.ui.PageLayout[]} pages Pages to add
2061 * @param {number} index Index of the insertion point
2065 OO
.ui
.BookletLayout
.prototype.addPages = function ( pages
, index
) {
2066 var i
, len
, name
, page
, item
, currentIndex
,
2067 stackLayoutPages
= this.stackLayout
.getItems(),
2071 // Remove pages with same names
2072 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
2074 name
= page
.getName();
2076 if ( Object
.prototype.hasOwnProperty
.call( this.pages
, name
) ) {
2077 // Correct the insertion index
2078 currentIndex
= stackLayoutPages
.indexOf( this.pages
[ name
] );
2079 if ( currentIndex
!== -1 && currentIndex
+ 1 < index
) {
2082 remove
.push( this.pages
[ name
] );
2085 if ( remove
.length
) {
2086 this.removePages( remove
);
2090 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
2092 name
= page
.getName();
2093 this.pages
[ page
.getName() ] = page
;
2094 if ( this.outlined
) {
2095 item
= new OO
.ui
.OutlineOptionWidget( { data
: name
} );
2096 page
.setOutlineItem( item
);
2101 if ( this.outlined
&& items
.length
) {
2102 this.outlineSelectWidget
.addItems( items
, index
);
2103 this.selectFirstSelectablePage();
2105 this.stackLayout
.addItems( pages
, index
);
2106 this.emit( 'add', pages
, index
);
2112 * Remove the specified pages from the booklet layout.
2114 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
2116 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
2120 OO
.ui
.BookletLayout
.prototype.removePages = function ( pages
) {
2121 var i
, len
, name
, page
,
2124 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
2126 name
= page
.getName();
2127 delete this.pages
[ name
];
2128 if ( this.outlined
) {
2129 items
.push( this.outlineSelectWidget
.getItemFromData( name
) );
2130 page
.setOutlineItem( null );
2133 if ( this.outlined
&& items
.length
) {
2134 this.outlineSelectWidget
.removeItems( items
);
2135 this.selectFirstSelectablePage();
2137 this.stackLayout
.removeItems( pages
);
2138 this.emit( 'remove', pages
);
2144 * Clear all pages from the booklet layout.
2146 * To remove only a subset of pages from the booklet, use the #removePages method.
2151 OO
.ui
.BookletLayout
.prototype.clearPages = function () {
2153 pages
= this.stackLayout
.getItems();
2156 this.currentPageName
= null;
2157 if ( this.outlined
) {
2158 this.outlineSelectWidget
.clearItems();
2159 for ( i
= 0, len
= pages
.length
; i
< len
; i
++ ) {
2160 pages
[ i
].setOutlineItem( null );
2163 this.stackLayout
.clearItems();
2165 this.emit( 'remove', pages
);
2171 * Set the current page by symbolic name.
2174 * @param {string} name Symbolic name of page
2176 OO
.ui
.BookletLayout
.prototype.setPage = function ( name
) {
2179 page
= this.pages
[ name
],
2180 previousPage
= this.currentPageName
&& this.pages
[ this.currentPageName
];
2182 if ( name
!== this.currentPageName
) {
2183 if ( this.outlined
) {
2184 selectedItem
= this.outlineSelectWidget
.getSelectedItem();
2185 if ( selectedItem
&& selectedItem
.getData() !== name
) {
2186 this.outlineSelectWidget
.selectItemByData( name
);
2190 if ( previousPage
) {
2191 previousPage
.setActive( false );
2192 // Blur anything focused if the next page doesn't have anything focusable.
2193 // This is not needed if the next page has something focusable (because once it is focused
2194 // this blur happens automatically). If the layout is non-continuous, this check is
2195 // meaningless because the next page is not visible yet and thus can't hold focus.
2198 !OO
.ui
.isMobile() &&
2199 this.stackLayout
.continuous
&&
2200 OO
.ui
.findFocusable( page
.$element
).length
!== 0
2202 $focused
= previousPage
.$element
.find( ':focus' );
2203 if ( $focused
.length
) {
2204 $focused
[ 0 ].blur();
2208 this.currentPageName
= name
;
2209 page
.setActive( true );
2210 this.stackLayout
.setItem( page
);
2211 if ( !this.stackLayout
.continuous
&& previousPage
) {
2212 // This should not be necessary, since any inputs on the previous page should have been
2213 // blurred when it was hidden, but browsers are not very consistent about this.
2214 $focused
= previousPage
.$element
.find( ':focus' );
2215 if ( $focused
.length
) {
2216 $focused
[ 0 ].blur();
2219 this.emit( 'set', page
);
2225 * Select the first selectable page.
2229 OO
.ui
.BookletLayout
.prototype.selectFirstSelectablePage = function () {
2230 if ( !this.outlineSelectWidget
.getSelectedItem() ) {
2231 this.outlineSelectWidget
.selectItem( this.outlineSelectWidget
.getFirstSelectableItem() );
2238 * IndexLayouts contain {@link OO.ui.CardLayout card layouts} as well as
2239 * {@link OO.ui.TabSelectWidget tabs} that allow users to easily navigate through the cards and
2240 * select which one to display. By default, only one card is displayed at a time. When a user
2241 * navigates to a new card, the index layout automatically focuses on the first focusable element,
2242 * unless the default setting is changed.
2244 * TODO: This class is similar to BookletLayout, we may want to refactor to reduce duplication
2247 * // Example of a IndexLayout that contains two CardLayouts.
2249 * function CardOneLayout( name, config ) {
2250 * CardOneLayout.parent.call( this, name, config );
2251 * this.$element.append( '<p>First card</p>' );
2253 * OO.inheritClass( CardOneLayout, OO.ui.CardLayout );
2254 * CardOneLayout.prototype.setupTabItem = function () {
2255 * this.tabItem.setLabel( 'Card one' );
2258 * var card1 = new CardOneLayout( 'one' ),
2259 * card2 = new OO.ui.CardLayout( 'two', { label: 'Card two' } );
2261 * card2.$element.append( '<p>Second card</p>' );
2263 * var index = new OO.ui.IndexLayout();
2265 * index.addCards ( [ card1, card2 ] );
2266 * $( 'body' ).append( index.$element );
2269 * @extends OO.ui.MenuLayout
2272 * @param {Object} [config] Configuration options
2273 * @cfg {boolean} [continuous=false] Show all cards, one after another
2274 * @cfg {boolean} [expanded=true] Expand the content panel to fill the entire parent element.
2275 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new card is displayed. Disabled on mobile.
2277 OO
.ui
.IndexLayout
= function OoUiIndexLayout( config
) {
2278 // Configuration initialization
2279 config
= $.extend( {}, config
, { menuPosition
: 'top' } );
2281 // Parent constructor
2282 OO
.ui
.IndexLayout
.parent
.call( this, config
);
2285 this.currentCardName
= null;
2287 this.ignoreFocus
= false;
2288 this.stackLayout
= new OO
.ui
.StackLayout( {
2289 continuous
: !!config
.continuous
,
2290 expanded
: config
.expanded
2292 this.$content
.append( this.stackLayout
.$element
);
2293 this.autoFocus
= config
.autoFocus
=== undefined || !!config
.autoFocus
;
2295 this.tabSelectWidget
= new OO
.ui
.TabSelectWidget();
2296 this.tabPanel
= new OO
.ui
.PanelLayout();
2297 this.$menu
.append( this.tabPanel
.$element
);
2299 this.toggleMenu( true );
2302 this.stackLayout
.connect( this, { set: 'onStackLayoutSet' } );
2303 this.tabSelectWidget
.connect( this, { select
: 'onTabSelectWidgetSelect' } );
2304 if ( this.autoFocus
) {
2305 // Event 'focus' does not bubble, but 'focusin' does
2306 this.stackLayout
.$element
.on( 'focusin', this.onStackLayoutFocus
.bind( this ) );
2310 this.$element
.addClass( 'oo-ui-indexLayout' );
2311 this.stackLayout
.$element
.addClass( 'oo-ui-indexLayout-stackLayout' );
2312 this.tabPanel
.$element
2313 .addClass( 'oo-ui-indexLayout-tabPanel' )
2314 .append( this.tabSelectWidget
.$element
);
2319 OO
.inheritClass( OO
.ui
.IndexLayout
, OO
.ui
.MenuLayout
);
2324 * A 'set' event is emitted when a card is {@link #setCard set} to be displayed by the index layout.
2326 * @param {OO.ui.CardLayout} card Current card
2330 * An 'add' event is emitted when cards are {@link #addCards added} to the index layout.
2333 * @param {OO.ui.CardLayout[]} card Added cards
2334 * @param {number} index Index cards were added at
2338 * A 'remove' event is emitted when cards are {@link #clearCards cleared} or
2339 * {@link #removeCards removed} from the index.
2342 * @param {OO.ui.CardLayout[]} cards Removed cards
2348 * Handle stack layout focus.
2351 * @param {jQuery.Event} e Focusin event
2353 OO
.ui
.IndexLayout
.prototype.onStackLayoutFocus = function ( e
) {
2356 // Find the card that an element was focused within
2357 $target
= $( e
.target
).closest( '.oo-ui-cardLayout' );
2358 for ( name
in this.cards
) {
2359 // Check for card match, exclude current card to find only card changes
2360 if ( this.cards
[ name
].$element
[ 0 ] === $target
[ 0 ] && name
!== this.currentCardName
) {
2361 this.setCard( name
);
2368 * Handle stack layout set events.
2371 * @param {OO.ui.PanelLayout|null} card The card panel that is now the current panel
2373 OO
.ui
.IndexLayout
.prototype.onStackLayoutSet = function ( card
) {
2376 card
.scrollElementIntoView().done( function () {
2377 if ( layout
.autoFocus
&& !OO
.ui
.isMobile() ) {
2385 * Focus the first input in the current card.
2387 * If no card is selected, the first selectable card will be selected.
2388 * If the focus is already in an element on the current card, nothing will happen.
2390 * @param {number} [itemIndex] A specific item to focus on
2392 OO
.ui
.IndexLayout
.prototype.focus = function ( itemIndex
) {
2394 items
= this.stackLayout
.getItems();
2396 if ( itemIndex
!== undefined && items
[ itemIndex
] ) {
2397 card
= items
[ itemIndex
];
2399 card
= this.stackLayout
.getCurrentItem();
2403 this.selectFirstSelectableCard();
2404 card
= this.stackLayout
.getCurrentItem();
2409 // Only change the focus if is not already in the current page
2410 if ( !OO
.ui
.contains( card
.$element
[ 0 ], this.getElementDocument().activeElement
, true ) ) {
2416 * Find the first focusable input in the index layout and focus
2419 OO
.ui
.IndexLayout
.prototype.focusFirstFocusable = function () {
2420 OO
.ui
.findFocusable( this.stackLayout
.$element
).focus();
2424 * Handle tab widget select events.
2427 * @param {OO.ui.OptionWidget|null} item Selected item
2429 OO
.ui
.IndexLayout
.prototype.onTabSelectWidgetSelect = function ( item
) {
2431 this.setCard( item
.getData() );
2436 * Get the card closest to the specified card.
2438 * @param {OO.ui.CardLayout} card Card to use as a reference point
2439 * @return {OO.ui.CardLayout|null} Card closest to the specified card
2441 OO
.ui
.IndexLayout
.prototype.getClosestCard = function ( card
) {
2442 var next
, prev
, level
,
2443 cards
= this.stackLayout
.getItems(),
2444 index
= cards
.indexOf( card
);
2446 if ( index
!== -1 ) {
2447 next
= cards
[ index
+ 1 ];
2448 prev
= cards
[ index
- 1 ];
2449 // Prefer adjacent cards at the same level
2450 level
= this.tabSelectWidget
.getItemFromData( card
.getName() ).getLevel();
2453 level
=== this.tabSelectWidget
.getItemFromData( prev
.getName() ).getLevel()
2459 level
=== this.tabSelectWidget
.getItemFromData( next
.getName() ).getLevel()
2464 return prev
|| next
|| null;
2468 * Get the tabs widget.
2470 * @return {OO.ui.TabSelectWidget} Tabs widget
2472 OO
.ui
.IndexLayout
.prototype.getTabs = function () {
2473 return this.tabSelectWidget
;
2477 * Get a card by its symbolic name.
2479 * @param {string} name Symbolic name of card
2480 * @return {OO.ui.CardLayout|undefined} Card, if found
2482 OO
.ui
.IndexLayout
.prototype.getCard = function ( name
) {
2483 return this.cards
[ name
];
2487 * Get the current card.
2489 * @return {OO.ui.CardLayout|undefined} Current card, if found
2491 OO
.ui
.IndexLayout
.prototype.getCurrentCard = function () {
2492 var name
= this.getCurrentCardName();
2493 return name
? this.getCard( name
) : undefined;
2497 * Get the symbolic name of the current card.
2499 * @return {string|null} Symbolic name of the current card
2501 OO
.ui
.IndexLayout
.prototype.getCurrentCardName = function () {
2502 return this.currentCardName
;
2506 * Add cards to the index layout
2508 * When cards are added with the same names as existing cards, the existing cards will be
2509 * automatically removed before the new cards are added.
2511 * @param {OO.ui.CardLayout[]} cards Cards to add
2512 * @param {number} index Index of the insertion point
2516 OO
.ui
.IndexLayout
.prototype.addCards = function ( cards
, index
) {
2517 var i
, len
, name
, card
, item
, currentIndex
,
2518 stackLayoutCards
= this.stackLayout
.getItems(),
2522 // Remove cards with same names
2523 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
2525 name
= card
.getName();
2527 if ( Object
.prototype.hasOwnProperty
.call( this.cards
, name
) ) {
2528 // Correct the insertion index
2529 currentIndex
= stackLayoutCards
.indexOf( this.cards
[ name
] );
2530 if ( currentIndex
!== -1 && currentIndex
+ 1 < index
) {
2533 remove
.push( this.cards
[ name
] );
2536 if ( remove
.length
) {
2537 this.removeCards( remove
);
2541 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
2543 name
= card
.getName();
2544 this.cards
[ card
.getName() ] = card
;
2545 item
= new OO
.ui
.TabOptionWidget( { data
: name
} );
2546 card
.setTabItem( item
);
2550 if ( items
.length
) {
2551 this.tabSelectWidget
.addItems( items
, index
);
2552 this.selectFirstSelectableCard();
2554 this.stackLayout
.addItems( cards
, index
);
2555 this.emit( 'add', cards
, index
);
2561 * Remove the specified cards from the index layout.
2563 * To remove all cards from the index, you may wish to use the #clearCards method instead.
2565 * @param {OO.ui.CardLayout[]} cards An array of cards to remove
2569 OO
.ui
.IndexLayout
.prototype.removeCards = function ( cards
) {
2570 var i
, len
, name
, card
,
2573 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
2575 name
= card
.getName();
2576 delete this.cards
[ name
];
2577 items
.push( this.tabSelectWidget
.getItemFromData( name
) );
2578 card
.setTabItem( null );
2580 if ( items
.length
) {
2581 this.tabSelectWidget
.removeItems( items
);
2582 this.selectFirstSelectableCard();
2584 this.stackLayout
.removeItems( cards
);
2585 this.emit( 'remove', cards
);
2591 * Clear all cards from the index layout.
2593 * To remove only a subset of cards from the index, use the #removeCards method.
2598 OO
.ui
.IndexLayout
.prototype.clearCards = function () {
2600 cards
= this.stackLayout
.getItems();
2603 this.currentCardName
= null;
2604 this.tabSelectWidget
.clearItems();
2605 for ( i
= 0, len
= cards
.length
; i
< len
; i
++ ) {
2606 cards
[ i
].setTabItem( null );
2608 this.stackLayout
.clearItems();
2610 this.emit( 'remove', cards
);
2616 * Set the current card by symbolic name.
2619 * @param {string} name Symbolic name of card
2621 OO
.ui
.IndexLayout
.prototype.setCard = function ( name
) {
2624 card
= this.cards
[ name
],
2625 previousCard
= this.currentCardName
&& this.cards
[ this.currentCardName
];
2627 if ( name
!== this.currentCardName
) {
2628 selectedItem
= this.tabSelectWidget
.getSelectedItem();
2629 if ( selectedItem
&& selectedItem
.getData() !== name
) {
2630 this.tabSelectWidget
.selectItemByData( name
);
2633 if ( previousCard
) {
2634 previousCard
.setActive( false );
2635 // Blur anything focused if the next card doesn't have anything focusable.
2636 // This is not needed if the next card has something focusable (because once it is focused
2637 // this blur happens automatically). If the layout is non-continuous, this check is
2638 // meaningless because the next card is not visible yet and thus can't hold focus.
2641 !OO
.ui
.isMobile() &&
2642 this.stackLayout
.continuous
&&
2643 OO
.ui
.findFocusable( card
.$element
).length
!== 0
2645 $focused
= previousCard
.$element
.find( ':focus' );
2646 if ( $focused
.length
) {
2647 $focused
[ 0 ].blur();
2651 this.currentCardName
= name
;
2652 card
.setActive( true );
2653 this.stackLayout
.setItem( card
);
2654 if ( !this.stackLayout
.continuous
&& previousCard
) {
2655 // This should not be necessary, since any inputs on the previous card should have been
2656 // blurred when it was hidden, but browsers are not very consistent about this.
2657 $focused
= previousCard
.$element
.find( ':focus' );
2658 if ( $focused
.length
) {
2659 $focused
[ 0 ].blur();
2662 this.emit( 'set', card
);
2668 * Select the first selectable card.
2672 OO
.ui
.IndexLayout
.prototype.selectFirstSelectableCard = function () {
2673 if ( !this.tabSelectWidget
.getSelectedItem() ) {
2674 this.tabSelectWidget
.selectItem( this.tabSelectWidget
.getFirstSelectableItem() );
2681 * ToggleWidget implements basic behavior of widgets with an on/off state.
2682 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
2686 * @extends OO.ui.Widget
2689 * @param {Object} [config] Configuration options
2690 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
2691 * By default, the toggle is in the 'off' state.
2693 OO
.ui
.ToggleWidget
= function OoUiToggleWidget( config
) {
2694 // Configuration initialization
2695 config
= config
|| {};
2697 // Parent constructor
2698 OO
.ui
.ToggleWidget
.parent
.call( this, config
);
2704 this.$element
.addClass( 'oo-ui-toggleWidget' );
2705 this.setValue( !!config
.value
);
2710 OO
.inheritClass( OO
.ui
.ToggleWidget
, OO
.ui
.Widget
);
2717 * A change event is emitted when the on/off state of the toggle changes.
2719 * @param {boolean} value Value representing the new state of the toggle
2725 * Get the value representing the toggle’s state.
2727 * @return {boolean} The on/off state of the toggle
2729 OO
.ui
.ToggleWidget
.prototype.getValue = function () {
2734 * Set the state of the toggle: `true` for 'on', `false' for 'off'.
2736 * @param {boolean} value The state of the toggle
2740 OO
.ui
.ToggleWidget
.prototype.setValue = function ( value
) {
2742 if ( this.value
!== value
) {
2744 this.emit( 'change', value
);
2745 this.$element
.toggleClass( 'oo-ui-toggleWidget-on', value
);
2746 this.$element
.toggleClass( 'oo-ui-toggleWidget-off', !value
);
2747 this.$element
.attr( 'aria-checked', value
.toString() );
2753 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
2754 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
2755 * configured with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators},
2756 * {@link OO.ui.mixin.TitledElement titles}, {@link OO.ui.mixin.FlaggedElement styling flags},
2757 * and {@link OO.ui.mixin.LabelElement labels}. Please see
2758 * the [OOjs UI documentation][1] on MediaWiki for more information.
2761 * // Toggle buttons in the 'off' and 'on' state.
2762 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
2763 * label: 'Toggle Button off'
2765 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
2766 * label: 'Toggle Button on',
2769 * // Append the buttons to the DOM.
2770 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
2772 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
2775 * @extends OO.ui.ToggleWidget
2776 * @mixins OO.ui.mixin.ButtonElement
2777 * @mixins OO.ui.mixin.IconElement
2778 * @mixins OO.ui.mixin.IndicatorElement
2779 * @mixins OO.ui.mixin.LabelElement
2780 * @mixins OO.ui.mixin.TitledElement
2781 * @mixins OO.ui.mixin.FlaggedElement
2782 * @mixins OO.ui.mixin.TabIndexedElement
2785 * @param {Object} [config] Configuration options
2786 * @cfg {boolean} [value=false] The toggle button’s initial on/off
2787 * state. By default, the button is in the 'off' state.
2789 OO
.ui
.ToggleButtonWidget
= function OoUiToggleButtonWidget( config
) {
2790 // Configuration initialization
2791 config
= config
|| {};
2793 // Parent constructor
2794 OO
.ui
.ToggleButtonWidget
.parent
.call( this, config
);
2796 // Mixin constructors
2797 OO
.ui
.mixin
.ButtonElement
.call( this, $.extend( {}, config
, { active
: this.active
} ) );
2798 OO
.ui
.mixin
.IconElement
.call( this, config
);
2799 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
2800 OO
.ui
.mixin
.LabelElement
.call( this, config
);
2801 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
2802 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
2803 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
2806 this.connect( this, { click
: 'onAction' } );
2809 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
2811 .addClass( 'oo-ui-toggleButtonWidget' )
2812 .append( this.$button
);
2817 OO
.inheritClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.ToggleWidget
);
2818 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
2819 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.IconElement
);
2820 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
2821 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.LabelElement
);
2822 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.TitledElement
);
2823 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
2824 OO
.mixinClass( OO
.ui
.ToggleButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
2826 /* Static Properties */
2832 OO
.ui
.ToggleButtonWidget
.static.tagName
= 'span';
2837 * Handle the button action being triggered.
2841 OO
.ui
.ToggleButtonWidget
.prototype.onAction = function () {
2842 this.setValue( !this.value
);
2848 OO
.ui
.ToggleButtonWidget
.prototype.setValue = function ( value
) {
2850 if ( value
!== this.value
) {
2851 // Might be called from parent constructor before ButtonElement constructor
2852 if ( this.$button
) {
2853 this.$button
.attr( 'aria-pressed', value
.toString() );
2855 this.setActive( value
);
2859 OO
.ui
.ToggleButtonWidget
.parent
.prototype.setValue
.call( this, value
);
2867 OO
.ui
.ToggleButtonWidget
.prototype.setButtonElement = function ( $button
) {
2868 if ( this.$button
) {
2869 this.$button
.removeAttr( 'aria-pressed' );
2871 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement
.call( this, $button
);
2872 this.$button
.attr( 'aria-pressed', this.value
.toString() );
2876 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
2877 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
2878 * visually by a slider in the leftmost position.
2881 * // Toggle switches in the 'off' and 'on' position.
2882 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
2883 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
2887 * // Create a FieldsetLayout to layout and label switches
2888 * var fieldset = new OO.ui.FieldsetLayout( {
2889 * label: 'Toggle switches'
2891 * fieldset.addItems( [
2892 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
2893 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
2895 * $( 'body' ).append( fieldset.$element );
2898 * @extends OO.ui.ToggleWidget
2899 * @mixins OO.ui.mixin.TabIndexedElement
2902 * @param {Object} [config] Configuration options
2903 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
2904 * By default, the toggle switch is in the 'off' position.
2906 OO
.ui
.ToggleSwitchWidget
= function OoUiToggleSwitchWidget( config
) {
2907 // Parent constructor
2908 OO
.ui
.ToggleSwitchWidget
.parent
.call( this, config
);
2910 // Mixin constructors
2911 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
2914 this.dragging
= false;
2915 this.dragStart
= null;
2916 this.sliding
= false;
2917 this.$glow
= $( '<span>' );
2918 this.$grip
= $( '<span>' );
2922 click
: this.onClick
.bind( this ),
2923 keypress
: this.onKeyPress
.bind( this )
2927 this.$glow
.addClass( 'oo-ui-toggleSwitchWidget-glow' );
2928 this.$grip
.addClass( 'oo-ui-toggleSwitchWidget-grip' );
2930 .addClass( 'oo-ui-toggleSwitchWidget' )
2931 .attr( 'role', 'checkbox' )
2932 .append( this.$glow
, this.$grip
);
2937 OO
.inheritClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.ToggleWidget
);
2938 OO
.mixinClass( OO
.ui
.ToggleSwitchWidget
, OO
.ui
.mixin
.TabIndexedElement
);
2943 * Handle mouse click events.
2946 * @param {jQuery.Event} e Mouse click event
2948 OO
.ui
.ToggleSwitchWidget
.prototype.onClick = function ( e
) {
2949 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
2950 this.setValue( !this.value
);
2956 * Handle key press events.
2959 * @param {jQuery.Event} e Key press event
2961 OO
.ui
.ToggleSwitchWidget
.prototype.onKeyPress = function ( e
) {
2962 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
2963 this.setValue( !this.value
);
2969 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
2970 * Controls include moving items up and down, removing items, and adding different kinds of items.
2972 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
2975 * @extends OO.ui.Widget
2976 * @mixins OO.ui.mixin.GroupElement
2977 * @mixins OO.ui.mixin.IconElement
2980 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
2981 * @param {Object} [config] Configuration options
2982 * @cfg {Object} [abilities] List of abilties
2983 * @cfg {boolean} [abilities.move=true] Allow moving movable items
2984 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
2986 OO
.ui
.OutlineControlsWidget
= function OoUiOutlineControlsWidget( outline
, config
) {
2987 // Allow passing positional parameters inside the config object
2988 if ( OO
.isPlainObject( outline
) && config
=== undefined ) {
2990 outline
= config
.outline
;
2993 // Configuration initialization
2994 config
= $.extend( { icon
: 'add' }, config
);
2996 // Parent constructor
2997 OO
.ui
.OutlineControlsWidget
.parent
.call( this, config
);
2999 // Mixin constructors
3000 OO
.ui
.mixin
.GroupElement
.call( this, config
);
3001 OO
.ui
.mixin
.IconElement
.call( this, config
);
3004 this.outline
= outline
;
3005 this.$movers
= $( '<div>' );
3006 this.upButton
= new OO
.ui
.ButtonWidget( {
3009 title
: OO
.ui
.msg( 'ooui-outline-control-move-up' )
3011 this.downButton
= new OO
.ui
.ButtonWidget( {
3014 title
: OO
.ui
.msg( 'ooui-outline-control-move-down' )
3016 this.removeButton
= new OO
.ui
.ButtonWidget( {
3019 title
: OO
.ui
.msg( 'ooui-outline-control-remove' )
3021 this.abilities
= { move: true, remove
: true };
3024 outline
.connect( this, {
3025 select
: 'onOutlineChange',
3026 add
: 'onOutlineChange',
3027 remove
: 'onOutlineChange'
3029 this.upButton
.connect( this, { click
: [ 'emit', 'move', -1 ] } );
3030 this.downButton
.connect( this, { click
: [ 'emit', 'move', 1 ] } );
3031 this.removeButton
.connect( this, { click
: [ 'emit', 'remove' ] } );
3034 this.$element
.addClass( 'oo-ui-outlineControlsWidget' );
3035 this.$group
.addClass( 'oo-ui-outlineControlsWidget-items' );
3037 .addClass( 'oo-ui-outlineControlsWidget-movers' )
3038 .append( this.removeButton
.$element
, this.upButton
.$element
, this.downButton
.$element
);
3039 this.$element
.append( this.$icon
, this.$group
, this.$movers
);
3040 this.setAbilities( config
.abilities
|| {} );
3045 OO
.inheritClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.Widget
);
3046 OO
.mixinClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.mixin
.GroupElement
);
3047 OO
.mixinClass( OO
.ui
.OutlineControlsWidget
, OO
.ui
.mixin
.IconElement
);
3053 * @param {number} places Number of places to move
3065 * @param {Object} abilities List of abilties
3066 * @param {boolean} [abilities.move] Allow moving movable items
3067 * @param {boolean} [abilities.remove] Allow removing removable items
3069 OO
.ui
.OutlineControlsWidget
.prototype.setAbilities = function ( abilities
) {
3072 for ( ability
in this.abilities
) {
3073 if ( abilities
[ ability
] !== undefined ) {
3074 this.abilities
[ ability
] = !!abilities
[ ability
];
3078 this.onOutlineChange();
3082 * Handle outline change events.
3086 OO
.ui
.OutlineControlsWidget
.prototype.onOutlineChange = function () {
3087 var i
, len
, firstMovable
, lastMovable
,
3088 items
= this.outline
.getItems(),
3089 selectedItem
= this.outline
.getSelectedItem(),
3090 movable
= this.abilities
.move && selectedItem
&& selectedItem
.isMovable(),
3091 removable
= this.abilities
.remove
&& selectedItem
&& selectedItem
.isRemovable();
3096 while ( ++i
< len
) {
3097 if ( items
[ i
].isMovable() ) {
3098 firstMovable
= items
[ i
];
3104 if ( items
[ i
].isMovable() ) {
3105 lastMovable
= items
[ i
];
3110 this.upButton
.setDisabled( !movable
|| selectedItem
=== firstMovable
);
3111 this.downButton
.setDisabled( !movable
|| selectedItem
=== lastMovable
);
3112 this.removeButton
.setDisabled( !removable
);
3116 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
3118 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
3119 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
3123 * @extends OO.ui.DecoratedOptionWidget
3126 * @param {Object} [config] Configuration options
3127 * @cfg {number} [level] Indentation level
3128 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
3130 OO
.ui
.OutlineOptionWidget
= function OoUiOutlineOptionWidget( config
) {
3131 // Configuration initialization
3132 config
= config
|| {};
3134 // Parent constructor
3135 OO
.ui
.OutlineOptionWidget
.parent
.call( this, config
);
3139 this.movable
= !!config
.movable
;
3140 this.removable
= !!config
.removable
;
3143 this.$element
.addClass( 'oo-ui-outlineOptionWidget' );
3144 this.setLevel( config
.level
);
3149 OO
.inheritClass( OO
.ui
.OutlineOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
3151 /* Static Properties */
3157 OO
.ui
.OutlineOptionWidget
.static.highlightable
= true;
3163 OO
.ui
.OutlineOptionWidget
.static.scrollIntoViewOnSelect
= true;
3168 * @property {string}
3170 OO
.ui
.OutlineOptionWidget
.static.levelClass
= 'oo-ui-outlineOptionWidget-level-';
3175 * @property {number}
3177 OO
.ui
.OutlineOptionWidget
.static.levels
= 3;
3182 * Check if item is movable.
3184 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
3186 * @return {boolean} Item is movable
3188 OO
.ui
.OutlineOptionWidget
.prototype.isMovable = function () {
3189 return this.movable
;
3193 * Check if item is removable.
3195 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
3197 * @return {boolean} Item is removable
3199 OO
.ui
.OutlineOptionWidget
.prototype.isRemovable = function () {
3200 return this.removable
;
3204 * Get indentation level.
3206 * @return {number} Indentation level
3208 OO
.ui
.OutlineOptionWidget
.prototype.getLevel = function () {
3215 OO
.ui
.OutlineOptionWidget
.prototype.setPressed = function ( state
) {
3216 OO
.ui
.OutlineOptionWidget
.parent
.prototype.setPressed
.call( this, state
);
3217 if ( this.pressed
) {
3218 this.setFlags( { progressive
: true } );
3219 } else if ( !this.selected
) {
3220 this.setFlags( { progressive
: false } );
3228 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
3230 * @param {boolean} movable Item is movable
3233 OO
.ui
.OutlineOptionWidget
.prototype.setMovable = function ( movable
) {
3234 this.movable
= !!movable
;
3235 this.updateThemeClasses();
3242 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
3244 * @param {boolean} removable Item is removable
3247 OO
.ui
.OutlineOptionWidget
.prototype.setRemovable = function ( removable
) {
3248 this.removable
= !!removable
;
3249 this.updateThemeClasses();
3256 OO
.ui
.OutlineOptionWidget
.prototype.setSelected = function ( state
) {
3257 OO
.ui
.OutlineOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
3258 if ( this.selected
) {
3259 this.setFlags( { progressive
: true } );
3261 this.setFlags( { progressive
: false } );
3267 * Set indentation level.
3269 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
3272 OO
.ui
.OutlineOptionWidget
.prototype.setLevel = function ( level
) {
3273 var levels
= this.constructor.static.levels
,
3274 levelClass
= this.constructor.static.levelClass
,
3277 this.level
= level
? Math
.max( 0, Math
.min( levels
- 1, level
) ) : 0;
3279 if ( this.level
=== i
) {
3280 this.$element
.addClass( levelClass
+ i
);
3282 this.$element
.removeClass( levelClass
+ i
);
3285 this.updateThemeClasses();
3291 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
3292 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
3294 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
3297 * @extends OO.ui.SelectWidget
3298 * @mixins OO.ui.mixin.TabIndexedElement
3301 * @param {Object} [config] Configuration options
3303 OO
.ui
.OutlineSelectWidget
= function OoUiOutlineSelectWidget( config
) {
3304 // Parent constructor
3305 OO
.ui
.OutlineSelectWidget
.parent
.call( this, config
);
3307 // Mixin constructors
3308 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
3312 focus
: this.bindKeyDownListener
.bind( this ),
3313 blur
: this.unbindKeyDownListener
.bind( this )
3317 this.$element
.addClass( 'oo-ui-outlineSelectWidget' );
3322 OO
.inheritClass( OO
.ui
.OutlineSelectWidget
, OO
.ui
.SelectWidget
);
3323 OO
.mixinClass( OO
.ui
.OutlineSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
3326 * ButtonOptionWidget is a special type of {@link OO.ui.mixin.ButtonElement button element} that
3327 * can be selected and configured with data. The class is
3328 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
3329 * [OOjs UI documentation on MediaWiki] [1] for more information.
3331 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
3334 * @extends OO.ui.OptionWidget
3335 * @mixins OO.ui.mixin.ButtonElement
3336 * @mixins OO.ui.mixin.IconElement
3337 * @mixins OO.ui.mixin.IndicatorElement
3338 * @mixins OO.ui.mixin.TitledElement
3341 * @param {Object} [config] Configuration options
3343 OO
.ui
.ButtonOptionWidget
= function OoUiButtonOptionWidget( config
) {
3344 // Configuration initialization
3345 config
= config
|| {};
3347 // Parent constructor
3348 OO
.ui
.ButtonOptionWidget
.parent
.call( this, config
);
3350 // Mixin constructors
3351 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
3352 OO
.ui
.mixin
.IconElement
.call( this, config
);
3353 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
3354 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
3357 this.$element
.addClass( 'oo-ui-buttonOptionWidget' );
3358 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
3359 this.$element
.append( this.$button
);
3364 OO
.inheritClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.OptionWidget
);
3365 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.mixin
.ButtonElement
);
3366 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.mixin
.IconElement
);
3367 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.mixin
.IndicatorElement
);
3368 OO
.mixinClass( OO
.ui
.ButtonOptionWidget
, OO
.ui
.mixin
.TitledElement
);
3370 /* Static Properties */
3373 * Allow button mouse down events to pass through so they can be handled by the parent select widget
3378 OO
.ui
.ButtonOptionWidget
.static.cancelButtonMouseDownEvents
= false;
3384 OO
.ui
.ButtonOptionWidget
.static.highlightable
= false;
3391 OO
.ui
.ButtonOptionWidget
.prototype.setSelected = function ( state
) {
3392 OO
.ui
.ButtonOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
3394 if ( this.constructor.static.selectable
) {
3395 this.setActive( state
);
3402 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
3403 * button options and is used together with
3404 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
3405 * highlighting, choosing, and selecting mutually exclusive options. Please see
3406 * the [OOjs UI documentation on MediaWiki] [1] for more information.
3409 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
3410 * var option1 = new OO.ui.ButtonOptionWidget( {
3412 * label: 'Option 1',
3413 * title: 'Button option 1'
3416 * var option2 = new OO.ui.ButtonOptionWidget( {
3418 * label: 'Option 2',
3419 * title: 'Button option 2'
3422 * var option3 = new OO.ui.ButtonOptionWidget( {
3424 * label: 'Option 3',
3425 * title: 'Button option 3'
3428 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
3429 * items: [ option1, option2, option3 ]
3431 * $( 'body' ).append( buttonSelect.$element );
3433 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
3436 * @extends OO.ui.SelectWidget
3437 * @mixins OO.ui.mixin.TabIndexedElement
3440 * @param {Object} [config] Configuration options
3442 OO
.ui
.ButtonSelectWidget
= function OoUiButtonSelectWidget( config
) {
3443 // Parent constructor
3444 OO
.ui
.ButtonSelectWidget
.parent
.call( this, config
);
3446 // Mixin constructors
3447 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
3451 focus
: this.bindKeyDownListener
.bind( this ),
3452 blur
: this.unbindKeyDownListener
.bind( this )
3456 this.$element
.addClass( 'oo-ui-buttonSelectWidget' );
3461 OO
.inheritClass( OO
.ui
.ButtonSelectWidget
, OO
.ui
.SelectWidget
);
3462 OO
.mixinClass( OO
.ui
.ButtonSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
3465 * TabOptionWidget is an item in a {@link OO.ui.TabSelectWidget TabSelectWidget}.
3467 * Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}, which contain
3468 * {@link OO.ui.CardLayout card layouts}. See {@link OO.ui.IndexLayout IndexLayout}
3472 * @extends OO.ui.OptionWidget
3475 * @param {Object} [config] Configuration options
3477 OO
.ui
.TabOptionWidget
= function OoUiTabOptionWidget( config
) {
3478 // Configuration initialization
3479 config
= config
|| {};
3481 // Parent constructor
3482 OO
.ui
.TabOptionWidget
.parent
.call( this, config
);
3485 this.$element
.addClass( 'oo-ui-tabOptionWidget' );
3490 OO
.inheritClass( OO
.ui
.TabOptionWidget
, OO
.ui
.OptionWidget
);
3492 /* Static Properties */
3498 OO
.ui
.TabOptionWidget
.static.highlightable
= false;
3501 * TabSelectWidget is a list that contains {@link OO.ui.TabOptionWidget tab options}
3503 * **Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}.**
3506 * @extends OO.ui.SelectWidget
3507 * @mixins OO.ui.mixin.TabIndexedElement
3510 * @param {Object} [config] Configuration options
3512 OO
.ui
.TabSelectWidget
= function OoUiTabSelectWidget( config
) {
3513 // Parent constructor
3514 OO
.ui
.TabSelectWidget
.parent
.call( this, config
);
3516 // Mixin constructors
3517 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
3521 focus
: this.bindKeyDownListener
.bind( this ),
3522 blur
: this.unbindKeyDownListener
.bind( this )
3526 this.$element
.addClass( 'oo-ui-tabSelectWidget' );
3531 OO
.inheritClass( OO
.ui
.TabSelectWidget
, OO
.ui
.SelectWidget
);
3532 OO
.mixinClass( OO
.ui
.TabSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
3535 * CapsuleItemWidgets are used within a {@link OO.ui.CapsuleMultiselectWidget
3536 * CapsuleMultiselectWidget} to display the selected items.
3539 * @extends OO.ui.Widget
3540 * @mixins OO.ui.mixin.ItemWidget
3541 * @mixins OO.ui.mixin.LabelElement
3542 * @mixins OO.ui.mixin.FlaggedElement
3543 * @mixins OO.ui.mixin.TabIndexedElement
3546 * @param {Object} [config] Configuration options
3548 OO
.ui
.CapsuleItemWidget
= function OoUiCapsuleItemWidget( config
) {
3549 // Configuration initialization
3550 config
= config
|| {};
3552 // Parent constructor
3553 OO
.ui
.CapsuleItemWidget
.parent
.call( this, config
);
3555 // Mixin constructors
3556 OO
.ui
.mixin
.ItemWidget
.call( this );
3557 OO
.ui
.mixin
.LabelElement
.call( this, config
);
3558 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
3559 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
3562 this.closeButton
= new OO
.ui
.ButtonWidget( {
3566 } ).on( 'click', this.onCloseClick
.bind( this ) );
3568 this.on( 'disable', function ( disabled
) {
3569 this.closeButton
.setDisabled( disabled
);
3575 click
: this.onClick
.bind( this ),
3576 keydown
: this.onKeyDown
.bind( this )
3578 .addClass( 'oo-ui-capsuleItemWidget' )
3579 .append( this.$label
, this.closeButton
.$element
);
3584 OO
.inheritClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.Widget
);
3585 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.ItemWidget
);
3586 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.LabelElement
);
3587 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.FlaggedElement
);
3588 OO
.mixinClass( OO
.ui
.CapsuleItemWidget
, OO
.ui
.mixin
.TabIndexedElement
);
3593 * Handle close icon clicks
3595 OO
.ui
.CapsuleItemWidget
.prototype.onCloseClick = function () {
3596 var element
= this.getElementGroup();
3598 if ( element
&& $.isFunction( element
.removeItems
) ) {
3599 element
.removeItems( [ this ] );
3605 * Handle click event for the entire capsule
3607 OO
.ui
.CapsuleItemWidget
.prototype.onClick = function () {
3608 var element
= this.getElementGroup();
3610 if ( !this.isDisabled() && element
&& $.isFunction( element
.editItem
) ) {
3611 element
.editItem( this );
3616 * Handle keyDown event for the entire capsule
3618 * @param {jQuery.Event} e Key down event
3620 OO
.ui
.CapsuleItemWidget
.prototype.onKeyDown = function ( e
) {
3621 var element
= this.getElementGroup();
3623 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
|| e
.keyCode
=== OO
.ui
.Keys
.DELETE
) {
3624 element
.removeItems( [ this ] );
3627 } else if ( e
.keyCode
=== OO
.ui
.Keys
.ENTER
) {
3628 element
.editItem( this );
3630 } else if ( e
.keyCode
=== OO
.ui
.Keys
.LEFT
) {
3631 element
.getPreviousItem( this ).focus();
3632 } else if ( e
.keyCode
=== OO
.ui
.Keys
.RIGHT
) {
3633 element
.getNextItem( this ).focus();
3638 * Focuses the capsule
3640 OO
.ui
.CapsuleItemWidget
.prototype.focus = function () {
3641 this.$element
.focus();
3645 * CapsuleMultiselectWidgets are something like a {@link OO.ui.ComboBoxInputWidget combo box widget}
3646 * that allows for selecting multiple values.
3648 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
3651 * // Example: A CapsuleMultiselectWidget.
3652 * var capsule = new OO.ui.CapsuleMultiselectWidget( {
3653 * label: 'CapsuleMultiselectWidget',
3654 * selected: [ 'Option 1', 'Option 3' ],
3657 * new OO.ui.MenuOptionWidget( {
3659 * label: 'Option One'
3661 * new OO.ui.MenuOptionWidget( {
3663 * label: 'Option Two'
3665 * new OO.ui.MenuOptionWidget( {
3667 * label: 'Option Three'
3669 * new OO.ui.MenuOptionWidget( {
3671 * label: 'Option Four'
3673 * new OO.ui.MenuOptionWidget( {
3675 * label: 'Option Five'
3680 * $( 'body' ).append( capsule.$element );
3682 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
3685 * @extends OO.ui.Widget
3686 * @mixins OO.ui.mixin.GroupElement
3687 * @mixins OO.ui.mixin.PopupElement
3688 * @mixins OO.ui.mixin.TabIndexedElement
3689 * @mixins OO.ui.mixin.IndicatorElement
3690 * @mixins OO.ui.mixin.IconElement
3691 * @uses OO.ui.CapsuleItemWidget
3692 * @uses OO.ui.FloatingMenuSelectWidget
3695 * @param {Object} [config] Configuration options
3696 * @cfg {string} [placeholder] Placeholder text
3697 * @cfg {boolean} [allowArbitrary=false] Allow data items to be added even if not present in the menu.
3698 * @cfg {boolean} [allowDuplicates=false] Allow duplicate items to be added.
3699 * @cfg {Object} [menu] (required) Configuration options to pass to the
3700 * {@link OO.ui.MenuSelectWidget menu select widget}.
3701 * @cfg {Object} [popup] Configuration options to pass to the {@link OO.ui.PopupWidget popup widget}.
3702 * If specified, this popup will be shown instead of the menu (but the menu
3703 * will still be used for item labels and allowArbitrary=false). The widgets
3704 * in the popup should use {@link #addItemsFromData} or {@link #addItems} as necessary.
3705 * @cfg {jQuery} [$overlay=this.$element] Render the menu or popup into a separate layer.
3706 * This configuration is useful in cases where the expanded menu is larger than
3707 * its containing `<div>`. The specified overlay layer is usually on top of
3708 * the containing `<div>` and has a larger area. By default, the menu uses
3709 * relative positioning.
3710 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
3712 OO
.ui
.CapsuleMultiselectWidget
= function OoUiCapsuleMultiselectWidget( config
) {
3715 // Parent constructor
3716 OO
.ui
.CapsuleMultiselectWidget
.parent
.call( this, config
);
3718 // Configuration initialization
3719 config
= $.extend( {
3720 allowArbitrary
: false,
3721 allowDuplicates
: false,
3722 $overlay
: this.$element
3725 // Properties (must be set before mixin constructor calls)
3726 this.$handle
= $( '<div>' );
3727 this.$input
= config
.popup
? null : $( '<input>' );
3728 if ( config
.placeholder
!== undefined && config
.placeholder
!== '' ) {
3729 this.$input
.attr( 'placeholder', config
.placeholder
);
3732 // Mixin constructors
3733 OO
.ui
.mixin
.GroupElement
.call( this, config
);
3734 if ( config
.popup
) {
3735 config
.popup
= $.extend( {}, config
.popup
, {
3739 OO
.ui
.mixin
.PopupElement
.call( this, config
);
3740 $tabFocus
= $( '<span>' );
3741 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: $tabFocus
} ) );
3745 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
3747 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
3748 OO
.ui
.mixin
.IconElement
.call( this, config
);
3751 this.$content
= $( '<div>' );
3752 this.allowArbitrary
= config
.allowArbitrary
;
3753 this.allowDuplicates
= config
.allowDuplicates
;
3754 this.$overlay
= config
.$overlay
;
3755 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend(
3758 $input
: this.$input
,
3759 $container
: this.$element
,
3760 filterFromInput
: true,
3761 disabled
: this.isDisabled()
3769 focus
: this.focus
.bind( this )
3771 this.popup
.$element
.on( 'focusout', this.onPopupFocusOut
.bind( this ) );
3772 if ( this.popup
.$autoCloseIgnore
) {
3773 this.popup
.$autoCloseIgnore
.on( 'focusout', this.onPopupFocusOut
.bind( this ) );
3775 this.popup
.connect( this, {
3776 toggle: function ( visible
) {
3777 $tabFocus
.toggle( !visible
);
3782 focus
: this.onInputFocus
.bind( this ),
3783 blur
: this.onInputBlur
.bind( this ),
3784 'propertychange change click mouseup keydown keyup input cut paste select focus':
3785 OO
.ui
.debounce( this.updateInputSize
.bind( this ) ),
3786 keydown
: this.onKeyDown
.bind( this ),
3787 keypress
: this.onKeyPress
.bind( this )
3790 this.menu
.connect( this, {
3791 choose
: 'onMenuChoose',
3792 toggle
: 'onMenuToggle',
3793 add
: 'onMenuItemsChange',
3794 remove
: 'onMenuItemsChange'
3797 mousedown
: this.onMouseDown
.bind( this )
3801 if ( this.$input
) {
3802 this.$input
.prop( 'disabled', this.isDisabled() );
3805 'aria-owns': this.menu
.getElementId(),
3806 'aria-autocomplete': 'list'
3809 if ( config
.data
) {
3810 this.setItemsFromData( config
.data
);
3812 this.$content
.addClass( 'oo-ui-capsuleMultiselectWidget-content' )
3813 .append( this.$group
);
3814 this.$group
.addClass( 'oo-ui-capsuleMultiselectWidget-group' );
3815 this.$handle
.addClass( 'oo-ui-capsuleMultiselectWidget-handle' )
3816 .append( this.$indicator
, this.$icon
, this.$content
);
3817 this.$element
.addClass( 'oo-ui-capsuleMultiselectWidget' )
3818 .append( this.$handle
);
3820 this.popup
.$element
.addClass( 'oo-ui-capsuleMultiselectWidget-popup' );
3821 this.$content
.append( $tabFocus
);
3822 this.$overlay
.append( this.popup
.$element
);
3824 this.$content
.append( this.$input
);
3825 this.$overlay
.append( this.menu
.$element
);
3828 $tabFocus
.addClass( 'oo-ui-capsuleMultiselectWidget-focusTrap' );
3831 // Input size needs to be calculated after everything else is rendered
3832 setTimeout( function () {
3833 if ( this.$input
) {
3834 this.updateInputSize();
3838 this.onMenuItemsChange();
3843 OO
.inheritClass( OO
.ui
.CapsuleMultiselectWidget
, OO
.ui
.Widget
);
3844 OO
.mixinClass( OO
.ui
.CapsuleMultiselectWidget
, OO
.ui
.mixin
.GroupElement
);
3845 OO
.mixinClass( OO
.ui
.CapsuleMultiselectWidget
, OO
.ui
.mixin
.PopupElement
);
3846 OO
.mixinClass( OO
.ui
.CapsuleMultiselectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
3847 OO
.mixinClass( OO
.ui
.CapsuleMultiselectWidget
, OO
.ui
.mixin
.IndicatorElement
);
3848 OO
.mixinClass( OO
.ui
.CapsuleMultiselectWidget
, OO
.ui
.mixin
.IconElement
);
3850 /* Static Properties */
3852 OO
.ui
.CapsuleMultiselectWidget
.static.supportsSimpleLabel
= true;
3859 * A change event is emitted when the set of selected items changes.
3861 * @param {Mixed[]} datas Data of the now-selected items
3867 * A resize event is emitted when the widget's dimensions change to accomodate newly added items or
3868 * current user input.
3874 * Construct a OO.ui.CapsuleItemWidget (or a subclass thereof) from given label and data.
3875 * May return `null` if the given label and data are not valid.
3878 * @param {Mixed} data Custom data of any type.
3879 * @param {string} label The label text.
3880 * @return {OO.ui.CapsuleItemWidget|null}
3882 OO
.ui
.CapsuleMultiselectWidget
.prototype.createItemWidget = function ( data
, label
) {
3883 if ( label
=== '' ) {
3886 return new OO
.ui
.CapsuleItemWidget( { data
: data
, label
: label
} );
3890 * Get the widget's input's id, or generate one, if it has an input.
3894 OO
.ui
.CapsuleMultiselectWidget
.prototype.getInputId = function () {
3896 if ( !this.$input
) {
3900 id
= this.$input
.attr( 'id' );
3901 if ( id
=== undefined ) {
3902 id
= OO
.ui
.generateElementId();
3903 this.$input
.attr( 'id', id
);
3910 * Get the data of the items in the capsule
3914 OO
.ui
.CapsuleMultiselectWidget
.prototype.getItemsData = function () {
3915 return this.getItems().map( function ( item
) {
3921 * Set the items in the capsule by providing data
3924 * @param {Mixed[]} datas
3925 * @return {OO.ui.CapsuleMultiselectWidget}
3927 OO
.ui
.CapsuleMultiselectWidget
.prototype.setItemsFromData = function ( datas
) {
3930 items
= this.getItems();
3932 $.each( datas
, function ( i
, data
) {
3934 item
= menu
.getItemFromData( data
);
3938 } else if ( widget
.allowArbitrary
) {
3939 label
= String( data
);
3945 for ( j
= 0; j
< items
.length
; j
++ ) {
3946 if ( items
[ j
].data
=== data
&& items
[ j
].label
=== label
) {
3948 items
.splice( j
, 1 );
3953 item
= widget
.createItemWidget( data
, label
);
3956 widget
.addItems( [ item
], i
);
3960 if ( items
.length
) {
3961 widget
.removeItems( items
);
3968 * Add items to the capsule by providing their data
3971 * @param {Mixed[]} datas
3972 * @return {OO.ui.CapsuleMultiselectWidget}
3974 OO
.ui
.CapsuleMultiselectWidget
.prototype.addItemsFromData = function ( datas
) {
3979 $.each( datas
, function ( i
, data
) {
3982 if ( !widget
.getItemFromData( data
) || widget
.allowDuplicates
) {
3983 item
= menu
.getItemFromData( data
);
3985 item
= widget
.createItemWidget( data
, item
.label
);
3986 } else if ( widget
.allowArbitrary
) {
3987 item
= widget
.createItemWidget( data
, String( data
) );
3995 if ( items
.length
) {
3996 this.addItems( items
);
4003 * Add items to the capsule by providing a label
4005 * @param {string} label
4006 * @return {boolean} Whether the item was added or not
4008 OO
.ui
.CapsuleMultiselectWidget
.prototype.addItemFromLabel = function ( label
) {
4010 item
= this.menu
.getItemFromLabel( label
, true );
4012 this.addItemsFromData( [ item
.data
] );
4014 } else if ( this.allowArbitrary
) {
4015 items
= this.getItems();
4016 this.addItemsFromData( [ label
] );
4017 return !OO
.compare( this.getItems(), items
);
4023 * Remove items by data
4026 * @param {Mixed[]} datas
4027 * @return {OO.ui.CapsuleMultiselectWidget}
4029 OO
.ui
.CapsuleMultiselectWidget
.prototype.removeItemsFromData = function ( datas
) {
4033 $.each( datas
, function ( i
, data
) {
4034 var item
= widget
.getItemFromData( data
);
4040 if ( items
.length
) {
4041 this.removeItems( items
);
4050 OO
.ui
.CapsuleMultiselectWidget
.prototype.addItems = function ( items
) {
4052 oldItems
= this.items
.slice();
4054 OO
.ui
.mixin
.GroupElement
.prototype.addItems
.call( this, items
);
4056 if ( this.items
.length
!== oldItems
.length
) {
4060 for ( i
= 0, l
= oldItems
.length
; same
&& i
< l
; i
++ ) {
4061 same
= same
&& this.items
[ i
] === oldItems
[ i
];
4065 this.emit( 'change', this.getItemsData() );
4066 this.updateInputSize();
4073 * Removes the item from the list and copies its label to `this.$input`.
4075 * @param {Object} item
4077 OO
.ui
.CapsuleMultiselectWidget
.prototype.editItem = function ( item
) {
4078 this.addItemFromLabel( this.$input
.val() );
4080 this.$input
.val( item
.label
);
4081 this.updateInputSize();
4083 this.menu
.updateItemVisibility(); // Hack, we shouldn't be calling this method directly
4084 this.removeItems( [ item
] );
4090 OO
.ui
.CapsuleMultiselectWidget
.prototype.removeItems = function ( items
) {
4092 oldItems
= this.items
.slice();
4094 OO
.ui
.mixin
.GroupElement
.prototype.removeItems
.call( this, items
);
4096 if ( this.items
.length
!== oldItems
.length
) {
4100 for ( i
= 0, l
= oldItems
.length
; same
&& i
< l
; i
++ ) {
4101 same
= same
&& this.items
[ i
] === oldItems
[ i
];
4105 this.emit( 'change', this.getItemsData() );
4106 this.updateInputSize();
4115 OO
.ui
.CapsuleMultiselectWidget
.prototype.clearItems = function () {
4116 if ( this.items
.length
) {
4117 OO
.ui
.mixin
.GroupElement
.prototype.clearItems
.call( this );
4118 this.emit( 'change', this.getItemsData() );
4119 this.updateInputSize();
4125 * Given an item, returns the item after it. If its the last item,
4126 * returns `this.$input`. If no item is passed, returns the very first
4129 * @param {OO.ui.CapsuleItemWidget} [item]
4130 * @return {OO.ui.CapsuleItemWidget|jQuery|boolean}
4132 OO
.ui
.CapsuleMultiselectWidget
.prototype.getNextItem = function ( item
) {
4135 if ( item
=== undefined ) {
4136 return this.items
[ 0 ];
4139 itemIndex
= this.items
.indexOf( item
);
4140 if ( itemIndex
< 0 ) { // Item not in list
4142 } else if ( itemIndex
=== this.items
.length
- 1 ) { // Last item
4145 return this.items
[ itemIndex
+ 1 ];
4150 * Given an item, returns the item before it. If its the first item,
4151 * returns `this.$input`. If no item is passed, returns the very last
4154 * @param {OO.ui.CapsuleItemWidget} [item]
4155 * @return {OO.ui.CapsuleItemWidget|jQuery|boolean}
4157 OO
.ui
.CapsuleMultiselectWidget
.prototype.getPreviousItem = function ( item
) {
4160 if ( item
=== undefined ) {
4161 return this.items
[ this.items
.length
- 1 ];
4164 itemIndex
= this.items
.indexOf( item
);
4165 if ( itemIndex
< 0 ) { // Item not in list
4167 } else if ( itemIndex
=== 0 ) { // First item
4170 return this.items
[ itemIndex
- 1 ];
4175 * Get the capsule widget's menu.
4177 * @return {OO.ui.MenuSelectWidget} Menu widget
4179 OO
.ui
.CapsuleMultiselectWidget
.prototype.getMenu = function () {
4184 * Handle focus events
4187 * @param {jQuery.Event} event
4189 OO
.ui
.CapsuleMultiselectWidget
.prototype.onInputFocus = function () {
4190 if ( !this.isDisabled() ) {
4191 this.menu
.toggle( true );
4196 * Handle blur events
4199 * @param {jQuery.Event} event
4201 OO
.ui
.CapsuleMultiselectWidget
.prototype.onInputBlur = function () {
4202 this.addItemFromLabel( this.$input
.val() );
4207 * Handles popup focus out events.
4210 * @param {jQuery.Event} e Focus out event
4212 OO
.ui
.CapsuleMultiselectWidget
.prototype.onPopupFocusOut = function () {
4213 var widget
= this.popup
;
4215 setTimeout( function () {
4217 widget
.isVisible() &&
4218 !OO
.ui
.contains( widget
.$element
.add( widget
.$autoCloseIgnore
).get(), document
.activeElement
, true )
4220 widget
.toggle( false );
4226 * Handle mouse down events.
4229 * @param {jQuery.Event} e Mouse down event
4231 OO
.ui
.CapsuleMultiselectWidget
.prototype.onMouseDown = function ( e
) {
4232 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
4236 this.updateInputSize();
4241 * Handle key press events.
4244 * @param {jQuery.Event} e Key press event
4246 OO
.ui
.CapsuleMultiselectWidget
.prototype.onKeyPress = function ( e
) {
4247 if ( !this.isDisabled() ) {
4248 if ( e
.which
=== OO
.ui
.Keys
.ESCAPE
) {
4253 if ( !this.popup
) {
4254 this.menu
.toggle( true );
4255 if ( e
.which
=== OO
.ui
.Keys
.ENTER
) {
4256 if ( this.addItemFromLabel( this.$input
.val() ) ) {
4262 // Make sure the input gets resized.
4263 setTimeout( this.updateInputSize
.bind( this ), 0 );
4269 * Handle key down events.
4272 * @param {jQuery.Event} e Key down event
4274 OO
.ui
.CapsuleMultiselectWidget
.prototype.onKeyDown = function ( e
) {
4276 !this.isDisabled() &&
4277 this.$input
.val() === '' &&
4280 // 'keypress' event is not triggered for Backspace
4281 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
) {
4282 if ( e
.metaKey
|| e
.ctrlKey
) {
4283 this.removeItems( this.items
.slice( -1 ) );
4285 this.editItem( this.items
[ this.items
.length
- 1 ] );
4288 } else if ( e
.keyCode
=== OO
.ui
.Keys
.LEFT
) {
4289 this.getPreviousItem().focus();
4290 } else if ( e
.keyCode
=== OO
.ui
.Keys
.RIGHT
) {
4291 this.getNextItem().focus();
4297 * Update the dimensions of the text input field to encompass all available area.
4300 * @param {jQuery.Event} e Event of some sort
4302 OO
.ui
.CapsuleMultiselectWidget
.prototype.updateInputSize = function () {
4303 var $lastItem
, direction
, contentWidth
, currentWidth
, bestWidth
;
4304 if ( this.$input
&& !this.isDisabled() ) {
4305 this.$input
.css( 'width', '1em' );
4306 $lastItem
= this.$group
.children().last();
4307 direction
= OO
.ui
.Element
.static.getDir( this.$handle
);
4309 // Get the width of the input with the placeholder text as
4310 // the value and save it so that we don't keep recalculating
4312 this.contentWidthWithPlaceholder
=== undefined &&
4313 this.$input
.val() === '' &&
4314 this.$input
.attr( 'placeholder' ) !== undefined
4316 this.$input
.val( this.$input
.attr( 'placeholder' ) );
4317 this.contentWidthWithPlaceholder
= this.$input
[ 0 ].scrollWidth
;
4318 this.$input
.val( '' );
4322 // Always keep the input wide enough for the placeholder text
4323 contentWidth
= Math
.max(
4324 this.$input
[ 0 ].scrollWidth
,
4325 // undefined arguments in Math.max lead to NaN
4326 ( this.contentWidthWithPlaceholder
=== undefined ) ?
4327 0 : this.contentWidthWithPlaceholder
4329 currentWidth
= this.$input
.width();
4331 if ( contentWidth
< currentWidth
) {
4332 this.updateIfHeightChanged();
4333 // All is fine, don't perform expensive calculations
4337 if ( $lastItem
.length
=== 0 ) {
4338 bestWidth
= this.$content
.innerWidth();
4340 bestWidth
= direction
=== 'ltr' ?
4341 this.$content
.innerWidth() - $lastItem
.position().left
- $lastItem
.outerWidth() :
4342 $lastItem
.position().left
;
4345 // Some safety margin for sanity, because I *really* don't feel like finding out where the few
4346 // pixels this is off by are coming from.
4348 if ( contentWidth
> bestWidth
) {
4349 // This will result in the input getting shifted to the next line
4350 bestWidth
= this.$content
.innerWidth() - 10;
4352 this.$input
.width( Math
.floor( bestWidth
) );
4353 this.updateIfHeightChanged();
4355 this.updateIfHeightChanged();
4360 * Determine if widget height changed, and if so, update menu position and emit 'resize' event.
4364 OO
.ui
.CapsuleMultiselectWidget
.prototype.updateIfHeightChanged = function () {
4365 var height
= this.$element
.height();
4366 if ( height
!== this.height
) {
4367 this.height
= height
;
4368 this.menu
.position();
4370 this.popup
.updateDimensions();
4372 this.emit( 'resize' );
4377 * Handle menu choose events.
4380 * @param {OO.ui.OptionWidget} item Chosen item
4382 OO
.ui
.CapsuleMultiselectWidget
.prototype.onMenuChoose = function ( item
) {
4383 if ( item
&& item
.isVisible() ) {
4384 this.addItemsFromData( [ item
.getData() ] );
4390 * Handle menu toggle events.
4393 * @param {boolean} isVisible Menu toggle event
4395 OO
.ui
.CapsuleMultiselectWidget
.prototype.onMenuToggle = function ( isVisible
) {
4396 this.$element
.toggleClass( 'oo-ui-capsuleMultiselectWidget-open', isVisible
);
4400 * Handle menu item change events.
4404 OO
.ui
.CapsuleMultiselectWidget
.prototype.onMenuItemsChange = function () {
4405 this.setItemsFromData( this.getItemsData() );
4406 this.$element
.toggleClass( 'oo-ui-capsuleMultiselectWidget-empty', this.menu
.isEmpty() );
4410 * Clear the input field
4414 OO
.ui
.CapsuleMultiselectWidget
.prototype.clearInput = function () {
4415 if ( this.$input
) {
4416 this.$input
.val( '' );
4417 this.updateInputSize();
4420 this.popup
.toggle( false );
4422 this.menu
.toggle( false );
4423 this.menu
.selectItem();
4424 this.menu
.highlightItem();
4430 OO
.ui
.CapsuleMultiselectWidget
.prototype.setDisabled = function ( disabled
) {
4434 OO
.ui
.CapsuleMultiselectWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
4436 if ( this.$input
) {
4437 this.$input
.prop( 'disabled', this.isDisabled() );
4440 this.menu
.setDisabled( this.isDisabled() );
4443 this.popup
.setDisabled( this.isDisabled() );
4447 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4448 this.items
[ i
].updateDisabled();
4459 * @return {OO.ui.CapsuleMultiselectWidget}
4461 OO
.ui
.CapsuleMultiselectWidget
.prototype.focus = function () {
4462 if ( !this.isDisabled() ) {
4464 this.popup
.setSize( this.$handle
.outerWidth() );
4465 this.popup
.toggle( true );
4466 OO
.ui
.findFocusable( this.popup
.$element
).focus();
4468 this.updateInputSize();
4469 this.menu
.toggle( true );
4470 this.$input
.focus();
4477 * TagItemWidgets are used within a {@link OO.ui.TagMultiselectWidget
4478 * TagMultiselectWidget} to display the selected items.
4481 * @extends OO.ui.Widget
4482 * @mixins OO.ui.mixin.ItemWidget
4483 * @mixins OO.ui.mixin.LabelElement
4484 * @mixins OO.ui.mixin.FlaggedElement
4485 * @mixins OO.ui.mixin.TabIndexedElement
4486 * @mixins OO.ui.mixin.DraggableElement
4489 * @param {Object} [config] Configuration object
4490 * @cfg {boolean} [valid=true] Item is valid
4492 OO
.ui
.TagItemWidget
= function OoUiTagItemWidget( config
) {
4493 config
= config
|| {};
4495 // Parent constructor
4496 OO
.ui
.TagItemWidget
.parent
.call( this, config
);
4498 // Mixin constructors
4499 OO
.ui
.mixin
.ItemWidget
.call( this );
4500 OO
.ui
.mixin
.LabelElement
.call( this, config
);
4501 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
4502 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
4503 OO
.ui
.mixin
.DraggableElement
.call( this, config
);
4505 this.valid
= config
.valid
=== undefined ? true : !!config
.valid
;
4507 this.closeButton
= new OO
.ui
.ButtonWidget( {
4512 this.closeButton
.setDisabled( this.isDisabled() );
4516 .connect( this, { click
: 'remove' } );
4518 .on( 'click', this.select
.bind( this ) )
4519 .on( 'keydown', this.onKeyDown
.bind( this ) )
4520 // Prevent propagation of mousedown; the tag item "lives" in the
4521 // clickable area of the TagMultiselectWidget, which listens to
4522 // mousedown to open the menu or popup. We want to prevent that
4523 // for clicks specifically on the tag itself, so the actions taken
4524 // are more deliberate. When the tag is clicked, it will emit the
4525 // selection event (similar to how #OO.ui.MultioptionWidget emits 'change')
4526 // and can be handled separately.
4527 .on( 'mousedown', function ( e
) { e
.stopPropagation(); } );
4531 .addClass( 'oo-ui-tagItemWidget' )
4532 .append( this.$label
, this.closeButton
.$element
);
4535 /* Initialization */
4537 OO
.inheritClass( OO
.ui
.TagItemWidget
, OO
.ui
.Widget
);
4538 OO
.mixinClass( OO
.ui
.TagItemWidget
, OO
.ui
.mixin
.ItemWidget
);
4539 OO
.mixinClass( OO
.ui
.TagItemWidget
, OO
.ui
.mixin
.LabelElement
);
4540 OO
.mixinClass( OO
.ui
.TagItemWidget
, OO
.ui
.mixin
.FlaggedElement
);
4541 OO
.mixinClass( OO
.ui
.TagItemWidget
, OO
.ui
.mixin
.TabIndexedElement
);
4542 OO
.mixinClass( OO
.ui
.TagItemWidget
, OO
.ui
.mixin
.DraggableElement
);
4549 * A remove action was performed on the item
4554 * @param {string} direction Direction of the movement, forward or backwards
4556 * A navigate action was performed on the item
4562 * The tag widget was selected. This can occur when the widget
4563 * is either clicked or enter was pressed on it.
4568 * @param {boolean} isValid Item is valid
4570 * Item validity has changed
4578 OO
.ui
.TagItemWidget
.prototype.setDisabled = function ( state
) {
4580 OO
.ui
.TagItemWidget
.parent
.prototype.setDisabled
.call( this, state
);
4582 if ( this.closeButton
) {
4583 this.closeButton
.setDisabled( state
);
4589 * Handle removal of the item
4591 * This is mainly for extensibility concerns, so other children
4592 * of this class can change the behavior if they need to. This
4593 * is called by both clicking the 'remove' button but also
4594 * on keypress, which is harder to override if needed.
4598 OO
.ui
.TagItemWidget
.prototype.remove = function () {
4599 if ( !this.isDisabled() ) {
4600 this.emit( 'remove' );
4605 * Handle a keydown event on the widget
4609 * @return {boolean|undefined} false to stop the operation
4611 OO
.ui
.TagItemWidget
.prototype.onKeyDown = function ( e
) {
4614 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
|| e
.keyCode
=== OO
.ui
.Keys
.DELETE
) {
4617 } else if ( e
.keyCode
=== OO
.ui
.Keys
.ENTER
) {
4621 e
.keyCode
=== OO
.ui
.Keys
.LEFT
||
4622 e
.keyCode
=== OO
.ui
.Keys
.RIGHT
4624 if ( OO
.ui
.Element
.static.getDir( this.$element
) === 'rtl' ) {
4638 e
.keyCode
=== OO
.ui
.Keys
.LEFT
?
4639 movement
.left
: movement
.right
4645 * Focuses the capsule
4647 OO
.ui
.TagItemWidget
.prototype.focus = function () {
4648 if ( !this.isDisabled() ) {
4649 this.$element
.focus();
4658 OO
.ui
.TagItemWidget
.prototype.select = function () {
4659 if ( !this.isDisabled() ) {
4660 this.emit( 'select' );
4665 * Set the valid state of this item
4667 * @param {boolean} [valid] Item is valid
4670 OO
.ui
.TagItemWidget
.prototype.toggleValid = function ( valid
) {
4671 valid
= valid
=== undefined ? !this.valid
: !!valid
;
4673 if ( this.valid
!== valid
) {
4676 this.setFlags( { invalid
: !this.valid
} );
4678 this.emit( 'valid', this.valid
);
4683 * Check whether the item is valid
4685 * @return {boolean} Item is valid
4687 OO
.ui
.TagItemWidget
.prototype.isValid = function () {
4692 * A basic tag multiselect widget, similar in concept to {@link OO.ui.ComboBoxInputWidget combo box widget}
4693 * that allows the user to add multiple values that are displayed in a tag area.
4695 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
4697 * This widget is a base widget; see {@link OO.ui.MenuTagMultiselectWidget MenuTagMultiselectWidget} and
4698 * {@link OO.ui.PopupTagMultiselectWidget PopupTagMultiselectWidget} for the implementations that use
4699 * a menu and a popup respectively.
4702 * // Example: A basic TagMultiselectWidget.
4703 * var widget = new OO.ui.TagMultiselectWidget( {
4704 * inputPosition: 'outline',
4705 * allowedValues: [ 'Option 1', 'Option 2', 'Option 3' ],
4706 * selected: [ 'Option 1' ]
4708 * $( 'body' ).append( widget.$element );
4710 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
4713 * @extends OO.ui.Widget
4714 * @mixins OO.ui.mixin.GroupWidget
4715 * @mixins OO.ui.mixin.DraggableGroupElement
4716 * @mixins OO.ui.mixin.IndicatorElement
4717 * @mixins OO.ui.mixin.IconElement
4718 * @mixins OO.ui.mixin.TabIndexedElement
4719 * @mixins OO.ui.mixin.FlaggedElement
4722 * @param {Object} config Configuration object
4723 * @cfg {Object} [input] Configuration options for the input widget
4724 * @cfg {OO.ui.InputWidget} [inputWidget] An optional input widget. If given, it will
4725 * replace the input widget used in the TagMultiselectWidget. If not given,
4726 * TagMultiselectWidget creates its own.
4727 * @cfg {boolean} [inputPosition='inline'] Position of the input. Options are:
4728 * - inline: The input is invisible, but exists inside the tag list, so
4729 * the user types into the tag groups to add tags.
4730 * - outline: The input is underneath the tag area.
4731 * - none: No input supplied
4732 * @cfg {boolean} [allowEditTags=true] Allow editing of the tags by clicking them
4733 * @cfg {boolean} [allowArbitrary=false] Allow data items to be added even if
4734 * not present in the menu.
4735 * @cfg {Object[]} [allowedValues] An array representing the allowed items
4737 * @cfg {boolean} [allowDuplicates=false] Allow duplicate items to be added
4738 * @cfg {boolean} [allowDisplayInvalidTags=false] Allow the display of
4739 * invalid tags. These tags will display with an invalid state, and
4740 * the widget as a whole will have an invalid state if any invalid tags
4742 * @cfg {boolean} [allowReordering=true] Allow reordering of the items
4743 * @cfg {Object[]|String[]} [selected] A set of selected tags. If given,
4744 * these will appear in the tag list on initialization, as long as they
4745 * pass the validity tests.
4747 OO
.ui
.TagMultiselectWidget
= function OoUiTagMultiselectWidget( config
) {
4749 rAF
= window
.requestAnimationFrame
|| setTimeout
,
4751 $tabFocus
= $( '<span>' )
4752 .addClass( 'oo-ui-tagMultiselectWidget-focusTrap' );
4754 config
= config
|| {};
4756 // Parent constructor
4757 OO
.ui
.TagMultiselectWidget
.parent
.call( this, config
);
4759 // Mixin constructors
4760 OO
.ui
.mixin
.GroupWidget
.call( this, config
);
4761 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
4762 OO
.ui
.mixin
.IconElement
.call( this, config
);
4763 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
4764 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
4765 OO
.ui
.mixin
.DraggableGroupElement
.call( this, config
);
4767 this.toggleDraggable(
4768 config
.allowReordering
=== undefined ?
4769 true : !!config
.allowReordering
4772 this.inputPosition
= this.constructor.static.allowedInputPositions
.indexOf( config
.inputPosition
) > -1 ?
4773 config
.inputPosition
: 'inline';
4774 this.allowEditTags
= config
.allowEditTags
=== undefined ? true : !!config
.allowEditTags
;
4775 this.allowArbitrary
= !!config
.allowArbitrary
;
4776 this.allowDuplicates
= !!config
.allowDuplicates
;
4777 this.allowedValues
= config
.allowedValues
|| [];
4778 this.allowDisplayInvalidTags
= config
.allowDisplayInvalidTags
;
4779 this.hasInput
= this.inputPosition
!== 'none';
4783 this.$content
= $( '<div>' )
4784 .addClass( 'oo-ui-tagMultiselectWidget-content' );
4785 this.$handle
= $( '<div>' )
4786 .addClass( 'oo-ui-tagMultiselectWidget-handle' )
4793 .addClass( 'oo-ui-tagMultiselectWidget-group' )
4799 remove
: 'itemRemove',
4800 navigate
: 'itemNavigate',
4801 select
: 'itemSelect'
4803 this.connect( this, {
4804 itemRemove
: 'onTagRemove',
4805 itemSelect
: 'onTagSelect',
4806 itemNavigate
: 'onTagNavigate',
4807 change
: 'onChangeTags'
4810 mousedown
: this.onMouseDown
.bind( this )
4815 .addClass( 'oo-ui-tagMultiselectWidget' )
4816 .append( this.$handle
);
4818 if ( this.hasInput
) {
4819 if ( config
.inputWidget
) {
4820 this.input
= config
.inputWidget
;
4822 this.input
= new OO
.ui
.TextInputWidget( $.extend( {
4823 placeholder
: config
.placeholder
,
4824 classes
: [ 'oo-ui-tagMultiselectWidget-input' ]
4825 }, config
.input
) );
4827 this.input
.setDisabled( this.isDisabled() );
4830 focus
: this.onInputFocus
.bind( this ),
4831 blur
: this.onInputBlur
.bind( this ),
4832 'propertychange change click mouseup keydown keyup input cut paste select focus':
4833 OO
.ui
.debounce( this.updateInputSize
.bind( this ) ),
4834 keydown
: this.onInputKeyDown
.bind( this ),
4835 keypress
: this.onInputKeyPress
.bind( this )
4838 this.input
.$input
.on( inputEvents
);
4840 if ( this.inputPosition
=== 'outline' ) {
4841 // Override max-height for the input widget
4842 // in the case the widget is outline so it can
4843 // stretch all the way if the widet is wide
4844 this.input
.$element
.css( 'max-width', 'inherit' );
4846 .addClass( 'oo-ui-tagMultiselectWidget-outlined' )
4847 .append( this.input
.$element
);
4849 this.$element
.addClass( 'oo-ui-tagMultiselectWidget-inlined' );
4850 // HACK: When the widget is using 'inline' input, the
4851 // behavior needs to only use the $input itself
4852 // so we style and size it accordingly (otherwise
4853 // the styling and sizing can get very convoluted
4854 // when the wrapping divs and other elements)
4855 // We are taking advantage of still being able to
4856 // call the widget itself for operations like
4857 // .getValue() and setDisabled() and .focus() but
4858 // having only the $input attached to the DOM
4859 this.$content
.append( this.input
.$input
);
4863 this.setTabIndexedElement(
4869 if ( config
.selected
) {
4870 this.setValue( config
.selected
);
4873 // HACK: Input size needs to be calculated after everything
4876 if ( widget
.hasInput
) {
4877 widget
.updateInputSize();
4882 /* Initialization */
4884 OO
.inheritClass( OO
.ui
.TagMultiselectWidget
, OO
.ui
.Widget
);
4885 OO
.mixinClass( OO
.ui
.TagMultiselectWidget
, OO
.ui
.mixin
.GroupWidget
);
4886 OO
.mixinClass( OO
.ui
.TagMultiselectWidget
, OO
.ui
.mixin
.DraggableGroupElement
);
4887 OO
.mixinClass( OO
.ui
.TagMultiselectWidget
, OO
.ui
.mixin
.IndicatorElement
);
4888 OO
.mixinClass( OO
.ui
.TagMultiselectWidget
, OO
.ui
.mixin
.IconElement
);
4889 OO
.mixinClass( OO
.ui
.TagMultiselectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
4890 OO
.mixinClass( OO
.ui
.TagMultiselectWidget
, OO
.ui
.mixin
.FlaggedElement
);
4892 /* Static properties */
4895 * Allowed input positions.
4896 * - inline: The input is inside the tag list
4897 * - outline: The input is under the tag list
4898 * - none: There is no input
4902 OO
.ui
.TagMultiselectWidget
.static.allowedInputPositions
= [ 'inline', 'outline', 'none' ];
4907 * Handle mouse down events.
4910 * @param {jQuery.Event} e Mouse down event
4911 * @return {boolean} False to prevent defaults
4913 OO
.ui
.TagMultiselectWidget
.prototype.onMouseDown = function ( e
) {
4914 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
4921 * Handle key press events.
4924 * @param {jQuery.Event} e Key press event
4925 * @return {boolean} Whether to prevent defaults
4927 OO
.ui
.TagMultiselectWidget
.prototype.onInputKeyPress = function ( e
) {
4929 withMetaKey
= e
.metaKey
|| e
.ctrlKey
;
4931 if ( !this.isDisabled() ) {
4932 if ( e
.which
=== OO
.ui
.Keys
.ENTER
) {
4933 stopOrContinue
= this.doInputEnter( e
, withMetaKey
);
4936 // Make sure the input gets resized.
4937 setTimeout( this.updateInputSize
.bind( this ), 0 );
4938 return stopOrContinue
;
4943 * Handle key down events.
4946 * @param {jQuery.Event} e Key down event
4949 OO
.ui
.TagMultiselectWidget
.prototype.onInputKeyDown = function ( e
) {
4950 var movement
, direction
,
4951 withMetaKey
= e
.metaKey
|| e
.ctrlKey
;
4953 if ( !this.isDisabled() ) {
4954 // 'keypress' event is not triggered for Backspace
4955 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
) {
4956 return this.doInputBackspace( e
, withMetaKey
);
4957 } else if ( e
.keyCode
=== OO
.ui
.Keys
.ESCAPE
) {
4958 return this.doInputEscape( e
);
4960 e
.keyCode
=== OO
.ui
.Keys
.LEFT
||
4961 e
.keyCode
=== OO
.ui
.Keys
.RIGHT
4963 if ( OO
.ui
.Element
.static.getDir( this.$element
) === 'rtl' ) {
4974 direction
= e
.keyCode
=== OO
.ui
.Keys
.LEFT
?
4975 movement
.left
: movement
.right
;
4977 return this.doInputArrow( e
, direction
, withMetaKey
);
4983 * Respond to input focus event
4985 OO
.ui
.TagMultiselectWidget
.prototype.onInputFocus = function () {};
4988 * Respond to input blur event
4990 OO
.ui
.TagMultiselectWidget
.prototype.onInputBlur = function () {};
4993 * Perform an action after the enter key on the input
4995 * @param {jQuery.Event} e Event data
4996 * @param {boolean} [withMetaKey] Whether this key was pressed with
4997 * a meta key like 'ctrl'
4998 * @return {boolean} Whether to prevent defaults
5000 OO
.ui
.TagMultiselectWidget
.prototype.doInputEnter = function () {
5001 this.addTagFromInput();
5006 * Perform an action responding to the enter key on the input
5008 * @param {jQuery.Event} e Event data
5009 * @param {boolean} [withMetaKey] Whether this key was pressed with
5010 * a meta key like 'ctrl'
5011 * @return {boolean} Whether to prevent defaults
5013 OO
.ui
.TagMultiselectWidget
.prototype.doInputBackspace = function () {
5017 this.inputPosition
=== 'inline' &&
5018 this.input
.getValue() === '' &&
5021 // Delete the last item
5022 items
= this.getItems();
5023 item
= items
[ items
.length
- 1 ];
5024 this.input
.setValue( item
.getData() );
5025 this.removeItems( [ item
] );
5032 * Perform an action after the escape key on the input
5034 * @param {jQuery.Event} e Event data
5035 * @return {boolean} Whether to prevent defaults
5037 OO
.ui
.TagMultiselectWidget
.prototype.doInputEscape = function () {
5042 * Perform an action after the arrow key on the input, select the previous
5043 * or next item from the input.
5044 * See #getPreviousItem and #getNextItem
5046 * @param {jQuery.Event} e Event data
5047 * @param {string} direction Direction of the movement; forwards or backwards
5048 * @param {boolean} [withMetaKey] Whether this key was pressed with
5049 * a meta key like 'ctrl'
5050 * @return {boolean} Whether to prevent defaults
5052 OO
.ui
.TagMultiselectWidget
.prototype.doInputArrow = function ( direction
) {
5054 this.inputPosition
=== 'inline' &&
5057 if ( direction
=== 'backwards' ) {
5058 // Get previous item
5059 this.getPreviousItem().focus();
5062 this.getNextItem().focus();
5068 * Respond to item select event
5070 OO
.ui
.TagMultiselectWidget
.prototype.onTagSelect = function ( item
) {
5071 if ( this.hasInput
&& this.allowEditTags
) {
5072 if ( this.input
.getValue() ) {
5073 this.addTagFromInput();
5075 // 1. Get the label of the tag into the input
5076 this.input
.setValue( item
.getData() );
5077 // 2. Remove the tag
5078 this.removeItems( [ item
] );
5079 // 3. Focus the input
5085 * Respond to change event, where items were added, removed, or cleared.
5087 OO
.ui
.TagMultiselectWidget
.prototype.onChangeTags = function () {
5088 this.toggleValid( this.checkValidity() );
5089 if ( this.hasInput
) {
5090 this.updateInputSize();
5092 this.updateIfHeightChanged();
5098 OO
.ui
.TagMultiselectWidget
.prototype.setDisabled = function ( isDisabled
) {
5100 OO
.ui
.TagMultiselectWidget
.parent
.prototype.setDisabled
.call( this, isDisabled
);
5102 if ( this.hasInput
&& this.input
) {
5103 this.input
.setDisabled( !!isDisabled
);
5107 this.getItems().forEach( function ( item
) {
5108 item
.setDisabled( !!isDisabled
);
5114 * Respond to tag remove event
5115 * @param {OO.ui.TagItemWidget} item Removed tag
5117 OO
.ui
.TagMultiselectWidget
.prototype.onTagRemove = function ( item
) {
5118 this.removeTagByData( item
.getData() );
5122 * Respond to navigate event on the tag
5124 * @param {OO.ui.TagItemWidget} item Removed tag
5125 * @param {string} direction Direction of movement; 'forwards' or 'backwards'
5127 OO
.ui
.TagMultiselectWidget
.prototype.onTagNavigate = function ( item
, direction
) {
5128 if ( direction
=== 'forwards' ) {
5129 this.getNextItem( item
).focus();
5131 this.getPreviousItem( item
).focus();
5136 * Add tag from input value
5138 OO
.ui
.TagMultiselectWidget
.prototype.addTagFromInput = function () {
5139 var val
= this.input
.getValue(),
5140 isValid
= this.isAllowedData( val
);
5146 if ( isValid
|| this.allowDisplayInvalidTags
) {
5156 OO
.ui
.TagMultiselectWidget
.prototype.clearInput = function () {
5157 this.input
.setValue( '' );
5161 * Check whether the given value is a duplicate of an existing
5162 * tag already in the list.
5164 * @param {string|Object} data Requested value
5165 * @return {boolean} Value is duplicate
5167 OO
.ui
.TagMultiselectWidget
.prototype.isDuplicateData = function ( data
) {
5168 return !!this.getItemFromData( data
);
5172 * Check whether a given value is allowed to be added
5174 * @param {string|Object} data Requested value
5175 * @return {boolean} Value is allowed
5177 OO
.ui
.TagMultiselectWidget
.prototype.isAllowedData = function ( data
) {
5178 if ( this.allowArbitrary
) {
5183 !this.allowDuplicates
&&
5184 this.isDuplicateData( data
)
5189 // Check with allowed values
5191 this.getAllowedValues().some( function ( value
) {
5192 return data
=== value
;
5202 * Get the allowed values list
5204 * @return {string[]} Allowed data values
5206 OO
.ui
.TagMultiselectWidget
.prototype.getAllowedValues = function () {
5207 return this.allowedValues
;
5211 * Add a value to the allowed values list
5213 * @param {string} value Allowed data value
5215 OO
.ui
.TagMultiselectWidget
.prototype.addAllowedValue = function ( value
) {
5216 if ( this.allowedValues
.indexOf( value
) === -1 ) {
5217 this.allowedValues
.push( value
);
5224 OO
.ui
.TagMultiselectWidget
.prototype.focus = function () {
5225 if ( this.hasInput
) {
5231 * Get the datas of the currently selected items
5233 * @return {string[]|Object[]} Datas of currently selected items
5235 OO
.ui
.TagMultiselectWidget
.prototype.getValue = function () {
5236 return this.getItems()
5237 .filter( function ( item
) {
5238 return item
.isValid();
5240 .map( function ( item
) {
5241 return item
.getData();
5246 * Set the value of this widget by datas.
5248 * @param {string|string[]|Object|Object[]} value An object representing the data
5249 * and label of the value. If the widget allows arbitrary values,
5250 * the items will be added as-is. Otherwise, the data value will
5251 * be checked against allowedValues.
5252 * This object must contain at least a data key. Example:
5253 * { data: 'foo', label: 'Foo item' }
5254 * For multiple items, use an array of objects. For example:
5256 * { data: 'foo', label: 'Foo item' },
5257 * { data: 'bar', label: 'Bar item' }
5259 * Value can also be added with plaintext array, for example:
5260 * [ 'foo', 'bar', 'bla' ] or a single string, like 'foo'
5262 OO
.ui
.TagMultiselectWidget
.prototype.setValue = function ( valueObject
) {
5263 valueObject
= Array
.isArray( valueObject
) ? valueObject
: [ valueObject
];
5266 valueObject
.forEach( function ( obj
) {
5267 if ( typeof obj
=== 'string' ) {
5270 this.addTag( obj
.data
, obj
.label
);
5276 * Add tag to the display area
5278 * @param {string|Object} data Tag data
5279 * @param {string} [label] Tag label. If no label is provided, the
5280 * stringified version of the data will be used instead.
5281 * @return {boolean} Item was added successfully
5283 OO
.ui
.TagMultiselectWidget
.prototype.addTag = function ( data
, label
) {
5285 isValid
= this.isAllowedData( data
);
5287 if ( isValid
|| this.allowDisplayInvalidTags
) {
5288 newItemWidget
= this.createTagItemWidget( data
, label
);
5289 newItemWidget
.toggleValid( isValid
);
5290 this.addItems( [ newItemWidget
] );
5295 * Remove tag by its data property.
5297 * @param {string|Object} data Tag data
5299 OO
.ui
.TagMultiselectWidget
.prototype.removeTagByData = function ( data
) {
5300 var item
= this.getItemFromData( data
);
5302 this.removeItems( [ item
] );
5306 * Construct a OO.ui.TagItemWidget (or a subclass thereof) from given label and data.
5309 * @param {string} data Item data
5310 * @param {string} label The label text.
5311 * @return {OO.ui.TagItemWidget}
5313 OO
.ui
.TagMultiselectWidget
.prototype.createTagItemWidget = function ( data
, label
) {
5314 label
= label
|| data
;
5316 return new OO
.ui
.TagItemWidget( { data
: data
, label
: label
} );
5320 * Given an item, returns the item after it. If the item is already the
5321 * last item, return `this.input`. If no item is passed, returns the
5325 * @param {OO.ui.TagItemWidget} [item] Tag item
5326 * @return {OO.ui.Widget} The next widget available.
5328 OO
.ui
.TagMultiselectWidget
.prototype.getNextItem = function ( item
) {
5329 var itemIndex
= this.items
.indexOf( item
);
5331 if ( item
=== undefined || itemIndex
=== -1 ) {
5332 return this.items
[ 0 ];
5335 if ( itemIndex
=== this.items
.length
- 1 ) { // Last item
5336 if ( this.hasInput
) {
5339 // Return first item
5340 return this.items
[ 0 ];
5343 return this.items
[ itemIndex
+ 1 ];
5348 * Given an item, returns the item before it. If the item is already the
5349 * first item, return `this.input`. If no item is passed, returns the
5353 * @param {OO.ui.TagItemWidget} [item] Tag item
5354 * @return {OO.ui.Widget} The previous widget available.
5356 OO
.ui
.TagMultiselectWidget
.prototype.getPreviousItem = function ( item
) {
5357 var itemIndex
= this.items
.indexOf( item
);
5359 if ( item
=== undefined || itemIndex
=== -1 ) {
5360 return this.items
[ this.items
.length
- 1 ];
5363 if ( itemIndex
=== 0 ) {
5364 if ( this.hasInput
) {
5367 // Return the last item
5368 return this.items
[ this.items
.length
- 1 ];
5371 return this.items
[ itemIndex
- 1 ];
5376 * Update the dimensions of the text input field to encompass all available area.
5377 * This is especially relevant for when the input is at the edge of a line
5378 * and should get smaller. The usual operation (as an inline-block with min-width)
5379 * does not work in that case, pushing the input downwards to the next line.
5383 OO
.ui
.TagMultiselectWidget
.prototype.updateInputSize = function () {
5384 var $lastItem
, direction
, contentWidth
, currentWidth
, bestWidth
;
5385 if ( this.inputPosition
=== 'inline' && !this.isDisabled() ) {
5386 this.input
.$input
.css( 'width', '1em' );
5387 $lastItem
= this.$group
.children().last();
5388 direction
= OO
.ui
.Element
.static.getDir( this.$handle
);
5390 // Get the width of the input with the placeholder text as
5391 // the value and save it so that we don't keep recalculating
5393 this.contentWidthWithPlaceholder
=== undefined &&
5394 this.input
.getValue() === '' &&
5395 this.input
.$input
.attr( 'placeholder' ) !== undefined
5397 this.input
.setValue( this.input
.$input
.attr( 'placeholder' ) );
5398 this.contentWidthWithPlaceholder
= this.input
.$input
[ 0 ].scrollWidth
;
5399 this.input
.setValue( '' );
5403 // Always keep the input wide enough for the placeholder text
5404 contentWidth
= Math
.max(
5405 this.input
.$input
[ 0 ].scrollWidth
,
5406 // undefined arguments in Math.max lead to NaN
5407 ( this.contentWidthWithPlaceholder
=== undefined ) ?
5408 0 : this.contentWidthWithPlaceholder
5410 currentWidth
= this.input
.$input
.width();
5412 if ( contentWidth
< currentWidth
) {
5413 this.updateIfHeightChanged();
5414 // All is fine, don't perform expensive calculations
5418 if ( $lastItem
.length
=== 0 ) {
5419 bestWidth
= this.$content
.innerWidth();
5421 bestWidth
= direction
=== 'ltr' ?
5422 this.$content
.innerWidth() - $lastItem
.position().left
- $lastItem
.outerWidth() :
5423 $lastItem
.position().left
;
5426 // Some safety margin for sanity, because I *really* don't feel like finding out where the few
5427 // pixels this is off by are coming from.
5429 if ( contentWidth
> bestWidth
) {
5430 // This will result in the input getting shifted to the next line
5431 bestWidth
= this.$content
.innerWidth() - 10;
5433 this.input
.$input
.width( Math
.floor( bestWidth
) );
5434 this.updateIfHeightChanged();
5436 this.updateIfHeightChanged();
5441 * Determine if widget height changed, and if so,
5442 * emit the resize event. This is useful for when there are either
5443 * menus or popups attached to the bottom of the widget, to allow
5444 * them to change their positioning in case the widget moved down
5449 OO
.ui
.TagMultiselectWidget
.prototype.updateIfHeightChanged = function () {
5450 var height
= this.$element
.height();
5451 if ( height
!== this.height
) {
5452 this.height
= height
;
5453 this.emit( 'resize' );
5458 * Check whether all items in the widget are valid
5460 * @return {boolean} Widget is valid
5462 OO
.ui
.TagMultiselectWidget
.prototype.checkValidity = function () {
5463 return this.getItems().every( function ( item
) {
5464 return item
.isValid();
5469 * Set the valid state of this item
5471 * @param {boolean} [valid] Item is valid
5474 OO
.ui
.TagMultiselectWidget
.prototype.toggleValid = function ( valid
) {
5475 valid
= valid
=== undefined ? !this.valid
: !!valid
;
5477 if ( this.valid
!== valid
) {
5480 this.setFlags( { invalid
: !this.valid
} );
5482 this.emit( 'valid', this.valid
);
5487 * Get the current valid state of the widget
5489 * @return {boolean} Widget is valid
5491 OO
.ui
.TagMultiselectWidget
.prototype.isValid = function () {
5496 * PopupTagMultiselectWidget is a {@link OO.ui.TagMultiselectWidget OO.ui.TagMultiselectWidget} intended
5497 * to use a popup. The popup can be configured to have a default input to insert values into the widget.
5499 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
5502 * // Example: A basic PopupTagMultiselectWidget.
5503 * var widget = new OO.ui.PopupTagMultiselectWidget();
5504 * $( 'body' ).append( widget.$element );
5506 * // Example: A PopupTagMultiselectWidget with an external popup.
5507 * var popupInput = new OO.ui.TextInputWidget(),
5508 * widget = new OO.ui.PopupTagMultiselectWidget( {
5509 * popupInput: popupInput,
5511 * $content: popupInput.$element
5514 * $( 'body' ).append( widget.$element );
5516 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
5519 * @extends OO.ui.TagMultiselectWidget
5520 * @mixins OO.ui.mixin.PopupElement
5522 * @param {Object} config Configuration object
5523 * @cfg {jQuery} [$overlay] An overlay for the popup.
5524 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
5525 * @cfg {Object} [popup] Configuration options for the popup
5526 * @cfg {OO.ui.InputWidget} [popupInput] An input widget inside the popup that will be
5527 * focused when the popup is opened and will be used as replacement for the
5528 * general input in the widget.
5530 OO
.ui
.PopupTagMultiselectWidget
= function OoUiPopupTagMultiselectWidget( config
) {
5532 defaultConfig
= { popup
: {} };
5534 config
= config
|| {};
5536 // Parent constructor
5537 OO
.ui
.PopupTagMultiselectWidget
.parent
.call( this, $.extend( { inputPosition
: 'none' }, config
) );
5539 this.$overlay
= config
.$overlay
|| this.$element
;
5541 if ( !config
.popup
) {
5542 // For the default base implementation, we give a popup
5543 // with an input widget inside it. For any other use cases
5544 // the popup needs to be populated externally and the
5545 // event handled to add tags separately and manually
5546 defaultInput
= new OO
.ui
.TextInputWidget();
5548 defaultConfig
.popupInput
= defaultInput
;
5549 defaultConfig
.popup
.$content
= defaultInput
.$element
;
5551 this.$element
.addClass( 'oo-ui-popupTagMultiselectWidget-defaultPopup' );
5554 // Add overlay, and add that to the autoCloseIgnore
5555 defaultConfig
.popup
.$overlay
= this.$overlay
;
5556 defaultConfig
.popup
.$autoCloseIgnore
= this.hasInput
?
5557 this.input
.$element
.add( this.$overlay
) : this.$overlay
;
5559 // Allow extending any of the above
5560 config
= $.extend( defaultConfig
, config
);
5562 // Mixin constructors
5563 OO
.ui
.mixin
.PopupElement
.call( this, config
);
5565 if ( this.hasInput
) {
5566 this.input
.$input
.on( 'focus', this.popup
.toggle
.bind( this.popup
, true ) );
5569 // Configuration options
5570 this.popupInput
= config
.popupInput
;
5571 if ( this.popupInput
) {
5572 this.popupInput
.connect( this, {
5573 enter
: 'onPopupInputEnter'
5578 this.on( 'resize', this.popup
.updateDimensions
.bind( this.popup
) );
5579 this.popup
.connect( this, { toggle
: 'onPopupToggle' } );
5581 .on( 'focus', this.focus
.bind( this ) );
5585 .append( this.popup
.$element
)
5586 .addClass( 'oo-ui-popupTagMultiselectWidget' );
5589 /* Initialization */
5591 OO
.inheritClass( OO
.ui
.PopupTagMultiselectWidget
, OO
.ui
.TagMultiselectWidget
);
5592 OO
.mixinClass( OO
.ui
.PopupTagMultiselectWidget
, OO
.ui
.mixin
.PopupElement
);
5599 OO
.ui
.PopupTagMultiselectWidget
.prototype.focus = function () {
5600 // Since the parent deals with input focus, only
5601 // call the parent method if our input isn't in the
5603 if ( !this.popupInput
) {
5605 OO
.ui
.PopupTagMultiselectWidget
.parent
.prototype.focus
.call( this );
5608 this.popup
.toggle( true );
5612 * Respond to popup toggle event
5614 * @param {boolean} isVisible Popup is visible
5616 OO
.ui
.PopupTagMultiselectWidget
.prototype.onPopupToggle = function ( isVisible
) {
5617 if ( isVisible
&& this.popupInput
) {
5618 this.popupInput
.focus();
5623 * Respond to popup input enter event
5625 OO
.ui
.PopupTagMultiselectWidget
.prototype.onPopupInputEnter = function () {
5626 if ( this.popupInput
) {
5627 this.addTagByPopupValue( this.popupInput
.getValue() );
5628 this.popupInput
.setValue( '' );
5635 OO
.ui
.PopupTagMultiselectWidget
.prototype.onTagSelect = function ( item
) {
5636 if ( this.popupInput
&& this.allowEditTags
) {
5637 this.popupInput
.setValue( item
.getData() );
5638 this.removeItems( [ item
] );
5640 this.popup
.toggle( true );
5641 this.popupInput
.focus();
5644 OO
.ui
.PopupTagMultiselectWidget
.parent
.prototype.onTagSelect
.call( this, item
);
5649 * Add a tag by the popup value.
5650 * Whatever is responsible for setting the value in the popup should call
5651 * this method to add a tag, or use the regular methods like #addTag or
5652 * #setValue directly.
5654 * @param {string} data The value of item
5655 * @param {string} [label] The label of the tag. If not given, the data is used.
5657 OO
.ui
.PopupTagMultiselectWidget
.prototype.addTagByPopupValue = function ( data
, label
) {
5658 this.addTag( data
, label
);
5662 * MenuTagMultiselectWidget is a {@link OO.ui.TagMultiselectWidget OO.ui.TagMultiselectWidget} intended
5663 * to use a menu of selectable options.
5665 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
5668 * // Example: A basic MenuTagMultiselectWidget.
5669 * var widget = new OO.ui.MenuTagMultiselectWidget( {
5670 * inputPosition: 'outline',
5672 * { data: 'option1', label: 'Option 1' },
5673 * { data: 'option2', label: 'Option 2' },
5674 * { data: 'option3', label: 'Option 3' },
5676 * selected: [ 'option1', 'option2' ]
5678 * $( 'body' ).append( widget.$element );
5680 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
5683 * @extends OO.ui.TagMultiselectWidget
5686 * @param {Object} [config] Configuration object
5687 * @cfg {Object} [menu] Configuration object for the menu widget
5688 * @cfg {jQuery} [$overlay] An overlay for the menu.
5689 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
5690 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
5692 OO
.ui
.MenuTagMultiselectWidget
= function OoUiMenuTagMultiselectWidget( config
) {
5693 config
= config
|| {};
5695 // Parent constructor
5696 OO
.ui
.MenuTagMultiselectWidget
.parent
.call( this, config
);
5698 this.$overlay
= config
.$overlay
|| this.$element
;
5700 this.menu
= this.createMenuWidget( $.extend( {
5702 input
: this.hasInput
? this.input
: null,
5703 $input
: this.hasInput
? this.input
.$input
: null,
5704 filterFromInput
: !!this.hasInput
,
5705 $autoCloseIgnore
: this.hasInput
?
5706 this.input
.$element
.add( this.$overlay
) : this.$overlay
,
5707 $container
: this.hasInput
&& this.inputPosition
=== 'outline' ?
5708 this.input
.$element
: this.$element
,
5709 $overlay
: this.$overlay
,
5710 disabled
: this.isDisabled()
5712 this.addOptions( config
.options
|| [] );
5715 this.menu
.connect( this, {
5716 choose
: 'onMenuChoose',
5717 toggle
: 'onMenuToggle'
5719 if ( this.hasInput
) {
5720 this.input
.connect( this, { change
: 'onInputChange' } );
5722 this.connect( this, { resize
: 'onResize' } );
5726 .append( this.menu
.$element
);
5728 .addClass( 'oo-ui-menuTagMultiselectWidget' );
5731 /* Initialization */
5733 OO
.inheritClass( OO
.ui
.MenuTagMultiselectWidget
, OO
.ui
.TagMultiselectWidget
);
5738 * Respond to resize event
5740 OO
.ui
.MenuTagMultiselectWidget
.prototype.onResize = function () {
5741 // Reposition the menu
5742 this.menu
.position();
5748 OO
.ui
.MenuTagMultiselectWidget
.prototype.onInputFocus = function () {
5750 OO
.ui
.MenuTagMultiselectWidget
.parent
.prototype.onInputFocus
.call( this );
5752 this.menu
.toggle( true );
5756 * Respond to input change event
5758 OO
.ui
.MenuTagMultiselectWidget
.prototype.onInputChange = function () {
5759 this.menu
.toggle( true );
5763 * Respond to menu choose event
5765 * @param {OO.ui.OptionWidget} menuItem Chosen menu item
5767 OO
.ui
.MenuTagMultiselectWidget
.prototype.onMenuChoose = function ( menuItem
) {
5769 this.addTag( menuItem
.getData(), menuItem
.getLabel() );
5773 * Respond to menu toggle event. Reset item highlights on hide.
5775 * @param {boolean} isVisible The menu is visible
5777 OO
.ui
.MenuTagMultiselectWidget
.prototype.onMenuToggle = function ( isVisible
) {
5779 this.menu
.selectItem( null );
5780 this.menu
.highlightItem( null );
5787 OO
.ui
.MenuTagMultiselectWidget
.prototype.onTagSelect = function ( tagItem
) {
5788 var menuItem
= this.menu
.getItemFromData( tagItem
.getData() );
5789 // Override the base behavior from TagMultiselectWidget; the base behavior
5790 // in TagMultiselectWidget is to remove the tag to edit it in the input,
5791 // but in our case, we want to utilize the menu selection behavior, and
5792 // definitely not remove the item.
5794 // Select the menu item
5795 this.menu
.selectItem( menuItem
);
5803 OO
.ui
.MenuTagMultiselectWidget
.prototype.addTagFromInput = function () {
5804 var inputValue
= this.input
.getValue(),
5805 highlightedItem
= this.menu
.getHighlightedItem(),
5806 item
= this.menu
.getItemFromData( inputValue
);
5808 // Override the parent method so we add from the menu
5809 // rather than directly from the input
5811 // Look for a highlighted item first
5812 if ( highlightedItem
) {
5813 this.addTag( highlightedItem
.getData(), highlightedItem
.getLabel() );
5814 } else if ( item
) {
5815 // Look for the element that fits the data
5816 this.addTag( item
.getData(), item
.getLabel() );
5818 // Otherwise, add the tag - the method will only add if the
5819 // tag is valid or if invalid tags are allowed
5820 this.addTag( inputValue
);
5825 * Return the visible items in the menu. This is mainly used for when
5826 * the menu is filtering results.
5828 * @return {OO.ui.MenuOptionWidget[]} Visible results
5830 OO
.ui
.MenuTagMultiselectWidget
.prototype.getMenuVisibleItems = function () {
5831 return this.menu
.getItems().filter( function ( menuItem
) {
5832 return menuItem
.isVisible();
5837 * Create the menu for this widget. This is in a separate method so that
5838 * child classes can override this without polluting the constructor with
5839 * unnecessary extra objects that will be overidden.
5841 * @param {Object} menuConfig Configuration options
5842 * @return {OO.ui.MenuSelectWidget} Menu widget
5844 OO
.ui
.MenuTagMultiselectWidget
.prototype.createMenuWidget = function ( menuConfig
) {
5845 return new OO
.ui
.FloatingMenuSelectWidget( menuConfig
);
5849 * Add options to the menu
5851 * @param {Object[]} options Object defining options
5853 OO
.ui
.MenuTagMultiselectWidget
.prototype.addOptions = function ( menuOptions
) {
5855 items
= menuOptions
.map( function ( obj
) {
5856 return widget
.createMenuOptionWidget( obj
.data
, obj
.label
);
5859 this.menu
.addItems( items
);
5863 * Create a menu option widget.
5865 * @param {string} data Item data
5866 * @param {string} [label] Item label
5867 * @return {OO.ui.OptionWidget} Option widget
5869 OO
.ui
.MenuTagMultiselectWidget
.prototype.createMenuOptionWidget = function ( data
, label
) {
5870 return new OO
.ui
.MenuOptionWidget( {
5872 label
: label
|| data
5879 * @return {OO.ui.MenuSelectWidget} Menu
5881 OO
.ui
.MenuTagMultiselectWidget
.prototype.getMenu = function () {
5886 * Get the allowed values list
5888 * @return {string[]} Allowed data values
5890 OO
.ui
.MenuTagMultiselectWidget
.prototype.getAllowedValues = function () {
5891 var menuDatas
= this.menu
.getItems().map( function ( menuItem
) {
5892 return menuItem
.getData();
5894 return this.allowedValues
.concat( menuDatas
);
5900 OO
.ui
.MenuTagMultiselectWidget
.prototype.focus = function () {
5902 OO
.ui
.MenuTagMultiselectWidget
.parent
.prototype.focus
.call( this );
5904 if ( !this.isDisabled() ) {
5905 this.menu
.toggle( true );
5910 * SelectFileWidgets allow for selecting files, using the HTML5 File API. These
5911 * widgets can be configured with {@link OO.ui.mixin.IconElement icons} and {@link
5912 * OO.ui.mixin.IndicatorElement indicators}.
5913 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
5916 * // Example of a file select widget
5917 * var selectFile = new OO.ui.SelectFileWidget();
5918 * $( 'body' ).append( selectFile.$element );
5920 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets
5923 * @extends OO.ui.Widget
5924 * @mixins OO.ui.mixin.IconElement
5925 * @mixins OO.ui.mixin.IndicatorElement
5926 * @mixins OO.ui.mixin.PendingElement
5927 * @mixins OO.ui.mixin.LabelElement
5930 * @param {Object} [config] Configuration options
5931 * @cfg {string[]|null} [accept=null] MIME types to accept. null accepts all types.
5932 * @cfg {string} [placeholder] Text to display when no file is selected.
5933 * @cfg {string} [notsupported] Text to display when file support is missing in the browser.
5934 * @cfg {boolean} [droppable=true] Whether to accept files by drag and drop.
5935 * @cfg {boolean} [showDropTarget=false] Whether to show a drop target. Requires droppable to be true.
5936 * @cfg {number} [thumbnailSizeLimit=20] File size limit in MiB above which to not try and show a
5937 * preview (for performance)
5939 OO
.ui
.SelectFileWidget
= function OoUiSelectFileWidget( config
) {
5942 // Configuration initialization
5943 config
= $.extend( {
5945 placeholder
: OO
.ui
.msg( 'ooui-selectfile-placeholder' ),
5946 notsupported
: OO
.ui
.msg( 'ooui-selectfile-not-supported' ),
5948 showDropTarget
: false,
5949 thumbnailSizeLimit
: 20
5952 // Parent constructor
5953 OO
.ui
.SelectFileWidget
.parent
.call( this, config
);
5955 // Mixin constructors
5956 OO
.ui
.mixin
.IconElement
.call( this, config
);
5957 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
5958 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$info
} ) );
5959 OO
.ui
.mixin
.LabelElement
.call( this, config
);
5962 this.$info
= $( '<span>' );
5963 this.showDropTarget
= config
.showDropTarget
;
5964 this.thumbnailSizeLimit
= config
.thumbnailSizeLimit
;
5965 this.isSupported
= this.constructor.static.isSupported();
5966 this.currentFile
= null;
5967 if ( Array
.isArray( config
.accept
) ) {
5968 this.accept
= config
.accept
;
5972 this.placeholder
= config
.placeholder
;
5973 this.notsupported
= config
.notsupported
;
5974 this.onFileSelectedHandler
= this.onFileSelected
.bind( this );
5976 this.selectButton
= new OO
.ui
.ButtonWidget( {
5977 classes
: [ 'oo-ui-selectFileWidget-selectButton' ],
5978 label
: OO
.ui
.msg( 'ooui-selectfile-button-select' ),
5979 disabled
: this.disabled
|| !this.isSupported
5982 this.clearButton
= new OO
.ui
.ButtonWidget( {
5983 classes
: [ 'oo-ui-selectFileWidget-clearButton' ],
5986 disabled
: this.disabled
5990 this.selectButton
.$button
.on( {
5991 keypress
: this.onKeyPress
.bind( this )
5993 this.clearButton
.connect( this, {
5994 click
: 'onClearClick'
5996 if ( config
.droppable
) {
5997 dragHandler
= this.onDragEnterOrOver
.bind( this );
5999 dragenter
: dragHandler
,
6000 dragover
: dragHandler
,
6001 dragleave
: this.onDragLeave
.bind( this ),
6002 drop
: this.onDrop
.bind( this )
6008 this.$label
.addClass( 'oo-ui-selectFileWidget-label' );
6010 .addClass( 'oo-ui-selectFileWidget-info' )
6011 .append( this.$icon
, this.$label
, this.clearButton
.$element
, this.$indicator
);
6013 if ( config
.droppable
&& config
.showDropTarget
) {
6014 this.selectButton
.setIcon( 'upload' );
6015 this.$thumbnail
= $( '<div>' ).addClass( 'oo-ui-selectFileWidget-thumbnail' );
6016 this.setPendingElement( this.$thumbnail
);
6018 .addClass( 'oo-ui-selectFileWidget-dropTarget oo-ui-selectFileWidget' )
6020 click
: this.onDropTargetClick
.bind( this )
6025 this.selectButton
.$element
,
6027 .addClass( 'oo-ui-selectFileWidget-dropLabel' )
6028 .text( OO
.ui
.msg( 'ooui-selectfile-dragdrop-placeholder' ) )
6032 .addClass( 'oo-ui-selectFileWidget' )
6033 .append( this.$info
, this.selectButton
.$element
);
6040 OO
.inheritClass( OO
.ui
.SelectFileWidget
, OO
.ui
.Widget
);
6041 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.IconElement
);
6042 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.IndicatorElement
);
6043 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.PendingElement
);
6044 OO
.mixinClass( OO
.ui
.SelectFileWidget
, OO
.ui
.mixin
.LabelElement
);
6046 /* Static Properties */
6049 * Check if this widget is supported
6054 OO
.ui
.SelectFileWidget
.static.isSupported = function () {
6056 if ( OO
.ui
.SelectFileWidget
.static.isSupportedCache
=== null ) {
6057 $input
= $( '<input>' ).attr( 'type', 'file' );
6058 OO
.ui
.SelectFileWidget
.static.isSupportedCache
= $input
[ 0 ].files
!== undefined;
6060 return OO
.ui
.SelectFileWidget
.static.isSupportedCache
;
6063 OO
.ui
.SelectFileWidget
.static.isSupportedCache
= null;
6070 * A change event is emitted when the on/off state of the toggle changes.
6072 * @param {File|null} value New value
6078 * Get the current value of the field
6080 * @return {File|null}
6082 OO
.ui
.SelectFileWidget
.prototype.getValue = function () {
6083 return this.currentFile
;
6087 * Set the current value of the field
6089 * @param {File|null} file File to select
6091 OO
.ui
.SelectFileWidget
.prototype.setValue = function ( file
) {
6092 if ( this.currentFile
!== file
) {
6093 this.currentFile
= file
;
6095 this.emit( 'change', this.currentFile
);
6102 * Focusses the select file button.
6106 OO
.ui
.SelectFileWidget
.prototype.focus = function () {
6107 this.selectButton
.$button
[ 0 ].focus();
6112 * Update the user interface when a file is selected or unselected
6116 OO
.ui
.SelectFileWidget
.prototype.updateUI = function () {
6118 if ( !this.isSupported
) {
6119 this.$element
.addClass( 'oo-ui-selectFileWidget-notsupported' );
6120 this.$element
.removeClass( 'oo-ui-selectFileWidget-empty' );
6121 this.setLabel( this.notsupported
);
6123 this.$element
.addClass( 'oo-ui-selectFileWidget-supported' );
6124 if ( this.currentFile
) {
6125 this.$element
.removeClass( 'oo-ui-selectFileWidget-empty' );
6127 $label
= $label
.add(
6129 .addClass( 'oo-ui-selectFileWidget-fileName' )
6130 .text( this.currentFile
.name
)
6132 this.setLabel( $label
);
6134 if ( this.showDropTarget
) {
6136 this.loadAndGetImageUrl().done( function ( url
) {
6137 this.$thumbnail
.css( 'background-image', 'url( ' + url
+ ' )' );
6138 }.bind( this ) ).fail( function () {
6139 this.$thumbnail
.append(
6140 new OO
.ui
.IconWidget( {
6142 classes
: [ 'oo-ui-selectFileWidget-noThumbnail-icon' ]
6145 }.bind( this ) ).always( function () {
6148 this.$element
.off( 'click' );
6151 if ( this.showDropTarget
) {
6152 this.$element
.off( 'click' );
6154 click
: this.onDropTargetClick
.bind( this )
6158 .css( 'background-image', '' );
6160 this.$element
.addClass( 'oo-ui-selectFileWidget-empty' );
6161 this.setLabel( this.placeholder
);
6167 * If the selected file is an image, get its URL and load it.
6169 * @return {jQuery.Promise} Promise resolves with the image URL after it has loaded
6171 OO
.ui
.SelectFileWidget
.prototype.loadAndGetImageUrl = function () {
6172 var deferred
= $.Deferred(),
6173 file
= this.currentFile
,
6174 reader
= new FileReader();
6178 ( OO
.getProp( file
, 'type' ) || '' ).indexOf( 'image/' ) === 0 &&
6179 file
.size
< this.thumbnailSizeLimit
* 1024 * 1024
6181 reader
.onload = function ( event
) {
6182 var img
= document
.createElement( 'img' );
6183 img
.addEventListener( 'load', function () {
6185 img
.naturalWidth
=== 0 ||
6186 img
.naturalHeight
=== 0 ||
6187 img
.complete
=== false
6191 deferred
.resolve( event
.target
.result
);
6194 img
.src
= event
.target
.result
;
6196 reader
.readAsDataURL( file
);
6201 return deferred
.promise();
6205 * Add the input to the widget
6209 OO
.ui
.SelectFileWidget
.prototype.addInput = function () {
6210 if ( this.$input
) {
6211 this.$input
.remove();
6214 if ( !this.isSupported
) {
6219 this.$input
= $( '<input>' ).attr( 'type', 'file' );
6220 this.$input
.on( 'change', this.onFileSelectedHandler
);
6221 this.$input
.on( 'click', function ( e
) {
6222 // Prevents dropTarget to get clicked which calls
6223 // a click on this input
6224 e
.stopPropagation();
6229 if ( this.accept
) {
6230 this.$input
.attr( 'accept', this.accept
.join( ', ' ) );
6232 this.selectButton
.$button
.append( this.$input
);
6236 * Determine if we should accept this file
6239 * @param {string} mimeType File MIME type
6242 OO
.ui
.SelectFileWidget
.prototype.isAllowedType = function ( mimeType
) {
6245 if ( !this.accept
|| !mimeType
) {
6249 for ( i
= 0; i
< this.accept
.length
; i
++ ) {
6250 mimeTest
= this.accept
[ i
];
6251 if ( mimeTest
=== mimeType
) {
6253 } else if ( mimeTest
.substr( -2 ) === '/*' ) {
6254 mimeTest
= mimeTest
.substr( 0, mimeTest
.length
- 1 );
6255 if ( mimeType
.substr( 0, mimeTest
.length
) === mimeTest
) {
6265 * Handle file selection from the input
6268 * @param {jQuery.Event} e
6270 OO
.ui
.SelectFileWidget
.prototype.onFileSelected = function ( e
) {
6271 var file
= OO
.getProp( e
.target
, 'files', 0 ) || null;
6273 if ( file
&& !this.isAllowedType( file
.type
) ) {
6277 this.setValue( file
);
6282 * Handle clear button click events.
6286 OO
.ui
.SelectFileWidget
.prototype.onClearClick = function () {
6287 this.setValue( null );
6292 * Handle key press events.
6295 * @param {jQuery.Event} e Key press event
6297 OO
.ui
.SelectFileWidget
.prototype.onKeyPress = function ( e
) {
6298 if ( this.isSupported
&& !this.isDisabled() && this.$input
&&
6299 ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
6301 this.$input
.click();
6307 * Handle drop target click events.
6310 * @param {jQuery.Event} e Key press event
6312 OO
.ui
.SelectFileWidget
.prototype.onDropTargetClick = function () {
6313 if ( this.isSupported
&& !this.isDisabled() && this.$input
) {
6314 this.$input
.click();
6320 * Handle drag enter and over events
6323 * @param {jQuery.Event} e Drag event
6325 OO
.ui
.SelectFileWidget
.prototype.onDragEnterOrOver = function ( e
) {
6327 droppableFile
= false,
6328 dt
= e
.originalEvent
.dataTransfer
;
6331 e
.stopPropagation();
6333 if ( this.isDisabled() || !this.isSupported
) {
6334 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
6335 dt
.dropEffect
= 'none';
6339 // DataTransferItem and File both have a type property, but in Chrome files
6340 // have no information at this point.
6341 itemOrFile
= OO
.getProp( dt
, 'items', 0 ) || OO
.getProp( dt
, 'files', 0 );
6343 if ( this.isAllowedType( itemOrFile
.type
) ) {
6344 droppableFile
= true;
6346 // dt.types is Array-like, but not an Array
6347 } else if ( Array
.prototype.indexOf
.call( OO
.getProp( dt
, 'types' ) || [], 'Files' ) !== -1 ) {
6348 // File information is not available at this point for security so just assume
6349 // it is acceptable for now.
6350 // https://bugzilla.mozilla.org/show_bug.cgi?id=640534
6351 droppableFile
= true;
6354 this.$element
.toggleClass( 'oo-ui-selectFileWidget-canDrop', droppableFile
);
6355 if ( !droppableFile
) {
6356 dt
.dropEffect
= 'none';
6363 * Handle drag leave events
6366 * @param {jQuery.Event} e Drag event
6368 OO
.ui
.SelectFileWidget
.prototype.onDragLeave = function () {
6369 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
6373 * Handle drop events
6376 * @param {jQuery.Event} e Drop event
6378 OO
.ui
.SelectFileWidget
.prototype.onDrop = function ( e
) {
6380 dt
= e
.originalEvent
.dataTransfer
;
6383 e
.stopPropagation();
6384 this.$element
.removeClass( 'oo-ui-selectFileWidget-canDrop' );
6386 if ( this.isDisabled() || !this.isSupported
) {
6390 file
= OO
.getProp( dt
, 'files', 0 );
6391 if ( file
&& !this.isAllowedType( file
.type
) ) {
6395 this.setValue( file
);
6404 OO
.ui
.SelectFileWidget
.prototype.setDisabled = function ( disabled
) {
6405 OO
.ui
.SelectFileWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
6406 if ( this.selectButton
) {
6407 this.selectButton
.setDisabled( disabled
);
6409 if ( this.clearButton
) {
6410 this.clearButton
.setDisabled( disabled
);
6416 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
6417 * and a menu of search results, which is displayed beneath the query
6418 * field. Unlike {@link OO.ui.mixin.LookupElement lookup menus}, search result menus are always visible to the user.
6419 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
6420 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
6422 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
6423 * the [OOjs UI demos][1] for an example.
6425 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
6428 * @extends OO.ui.Widget
6431 * @param {Object} [config] Configuration options
6432 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
6433 * @cfg {string} [value] Initial query value
6435 OO
.ui
.SearchWidget
= function OoUiSearchWidget( config
) {
6436 // Configuration initialization
6437 config
= config
|| {};
6439 // Parent constructor
6440 OO
.ui
.SearchWidget
.parent
.call( this, config
);
6443 this.query
= new OO
.ui
.TextInputWidget( {
6445 placeholder
: config
.placeholder
,
6448 this.results
= new OO
.ui
.SelectWidget();
6449 this.$query
= $( '<div>' );
6450 this.$results
= $( '<div>' );
6453 this.query
.connect( this, {
6454 change
: 'onQueryChange',
6455 enter
: 'onQueryEnter'
6457 this.query
.$input
.on( 'keydown', this.onQueryKeydown
.bind( this ) );
6461 .addClass( 'oo-ui-searchWidget-query' )
6462 .append( this.query
.$element
);
6464 .addClass( 'oo-ui-searchWidget-results' )
6465 .append( this.results
.$element
);
6467 .addClass( 'oo-ui-searchWidget' )
6468 .append( this.$results
, this.$query
);
6473 OO
.inheritClass( OO
.ui
.SearchWidget
, OO
.ui
.Widget
);
6478 * Handle query key down events.
6481 * @param {jQuery.Event} e Key down event
6483 OO
.ui
.SearchWidget
.prototype.onQueryKeydown = function ( e
) {
6484 var highlightedItem
, nextItem
,
6485 dir
= e
.which
=== OO
.ui
.Keys
.DOWN
? 1 : ( e
.which
=== OO
.ui
.Keys
.UP
? -1 : 0 );
6488 highlightedItem
= this.results
.getHighlightedItem();
6489 if ( !highlightedItem
) {
6490 highlightedItem
= this.results
.getSelectedItem();
6492 nextItem
= this.results
.getRelativeSelectableItem( highlightedItem
, dir
);
6493 this.results
.highlightItem( nextItem
);
6494 nextItem
.scrollElementIntoView();
6499 * Handle select widget select events.
6501 * Clears existing results. Subclasses should repopulate items according to new query.
6504 * @param {string} value New value
6506 OO
.ui
.SearchWidget
.prototype.onQueryChange = function () {
6508 this.results
.clearItems();
6512 * Handle select widget enter key events.
6514 * Chooses highlighted item.
6517 * @param {string} value New value
6519 OO
.ui
.SearchWidget
.prototype.onQueryEnter = function () {
6520 var highlightedItem
= this.results
.getHighlightedItem();
6521 if ( highlightedItem
) {
6522 this.results
.chooseItem( highlightedItem
);
6527 * Get the query input.
6529 * @return {OO.ui.TextInputWidget} Query input
6531 OO
.ui
.SearchWidget
.prototype.getQuery = function () {
6536 * Get the search results menu.
6538 * @return {OO.ui.SelectWidget} Menu of search results
6540 OO
.ui
.SearchWidget
.prototype.getResults = function () {
6541 return this.results
;
6545 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
6546 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
6547 * (to adjust the value in increments) to allow the user to enter a number.
6550 * // Example: A NumberInputWidget.
6551 * var numberInput = new OO.ui.NumberInputWidget( {
6552 * label: 'NumberInputWidget',
6553 * input: { value: 5 },
6557 * $( 'body' ).append( numberInput.$element );
6560 * @extends OO.ui.TextInputWidget
6563 * @param {Object} [config] Configuration options
6564 * @cfg {Object} [minusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget decrementing button widget}.
6565 * @cfg {Object} [plusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget incrementing button widget}.
6566 * @cfg {boolean} [allowInteger=false] Whether the field accepts only integer values.
6567 * @cfg {number} [min=-Infinity] Minimum allowed value
6568 * @cfg {number} [max=Infinity] Maximum allowed value
6569 * @cfg {number} [step=1] Delta when using the buttons or up/down arrow keys
6570 * @cfg {number|null} [pageStep] Delta when using the page-up/page-down keys. Defaults to 10 times #step.
6571 * @cfg {boolean} [showButtons=true] Whether to show the plus and minus buttons.
6573 OO
.ui
.NumberInputWidget
= function OoUiNumberInputWidget( config
) {
6574 var $field
= $( '<div>' )
6575 .addClass( 'oo-ui-numberInputWidget-field' );
6577 // Configuration initialization
6578 config
= $.extend( {
6587 // For backward compatibility
6588 $.extend( config
, config
.input
);
6591 // Parent constructor
6592 OO
.ui
.NumberInputWidget
.parent
.call( this, $.extend( config
, {
6596 if ( config
.showButtons
) {
6597 this.minusButton
= new OO
.ui
.ButtonWidget( $.extend(
6599 disabled
: this.isDisabled(),
6601 classes
: [ 'oo-ui-numberInputWidget-minusButton' ],
6606 this.plusButton
= new OO
.ui
.ButtonWidget( $.extend(
6608 disabled
: this.isDisabled(),
6610 classes
: [ 'oo-ui-numberInputWidget-plusButton' ],
6619 keydown
: this.onKeyDown
.bind( this ),
6620 'wheel mousewheel DOMMouseScroll': this.onWheel
.bind( this )
6622 if ( config
.showButtons
) {
6623 this.plusButton
.connect( this, {
6624 click
: [ 'onButtonClick', +1 ]
6626 this.minusButton
.connect( this, {
6627 click
: [ 'onButtonClick', -1 ]
6632 $field
.append( this.$input
);
6633 if ( config
.showButtons
) {
6635 .prepend( this.minusButton
.$element
)
6636 .append( this.plusButton
.$element
);
6640 this.setAllowInteger( config
.isInteger
|| config
.allowInteger
);
6641 this.setRange( config
.min
, config
.max
);
6642 this.setStep( config
.step
, config
.pageStep
);
6643 // Set the validation method after we set isInteger and range
6644 // so that it doesn't immediately call setValidityFlag
6645 this.setValidation( this.validateNumber
.bind( this ) );
6648 .addClass( 'oo-ui-numberInputWidget' )
6649 .toggleClass( 'oo-ui-numberInputWidget-buttoned', config
.showButtons
)
6655 OO
.inheritClass( OO
.ui
.NumberInputWidget
, OO
.ui
.TextInputWidget
);
6660 * Set whether only integers are allowed
6662 * @param {boolean} flag
6664 OO
.ui
.NumberInputWidget
.prototype.setAllowInteger = function ( flag
) {
6665 this.isInteger
= !!flag
;
6666 this.setValidityFlag();
6668 // Backward compatibility
6669 OO
.ui
.NumberInputWidget
.prototype.setIsInteger
= OO
.ui
.NumberInputWidget
.prototype.setAllowInteger
;
6672 * Get whether only integers are allowed
6674 * @return {boolean} Flag value
6676 OO
.ui
.NumberInputWidget
.prototype.getAllowInteger = function () {
6677 return this.isInteger
;
6679 // Backward compatibility
6680 OO
.ui
.NumberInputWidget
.prototype.getIsInteger
= OO
.ui
.NumberInputWidget
.prototype.getAllowInteger
;
6683 * Set the range of allowed values
6685 * @param {number} min Minimum allowed value
6686 * @param {number} max Maximum allowed value
6688 OO
.ui
.NumberInputWidget
.prototype.setRange = function ( min
, max
) {
6690 throw new Error( 'Minimum (' + min
+ ') must not be greater than maximum (' + max
+ ')' );
6694 this.setValidityFlag();
6698 * Get the current range
6700 * @return {number[]} Minimum and maximum values
6702 OO
.ui
.NumberInputWidget
.prototype.getRange = function () {
6703 return [ this.min
, this.max
];
6707 * Set the stepping deltas
6709 * @param {number} step Normal step
6710 * @param {number|null} pageStep Page step. If null, 10 * step will be used.
6712 OO
.ui
.NumberInputWidget
.prototype.setStep = function ( step
, pageStep
) {
6714 throw new Error( 'Step value must be positive' );
6716 if ( pageStep
=== null ) {
6717 pageStep
= step
* 10;
6718 } else if ( pageStep
<= 0 ) {
6719 throw new Error( 'Page step value must be positive' );
6722 this.pageStep
= pageStep
;
6726 * Get the current stepping values
6728 * @return {number[]} Step and page step
6730 OO
.ui
.NumberInputWidget
.prototype.getStep = function () {
6731 return [ this.step
, this.pageStep
];
6735 * Get the current value of the widget as a number
6737 * @return {number} May be NaN, or an invalid number
6739 OO
.ui
.NumberInputWidget
.prototype.getNumericValue = function () {
6740 return +this.getValue();
6744 * Adjust the value of the widget
6746 * @param {number} delta Adjustment amount
6748 OO
.ui
.NumberInputWidget
.prototype.adjustValue = function ( delta
) {
6749 var n
, v
= this.getNumericValue();
6752 if ( isNaN( delta
) || !isFinite( delta
) ) {
6753 throw new Error( 'Delta must be a finite number' );
6760 n
= Math
.max( Math
.min( n
, this.max
), this.min
);
6761 if ( this.isInteger
) {
6762 n
= Math
.round( n
);
6774 * @param {string} value Field value
6777 OO
.ui
.NumberInputWidget
.prototype.validateNumber = function ( value
) {
6779 if ( value
=== '' ) {
6780 return !this.isRequired();
6783 if ( isNaN( n
) || !isFinite( n
) ) {
6787 if ( this.isInteger
&& Math
.floor( n
) !== n
) {
6791 if ( n
< this.min
|| n
> this.max
) {
6799 * Handle mouse click events.
6802 * @param {number} dir +1 or -1
6804 OO
.ui
.NumberInputWidget
.prototype.onButtonClick = function ( dir
) {
6805 this.adjustValue( dir
* this.step
);
6809 * Handle mouse wheel events.
6812 * @param {jQuery.Event} event
6814 OO
.ui
.NumberInputWidget
.prototype.onWheel = function ( event
) {
6817 if ( !this.isDisabled() && this.$input
.is( ':focus' ) ) {
6818 // Standard 'wheel' event
6819 if ( event
.originalEvent
.deltaMode
!== undefined ) {
6820 this.sawWheelEvent
= true;
6822 if ( event
.originalEvent
.deltaY
) {
6823 delta
= -event
.originalEvent
.deltaY
;
6824 } else if ( event
.originalEvent
.deltaX
) {
6825 delta
= event
.originalEvent
.deltaX
;
6828 // Non-standard events
6829 if ( !this.sawWheelEvent
) {
6830 if ( event
.originalEvent
.wheelDeltaX
) {
6831 delta
= -event
.originalEvent
.wheelDeltaX
;
6832 } else if ( event
.originalEvent
.wheelDeltaY
) {
6833 delta
= event
.originalEvent
.wheelDeltaY
;
6834 } else if ( event
.originalEvent
.wheelDelta
) {
6835 delta
= event
.originalEvent
.wheelDelta
;
6836 } else if ( event
.originalEvent
.detail
) {
6837 delta
= -event
.originalEvent
.detail
;
6842 delta
= delta
< 0 ? -1 : 1;
6843 this.adjustValue( delta
* this.step
);
6851 * Handle key down events.
6854 * @param {jQuery.Event} e Key down event
6856 OO
.ui
.NumberInputWidget
.prototype.onKeyDown = function ( e
) {
6857 if ( !this.isDisabled() ) {
6858 switch ( e
.which
) {
6860 this.adjustValue( this.step
);
6862 case OO
.ui
.Keys
.DOWN
:
6863 this.adjustValue( -this.step
);
6865 case OO
.ui
.Keys
.PAGEUP
:
6866 this.adjustValue( this.pageStep
);
6868 case OO
.ui
.Keys
.PAGEDOWN
:
6869 this.adjustValue( -this.pageStep
);
6878 OO
.ui
.NumberInputWidget
.prototype.setDisabled = function ( disabled
) {
6880 OO
.ui
.NumberInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
6882 if ( this.minusButton
) {
6883 this.minusButton
.setDisabled( this.isDisabled() );
6885 if ( this.plusButton
) {
6886 this.plusButton
.setDisabled( this.isDisabled() );