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