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