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