Update OOjs UI to v0.17.0
[lhc/web/wiklou.git] / resources / lib / oojs-ui / oojs-ui-widgets.js
1 /*!
2 * OOjs UI v0.17.0
3 * https://www.mediawiki.org/wiki/OOjs_UI
4 *
5 * Copyright 2011–2016 OOjs UI Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
8 *
9 * Date: 2016-04-26T21:34:01Z
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.OptionWidget
3237 * @mixins OO.ui.mixin.ButtonElement
3238 * @mixins OO.ui.mixin.IconElement
3239 * @mixins OO.ui.mixin.IndicatorElement
3240 * @mixins OO.ui.mixin.TabIndexedElement
3241 * @mixins OO.ui.mixin.TitledElement
3242 *
3243 * @constructor
3244 * @param {Object} [config] Configuration options
3245 */
3246 OO.ui.ButtonOptionWidget = function OoUiButtonOptionWidget( config ) {
3247 // Configuration initialization
3248 config = config || {};
3249
3250 // Parent constructor
3251 OO.ui.ButtonOptionWidget.parent.call( this, config );
3252
3253 // Mixin constructors
3254 OO.ui.mixin.ButtonElement.call( this, config );
3255 OO.ui.mixin.IconElement.call( this, config );
3256 OO.ui.mixin.IndicatorElement.call( this, config );
3257 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
3258 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, {
3259 $tabIndexed: this.$button,
3260 tabIndex: -1
3261 } ) );
3262
3263 // Initialization
3264 this.$element.addClass( 'oo-ui-buttonOptionWidget' );
3265 this.$button.append( this.$icon, this.$label, this.$indicator );
3266 this.$element.append( this.$button );
3267 };
3268
3269 /* Setup */
3270
3271 OO.inheritClass( OO.ui.ButtonOptionWidget, OO.ui.OptionWidget );
3272 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.ButtonElement );
3273 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.IconElement );
3274 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.IndicatorElement );
3275 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.TitledElement );
3276 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.TabIndexedElement );
3277
3278 /* Static Properties */
3279
3280 // Allow button mouse down events to pass through so they can be handled by the parent select widget
3281 OO.ui.ButtonOptionWidget.static.cancelButtonMouseDownEvents = false;
3282
3283 OO.ui.ButtonOptionWidget.static.highlightable = false;
3284
3285 /* Methods */
3286
3287 /**
3288 * @inheritdoc
3289 */
3290 OO.ui.ButtonOptionWidget.prototype.setSelected = function ( state ) {
3291 OO.ui.ButtonOptionWidget.parent.prototype.setSelected.call( this, state );
3292
3293 if ( this.constructor.static.selectable ) {
3294 this.setActive( state );
3295 }
3296
3297 return this;
3298 };
3299
3300 /**
3301 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
3302 * button options and is used together with
3303 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
3304 * highlighting, choosing, and selecting mutually exclusive options. Please see
3305 * the [OOjs UI documentation on MediaWiki] [1] for more information.
3306 *
3307 * @example
3308 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
3309 * var option1 = new OO.ui.ButtonOptionWidget( {
3310 * data: 1,
3311 * label: 'Option 1',
3312 * title: 'Button option 1'
3313 * } );
3314 *
3315 * var option2 = new OO.ui.ButtonOptionWidget( {
3316 * data: 2,
3317 * label: 'Option 2',
3318 * title: 'Button option 2'
3319 * } );
3320 *
3321 * var option3 = new OO.ui.ButtonOptionWidget( {
3322 * data: 3,
3323 * label: 'Option 3',
3324 * title: 'Button option 3'
3325 * } );
3326 *
3327 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
3328 * items: [ option1, option2, option3 ]
3329 * } );
3330 * $( 'body' ).append( buttonSelect.$element );
3331 *
3332 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
3333 *
3334 * @class
3335 * @extends OO.ui.SelectWidget
3336 * @mixins OO.ui.mixin.TabIndexedElement
3337 *
3338 * @constructor
3339 * @param {Object} [config] Configuration options
3340 */
3341 OO.ui.ButtonSelectWidget = function OoUiButtonSelectWidget( config ) {
3342 // Parent constructor
3343 OO.ui.ButtonSelectWidget.parent.call( this, config );
3344
3345 // Mixin constructors
3346 OO.ui.mixin.TabIndexedElement.call( this, config );
3347
3348 // Events
3349 this.$element.on( {
3350 focus: this.bindKeyDownListener.bind( this ),
3351 blur: this.unbindKeyDownListener.bind( this )
3352 } );
3353
3354 // Initialization
3355 this.$element.addClass( 'oo-ui-buttonSelectWidget' );
3356 };
3357
3358 /* Setup */
3359
3360 OO.inheritClass( OO.ui.ButtonSelectWidget, OO.ui.SelectWidget );
3361 OO.mixinClass( OO.ui.ButtonSelectWidget, OO.ui.mixin.TabIndexedElement );
3362
3363 /**
3364 * TabOptionWidget is an item in a {@link OO.ui.TabSelectWidget TabSelectWidget}.
3365 *
3366 * Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}, which contain
3367 * {@link OO.ui.CardLayout card layouts}. See {@link OO.ui.IndexLayout IndexLayout}
3368 * for an example.
3369 *
3370 * @class
3371 * @extends OO.ui.OptionWidget
3372 *
3373 * @constructor
3374 * @param {Object} [config] Configuration options
3375 */
3376 OO.ui.TabOptionWidget = function OoUiTabOptionWidget( config ) {
3377 // Configuration initialization
3378 config = config || {};
3379
3380 // Parent constructor
3381 OO.ui.TabOptionWidget.parent.call( this, config );
3382
3383 // Initialization
3384 this.$element.addClass( 'oo-ui-tabOptionWidget' );
3385 };
3386
3387 /* Setup */
3388
3389 OO.inheritClass( OO.ui.TabOptionWidget, OO.ui.OptionWidget );
3390
3391 /* Static Properties */
3392
3393 OO.ui.TabOptionWidget.static.highlightable = false;
3394
3395 /**
3396 * TabSelectWidget is a list that contains {@link OO.ui.TabOptionWidget tab options}
3397 *
3398 * **Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}.**
3399 *
3400 * @class
3401 * @extends OO.ui.SelectWidget
3402 * @mixins OO.ui.mixin.TabIndexedElement
3403 *
3404 * @constructor
3405 * @param {Object} [config] Configuration options
3406 */
3407 OO.ui.TabSelectWidget = function OoUiTabSelectWidget( config ) {
3408 // Parent constructor
3409 OO.ui.TabSelectWidget.parent.call( this, config );
3410
3411 // Mixin constructors
3412 OO.ui.mixin.TabIndexedElement.call( this, config );
3413
3414 // Events
3415 this.$element.on( {
3416 focus: this.bindKeyDownListener.bind( this ),
3417 blur: this.unbindKeyDownListener.bind( this )
3418 } );
3419
3420 // Initialization
3421 this.$element.addClass( 'oo-ui-tabSelectWidget' );
3422 };
3423
3424 /* Setup */
3425
3426 OO.inheritClass( OO.ui.TabSelectWidget, OO.ui.SelectWidget );
3427 OO.mixinClass( OO.ui.TabSelectWidget, OO.ui.mixin.TabIndexedElement );
3428
3429 /**
3430 * CapsuleItemWidgets are used within a {@link OO.ui.CapsuleMultiSelectWidget
3431 * CapsuleMultiSelectWidget} to display the selected items.
3432 *
3433 * @class
3434 * @extends OO.ui.Widget
3435 * @mixins OO.ui.mixin.ItemWidget
3436 * @mixins OO.ui.mixin.LabelElement
3437 * @mixins OO.ui.mixin.FlaggedElement
3438 * @mixins OO.ui.mixin.TabIndexedElement
3439 *
3440 * @constructor
3441 * @param {Object} [config] Configuration options
3442 */
3443 OO.ui.CapsuleItemWidget = function OoUiCapsuleItemWidget( config ) {
3444 // Configuration initialization
3445 config = config || {};
3446
3447 // Parent constructor
3448 OO.ui.CapsuleItemWidget.parent.call( this, config );
3449
3450 // Mixin constructors
3451 OO.ui.mixin.ItemWidget.call( this );
3452 OO.ui.mixin.LabelElement.call( this, config );
3453 OO.ui.mixin.FlaggedElement.call( this, config );
3454 OO.ui.mixin.TabIndexedElement.call( this, config );
3455
3456 // Events
3457 this.closeButton = new OO.ui.ButtonWidget( {
3458 framed: false,
3459 indicator: 'clear',
3460 tabIndex: -1
3461 } ).on( 'click', this.onCloseClick.bind( this ) );
3462
3463 this.on( 'disable', function ( disabled ) {
3464 this.closeButton.setDisabled( disabled );
3465 }.bind( this ) );
3466
3467 // Initialization
3468 this.$element
3469 .on( {
3470 click: this.onClick.bind( this ),
3471 keydown: this.onKeyDown.bind( this )
3472 } )
3473 .addClass( 'oo-ui-capsuleItemWidget' )
3474 .append( this.$label, this.closeButton.$element );
3475 };
3476
3477 /* Setup */
3478
3479 OO.inheritClass( OO.ui.CapsuleItemWidget, OO.ui.Widget );
3480 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.ItemWidget );
3481 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.LabelElement );
3482 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.FlaggedElement );
3483 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.TabIndexedElement );
3484
3485 /* Methods */
3486
3487 /**
3488 * Handle close icon clicks
3489 */
3490 OO.ui.CapsuleItemWidget.prototype.onCloseClick = function () {
3491 var element = this.getElementGroup();
3492
3493 if ( element && $.isFunction( element.removeItems ) ) {
3494 element.removeItems( [ this ] );
3495 element.focus();
3496 }
3497 };
3498
3499 /**
3500 * Handle click event for the entire capsule
3501 */
3502 OO.ui.CapsuleItemWidget.prototype.onClick = function () {
3503 var element = this.getElementGroup();
3504
3505 if ( !this.isDisabled() && element && $.isFunction( element.editItem ) ) {
3506 element.editItem( this );
3507 }
3508 };
3509
3510 /**
3511 * Handle keyDown event for the entire capsule
3512 */
3513 OO.ui.CapsuleItemWidget.prototype.onKeyDown = function ( e ) {
3514 var element = this.getElementGroup();
3515
3516 if ( e.keyCode === OO.ui.Keys.BACKSPACE || e.keyCode === OO.ui.Keys.DELETE ) {
3517 element.removeItems( [ this ] );
3518 element.focus();
3519 return false;
3520 } else if ( e.keyCode === OO.ui.Keys.ENTER ) {
3521 element.editItem( this );
3522 return false;
3523 } else if ( e.keyCode === OO.ui.Keys.LEFT ) {
3524 element.getPreviousItem( this ).focus();
3525 } else if ( e.keyCode === OO.ui.Keys.RIGHT ) {
3526 element.getNextItem( this ).focus();
3527 }
3528 };
3529
3530 /**
3531 * Focuses the capsule
3532 */
3533 OO.ui.CapsuleItemWidget.prototype.focus = function () {
3534 this.$element.focus();
3535 };
3536
3537 /**
3538 * CapsuleMultiSelectWidgets are something like a {@link OO.ui.ComboBoxInputWidget combo box widget}
3539 * that allows for selecting multiple values.
3540 *
3541 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
3542 *
3543 * @example
3544 * // Example: A CapsuleMultiSelectWidget.
3545 * var capsule = new OO.ui.CapsuleMultiSelectWidget( {
3546 * label: 'CapsuleMultiSelectWidget',
3547 * selected: [ 'Option 1', 'Option 3' ],
3548 * menu: {
3549 * items: [
3550 * new OO.ui.MenuOptionWidget( {
3551 * data: 'Option 1',
3552 * label: 'Option One'
3553 * } ),
3554 * new OO.ui.MenuOptionWidget( {
3555 * data: 'Option 2',
3556 * label: 'Option Two'
3557 * } ),
3558 * new OO.ui.MenuOptionWidget( {
3559 * data: 'Option 3',
3560 * label: 'Option Three'
3561 * } ),
3562 * new OO.ui.MenuOptionWidget( {
3563 * data: 'Option 4',
3564 * label: 'Option Four'
3565 * } ),
3566 * new OO.ui.MenuOptionWidget( {
3567 * data: 'Option 5',
3568 * label: 'Option Five'
3569 * } )
3570 * ]
3571 * }
3572 * } );
3573 * $( 'body' ).append( capsule.$element );
3574 *
3575 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
3576 *
3577 * @class
3578 * @extends OO.ui.Widget
3579 * @mixins OO.ui.mixin.TabIndexedElement
3580 * @mixins OO.ui.mixin.GroupElement
3581 * @uses OO.ui.CapsuleItemWidget
3582 * @uses OO.ui.FloatingMenuSelectWidget
3583 *
3584 * @constructor
3585 * @param {Object} [config] Configuration options
3586 * @cfg {boolean} [allowArbitrary=false] Allow data items to be added even if not present in the menu.
3587 * @cfg {Object} [menu] (required) Configuration options to pass to the
3588 * {@link OO.ui.MenuSelectWidget menu select widget}.
3589 * @cfg {Object} [popup] Configuration options to pass to the {@link OO.ui.PopupWidget popup widget}.
3590 * If specified, this popup will be shown instead of the menu (but the menu
3591 * will still be used for item labels and allowArbitrary=false). The widgets
3592 * in the popup should use {@link #addItemsFromData} or {@link #addItems} as necessary.
3593 * @cfg {jQuery} [$overlay=this.$element] Render the menu or popup into a separate layer.
3594 * This configuration is useful in cases where the expanded menu is larger than
3595 * its containing `<div>`. The specified overlay layer is usually on top of
3596 * the containing `<div>` and has a larger area. By default, the menu uses
3597 * relative positioning.
3598 */
3599 OO.ui.CapsuleMultiSelectWidget = function OoUiCapsuleMultiSelectWidget( config ) {
3600 var $tabFocus;
3601
3602 // Parent constructor
3603 OO.ui.CapsuleMultiSelectWidget.parent.call( this, config );
3604
3605 // Configuration initialization
3606 config = $.extend( {
3607 allowArbitrary: false,
3608 $overlay: this.$element
3609 }, config );
3610
3611 // Properties (must be set before mixin constructor calls)
3612 this.$input = config.popup ? null : $( '<input>' );
3613 this.$handle = $( '<div>' );
3614
3615 // Mixin constructors
3616 OO.ui.mixin.GroupElement.call( this, config );
3617 if ( config.popup ) {
3618 config.popup = $.extend( {}, config.popup, {
3619 align: 'forwards',
3620 anchor: false
3621 } );
3622 OO.ui.mixin.PopupElement.call( this, config );
3623 $tabFocus = $( '<span>' );
3624 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: $tabFocus } ) );
3625 } else {
3626 this.popup = null;
3627 $tabFocus = null;
3628 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
3629 }
3630 OO.ui.mixin.IndicatorElement.call( this, config );
3631 OO.ui.mixin.IconElement.call( this, config );
3632
3633 // Properties
3634 this.$content = $( '<div>' );
3635 this.allowArbitrary = config.allowArbitrary;
3636 this.$overlay = config.$overlay;
3637 this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend(
3638 {
3639 widget: this,
3640 $input: this.$input,
3641 $container: this.$element,
3642 filterFromInput: true,
3643 disabled: this.isDisabled()
3644 },
3645 config.menu
3646 ) );
3647
3648 // Events
3649 if ( this.popup ) {
3650 $tabFocus.on( {
3651 focus: this.onFocusForPopup.bind( this )
3652 } );
3653 this.popup.$element.on( 'focusout', this.onPopupFocusOut.bind( this ) );
3654 if ( this.popup.$autoCloseIgnore ) {
3655 this.popup.$autoCloseIgnore.on( 'focusout', this.onPopupFocusOut.bind( this ) );
3656 }
3657 this.popup.connect( this, {
3658 toggle: function ( visible ) {
3659 $tabFocus.toggle( !visible );
3660 }
3661 } );
3662 } else {
3663 this.$input.on( {
3664 focus: this.onInputFocus.bind( this ),
3665 blur: this.onInputBlur.bind( this ),
3666 'propertychange change click mouseup keydown keyup input cut paste select focus':
3667 OO.ui.debounce( this.updateInputSize.bind( this ) ),
3668 keydown: this.onKeyDown.bind( this ),
3669 keypress: this.onKeyPress.bind( this )
3670 } );
3671 }
3672 this.menu.connect( this, {
3673 choose: 'onMenuChoose',
3674 add: 'onMenuItemsChange',
3675 remove: 'onMenuItemsChange'
3676 } );
3677 this.$handle.on( {
3678 mousedown: this.onMouseDown.bind( this )
3679 } );
3680
3681 // Initialization
3682 if ( this.$input ) {
3683 this.$input.prop( 'disabled', this.isDisabled() );
3684 this.$input.attr( {
3685 role: 'combobox',
3686 'aria-autocomplete': 'list'
3687 } );
3688 this.updateInputSize();
3689 }
3690 if ( config.data ) {
3691 this.setItemsFromData( config.data );
3692 }
3693 this.$content.addClass( 'oo-ui-capsuleMultiSelectWidget-content' )
3694 .append( this.$group );
3695 this.$group.addClass( 'oo-ui-capsuleMultiSelectWidget-group' );
3696 this.$handle.addClass( 'oo-ui-capsuleMultiSelectWidget-handle' )
3697 .append( this.$indicator, this.$icon, this.$content );
3698 this.$element.addClass( 'oo-ui-capsuleMultiSelectWidget' )
3699 .append( this.$handle );
3700 if ( this.popup ) {
3701 this.$content.append( $tabFocus );
3702 this.$overlay.append( this.popup.$element );
3703 } else {
3704 this.$content.append( this.$input );
3705 this.$overlay.append( this.menu.$element );
3706 }
3707 this.onMenuItemsChange();
3708 };
3709
3710 /* Setup */
3711
3712 OO.inheritClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.Widget );
3713 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.GroupElement );
3714 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.PopupElement );
3715 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.TabIndexedElement );
3716 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.IndicatorElement );
3717 OO.mixinClass( OO.ui.CapsuleMultiSelectWidget, OO.ui.mixin.IconElement );
3718
3719 /* Events */
3720
3721 /**
3722 * @event change
3723 *
3724 * A change event is emitted when the set of selected items changes.
3725 *
3726 * @param {Mixed[]} datas Data of the now-selected items
3727 */
3728
3729 /**
3730 * @event resize
3731 *
3732 * A resize event is emitted when the widget's dimensions change to accomodate newly added items or
3733 * current user input.
3734 */
3735
3736 /* Methods */
3737
3738 /**
3739 * Construct a OO.ui.CapsuleItemWidget (or a subclass thereof) from given label and data.
3740 *
3741 * @protected
3742 * @param {Mixed} data Custom data of any type.
3743 * @param {string} label The label text.
3744 * @return {OO.ui.CapsuleItemWidget}
3745 */
3746 OO.ui.CapsuleMultiSelectWidget.prototype.createItemWidget = function ( data, label ) {
3747 return new OO.ui.CapsuleItemWidget( { data: data, label: label } );
3748 };
3749
3750 /**
3751 * Get the data of the items in the capsule
3752 *
3753 * @return {Mixed[]}
3754 */
3755 OO.ui.CapsuleMultiSelectWidget.prototype.getItemsData = function () {
3756 return $.map( this.getItems(), function ( e ) { return e.data; } );
3757 };
3758
3759 /**
3760 * Set the items in the capsule by providing data
3761 *
3762 * @chainable
3763 * @param {Mixed[]} datas
3764 * @return {OO.ui.CapsuleMultiSelectWidget}
3765 */
3766 OO.ui.CapsuleMultiSelectWidget.prototype.setItemsFromData = function ( datas ) {
3767 var widget = this,
3768 menu = this.menu,
3769 items = this.getItems();
3770
3771 $.each( datas, function ( i, data ) {
3772 var j, label,
3773 item = menu.getItemFromData( data );
3774
3775 if ( item ) {
3776 label = item.label;
3777 } else if ( widget.allowArbitrary ) {
3778 label = String( data );
3779 } else {
3780 return;
3781 }
3782
3783 item = null;
3784 for ( j = 0; j < items.length; j++ ) {
3785 if ( items[ j ].data === data && items[ j ].label === label ) {
3786 item = items[ j ];
3787 items.splice( j, 1 );
3788 break;
3789 }
3790 }
3791 if ( !item ) {
3792 item = widget.createItemWidget( data, label );
3793 }
3794 widget.addItems( [ item ], i );
3795 } );
3796
3797 if ( items.length ) {
3798 widget.removeItems( items );
3799 }
3800
3801 return this;
3802 };
3803
3804 /**
3805 * Add items to the capsule by providing their data
3806 *
3807 * @chainable
3808 * @param {Mixed[]} datas
3809 * @return {OO.ui.CapsuleMultiSelectWidget}
3810 */
3811 OO.ui.CapsuleMultiSelectWidget.prototype.addItemsFromData = function ( datas ) {
3812 var widget = this,
3813 menu = this.menu,
3814 items = [];
3815
3816 $.each( datas, function ( i, data ) {
3817 var item;
3818
3819 if ( !widget.getItemFromData( data ) ) {
3820 item = menu.getItemFromData( data );
3821 if ( item ) {
3822 items.push( widget.createItemWidget( data, item.label ) );
3823 } else if ( widget.allowArbitrary ) {
3824 items.push( widget.createItemWidget( data, String( data ) ) );
3825 }
3826 }
3827 } );
3828
3829 if ( items.length ) {
3830 this.addItems( items );
3831 }
3832
3833 return this;
3834 };
3835
3836 /**
3837 * Add items to the capsule by providing a label
3838 *
3839 * @param {string} label
3840 * @return {boolean} Whether the item was added or not
3841 */
3842 OO.ui.CapsuleMultiSelectWidget.prototype.addItemFromLabel = function ( label ) {
3843 var item = this.menu.getItemFromLabel( label, true );
3844 if ( item ) {
3845 this.addItemsFromData( [ item.data ] );
3846 return true;
3847 } else if ( this.allowArbitrary && this.$input.val().trim() !== '' ) {
3848 this.addItemsFromData( [ label ] );
3849 return true;
3850 }
3851 return false;
3852 };
3853
3854 /**
3855 * Remove items by data
3856 *
3857 * @chainable
3858 * @param {Mixed[]} datas
3859 * @return {OO.ui.CapsuleMultiSelectWidget}
3860 */
3861 OO.ui.CapsuleMultiSelectWidget.prototype.removeItemsFromData = function ( datas ) {
3862 var widget = this,
3863 items = [];
3864
3865 $.each( datas, function ( i, data ) {
3866 var item = widget.getItemFromData( data );
3867 if ( item ) {
3868 items.push( item );
3869 }
3870 } );
3871
3872 if ( items.length ) {
3873 this.removeItems( items );
3874 }
3875
3876 return this;
3877 };
3878
3879 /**
3880 * @inheritdoc
3881 */
3882 OO.ui.CapsuleMultiSelectWidget.prototype.addItems = function ( items ) {
3883 var same, i, l,
3884 oldItems = this.items.slice();
3885
3886 OO.ui.mixin.GroupElement.prototype.addItems.call( this, items );
3887
3888 if ( this.items.length !== oldItems.length ) {
3889 same = false;
3890 } else {
3891 same = true;
3892 for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
3893 same = same && this.items[ i ] === oldItems[ i ];
3894 }
3895 }
3896 if ( !same ) {
3897 this.emit( 'change', this.getItemsData() );
3898 this.updateIfHeightChanged();
3899 }
3900
3901 return this;
3902 };
3903
3904 /**
3905 * Removes the item from the list and copies its label to `this.$input`.
3906 *
3907 * @param {Object} item
3908 */
3909 OO.ui.CapsuleMultiSelectWidget.prototype.editItem = function ( item ) {
3910 this.$input.val( item.label );
3911 this.updateInputSize();
3912 this.focus();
3913 this.removeItems( [ item ] );
3914 };
3915
3916 /**
3917 * @inheritdoc
3918 */
3919 OO.ui.CapsuleMultiSelectWidget.prototype.removeItems = function ( items ) {
3920 var same, i, l,
3921 oldItems = this.items.slice();
3922
3923 OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items );
3924
3925 if ( this.items.length !== oldItems.length ) {
3926 same = false;
3927 } else {
3928 same = true;
3929 for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
3930 same = same && this.items[ i ] === oldItems[ i ];
3931 }
3932 }
3933 if ( !same ) {
3934 this.emit( 'change', this.getItemsData() );
3935 this.updateIfHeightChanged();
3936 }
3937
3938 return this;
3939 };
3940
3941 /**
3942 * @inheritdoc
3943 */
3944 OO.ui.CapsuleMultiSelectWidget.prototype.clearItems = function () {
3945 if ( this.items.length ) {
3946 OO.ui.mixin.GroupElement.prototype.clearItems.call( this );
3947 this.emit( 'change', this.getItemsData() );
3948 this.updateIfHeightChanged();
3949 }
3950 return this;
3951 };
3952
3953 /**
3954 * Given an item, returns the item after it. If its the last item,
3955 * returns `this.$input`. If no item is passed, returns the very first
3956 * item.
3957 *
3958 * @param {OO.ui.CapsuleItemWidget} [item]
3959 * @return {OO.ui.CapsuleItemWidget|jQuery|boolean}
3960 */
3961 OO.ui.CapsuleMultiSelectWidget.prototype.getNextItem = function ( item ) {
3962 var itemIndex;
3963
3964 if ( item === undefined ) {
3965 return this.items[ 0 ];
3966 }
3967
3968 itemIndex = this.items.indexOf( item );
3969 if ( itemIndex < 0 ) { // Item not in list
3970 return false;
3971 } else if ( itemIndex === this.items.length - 1 ) { // Last item
3972 return this.$input;
3973 } else {
3974 return this.items[ itemIndex + 1 ];
3975 }
3976 };
3977
3978 /**
3979 * Given an item, returns the item before it. If its the first item,
3980 * returns `this.$input`. If no item is passed, returns the very last
3981 * item.
3982 *
3983 * @param {OO.ui.CapsuleItemWidget} [item]
3984 * @return {OO.ui.CapsuleItemWidget|jQuery|boolean}
3985 */
3986 OO.ui.CapsuleMultiSelectWidget.prototype.getPreviousItem = function ( item ) {
3987 var itemIndex;
3988
3989 if ( item === undefined ) {
3990 return this.items[ this.items.length - 1 ];
3991 }
3992
3993 itemIndex = this.items.indexOf( item );
3994 if ( itemIndex < 0 ) { // Item not in list
3995 return false;
3996 } else if ( itemIndex === 0 ) { // First item
3997 return this.$input;
3998 } else {
3999 return this.items[ itemIndex - 1 ];
4000 }
4001 };
4002
4003 /**
4004 * Get the capsule widget's menu.
4005 *
4006 * @return {OO.ui.MenuSelectWidget} Menu widget
4007 */
4008 OO.ui.CapsuleMultiSelectWidget.prototype.getMenu = function () {
4009 return this.menu;
4010 };
4011
4012 /**
4013 * Handle focus events
4014 *
4015 * @private
4016 * @param {jQuery.Event} event
4017 */
4018 OO.ui.CapsuleMultiSelectWidget.prototype.onInputFocus = function () {
4019 if ( !this.isDisabled() ) {
4020 this.menu.toggle( true );
4021 }
4022 };
4023
4024 /**
4025 * Handle blur events
4026 *
4027 * @private
4028 * @param {jQuery.Event} event
4029 */
4030 OO.ui.CapsuleMultiSelectWidget.prototype.onInputBlur = function () {
4031 this.addItemFromLabel( this.$input.val() );
4032 this.clearInput();
4033 };
4034
4035 /**
4036 * Handle focus events
4037 *
4038 * @private
4039 * @param {jQuery.Event} event
4040 */
4041 OO.ui.CapsuleMultiSelectWidget.prototype.onFocusForPopup = function () {
4042 if ( !this.isDisabled() ) {
4043 this.popup.setSize( this.$handle.width() );
4044 this.popup.toggle( true );
4045 this.popup.$element.find( '*' )
4046 .filter( function () { return OO.ui.isFocusableElement( $( this ), true ); } )
4047 .first()
4048 .focus();
4049 }
4050 };
4051
4052 /**
4053 * Handles popup focus out events.
4054 *
4055 * @private
4056 * @param {jQuery.Event} e Focus out event
4057 */
4058 OO.ui.CapsuleMultiSelectWidget.prototype.onPopupFocusOut = function () {
4059 var widget = this.popup;
4060
4061 setTimeout( function () {
4062 if (
4063 widget.isVisible() &&
4064 !OO.ui.contains( widget.$element[ 0 ], document.activeElement, true ) &&
4065 ( !widget.$autoCloseIgnore || !widget.$autoCloseIgnore.has( document.activeElement ).length )
4066 ) {
4067 widget.toggle( false );
4068 }
4069 } );
4070 };
4071
4072 /**
4073 * Handle mouse down events.
4074 *
4075 * @private
4076 * @param {jQuery.Event} e Mouse down event
4077 */
4078 OO.ui.CapsuleMultiSelectWidget.prototype.onMouseDown = function ( e ) {
4079 if ( e.which === OO.ui.MouseButtons.LEFT ) {
4080 this.focus();
4081 return false;
4082 } else {
4083 this.updateInputSize();
4084 }
4085 };
4086
4087 /**
4088 * Handle key press events.
4089 *
4090 * @private
4091 * @param {jQuery.Event} e Key press event
4092 */
4093 OO.ui.CapsuleMultiSelectWidget.prototype.onKeyPress = function ( e ) {
4094 if ( !this.isDisabled() ) {
4095 if ( e.which === OO.ui.Keys.ESCAPE ) {
4096 this.clearInput();
4097 return false;
4098 }
4099
4100 if ( !this.popup ) {
4101 this.menu.toggle( true );
4102 if ( e.which === OO.ui.Keys.ENTER ) {
4103 if ( this.addItemFromLabel( this.$input.val() ) ) {
4104 this.clearInput();
4105 }
4106 return false;
4107 }
4108
4109 // Make sure the input gets resized.
4110 setTimeout( this.updateInputSize.bind( this ), 0 );
4111 }
4112 }
4113 };
4114
4115 /**
4116 * Handle key down events.
4117 *
4118 * @private
4119 * @param {jQuery.Event} e Key down event
4120 */
4121 OO.ui.CapsuleMultiSelectWidget.prototype.onKeyDown = function ( e ) {
4122 if (
4123 !this.isDisabled() &&
4124 this.$input.val() === '' &&
4125 this.items.length
4126 ) {
4127 // 'keypress' event is not triggered for Backspace
4128 if ( e.keyCode === OO.ui.Keys.BACKSPACE ) {
4129 if ( e.metaKey || e.ctrlKey ) {
4130 this.removeItems( this.items.slice( -1 ) );
4131 } else {
4132 this.editItem( this.items[ this.items.length - 1 ] );
4133 }
4134 return false;
4135 } else if ( e.keyCode === OO.ui.Keys.LEFT ) {
4136 this.getPreviousItem().focus();
4137 } else if ( e.keyCode === OO.ui.Keys.RIGHT ) {
4138 this.getNextItem().focus();
4139 }
4140 }
4141 };
4142
4143 /**
4144 * Update the dimensions of the text input field to encompass all available area.
4145 *
4146 * @private
4147 * @param {jQuery.Event} e Event of some sort
4148 */
4149 OO.ui.CapsuleMultiSelectWidget.prototype.updateInputSize = function () {
4150 var $lastItem, direction, contentWidth, currentWidth, bestWidth;
4151 if ( !this.isDisabled() ) {
4152 this.$input.css( 'width', '1em' );
4153 $lastItem = this.$group.children().last();
4154 direction = OO.ui.Element.static.getDir( this.$handle );
4155 contentWidth = this.$input[ 0 ].scrollWidth;
4156 currentWidth = this.$input.width();
4157
4158 if ( contentWidth < currentWidth ) {
4159 // All is fine, don't perform expensive calculations
4160 return;
4161 }
4162
4163 if ( !$lastItem.length ) {
4164 bestWidth = this.$content.innerWidth();
4165 } else {
4166 bestWidth = direction === 'ltr' ?
4167 this.$content.innerWidth() - $lastItem.position().left - $lastItem.outerWidth() :
4168 $lastItem.position().left;
4169 }
4170 // Some safety margin for sanity, because I *really* don't feel like finding out where the few
4171 // pixels this is off by are coming from.
4172 bestWidth -= 10;
4173 if ( contentWidth > bestWidth ) {
4174 // This will result in the input getting shifted to the next line
4175 bestWidth = this.$content.innerWidth() - 10;
4176 }
4177 this.$input.width( Math.floor( bestWidth ) );
4178 this.updateIfHeightChanged();
4179 }
4180 };
4181
4182 /**
4183 * Determine if widget height changed, and if so, update menu position and emit 'resize' event.
4184 *
4185 * @private
4186 */
4187 OO.ui.CapsuleMultiSelectWidget.prototype.updateIfHeightChanged = function () {
4188 var height = this.$element.height();
4189 if ( height !== this.height ) {
4190 this.height = height;
4191 this.menu.position();
4192 this.emit( 'resize' );
4193 }
4194 };
4195
4196 /**
4197 * Handle menu choose events.
4198 *
4199 * @private
4200 * @param {OO.ui.OptionWidget} item Chosen item
4201 */
4202 OO.ui.CapsuleMultiSelectWidget.prototype.onMenuChoose = function ( item ) {
4203 if ( item && item.isVisible() ) {
4204 this.addItemsFromData( [ item.getData() ] );
4205 this.clearInput();
4206 }
4207 };
4208
4209 /**
4210 * Handle menu item change events.
4211 *
4212 * @private
4213 */
4214 OO.ui.CapsuleMultiSelectWidget.prototype.onMenuItemsChange = function () {
4215 this.setItemsFromData( this.getItemsData() );
4216 this.$element.toggleClass( 'oo-ui-capsuleMultiSelectWidget-empty', this.menu.isEmpty() );
4217 };
4218
4219 /**
4220 * Clear the input field
4221 *
4222 * @private
4223 */
4224 OO.ui.CapsuleMultiSelectWidget.prototype.clearInput = function () {
4225 if ( this.$input ) {
4226 this.$input.val( '' );
4227 this.updateInputSize();
4228 }
4229 if ( this.popup ) {
4230 this.popup.toggle( false );
4231 }
4232 this.menu.toggle( false );
4233 this.menu.selectItem();
4234 this.menu.highlightItem();
4235 };
4236
4237 /**
4238 * @inheritdoc
4239 */
4240 OO.ui.CapsuleMultiSelectWidget.prototype.setDisabled = function ( disabled ) {
4241 var i, len;
4242
4243 // Parent method
4244 OO.ui.CapsuleMultiSelectWidget.parent.prototype.setDisabled.call( this, disabled );
4245
4246 if ( this.$input ) {
4247 this.$input.prop( 'disabled', this.isDisabled() );
4248 }
4249 if ( this.menu ) {
4250 this.menu.setDisabled( this.isDisabled() );
4251 }
4252 if ( this.popup ) {
4253 this.popup.setDisabled( this.isDisabled() );
4254 }
4255
4256 if ( this.items ) {
4257 for ( i = 0, len = this.items.length; i < len; i++ ) {
4258 this.items[ i ].updateDisabled();
4259 }
4260 }
4261
4262 return this;
4263 };
4264
4265 /**
4266 * Focus the widget
4267 *
4268 * @chainable
4269 * @return {OO.ui.CapsuleMultiSelectWidget}
4270 */
4271 OO.ui.CapsuleMultiSelectWidget.prototype.focus = function () {
4272 if ( !this.isDisabled() ) {
4273 if ( this.popup ) {
4274 this.popup.setSize( this.$handle.width() );
4275 this.popup.toggle( true );
4276 this.popup.$element.find( '*' )
4277 .filter( function () { return OO.ui.isFocusableElement( $( this ), true ); } )
4278 .first()
4279 .focus();
4280 } else {
4281 this.updateInputSize();
4282 this.menu.toggle( true );
4283 this.$input.focus();
4284 }
4285 }
4286 return this;
4287 };
4288
4289 /**
4290 * SelectFileWidgets allow for selecting files, using the HTML5 File API. These
4291 * widgets can be configured with {@link OO.ui.mixin.IconElement icons} and {@link
4292 * OO.ui.mixin.IndicatorElement indicators}.
4293 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
4294 *
4295 * @example
4296 * // Example of a file select widget
4297 * var selectFile = new OO.ui.SelectFileWidget();
4298 * $( 'body' ).append( selectFile.$element );
4299 *
4300 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets
4301 *
4302 * @class
4303 * @extends OO.ui.Widget
4304 * @mixins OO.ui.mixin.IconElement
4305 * @mixins OO.ui.mixin.IndicatorElement
4306 * @mixins OO.ui.mixin.PendingElement
4307 * @mixins OO.ui.mixin.LabelElement
4308 *
4309 * @constructor
4310 * @param {Object} [config] Configuration options
4311 * @cfg {string[]|null} [accept=null] MIME types to accept. null accepts all types.
4312 * @cfg {string} [placeholder] Text to display when no file is selected.
4313 * @cfg {string} [notsupported] Text to display when file support is missing in the browser.
4314 * @cfg {boolean} [droppable=true] Whether to accept files by drag and drop.
4315 * @cfg {boolean} [showDropTarget=false] Whether to show a drop target. Requires droppable to be true.
4316 * @cfg {number} [thumbnailSizeLimit=20] File size limit in MiB above which to not try and show a
4317 * preview (for performance)
4318 */
4319 OO.ui.SelectFileWidget = function OoUiSelectFileWidget( config ) {
4320 var dragHandler;
4321
4322 // Configuration initialization
4323 config = $.extend( {
4324 accept: null,
4325 placeholder: OO.ui.msg( 'ooui-selectfile-placeholder' ),
4326 notsupported: OO.ui.msg( 'ooui-selectfile-not-supported' ),
4327 droppable: true,
4328 showDropTarget: false,
4329 thumbnailSizeLimit: 20
4330 }, config );
4331
4332 // Parent constructor
4333 OO.ui.SelectFileWidget.parent.call( this, config );
4334
4335 // Mixin constructors
4336 OO.ui.mixin.IconElement.call( this, config );
4337 OO.ui.mixin.IndicatorElement.call( this, config );
4338 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$info } ) );
4339 OO.ui.mixin.LabelElement.call( this, config );
4340
4341 // Properties
4342 this.$info = $( '<span>' );
4343 this.showDropTarget = config.showDropTarget;
4344 this.thumbnailSizeLimit = config.thumbnailSizeLimit;
4345 this.isSupported = this.constructor.static.isSupported();
4346 this.currentFile = null;
4347 if ( Array.isArray( config.accept ) ) {
4348 this.accept = config.accept;
4349 } else {
4350 this.accept = null;
4351 }
4352 this.placeholder = config.placeholder;
4353 this.notsupported = config.notsupported;
4354 this.onFileSelectedHandler = this.onFileSelected.bind( this );
4355
4356 this.selectButton = new OO.ui.ButtonWidget( {
4357 classes: [ 'oo-ui-selectFileWidget-selectButton' ],
4358 label: OO.ui.msg( 'ooui-selectfile-button-select' ),
4359 disabled: this.disabled || !this.isSupported
4360 } );
4361
4362 this.clearButton = new OO.ui.ButtonWidget( {
4363 classes: [ 'oo-ui-selectFileWidget-clearButton' ],
4364 framed: false,
4365 icon: 'close',
4366 disabled: this.disabled
4367 } );
4368
4369 // Events
4370 this.selectButton.$button.on( {
4371 keypress: this.onKeyPress.bind( this )
4372 } );
4373 this.clearButton.connect( this, {
4374 click: 'onClearClick'
4375 } );
4376 if ( config.droppable ) {
4377 dragHandler = this.onDragEnterOrOver.bind( this );
4378 this.$element.on( {
4379 dragenter: dragHandler,
4380 dragover: dragHandler,
4381 dragleave: this.onDragLeave.bind( this ),
4382 drop: this.onDrop.bind( this )
4383 } );
4384 }
4385
4386 // Initialization
4387 this.addInput();
4388 this.$label.addClass( 'oo-ui-selectFileWidget-label' );
4389 this.$info
4390 .addClass( 'oo-ui-selectFileWidget-info' )
4391 .append( this.$icon, this.$label, this.clearButton.$element, this.$indicator );
4392
4393 if ( config.droppable && config.showDropTarget ) {
4394 this.selectButton.setIcon( 'upload' );
4395 this.$thumbnail = $( '<div>' ).addClass( 'oo-ui-selectFileWidget-thumbnail' );
4396 this.setPendingElement( this.$thumbnail );
4397 this.$dropTarget = $( '<div>' )
4398 .addClass( 'oo-ui-selectFileWidget-dropTarget' )
4399 .on( {
4400 click: this.onDropTargetClick.bind( this )
4401 } )
4402 .append(
4403 this.$thumbnail,
4404 this.$info,
4405 this.selectButton.$element,
4406 $( '<span>' )
4407 .addClass( 'oo-ui-selectFileWidget-dropLabel' )
4408 .text( OO.ui.msg( 'ooui-selectfile-dragdrop-placeholder' ) )
4409 );
4410 this.$element.append( this.$dropTarget );
4411 } else {
4412 this.$element
4413 .addClass( 'oo-ui-selectFileWidget' )
4414 .append( this.$info, this.selectButton.$element );
4415 }
4416 this.updateUI();
4417 };
4418
4419 /* Setup */
4420
4421 OO.inheritClass( OO.ui.SelectFileWidget, OO.ui.Widget );
4422 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IconElement );
4423 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IndicatorElement );
4424 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.PendingElement );
4425 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.LabelElement );
4426
4427 /* Static Properties */
4428
4429 /**
4430 * Check if this widget is supported
4431 *
4432 * @static
4433 * @return {boolean}
4434 */
4435 OO.ui.SelectFileWidget.static.isSupported = function () {
4436 var $input;
4437 if ( OO.ui.SelectFileWidget.static.isSupportedCache === null ) {
4438 $input = $( '<input>' ).attr( 'type', 'file' );
4439 OO.ui.SelectFileWidget.static.isSupportedCache = $input[ 0 ].files !== undefined;
4440 }
4441 return OO.ui.SelectFileWidget.static.isSupportedCache;
4442 };
4443
4444 OO.ui.SelectFileWidget.static.isSupportedCache = null;
4445
4446 /* Events */
4447
4448 /**
4449 * @event change
4450 *
4451 * A change event is emitted when the on/off state of the toggle changes.
4452 *
4453 * @param {File|null} value New value
4454 */
4455
4456 /* Methods */
4457
4458 /**
4459 * Get the current value of the field
4460 *
4461 * @return {File|null}
4462 */
4463 OO.ui.SelectFileWidget.prototype.getValue = function () {
4464 return this.currentFile;
4465 };
4466
4467 /**
4468 * Set the current value of the field
4469 *
4470 * @param {File|null} file File to select
4471 */
4472 OO.ui.SelectFileWidget.prototype.setValue = function ( file ) {
4473 if ( this.currentFile !== file ) {
4474 this.currentFile = file;
4475 this.updateUI();
4476 this.emit( 'change', this.currentFile );
4477 }
4478 };
4479
4480 /**
4481 * Focus the widget.
4482 *
4483 * Focusses the select file button.
4484 *
4485 * @chainable
4486 */
4487 OO.ui.SelectFileWidget.prototype.focus = function () {
4488 this.selectButton.$button[ 0 ].focus();
4489 return this;
4490 };
4491
4492 /**
4493 * Update the user interface when a file is selected or unselected
4494 *
4495 * @protected
4496 */
4497 OO.ui.SelectFileWidget.prototype.updateUI = function () {
4498 var $label;
4499 if ( !this.isSupported ) {
4500 this.$element.addClass( 'oo-ui-selectFileWidget-notsupported' );
4501 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
4502 this.setLabel( this.notsupported );
4503 } else {
4504 this.$element.addClass( 'oo-ui-selectFileWidget-supported' );
4505 if ( this.currentFile ) {
4506 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
4507 $label = $( [] );
4508 $label = $label.add(
4509 $( '<span>' )
4510 .addClass( 'oo-ui-selectFileWidget-fileName' )
4511 .text( this.currentFile.name )
4512 );
4513 if ( this.currentFile.type !== '' ) {
4514 $label = $label.add(
4515 $( '<span>' )
4516 .addClass( 'oo-ui-selectFileWidget-fileType' )
4517 .text( this.currentFile.type )
4518 );
4519 }
4520 this.setLabel( $label );
4521
4522 if ( this.showDropTarget ) {
4523 this.pushPending();
4524 this.loadAndGetImageUrl().done( function ( url ) {
4525 this.$thumbnail.css( 'background-image', 'url( ' + url + ' )' );
4526 }.bind( this ) ).fail( function () {
4527 this.$thumbnail.append(
4528 new OO.ui.IconWidget( {
4529 icon: 'attachment',
4530 classes: [ 'oo-ui-selectFileWidget-noThumbnail-icon' ]
4531 } ).$element
4532 );
4533 }.bind( this ) ).always( function () {
4534 this.popPending();
4535 }.bind( this ) );
4536 this.$dropTarget.off( 'click' );
4537 }
4538 } else {
4539 if ( this.showDropTarget ) {
4540 this.$dropTarget.off( 'click' );
4541 this.$dropTarget.on( {
4542 click: this.onDropTargetClick.bind( this )
4543 } );
4544 this.$thumbnail
4545 .empty()
4546 .css( 'background-image', '' );
4547 }
4548 this.$element.addClass( 'oo-ui-selectFileWidget-empty' );
4549 this.setLabel( this.placeholder );
4550 }
4551 }
4552 };
4553
4554 /**
4555 * If the selected file is an image, get its URL and load it.
4556 *
4557 * @return {jQuery.Promise} Promise resolves with the image URL after it has loaded
4558 */
4559 OO.ui.SelectFileWidget.prototype.loadAndGetImageUrl = function () {
4560 var deferred = $.Deferred(),
4561 file = this.currentFile,
4562 reader = new FileReader();
4563
4564 if (
4565 file &&
4566 ( OO.getProp( file, 'type' ) || '' ).indexOf( 'image/' ) === 0 &&
4567 file.size < this.thumbnailSizeLimit * 1024 * 1024
4568 ) {
4569 reader.onload = function ( event ) {
4570 var img = document.createElement( 'img' );
4571 img.addEventListener( 'load', function () {
4572 if (
4573 img.naturalWidth === 0 ||
4574 img.naturalHeight === 0 ||
4575 img.complete === false
4576 ) {
4577 deferred.reject();
4578 } else {
4579 deferred.resolve( event.target.result );
4580 }
4581 } );
4582 img.src = event.target.result;
4583 };
4584 reader.readAsDataURL( file );
4585 } else {
4586 deferred.reject();
4587 }
4588
4589 return deferred.promise();
4590 };
4591
4592 /**
4593 * Add the input to the widget
4594 *
4595 * @private
4596 */
4597 OO.ui.SelectFileWidget.prototype.addInput = function () {
4598 if ( this.$input ) {
4599 this.$input.remove();
4600 }
4601
4602 if ( !this.isSupported ) {
4603 this.$input = null;
4604 return;
4605 }
4606
4607 this.$input = $( '<input>' ).attr( 'type', 'file' );
4608 this.$input.on( 'change', this.onFileSelectedHandler );
4609 this.$input.on( 'click', function ( e ) {
4610 // Prevents dropTarget to get clicked which calls
4611 // a click on this input
4612 e.stopPropagation();
4613 } );
4614 this.$input.attr( {
4615 tabindex: -1
4616 } );
4617 if ( this.accept ) {
4618 this.$input.attr( 'accept', this.accept.join( ', ' ) );
4619 }
4620 this.selectButton.$button.append( this.$input );
4621 };
4622
4623 /**
4624 * Determine if we should accept this file
4625 *
4626 * @private
4627 * @param {string} mimeType File MIME type
4628 * @return {boolean}
4629 */
4630 OO.ui.SelectFileWidget.prototype.isAllowedType = function ( mimeType ) {
4631 var i, mimeTest;
4632
4633 if ( !this.accept || !mimeType ) {
4634 return true;
4635 }
4636
4637 for ( i = 0; i < this.accept.length; i++ ) {
4638 mimeTest = this.accept[ i ];
4639 if ( mimeTest === mimeType ) {
4640 return true;
4641 } else if ( mimeTest.substr( -2 ) === '/*' ) {
4642 mimeTest = mimeTest.substr( 0, mimeTest.length - 1 );
4643 if ( mimeType.substr( 0, mimeTest.length ) === mimeTest ) {
4644 return true;
4645 }
4646 }
4647 }
4648
4649 return false;
4650 };
4651
4652 /**
4653 * Handle file selection from the input
4654 *
4655 * @private
4656 * @param {jQuery.Event} e
4657 */
4658 OO.ui.SelectFileWidget.prototype.onFileSelected = function ( e ) {
4659 var file = OO.getProp( e.target, 'files', 0 ) || null;
4660
4661 if ( file && !this.isAllowedType( file.type ) ) {
4662 file = null;
4663 }
4664
4665 this.setValue( file );
4666 this.addInput();
4667 };
4668
4669 /**
4670 * Handle clear button click events.
4671 *
4672 * @private
4673 */
4674 OO.ui.SelectFileWidget.prototype.onClearClick = function () {
4675 this.setValue( null );
4676 return false;
4677 };
4678
4679 /**
4680 * Handle key press events.
4681 *
4682 * @private
4683 * @param {jQuery.Event} e Key press event
4684 */
4685 OO.ui.SelectFileWidget.prototype.onKeyPress = function ( e ) {
4686 if ( this.isSupported && !this.isDisabled() && this.$input &&
4687 ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
4688 ) {
4689 this.$input.click();
4690 return false;
4691 }
4692 };
4693
4694 /**
4695 * Handle drop target click events.
4696 *
4697 * @private
4698 * @param {jQuery.Event} e Key press event
4699 */
4700 OO.ui.SelectFileWidget.prototype.onDropTargetClick = function () {
4701 if ( this.isSupported && !this.isDisabled() && this.$input ) {
4702 this.$input.click();
4703 return false;
4704 }
4705 };
4706
4707 /**
4708 * Handle drag enter and over events
4709 *
4710 * @private
4711 * @param {jQuery.Event} e Drag event
4712 */
4713 OO.ui.SelectFileWidget.prototype.onDragEnterOrOver = function ( e ) {
4714 var itemOrFile,
4715 droppableFile = false,
4716 dt = e.originalEvent.dataTransfer;
4717
4718 e.preventDefault();
4719 e.stopPropagation();
4720
4721 if ( this.isDisabled() || !this.isSupported ) {
4722 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
4723 dt.dropEffect = 'none';
4724 return false;
4725 }
4726
4727 // DataTransferItem and File both have a type property, but in Chrome files
4728 // have no information at this point.
4729 itemOrFile = OO.getProp( dt, 'items', 0 ) || OO.getProp( dt, 'files', 0 );
4730 if ( itemOrFile ) {
4731 if ( this.isAllowedType( itemOrFile.type ) ) {
4732 droppableFile = true;
4733 }
4734 // dt.types is Array-like, but not an Array
4735 } else if ( Array.prototype.indexOf.call( OO.getProp( dt, 'types' ) || [], 'Files' ) !== -1 ) {
4736 // File information is not available at this point for security so just assume
4737 // it is acceptable for now.
4738 // https://bugzilla.mozilla.org/show_bug.cgi?id=640534
4739 droppableFile = true;
4740 }
4741
4742 this.$element.toggleClass( 'oo-ui-selectFileWidget-canDrop', droppableFile );
4743 if ( !droppableFile ) {
4744 dt.dropEffect = 'none';
4745 }
4746
4747 return false;
4748 };
4749
4750 /**
4751 * Handle drag leave events
4752 *
4753 * @private
4754 * @param {jQuery.Event} e Drag event
4755 */
4756 OO.ui.SelectFileWidget.prototype.onDragLeave = function () {
4757 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
4758 };
4759
4760 /**
4761 * Handle drop events
4762 *
4763 * @private
4764 * @param {jQuery.Event} e Drop event
4765 */
4766 OO.ui.SelectFileWidget.prototype.onDrop = function ( e ) {
4767 var file = null,
4768 dt = e.originalEvent.dataTransfer;
4769
4770 e.preventDefault();
4771 e.stopPropagation();
4772 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
4773
4774 if ( this.isDisabled() || !this.isSupported ) {
4775 return false;
4776 }
4777
4778 file = OO.getProp( dt, 'files', 0 );
4779 if ( file && !this.isAllowedType( file.type ) ) {
4780 file = null;
4781 }
4782 if ( file ) {
4783 this.setValue( file );
4784 }
4785
4786 return false;
4787 };
4788
4789 /**
4790 * @inheritdoc
4791 */
4792 OO.ui.SelectFileWidget.prototype.setDisabled = function ( disabled ) {
4793 OO.ui.SelectFileWidget.parent.prototype.setDisabled.call( this, disabled );
4794 if ( this.selectButton ) {
4795 this.selectButton.setDisabled( disabled );
4796 }
4797 if ( this.clearButton ) {
4798 this.clearButton.setDisabled( disabled );
4799 }
4800 return this;
4801 };
4802
4803 /**
4804 * Progress bars visually display the status of an operation, such as a download,
4805 * and can be either determinate or indeterminate:
4806 *
4807 * - **determinate** process bars show the percent of an operation that is complete.
4808 *
4809 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
4810 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
4811 * not use percentages.
4812 *
4813 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
4814 *
4815 * @example
4816 * // Examples of determinate and indeterminate progress bars.
4817 * var progressBar1 = new OO.ui.ProgressBarWidget( {
4818 * progress: 33
4819 * } );
4820 * var progressBar2 = new OO.ui.ProgressBarWidget();
4821 *
4822 * // Create a FieldsetLayout to layout progress bars
4823 * var fieldset = new OO.ui.FieldsetLayout;
4824 * fieldset.addItems( [
4825 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
4826 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
4827 * ] );
4828 * $( 'body' ).append( fieldset.$element );
4829 *
4830 * @class
4831 * @extends OO.ui.Widget
4832 *
4833 * @constructor
4834 * @param {Object} [config] Configuration options
4835 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
4836 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
4837 * By default, the progress bar is indeterminate.
4838 */
4839 OO.ui.ProgressBarWidget = function OoUiProgressBarWidget( config ) {
4840 // Configuration initialization
4841 config = config || {};
4842
4843 // Parent constructor
4844 OO.ui.ProgressBarWidget.parent.call( this, config );
4845
4846 // Properties
4847 this.$bar = $( '<div>' );
4848 this.progress = null;
4849
4850 // Initialization
4851 this.setProgress( config.progress !== undefined ? config.progress : false );
4852 this.$bar.addClass( 'oo-ui-progressBarWidget-bar' );
4853 this.$element
4854 .attr( {
4855 role: 'progressbar',
4856 'aria-valuemin': 0,
4857 'aria-valuemax': 100
4858 } )
4859 .addClass( 'oo-ui-progressBarWidget' )
4860 .append( this.$bar );
4861 };
4862
4863 /* Setup */
4864
4865 OO.inheritClass( OO.ui.ProgressBarWidget, OO.ui.Widget );
4866
4867 /* Static Properties */
4868
4869 OO.ui.ProgressBarWidget.static.tagName = 'div';
4870
4871 /* Methods */
4872
4873 /**
4874 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
4875 *
4876 * @return {number|boolean} Progress percent
4877 */
4878 OO.ui.ProgressBarWidget.prototype.getProgress = function () {
4879 return this.progress;
4880 };
4881
4882 /**
4883 * Set the percent of the process completed or `false` for an indeterminate process.
4884 *
4885 * @param {number|boolean} progress Progress percent or `false` for indeterminate
4886 */
4887 OO.ui.ProgressBarWidget.prototype.setProgress = function ( progress ) {
4888 this.progress = progress;
4889
4890 if ( progress !== false ) {
4891 this.$bar.css( 'width', this.progress + '%' );
4892 this.$element.attr( 'aria-valuenow', this.progress );
4893 } else {
4894 this.$bar.css( 'width', '' );
4895 this.$element.removeAttr( 'aria-valuenow' );
4896 }
4897 this.$element.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress );
4898 };
4899
4900 /**
4901 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
4902 * and a menu of search results, which is displayed beneath the query
4903 * field. Unlike {@link OO.ui.mixin.LookupElement lookup menus}, search result menus are always visible to the user.
4904 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
4905 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
4906 *
4907 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
4908 * the [OOjs UI demos][1] for an example.
4909 *
4910 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
4911 *
4912 * @class
4913 * @extends OO.ui.Widget
4914 *
4915 * @constructor
4916 * @param {Object} [config] Configuration options
4917 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
4918 * @cfg {string} [value] Initial query value
4919 */
4920 OO.ui.SearchWidget = function OoUiSearchWidget( config ) {
4921 // Configuration initialization
4922 config = config || {};
4923
4924 // Parent constructor
4925 OO.ui.SearchWidget.parent.call( this, config );
4926
4927 // Properties
4928 this.query = new OO.ui.TextInputWidget( {
4929 icon: 'search',
4930 placeholder: config.placeholder,
4931 value: config.value
4932 } );
4933 this.results = new OO.ui.SelectWidget();
4934 this.$query = $( '<div>' );
4935 this.$results = $( '<div>' );
4936
4937 // Events
4938 this.query.connect( this, {
4939 change: 'onQueryChange',
4940 enter: 'onQueryEnter'
4941 } );
4942 this.query.$input.on( 'keydown', this.onQueryKeydown.bind( this ) );
4943
4944 // Initialization
4945 this.$query
4946 .addClass( 'oo-ui-searchWidget-query' )
4947 .append( this.query.$element );
4948 this.$results
4949 .addClass( 'oo-ui-searchWidget-results' )
4950 .append( this.results.$element );
4951 this.$element
4952 .addClass( 'oo-ui-searchWidget' )
4953 .append( this.$results, this.$query );
4954 };
4955
4956 /* Setup */
4957
4958 OO.inheritClass( OO.ui.SearchWidget, OO.ui.Widget );
4959
4960 /* Methods */
4961
4962 /**
4963 * Handle query key down events.
4964 *
4965 * @private
4966 * @param {jQuery.Event} e Key down event
4967 */
4968 OO.ui.SearchWidget.prototype.onQueryKeydown = function ( e ) {
4969 var highlightedItem, nextItem,
4970 dir = e.which === OO.ui.Keys.DOWN ? 1 : ( e.which === OO.ui.Keys.UP ? -1 : 0 );
4971
4972 if ( dir ) {
4973 highlightedItem = this.results.getHighlightedItem();
4974 if ( !highlightedItem ) {
4975 highlightedItem = this.results.getSelectedItem();
4976 }
4977 nextItem = this.results.getRelativeSelectableItem( highlightedItem, dir );
4978 this.results.highlightItem( nextItem );
4979 nextItem.scrollElementIntoView();
4980 }
4981 };
4982
4983 /**
4984 * Handle select widget select events.
4985 *
4986 * Clears existing results. Subclasses should repopulate items according to new query.
4987 *
4988 * @private
4989 * @param {string} value New value
4990 */
4991 OO.ui.SearchWidget.prototype.onQueryChange = function () {
4992 // Reset
4993 this.results.clearItems();
4994 };
4995
4996 /**
4997 * Handle select widget enter key events.
4998 *
4999 * Chooses highlighted item.
5000 *
5001 * @private
5002 * @param {string} value New value
5003 */
5004 OO.ui.SearchWidget.prototype.onQueryEnter = function () {
5005 var highlightedItem = this.results.getHighlightedItem();
5006 if ( highlightedItem ) {
5007 this.results.chooseItem( highlightedItem );
5008 }
5009 };
5010
5011 /**
5012 * Get the query input.
5013 *
5014 * @return {OO.ui.TextInputWidget} Query input
5015 */
5016 OO.ui.SearchWidget.prototype.getQuery = function () {
5017 return this.query;
5018 };
5019
5020 /**
5021 * Get the search results menu.
5022 *
5023 * @return {OO.ui.SelectWidget} Menu of search results
5024 */
5025 OO.ui.SearchWidget.prototype.getResults = function () {
5026 return this.results;
5027 };
5028
5029 /**
5030 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
5031 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
5032 * (to adjust the value in increments) to allow the user to enter a number.
5033 *
5034 * @example
5035 * // Example: A NumberInputWidget.
5036 * var numberInput = new OO.ui.NumberInputWidget( {
5037 * label: 'NumberInputWidget',
5038 * input: { value: 5 },
5039 * min: 1,
5040 * max: 10
5041 * } );
5042 * $( 'body' ).append( numberInput.$element );
5043 *
5044 * @class
5045 * @extends OO.ui.Widget
5046 *
5047 * @constructor
5048 * @param {Object} [config] Configuration options
5049 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
5050 * @cfg {Object} [minusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget decrementing button widget}.
5051 * @cfg {Object} [plusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget incrementing button widget}.
5052 * @cfg {boolean} [isInteger=false] Whether the field accepts only integer values.
5053 * @cfg {number} [min=-Infinity] Minimum allowed value
5054 * @cfg {number} [max=Infinity] Maximum allowed value
5055 * @cfg {number} [step=1] Delta when using the buttons or up/down arrow keys
5056 * @cfg {number|null} [pageStep] Delta when using the page-up/page-down keys. Defaults to 10 times #step.
5057 * @cfg {boolean} [showButtons=true] Whether to show the plus and minus buttons.
5058 */
5059 OO.ui.NumberInputWidget = function OoUiNumberInputWidget( config ) {
5060 // Configuration initialization
5061 config = $.extend( {
5062 isInteger: false,
5063 min: -Infinity,
5064 max: Infinity,
5065 step: 1,
5066 pageStep: null,
5067 showButtons: true
5068 }, config );
5069
5070 // Parent constructor
5071 OO.ui.NumberInputWidget.parent.call( this, config );
5072
5073 // Properties
5074 this.input = new OO.ui.TextInputWidget( $.extend(
5075 {
5076 disabled: this.isDisabled(),
5077 type: 'number'
5078 },
5079 config.input
5080 ) );
5081 if ( config.showButtons ) {
5082 this.minusButton = new OO.ui.ButtonWidget( $.extend(
5083 {
5084 disabled: this.isDisabled(),
5085 tabIndex: -1
5086 },
5087 config.minusButton,
5088 {
5089 classes: [ 'oo-ui-numberInputWidget-minusButton' ],
5090 label: '−'
5091 }
5092 ) );
5093 this.plusButton = new OO.ui.ButtonWidget( $.extend(
5094 {
5095 disabled: this.isDisabled(),
5096 tabIndex: -1
5097 },
5098 config.plusButton,
5099 {
5100 classes: [ 'oo-ui-numberInputWidget-plusButton' ],
5101 label: '+'
5102 }
5103 ) );
5104 }
5105
5106 // Events
5107 this.input.connect( this, {
5108 change: this.emit.bind( this, 'change' ),
5109 enter: this.emit.bind( this, 'enter' )
5110 } );
5111 this.input.$input.on( {
5112 keydown: this.onKeyDown.bind( this ),
5113 'wheel mousewheel DOMMouseScroll': this.onWheel.bind( this )
5114 } );
5115 if ( config.showButtons ) {
5116 this.plusButton.connect( this, {
5117 click: [ 'onButtonClick', +1 ]
5118 } );
5119 this.minusButton.connect( this, {
5120 click: [ 'onButtonClick', -1 ]
5121 } );
5122 }
5123
5124 // Initialization
5125 this.setIsInteger( !!config.isInteger );
5126 this.setRange( config.min, config.max );
5127 this.setStep( config.step, config.pageStep );
5128
5129 this.$field = $( '<div>' ).addClass( 'oo-ui-numberInputWidget-field' )
5130 .append( this.input.$element );
5131 this.$element.addClass( 'oo-ui-numberInputWidget' ).append( this.$field );
5132 if ( config.showButtons ) {
5133 this.$field
5134 .prepend( this.minusButton.$element )
5135 .append( this.plusButton.$element );
5136 this.$element.addClass( 'oo-ui-numberInputWidget-buttoned' );
5137 }
5138 this.input.setValidation( this.validateNumber.bind( this ) );
5139 };
5140
5141 /* Setup */
5142
5143 OO.inheritClass( OO.ui.NumberInputWidget, OO.ui.Widget );
5144
5145 /* Events */
5146
5147 /**
5148 * A `change` event is emitted when the value of the input changes.
5149 *
5150 * @event change
5151 */
5152
5153 /**
5154 * An `enter` event is emitted when the user presses 'enter' inside the text box.
5155 *
5156 * @event enter
5157 */
5158
5159 /* Methods */
5160
5161 /**
5162 * Set whether only integers are allowed
5163 *
5164 * @param {boolean} flag
5165 */
5166 OO.ui.NumberInputWidget.prototype.setIsInteger = function ( flag ) {
5167 this.isInteger = !!flag;
5168 this.input.setValidityFlag();
5169 };
5170
5171 /**
5172 * Get whether only integers are allowed
5173 *
5174 * @return {boolean} Flag value
5175 */
5176 OO.ui.NumberInputWidget.prototype.getIsInteger = function () {
5177 return this.isInteger;
5178 };
5179
5180 /**
5181 * Set the range of allowed values
5182 *
5183 * @param {number} min Minimum allowed value
5184 * @param {number} max Maximum allowed value
5185 */
5186 OO.ui.NumberInputWidget.prototype.setRange = function ( min, max ) {
5187 if ( min > max ) {
5188 throw new Error( 'Minimum (' + min + ') must not be greater than maximum (' + max + ')' );
5189 }
5190 this.min = min;
5191 this.max = max;
5192 this.input.setValidityFlag();
5193 };
5194
5195 /**
5196 * Get the current range
5197 *
5198 * @return {number[]} Minimum and maximum values
5199 */
5200 OO.ui.NumberInputWidget.prototype.getRange = function () {
5201 return [ this.min, this.max ];
5202 };
5203
5204 /**
5205 * Set the stepping deltas
5206 *
5207 * @param {number} step Normal step
5208 * @param {number|null} pageStep Page step. If null, 10 * step will be used.
5209 */
5210 OO.ui.NumberInputWidget.prototype.setStep = function ( step, pageStep ) {
5211 if ( step <= 0 ) {
5212 throw new Error( 'Step value must be positive' );
5213 }
5214 if ( pageStep === null ) {
5215 pageStep = step * 10;
5216 } else if ( pageStep <= 0 ) {
5217 throw new Error( 'Page step value must be positive' );
5218 }
5219 this.step = step;
5220 this.pageStep = pageStep;
5221 };
5222
5223 /**
5224 * Get the current stepping values
5225 *
5226 * @return {number[]} Step and page step
5227 */
5228 OO.ui.NumberInputWidget.prototype.getStep = function () {
5229 return [ this.step, this.pageStep ];
5230 };
5231
5232 /**
5233 * Get the current value of the widget
5234 *
5235 * @return {string}
5236 */
5237 OO.ui.NumberInputWidget.prototype.getValue = function () {
5238 return this.input.getValue();
5239 };
5240
5241 /**
5242 * Get the current value of the widget as a number
5243 *
5244 * @return {number} May be NaN, or an invalid number
5245 */
5246 OO.ui.NumberInputWidget.prototype.getNumericValue = function () {
5247 return +this.input.getValue();
5248 };
5249
5250 /**
5251 * Set the value of the widget
5252 *
5253 * @param {string} value Invalid values are allowed
5254 */
5255 OO.ui.NumberInputWidget.prototype.setValue = function ( value ) {
5256 this.input.setValue( value );
5257 };
5258
5259 /**
5260 * Adjust the value of the widget
5261 *
5262 * @param {number} delta Adjustment amount
5263 */
5264 OO.ui.NumberInputWidget.prototype.adjustValue = function ( delta ) {
5265 var n, v = this.getNumericValue();
5266
5267 delta = +delta;
5268 if ( isNaN( delta ) || !isFinite( delta ) ) {
5269 throw new Error( 'Delta must be a finite number' );
5270 }
5271
5272 if ( isNaN( v ) ) {
5273 n = 0;
5274 } else {
5275 n = v + delta;
5276 n = Math.max( Math.min( n, this.max ), this.min );
5277 if ( this.isInteger ) {
5278 n = Math.round( n );
5279 }
5280 }
5281
5282 if ( n !== v ) {
5283 this.setValue( n );
5284 }
5285 };
5286
5287 /**
5288 * Validate input
5289 *
5290 * @private
5291 * @param {string} value Field value
5292 * @return {boolean}
5293 */
5294 OO.ui.NumberInputWidget.prototype.validateNumber = function ( value ) {
5295 var n = +value;
5296 if ( isNaN( n ) || !isFinite( n ) ) {
5297 return false;
5298 }
5299
5300 /*jshint bitwise: false */
5301 if ( this.isInteger && ( n | 0 ) !== n ) {
5302 return false;
5303 }
5304 /*jshint bitwise: true */
5305
5306 if ( n < this.min || n > this.max ) {
5307 return false;
5308 }
5309
5310 return true;
5311 };
5312
5313 /**
5314 * Handle mouse click events.
5315 *
5316 * @private
5317 * @param {number} dir +1 or -1
5318 */
5319 OO.ui.NumberInputWidget.prototype.onButtonClick = function ( dir ) {
5320 this.adjustValue( dir * this.step );
5321 };
5322
5323 /**
5324 * Handle mouse wheel events.
5325 *
5326 * @private
5327 * @param {jQuery.Event} event
5328 */
5329 OO.ui.NumberInputWidget.prototype.onWheel = function ( event ) {
5330 var delta = 0;
5331
5332 if ( !this.isDisabled() && this.input.$input.is( ':focus' ) ) {
5333 // Standard 'wheel' event
5334 if ( event.originalEvent.deltaMode !== undefined ) {
5335 this.sawWheelEvent = true;
5336 }
5337 if ( event.originalEvent.deltaY ) {
5338 delta = -event.originalEvent.deltaY;
5339 } else if ( event.originalEvent.deltaX ) {
5340 delta = event.originalEvent.deltaX;
5341 }
5342
5343 // Non-standard events
5344 if ( !this.sawWheelEvent ) {
5345 if ( event.originalEvent.wheelDeltaX ) {
5346 delta = -event.originalEvent.wheelDeltaX;
5347 } else if ( event.originalEvent.wheelDeltaY ) {
5348 delta = event.originalEvent.wheelDeltaY;
5349 } else if ( event.originalEvent.wheelDelta ) {
5350 delta = event.originalEvent.wheelDelta;
5351 } else if ( event.originalEvent.detail ) {
5352 delta = -event.originalEvent.detail;
5353 }
5354 }
5355
5356 if ( delta ) {
5357 delta = delta < 0 ? -1 : 1;
5358 this.adjustValue( delta * this.step );
5359 }
5360
5361 return false;
5362 }
5363 };
5364
5365 /**
5366 * Handle key down events.
5367 *
5368 * @private
5369 * @param {jQuery.Event} e Key down event
5370 */
5371 OO.ui.NumberInputWidget.prototype.onKeyDown = function ( e ) {
5372 if ( !this.isDisabled() ) {
5373 switch ( e.which ) {
5374 case OO.ui.Keys.UP:
5375 this.adjustValue( this.step );
5376 return false;
5377 case OO.ui.Keys.DOWN:
5378 this.adjustValue( -this.step );
5379 return false;
5380 case OO.ui.Keys.PAGEUP:
5381 this.adjustValue( this.pageStep );
5382 return false;
5383 case OO.ui.Keys.PAGEDOWN:
5384 this.adjustValue( -this.pageStep );
5385 return false;
5386 }
5387 }
5388 };
5389
5390 /**
5391 * @inheritdoc
5392 */
5393 OO.ui.NumberInputWidget.prototype.setDisabled = function ( disabled ) {
5394 // Parent method
5395 OO.ui.NumberInputWidget.parent.prototype.setDisabled.call( this, disabled );
5396
5397 if ( this.input ) {
5398 this.input.setDisabled( this.isDisabled() );
5399 }
5400 if ( this.minusButton ) {
5401 this.minusButton.setDisabled( this.isDisabled() );
5402 }
5403 if ( this.plusButton ) {
5404 this.plusButton.setDisabled( this.isDisabled() );
5405 }
5406
5407 return this;
5408 };
5409
5410 }( OO ) );