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