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