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