Merge "Fix and make some types in PHPDoc and JSDoc tags more specific"
[lhc/web/wiklou.git] / resources / lib / oojs-ui / oojs-ui-widgets.js
1 /*!
2 * OOjs UI v0.22.4
3 * https://www.mediawiki.org/wiki/OOjs_UI
4 *
5 * Copyright 2011–2017 OOjs UI Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
8 *
9 * Date: 2017-08-03T19:36:51Z
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 * @cfg {boolean} [draggable] The items are draggable. This can change with #toggleDraggable
28 * but the draggable state should be called from the DraggableGroupElement, which updates
29 * the whole group
30 */
31 OO.ui.mixin.DraggableElement = function OoUiMixinDraggableElement( config ) {
32 config = config || {};
33
34 // Properties
35 this.index = null;
36 this.$handle = config.$handle || this.$element;
37 this.wasHandleUsed = null;
38 this.draggable = config.draggable === undefined ? true : !!config.draggable;
39
40 // Initialize and events
41 this.$element.addClass( 'oo-ui-draggableElement' )
42 // We make the entire element draggable, not just the handle, so that
43 // the whole element appears to move. wasHandleUsed prevents drags from
44 // starting outside the handle
45 .attr( 'draggable', true )
46 .on( {
47 mousedown: this.onDragMouseDown.bind( this ),
48 dragstart: this.onDragStart.bind( this ),
49 dragover: this.onDragOver.bind( this ),
50 dragend: this.onDragEnd.bind( this ),
51 drop: this.onDrop.bind( this )
52 } );
53 this.$handle.addClass( 'oo-ui-draggableElement-handle' );
54 };
55
56 OO.initClass( OO.ui.mixin.DraggableElement );
57
58 /* Events */
59
60 /**
61 * @event dragstart
62 *
63 * A dragstart event is emitted when the user clicks and begins dragging an item.
64 * @param {OO.ui.mixin.DraggableElement} item The item the user has clicked and is dragging with the mouse.
65 */
66
67 /**
68 * @event dragend
69 * A dragend event is emitted when the user drags an item and releases the mouse,
70 * thus terminating the drag operation.
71 */
72
73 /**
74 * @event drop
75 * A drop event is emitted when the user drags an item and then releases the mouse button
76 * over a valid target.
77 */
78
79 /* Static Properties */
80
81 /**
82 * @inheritdoc OO.ui.mixin.ButtonElement
83 */
84 OO.ui.mixin.DraggableElement.static.cancelButtonMouseDownEvents = false;
85
86 /* Methods */
87
88 /**
89 * Change the draggable state of this widget.
90 * This allows users to temporarily halt the dragging operations.
91 *
92 * @param {boolean} isDraggable Widget supports draggable operations
93 * @fires draggable
94 */
95 OO.ui.mixin.DraggableElement.prototype.toggleDraggable = function ( isDraggable ) {
96 isDraggable = isDraggable !== undefined ? !!isDraggable : !this.draggable;
97
98 if ( this.draggable !== isDraggable ) {
99 this.draggable = isDraggable;
100
101 this.$handle.toggleClass( 'oo-ui-draggableElement-undraggable', !this.draggable );
102 }
103 };
104
105 /**
106 * Check the draggable state of this widget
107 *
108 * @return {boolean} Widget supports draggable operations
109 */
110 OO.ui.mixin.DraggableElement.prototype.isDraggable = function () {
111 return this.draggable;
112 };
113
114 /**
115 * Respond to mousedown event.
116 *
117 * @private
118 * @param {jQuery.Event} e Drag event
119 */
120 OO.ui.mixin.DraggableElement.prototype.onDragMouseDown = function ( e ) {
121 if ( !this.isDraggable() ) {
122 return;
123 }
124
125 this.wasHandleUsed =
126 // Optimization: if the handle is the whole element this is always true
127 this.$handle[ 0 ] === this.$element[ 0 ] ||
128 // Check the mousedown occurred inside the handle
129 OO.ui.contains( this.$handle[ 0 ], e.target, true );
130 };
131
132 /**
133 * Respond to dragstart event.
134 *
135 * @private
136 * @param {jQuery.Event} e Drag event
137 * @return {boolean} False if the event is cancelled
138 * @fires dragstart
139 */
140 OO.ui.mixin.DraggableElement.prototype.onDragStart = function ( e ) {
141 var element = this,
142 dataTransfer = e.originalEvent.dataTransfer;
143
144 if ( !this.wasHandleUsed || !this.isDraggable() ) {
145 return false;
146 }
147
148 // Define drop effect
149 dataTransfer.dropEffect = 'none';
150 dataTransfer.effectAllowed = 'move';
151 // Support: Firefox
152 // We must set up a dataTransfer data property or Firefox seems to
153 // ignore the fact the element is draggable.
154 try {
155 dataTransfer.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
156 } catch ( err ) {
157 // The above is only for Firefox. Move on if it fails.
158 }
159 // Briefly add a 'clone' class to style the browser's native drag image
160 this.$element.addClass( 'oo-ui-draggableElement-clone' );
161 // Add placeholder class after the browser has rendered the clone
162 setTimeout( function () {
163 element.$element
164 .removeClass( 'oo-ui-draggableElement-clone' )
165 .addClass( 'oo-ui-draggableElement-placeholder' );
166 } );
167 // Emit event
168 this.emit( 'dragstart', this );
169 return true;
170 };
171
172 /**
173 * Respond to dragend event.
174 *
175 * @private
176 * @fires dragend
177 */
178 OO.ui.mixin.DraggableElement.prototype.onDragEnd = function () {
179 this.$element.removeClass( 'oo-ui-draggableElement-placeholder' );
180 this.emit( 'dragend' );
181 };
182
183 /**
184 * Handle drop event.
185 *
186 * @private
187 * @param {jQuery.Event} e Drop event
188 * @fires drop
189 */
190 OO.ui.mixin.DraggableElement.prototype.onDrop = function ( e ) {
191 e.preventDefault();
192 this.emit( 'drop', e );
193 };
194
195 /**
196 * In order for drag/drop to work, the dragover event must
197 * return false and stop propogation.
198 *
199 * @param {jQuery.Event} e Drag event
200 * @private
201 */
202 OO.ui.mixin.DraggableElement.prototype.onDragOver = function ( e ) {
203 e.preventDefault();
204 };
205
206 /**
207 * Set item index.
208 * Store it in the DOM so we can access from the widget drag event
209 *
210 * @private
211 * @param {number} index Item index
212 */
213 OO.ui.mixin.DraggableElement.prototype.setIndex = function ( index ) {
214 if ( this.index !== index ) {
215 this.index = index;
216 this.$element.data( 'index', index );
217 }
218 };
219
220 /**
221 * Get item index
222 *
223 * @private
224 * @return {number} Item index
225 */
226 OO.ui.mixin.DraggableElement.prototype.getIndex = function () {
227 return this.index;
228 };
229
230 /**
231 * DraggableGroupElement is a mixin class used to create a group element to
232 * contain draggable elements, which are items that can be clicked and dragged by a mouse.
233 * The class is used with OO.ui.mixin.DraggableElement.
234 *
235 * @abstract
236 * @class
237 * @mixins OO.ui.mixin.GroupElement
238 *
239 * @constructor
240 * @param {Object} [config] Configuration options
241 * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation
242 * should match the layout of the items. Items displayed in a single row
243 * or in several rows should use horizontal orientation. The vertical orientation should only be
244 * used when the items are displayed in a single column. Defaults to 'vertical'
245 * @cfg {boolean} [draggable] The items are draggable. This can change with #toggleDraggable
246 */
247 OO.ui.mixin.DraggableGroupElement = function OoUiMixinDraggableGroupElement( config ) {
248 // Configuration initialization
249 config = config || {};
250
251 // Parent constructor
252 OO.ui.mixin.GroupElement.call( this, config );
253
254 // Properties
255 this.orientation = config.orientation || 'vertical';
256 this.dragItem = null;
257 this.itemKeys = {};
258 this.dir = null;
259 this.itemsOrder = null;
260 this.draggable = config.draggable === undefined ? true : !!config.draggable;
261
262 // Events
263 this.aggregate( {
264 dragstart: 'itemDragStart',
265 dragend: 'itemDragEnd',
266 drop: 'itemDrop'
267 } );
268 this.connect( this, {
269 itemDragStart: 'onItemDragStart',
270 itemDrop: 'onItemDropOrDragEnd',
271 itemDragEnd: 'onItemDropOrDragEnd'
272 } );
273
274 // Initialize
275 if ( Array.isArray( config.items ) ) {
276 this.addItems( config.items );
277 }
278 this.$element
279 .addClass( 'oo-ui-draggableGroupElement' )
280 .append( this.$status )
281 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation === 'horizontal' );
282 };
283
284 /* Setup */
285 OO.mixinClass( OO.ui.mixin.DraggableGroupElement, OO.ui.mixin.GroupElement );
286
287 /* Events */
288
289 /**
290 * An item has been dragged to a new position, but not yet dropped.
291 *
292 * @event drag
293 * @param {OO.ui.mixin.DraggableElement} item Dragged item
294 * @param {number} [newIndex] New index for the item
295 */
296
297 /**
298 * An item has been dropped at a new position.
299 *
300 * @event reorder
301 * @param {OO.ui.mixin.DraggableElement} item Reordered item
302 * @param {number} [newIndex] New index for the item
303 */
304
305 /**
306 * Draggable state of this widget has changed.
307 *
308 * @event draggable
309 * @param {boolean} [draggable] Widget is draggable
310 */
311
312 /* Methods */
313
314 /**
315 * Change the draggable state of this widget.
316 * This allows users to temporarily halt the dragging operations.
317 *
318 * @param {boolean} isDraggable Widget supports draggable operations
319 * @fires draggable
320 */
321 OO.ui.mixin.DraggableGroupElement.prototype.toggleDraggable = function ( isDraggable ) {
322 isDraggable = isDraggable !== undefined ? !!isDraggable : !this.draggable;
323
324 if ( this.draggable !== isDraggable ) {
325 this.draggable = isDraggable;
326
327 // Tell the items their draggable state changed
328 this.getItems().forEach( function ( item ) {
329 item.toggleDraggable( this.draggable );
330 }.bind( this ) );
331
332 // Emit event
333 this.emit( 'draggable', this.draggable );
334 }
335 };
336
337 /**
338 * Check the draggable state of this widget
339 *
340 * @return {boolean} Widget supports draggable operations
341 */
342 OO.ui.mixin.DraggableGroupElement.prototype.isDraggable = function () {
343 return this.draggable;
344 };
345
346 /**
347 * Respond to item drag start event
348 *
349 * @private
350 * @param {OO.ui.mixin.DraggableElement} item Dragged item
351 */
352 OO.ui.mixin.DraggableGroupElement.prototype.onItemDragStart = function ( item ) {
353 if ( !this.isDraggable() ) {
354 return;
355 }
356 // Make a shallow copy of this.items so we can re-order it during previews
357 // without affecting the original array.
358 this.itemsOrder = this.items.slice();
359 this.updateIndexes();
360 if ( this.orientation === 'horizontal' ) {
361 // Calculate and cache directionality on drag start - it's a little
362 // expensive and it shouldn't change while dragging.
363 this.dir = this.$element.css( 'direction' );
364 }
365 this.setDragItem( item );
366 };
367
368 /**
369 * Update the index properties of the items
370 */
371 OO.ui.mixin.DraggableGroupElement.prototype.updateIndexes = function () {
372 var i, len;
373
374 // Map the index of each object
375 for ( i = 0, len = this.itemsOrder.length; i < len; i++ ) {
376 this.itemsOrder[ i ].setIndex( i );
377 }
378 };
379
380 /**
381 * Handle drop or dragend event and switch the order of the items accordingly
382 *
383 * @private
384 * @param {OO.ui.mixin.DraggableElement} item Dropped item
385 */
386 OO.ui.mixin.DraggableGroupElement.prototype.onItemDropOrDragEnd = function () {
387 var targetIndex, originalIndex,
388 item = this.getDragItem();
389
390 // TODO: Figure out a way to configure a list of legally droppable
391 // elements even if they are not yet in the list
392 if ( item ) {
393 originalIndex = this.items.indexOf( item );
394 // If the item has moved forward, add one to the index to account for the left shift
395 targetIndex = item.getIndex() + ( item.getIndex() > originalIndex ? 1 : 0 );
396 if ( targetIndex !== originalIndex ) {
397 this.reorder( this.getDragItem(), targetIndex );
398 this.emit( 'reorder', this.getDragItem(), targetIndex );
399 }
400 this.updateIndexes();
401 }
402 this.unsetDragItem();
403 // Return false to prevent propogation
404 return false;
405 };
406
407 /**
408 * Respond to dragover event
409 *
410 * @private
411 * @param {jQuery.Event} e Dragover event
412 * @fires reorder
413 */
414 OO.ui.mixin.DraggableGroupElement.prototype.onDragOver = function ( e ) {
415 var overIndex, targetIndex,
416 item = this.getDragItem(),
417 dragItemIndex = item.getIndex();
418
419 // Get the OptionWidget item we are dragging over
420 overIndex = $( e.target ).closest( '.oo-ui-draggableElement' ).data( 'index' );
421
422 if ( overIndex !== undefined && overIndex !== dragItemIndex ) {
423 targetIndex = overIndex + ( overIndex > dragItemIndex ? 1 : 0 );
424
425 if ( targetIndex > 0 ) {
426 this.$group.children().eq( targetIndex - 1 ).after( item.$element );
427 } else {
428 this.$group.prepend( item.$element );
429 }
430 // Move item in itemsOrder array
431 this.itemsOrder.splice( overIndex, 0,
432 this.itemsOrder.splice( dragItemIndex, 1 )[ 0 ]
433 );
434 this.updateIndexes();
435 this.emit( 'drag', item, targetIndex );
436 }
437 // Prevent default
438 e.preventDefault();
439 };
440
441 /**
442 * Reorder the items in the group
443 *
444 * @param {OO.ui.mixin.DraggableElement} item Reordered item
445 * @param {number} newIndex New index
446 */
447 OO.ui.mixin.DraggableGroupElement.prototype.reorder = function ( item, newIndex ) {
448 this.addItems( [ item ], newIndex );
449 };
450
451 /**
452 * Set a dragged item
453 *
454 * @param {OO.ui.mixin.DraggableElement} item Dragged item
455 */
456 OO.ui.mixin.DraggableGroupElement.prototype.setDragItem = function ( item ) {
457 if ( this.dragItem !== item ) {
458 this.dragItem = item;
459 this.$element.on( 'dragover', this.onDragOver.bind( this ) );
460 this.$element.addClass( 'oo-ui-draggableGroupElement-dragging' );
461 }
462 };
463
464 /**
465 * Unset the current dragged item
466 */
467 OO.ui.mixin.DraggableGroupElement.prototype.unsetDragItem = function () {
468 if ( this.dragItem ) {
469 this.dragItem = null;
470 this.$element.off( 'dragover' );
471 this.$element.removeClass( 'oo-ui-draggableGroupElement-dragging' );
472 }
473 };
474
475 /**
476 * Get the item that is currently being dragged.
477 *
478 * @return {OO.ui.mixin.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged
479 */
480 OO.ui.mixin.DraggableGroupElement.prototype.getDragItem = function () {
481 return this.dragItem;
482 };
483
484 /**
485 * RequestManager is a mixin that manages the lifecycle of a promise-backed request for a widget, such as
486 * the {@link OO.ui.mixin.LookupElement}.
487 *
488 * @class
489 * @abstract
490 *
491 * @constructor
492 */
493 OO.ui.mixin.RequestManager = function OoUiMixinRequestManager() {
494 this.requestCache = {};
495 this.requestQuery = null;
496 this.requestRequest = null;
497 };
498
499 /* Setup */
500
501 OO.initClass( OO.ui.mixin.RequestManager );
502
503 /**
504 * Get request results for the current query.
505 *
506 * @return {jQuery.Promise} Promise object which will be passed response data as the first argument of
507 * the done event. If the request was aborted to make way for a subsequent request, this promise
508 * may not be rejected, depending on what jQuery feels like doing.
509 */
510 OO.ui.mixin.RequestManager.prototype.getRequestData = function () {
511 var widget = this,
512 value = this.getRequestQuery(),
513 deferred = $.Deferred(),
514 ourRequest;
515
516 this.abortRequest();
517 if ( Object.prototype.hasOwnProperty.call( this.requestCache, value ) ) {
518 deferred.resolve( this.requestCache[ value ] );
519 } else {
520 if ( this.pushPending ) {
521 this.pushPending();
522 }
523 this.requestQuery = value;
524 ourRequest = this.requestRequest = this.getRequest();
525 ourRequest
526 .always( function () {
527 // We need to pop pending even if this is an old request, otherwise
528 // the widget will remain pending forever.
529 // TODO: this assumes that an aborted request will fail or succeed soon after
530 // being aborted, or at least eventually. It would be nice if we could popPending()
531 // at abort time, but only if we knew that we hadn't already called popPending()
532 // for that request.
533 if ( widget.popPending ) {
534 widget.popPending();
535 }
536 } )
537 .done( function ( response ) {
538 // If this is an old request (and aborting it somehow caused it to still succeed),
539 // ignore its success completely
540 if ( ourRequest === widget.requestRequest ) {
541 widget.requestQuery = null;
542 widget.requestRequest = null;
543 widget.requestCache[ value ] = widget.getRequestCacheDataFromResponse( response );
544 deferred.resolve( widget.requestCache[ value ] );
545 }
546 } )
547 .fail( function () {
548 // If this is an old request (or a request failing because it's being aborted),
549 // ignore its failure completely
550 if ( ourRequest === widget.requestRequest ) {
551 widget.requestQuery = null;
552 widget.requestRequest = null;
553 deferred.reject();
554 }
555 } );
556 }
557 return deferred.promise();
558 };
559
560 /**
561 * Abort the currently pending request, if any.
562 *
563 * @private
564 */
565 OO.ui.mixin.RequestManager.prototype.abortRequest = function () {
566 var oldRequest = this.requestRequest;
567 if ( oldRequest ) {
568 // First unset this.requestRequest to the fail handler will notice
569 // that the request is no longer current
570 this.requestRequest = null;
571 this.requestQuery = null;
572 oldRequest.abort();
573 }
574 };
575
576 /**
577 * Get the query to be made.
578 *
579 * @protected
580 * @method
581 * @abstract
582 * @return {string} query to be used
583 */
584 OO.ui.mixin.RequestManager.prototype.getRequestQuery = null;
585
586 /**
587 * Get a new request object of the current query value.
588 *
589 * @protected
590 * @method
591 * @abstract
592 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
593 */
594 OO.ui.mixin.RequestManager.prototype.getRequest = null;
595
596 /**
597 * Pre-process data returned by the request from #getRequest.
598 *
599 * The return value of this function will be cached, and any further queries for the given value
600 * will use the cache rather than doing API requests.
601 *
602 * @protected
603 * @method
604 * @abstract
605 * @param {Mixed} response Response from server
606 * @return {Mixed} Cached result data
607 */
608 OO.ui.mixin.RequestManager.prototype.getRequestCacheDataFromResponse = null;
609
610 /**
611 * LookupElement is a mixin that creates a {@link OO.ui.MenuSelectWidget menu} of suggested values for
612 * a {@link OO.ui.TextInputWidget text input widget}. Suggested values are based on the characters the user types
613 * into the text input field and, in general, the menu is only displayed when the user types. If a suggested value is chosen
614 * from the lookup menu, that value becomes the value of the input field.
615 *
616 * Note that a new menu of suggested items is displayed when a value is chosen from the lookup menu. If this is
617 * not the desired behavior, disable lookup menus with the #setLookupsDisabled method, then set the value, then
618 * re-enable lookups.
619 *
620 * See the [OOjs UI demos][1] for an example.
621 *
622 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/index.html#widgets-apex-vector-ltr
623 *
624 * @class
625 * @abstract
626 * @mixins OO.ui.mixin.RequestManager
627 *
628 * @constructor
629 * @param {Object} [config] Configuration options
630 * @cfg {jQuery} [$overlay] Overlay for the lookup menu; defaults to relative positioning.
631 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
632 * @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element.
633 * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty.
634 * By default, the lookup menu is not generated and displayed until the user begins to type.
635 * @cfg {boolean} [highlightFirst=true] Whether the first lookup result should be highlighted (so, that the user can
636 * take it over into the input with simply pressing return) automatically or not.
637 */
638 OO.ui.mixin.LookupElement = function OoUiMixinLookupElement( config ) {
639 // Configuration initialization
640 config = $.extend( { highlightFirst: true }, config );
641
642 // Mixin constructors
643 OO.ui.mixin.RequestManager.call( this, config );
644
645 // Properties
646 this.$overlay = config.$overlay || this.$element;
647 this.lookupMenu = new OO.ui.MenuSelectWidget( {
648 widget: this,
649 input: this,
650 $floatableContainer: config.$container || this.$element
651 } );
652
653 this.allowSuggestionsWhenEmpty = config.allowSuggestionsWhenEmpty || false;
654
655 this.lookupsDisabled = false;
656 this.lookupInputFocused = false;
657 this.lookupHighlightFirstItem = config.highlightFirst;
658
659 // Events
660 this.$input.on( {
661 focus: this.onLookupInputFocus.bind( this ),
662 blur: this.onLookupInputBlur.bind( this ),
663 mousedown: this.onLookupInputMouseDown.bind( this )
664 } );
665 this.connect( this, { change: 'onLookupInputChange' } );
666 this.lookupMenu.connect( this, {
667 toggle: 'onLookupMenuToggle',
668 choose: 'onLookupMenuItemChoose'
669 } );
670
671 // Initialization
672 this.$input.attr( {
673 role: 'combobox',
674 'aria-owns': this.lookupMenu.getElementId(),
675 'aria-autocomplete': 'list'
676 } );
677 this.$element.addClass( 'oo-ui-lookupElement' );
678 this.lookupMenu.$element.addClass( 'oo-ui-lookupElement-menu' );
679 this.$overlay.append( this.lookupMenu.$element );
680 };
681
682 /* Setup */
683
684 OO.mixinClass( OO.ui.mixin.LookupElement, OO.ui.mixin.RequestManager );
685
686 /* Methods */
687
688 /**
689 * Handle input focus event.
690 *
691 * @protected
692 * @param {jQuery.Event} e Input focus event
693 */
694 OO.ui.mixin.LookupElement.prototype.onLookupInputFocus = function () {
695 this.lookupInputFocused = true;
696 this.populateLookupMenu();
697 };
698
699 /**
700 * Handle input blur event.
701 *
702 * @protected
703 * @param {jQuery.Event} e Input blur event
704 */
705 OO.ui.mixin.LookupElement.prototype.onLookupInputBlur = function () {
706 this.closeLookupMenu();
707 this.lookupInputFocused = false;
708 };
709
710 /**
711 * Handle input mouse down event.
712 *
713 * @protected
714 * @param {jQuery.Event} e Input mouse down event
715 */
716 OO.ui.mixin.LookupElement.prototype.onLookupInputMouseDown = function () {
717 // Only open the menu if the input was already focused.
718 // This way we allow the user to open the menu again after closing it with Esc
719 // by clicking in the input. Opening (and populating) the menu when initially
720 // clicking into the input is handled by the focus handler.
721 if ( this.lookupInputFocused && !this.lookupMenu.isVisible() ) {
722 this.populateLookupMenu();
723 }
724 };
725
726 /**
727 * Handle input change event.
728 *
729 * @protected
730 * @param {string} value New input value
731 */
732 OO.ui.mixin.LookupElement.prototype.onLookupInputChange = function () {
733 if ( this.lookupInputFocused ) {
734 this.populateLookupMenu();
735 }
736 };
737
738 /**
739 * Handle the lookup menu being shown/hidden.
740 *
741 * @protected
742 * @param {boolean} visible Whether the lookup menu is now visible.
743 */
744 OO.ui.mixin.LookupElement.prototype.onLookupMenuToggle = function ( visible ) {
745 if ( !visible ) {
746 // When the menu is hidden, abort any active request and clear the menu.
747 // This has to be done here in addition to closeLookupMenu(), because
748 // MenuSelectWidget will close itself when the user presses Esc.
749 this.abortLookupRequest();
750 this.lookupMenu.clearItems();
751 }
752 };
753
754 /**
755 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
756 *
757 * @protected
758 * @param {OO.ui.MenuOptionWidget} item Selected item
759 */
760 OO.ui.mixin.LookupElement.prototype.onLookupMenuItemChoose = function ( item ) {
761 this.setValue( item.getData() );
762 };
763
764 /**
765 * Get lookup menu.
766 *
767 * @private
768 * @return {OO.ui.MenuSelectWidget}
769 */
770 OO.ui.mixin.LookupElement.prototype.getLookupMenu = function () {
771 return this.lookupMenu;
772 };
773
774 /**
775 * Disable or re-enable lookups.
776 *
777 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
778 *
779 * @param {boolean} disabled Disable lookups
780 */
781 OO.ui.mixin.LookupElement.prototype.setLookupsDisabled = function ( disabled ) {
782 this.lookupsDisabled = !!disabled;
783 };
784
785 /**
786 * Open the menu. If there are no entries in the menu, this does nothing.
787 *
788 * @private
789 * @chainable
790 */
791 OO.ui.mixin.LookupElement.prototype.openLookupMenu = function () {
792 if ( !this.lookupMenu.isEmpty() ) {
793 this.lookupMenu.toggle( true );
794 }
795 return this;
796 };
797
798 /**
799 * Close the menu, empty it, and abort any pending request.
800 *
801 * @private
802 * @chainable
803 */
804 OO.ui.mixin.LookupElement.prototype.closeLookupMenu = function () {
805 this.lookupMenu.toggle( false );
806 this.abortLookupRequest();
807 this.lookupMenu.clearItems();
808 return this;
809 };
810
811 /**
812 * Request menu items based on the input's current value, and when they arrive,
813 * populate the menu with these items and show the menu.
814 *
815 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
816 *
817 * @private
818 * @chainable
819 */
820 OO.ui.mixin.LookupElement.prototype.populateLookupMenu = function () {
821 var widget = this,
822 value = this.getValue();
823
824 if ( this.lookupsDisabled || this.isReadOnly() ) {
825 return;
826 }
827
828 // If the input is empty, clear the menu, unless suggestions when empty are allowed.
829 if ( !this.allowSuggestionsWhenEmpty && value === '' ) {
830 this.closeLookupMenu();
831 // Skip population if there is already a request pending for the current value
832 } else if ( value !== this.lookupQuery ) {
833 this.getLookupMenuItems()
834 .done( function ( items ) {
835 widget.lookupMenu.clearItems();
836 if ( items.length ) {
837 widget.lookupMenu
838 .addItems( items )
839 .toggle( true );
840 widget.initializeLookupMenuSelection();
841 } else {
842 widget.lookupMenu.toggle( false );
843 }
844 } )
845 .fail( function () {
846 widget.lookupMenu.clearItems();
847 } );
848 }
849
850 return this;
851 };
852
853 /**
854 * Highlight the first selectable item in the menu, if configured.
855 *
856 * @private
857 * @chainable
858 */
859 OO.ui.mixin.LookupElement.prototype.initializeLookupMenuSelection = function () {
860 if ( this.lookupHighlightFirstItem && !this.lookupMenu.getSelectedItem() ) {
861 this.lookupMenu.highlightItem( this.lookupMenu.getFirstSelectableItem() );
862 }
863 };
864
865 /**
866 * Get lookup menu items for the current query.
867 *
868 * @private
869 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
870 * the done event. If the request was aborted to make way for a subsequent request, this promise
871 * will not be rejected: it will remain pending forever.
872 */
873 OO.ui.mixin.LookupElement.prototype.getLookupMenuItems = function () {
874 return this.getRequestData().then( function ( data ) {
875 return this.getLookupMenuOptionsFromData( data );
876 }.bind( this ) );
877 };
878
879 /**
880 * Abort the currently pending lookup request, if any.
881 *
882 * @private
883 */
884 OO.ui.mixin.LookupElement.prototype.abortLookupRequest = function () {
885 this.abortRequest();
886 };
887
888 /**
889 * Get a new request object of the current lookup query value.
890 *
891 * @protected
892 * @method
893 * @abstract
894 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
895 */
896 OO.ui.mixin.LookupElement.prototype.getLookupRequest = null;
897
898 /**
899 * Pre-process data returned by the request from #getLookupRequest.
900 *
901 * The return value of this function will be cached, and any further queries for the given value
902 * will use the cache rather than doing API requests.
903 *
904 * @protected
905 * @method
906 * @abstract
907 * @param {Mixed} response Response from server
908 * @return {Mixed} Cached result data
909 */
910 OO.ui.mixin.LookupElement.prototype.getLookupCacheDataFromResponse = null;
911
912 /**
913 * Get a list of menu option widgets from the (possibly cached) data returned by
914 * #getLookupCacheDataFromResponse.
915 *
916 * @protected
917 * @method
918 * @abstract
919 * @param {Mixed} data Cached result data, usually an array
920 * @return {OO.ui.MenuOptionWidget[]} Menu items
921 */
922 OO.ui.mixin.LookupElement.prototype.getLookupMenuOptionsFromData = null;
923
924 /**
925 * Set the read-only state of the widget.
926 *
927 * This will also disable/enable the lookups functionality.
928 *
929 * @param {boolean} readOnly Make input read-only
930 * @chainable
931 */
932 OO.ui.mixin.LookupElement.prototype.setReadOnly = function ( readOnly ) {
933 // Parent method
934 // Note: Calling #setReadOnly this way assumes this is mixed into an OO.ui.TextInputWidget
935 OO.ui.TextInputWidget.prototype.setReadOnly.call( this, readOnly );
936
937 // During construction, #setReadOnly is called before the OO.ui.mixin.LookupElement constructor
938 if ( this.isReadOnly() && this.lookupMenu ) {
939 this.closeLookupMenu();
940 }
941
942 return this;
943 };
944
945 /**
946 * @inheritdoc OO.ui.mixin.RequestManager
947 */
948 OO.ui.mixin.LookupElement.prototype.getRequestQuery = function () {
949 return this.getValue();
950 };
951
952 /**
953 * @inheritdoc OO.ui.mixin.RequestManager
954 */
955 OO.ui.mixin.LookupElement.prototype.getRequest = function () {
956 return this.getLookupRequest();
957 };
958
959 /**
960 * @inheritdoc OO.ui.mixin.RequestManager
961 */
962 OO.ui.mixin.LookupElement.prototype.getRequestCacheDataFromResponse = function ( response ) {
963 return this.getLookupCacheDataFromResponse( response );
964 };
965
966 /**
967 * TabPanelLayouts are used within {@link OO.ui.IndexLayout index layouts} to create tab panels that
968 * users can select and display from the index's optional {@link OO.ui.TabSelectWidget tab}
969 * navigation. TabPanels are usually not instantiated directly, rather extended to include the
970 * required content and functionality.
971 *
972 * Each tab panel must have a unique symbolic name, which is passed to the constructor. In addition,
973 * the tab panel's tab item is customized (with a label) using the #setupTabItem method. See
974 * {@link OO.ui.IndexLayout IndexLayout} for an example.
975 *
976 * @class
977 * @extends OO.ui.PanelLayout
978 *
979 * @constructor
980 * @param {string} name Unique symbolic name of tab panel
981 * @param {Object} [config] Configuration options
982 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] Label for tab panel's tab
983 */
984 OO.ui.TabPanelLayout = function OoUiTabPanelLayout( name, config ) {
985 // Allow passing positional parameters inside the config object
986 if ( OO.isPlainObject( name ) && config === undefined ) {
987 config = name;
988 name = config.name;
989 }
990
991 // Configuration initialization
992 config = $.extend( { scrollable: true }, config );
993
994 // Parent constructor
995 OO.ui.TabPanelLayout.parent.call( this, config );
996
997 // Properties
998 this.name = name;
999 this.label = config.label;
1000 this.tabItem = null;
1001 this.active = false;
1002
1003 // Initialization
1004 this.$element.addClass( 'oo-ui-tabPanelLayout' );
1005 };
1006
1007 /* Setup */
1008
1009 OO.inheritClass( OO.ui.TabPanelLayout, OO.ui.PanelLayout );
1010
1011 /* Events */
1012
1013 /**
1014 * An 'active' event is emitted when the tab panel becomes active. Tab panels become active when they are
1015 * shown in a index layout that is configured to display only one tab panel at a time.
1016 *
1017 * @event active
1018 * @param {boolean} active Tab panel is active
1019 */
1020
1021 /* Methods */
1022
1023 /**
1024 * Get the symbolic name of the tab panel.
1025 *
1026 * @return {string} Symbolic name of tab panel
1027 */
1028 OO.ui.TabPanelLayout.prototype.getName = function () {
1029 return this.name;
1030 };
1031
1032 /**
1033 * Check if tab panel is active.
1034 *
1035 * Tab panels become active when they are shown in a {@link OO.ui.IndexLayout index layout} that is configured to
1036 * display only one tab panel at a time. Additional CSS is applied to the tab panel's tab item to reflect the
1037 * active state.
1038 *
1039 * @return {boolean} Tab panel is active
1040 */
1041 OO.ui.TabPanelLayout.prototype.isActive = function () {
1042 return this.active;
1043 };
1044
1045 /**
1046 * Get tab item.
1047 *
1048 * The tab item allows users to access the tab panel from the index's tab
1049 * navigation. The tab item itself can be customized (with a label, level, etc.) using the #setupTabItem method.
1050 *
1051 * @return {OO.ui.TabOptionWidget|null} Tab option widget
1052 */
1053 OO.ui.TabPanelLayout.prototype.getTabItem = function () {
1054 return this.tabItem;
1055 };
1056
1057 /**
1058 * Set or unset the tab item.
1059 *
1060 * Specify a {@link OO.ui.TabOptionWidget tab option} to set it,
1061 * or `null` to clear the tab item. To customize the tab item itself (e.g., to set a label or tab
1062 * level), use #setupTabItem instead of this method.
1063 *
1064 * @param {OO.ui.TabOptionWidget|null} tabItem Tab option widget, null to clear
1065 * @chainable
1066 */
1067 OO.ui.TabPanelLayout.prototype.setTabItem = function ( tabItem ) {
1068 this.tabItem = tabItem || null;
1069 if ( tabItem ) {
1070 this.setupTabItem();
1071 }
1072 return this;
1073 };
1074
1075 /**
1076 * Set up the tab item.
1077 *
1078 * Use this method to customize the tab item (e.g., to add a label or tab level). To set or unset
1079 * the tab item itself (with a {@link OO.ui.TabOptionWidget tab option} or `null`), use
1080 * the #setTabItem method instead.
1081 *
1082 * @param {OO.ui.TabOptionWidget} tabItem Tab option widget to set up
1083 * @chainable
1084 */
1085 OO.ui.TabPanelLayout.prototype.setupTabItem = function () {
1086 if ( this.label ) {
1087 this.tabItem.setLabel( this.label );
1088 }
1089 return this;
1090 };
1091
1092 /**
1093 * Set the tab panel to its 'active' state.
1094 *
1095 * Tab panels become active when they are shown in a index layout that is configured to display only
1096 * one tab panel at a time. Additional CSS is applied to the tab item to reflect the tab panel's
1097 * active state. Outside of the index context, setting the active state on a tab panel does nothing.
1098 *
1099 * @param {boolean} active Tab panel is active
1100 * @fires active
1101 */
1102 OO.ui.TabPanelLayout.prototype.setActive = function ( active ) {
1103 active = !!active;
1104
1105 if ( active !== this.active ) {
1106 this.active = active;
1107 this.$element.toggleClass( 'oo-ui-tabPanelLayout-active', this.active );
1108 this.emit( 'active', this.active );
1109 }
1110 };
1111
1112 /**
1113 * The deprecated name for the TabPanelLayout, provided for backwards-compatibility.
1114 *
1115 * @class
1116 * @extends OO.ui.TabPanelLayout
1117 *
1118 * @constructor
1119 * @deprecated since v0.21.3
1120 */
1121 OO.ui.CardLayout = function OoUiCardLayout() {
1122 OO.ui.warnDeprecation( 'CardLayout has been renamed to TabPanel layout. Use that instead. See T155152' );
1123 // Parent constructor
1124 OO.ui.CardLayout.parent.apply( this, arguments );
1125 };
1126
1127 OO.inheritClass( OO.ui.CardLayout, OO.ui.TabPanelLayout );
1128
1129 /**
1130 * PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display
1131 * from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly,
1132 * rather extended to include the required content and functionality.
1133 *
1134 * Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline
1135 * item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See
1136 * {@link OO.ui.BookletLayout BookletLayout} for an example.
1137 *
1138 * @class
1139 * @extends OO.ui.PanelLayout
1140 *
1141 * @constructor
1142 * @param {string} name Unique symbolic name of page
1143 * @param {Object} [config] Configuration options
1144 */
1145 OO.ui.PageLayout = function OoUiPageLayout( name, config ) {
1146 // Allow passing positional parameters inside the config object
1147 if ( OO.isPlainObject( name ) && config === undefined ) {
1148 config = name;
1149 name = config.name;
1150 }
1151
1152 // Configuration initialization
1153 config = $.extend( { scrollable: true }, config );
1154
1155 // Parent constructor
1156 OO.ui.PageLayout.parent.call( this, config );
1157
1158 // Properties
1159 this.name = name;
1160 this.outlineItem = null;
1161 this.active = false;
1162
1163 // Initialization
1164 this.$element.addClass( 'oo-ui-pageLayout' );
1165 };
1166
1167 /* Setup */
1168
1169 OO.inheritClass( OO.ui.PageLayout, OO.ui.PanelLayout );
1170
1171 /* Events */
1172
1173 /**
1174 * An 'active' event is emitted when the page becomes active. Pages become active when they are
1175 * shown in a booklet layout that is configured to display only one page at a time.
1176 *
1177 * @event active
1178 * @param {boolean} active Page is active
1179 */
1180
1181 /* Methods */
1182
1183 /**
1184 * Get the symbolic name of the page.
1185 *
1186 * @return {string} Symbolic name of page
1187 */
1188 OO.ui.PageLayout.prototype.getName = function () {
1189 return this.name;
1190 };
1191
1192 /**
1193 * Check if page is active.
1194 *
1195 * Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display
1196 * only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state.
1197 *
1198 * @return {boolean} Page is active
1199 */
1200 OO.ui.PageLayout.prototype.isActive = function () {
1201 return this.active;
1202 };
1203
1204 /**
1205 * Get outline item.
1206 *
1207 * The outline item allows users to access the page from the booklet's outline
1208 * navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method.
1209 *
1210 * @return {OO.ui.OutlineOptionWidget|null} Outline option widget
1211 */
1212 OO.ui.PageLayout.prototype.getOutlineItem = function () {
1213 return this.outlineItem;
1214 };
1215
1216 /**
1217 * Set or unset the outline item.
1218 *
1219 * Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it,
1220 * or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline
1221 * level), use #setupOutlineItem instead of this method.
1222 *
1223 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear
1224 * @chainable
1225 */
1226 OO.ui.PageLayout.prototype.setOutlineItem = function ( outlineItem ) {
1227 this.outlineItem = outlineItem || null;
1228 if ( outlineItem ) {
1229 this.setupOutlineItem();
1230 }
1231 return this;
1232 };
1233
1234 /**
1235 * Set up the outline item.
1236 *
1237 * Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset
1238 * the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use
1239 * the #setOutlineItem method instead.
1240 *
1241 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up
1242 * @chainable
1243 */
1244 OO.ui.PageLayout.prototype.setupOutlineItem = function () {
1245 return this;
1246 };
1247
1248 /**
1249 * Set the page to its 'active' state.
1250 *
1251 * Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional
1252 * CSS is applied to the outline item to reflect the page's active state. Outside of the booklet
1253 * context, setting the active state on a page does nothing.
1254 *
1255 * @param {boolean} active Page is active
1256 * @fires active
1257 */
1258 OO.ui.PageLayout.prototype.setActive = function ( active ) {
1259 active = !!active;
1260
1261 if ( active !== this.active ) {
1262 this.active = active;
1263 this.$element.toggleClass( 'oo-ui-pageLayout-active', active );
1264 this.emit( 'active', this.active );
1265 }
1266 };
1267
1268 /**
1269 * StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed
1270 * at a time, though the stack layout can also be configured to show all contained panels, one after another,
1271 * by setting the #continuous option to 'true'.
1272 *
1273 * @example
1274 * // A stack layout with two panels, configured to be displayed continously
1275 * var myStack = new OO.ui.StackLayout( {
1276 * items: [
1277 * new OO.ui.PanelLayout( {
1278 * $content: $( '<p>Panel One</p>' ),
1279 * padded: true,
1280 * framed: true
1281 * } ),
1282 * new OO.ui.PanelLayout( {
1283 * $content: $( '<p>Panel Two</p>' ),
1284 * padded: true,
1285 * framed: true
1286 * } )
1287 * ],
1288 * continuous: true
1289 * } );
1290 * $( 'body' ).append( myStack.$element );
1291 *
1292 * @class
1293 * @extends OO.ui.PanelLayout
1294 * @mixins OO.ui.mixin.GroupElement
1295 *
1296 * @constructor
1297 * @param {Object} [config] Configuration options
1298 * @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time.
1299 * @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout.
1300 */
1301 OO.ui.StackLayout = function OoUiStackLayout( config ) {
1302 // Configuration initialization
1303 config = $.extend( { scrollable: true }, config );
1304
1305 // Parent constructor
1306 OO.ui.StackLayout.parent.call( this, config );
1307
1308 // Mixin constructors
1309 OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
1310
1311 // Properties
1312 this.currentItem = null;
1313 this.continuous = !!config.continuous;
1314
1315 // Initialization
1316 this.$element.addClass( 'oo-ui-stackLayout' );
1317 if ( this.continuous ) {
1318 this.$element.addClass( 'oo-ui-stackLayout-continuous' );
1319 this.$element.on( 'scroll', OO.ui.debounce( this.onScroll.bind( this ), 250 ) );
1320 }
1321 if ( Array.isArray( config.items ) ) {
1322 this.addItems( config.items );
1323 }
1324 };
1325
1326 /* Setup */
1327
1328 OO.inheritClass( OO.ui.StackLayout, OO.ui.PanelLayout );
1329 OO.mixinClass( OO.ui.StackLayout, OO.ui.mixin.GroupElement );
1330
1331 /* Events */
1332
1333 /**
1334 * A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed},
1335 * {@link #clearItems cleared} or {@link #setItem displayed}.
1336 *
1337 * @event set
1338 * @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown
1339 */
1340
1341 /**
1342 * When used in continuous mode, this event is emitted when the user scrolls down
1343 * far enough such that currentItem is no longer visible.
1344 *
1345 * @event visibleItemChange
1346 * @param {OO.ui.PanelLayout} panel The next visible item in the layout
1347 */
1348
1349 /* Methods */
1350
1351 /**
1352 * Handle scroll events from the layout element
1353 *
1354 * @param {jQuery.Event} e
1355 * @fires visibleItemChange
1356 */
1357 OO.ui.StackLayout.prototype.onScroll = function () {
1358 var currentRect,
1359 len = this.items.length,
1360 currentIndex = this.items.indexOf( this.currentItem ),
1361 newIndex = currentIndex,
1362 containerRect = this.$element[ 0 ].getBoundingClientRect();
1363
1364 if ( !containerRect || ( !containerRect.top && !containerRect.bottom ) ) {
1365 // Can't get bounding rect, possibly not attached.
1366 return;
1367 }
1368
1369 function getRect( item ) {
1370 return item.$element[ 0 ].getBoundingClientRect();
1371 }
1372
1373 function isVisible( item ) {
1374 var rect = getRect( item );
1375 return rect.bottom > containerRect.top && rect.top < containerRect.bottom;
1376 }
1377
1378 currentRect = getRect( this.currentItem );
1379
1380 if ( currentRect.bottom < containerRect.top ) {
1381 // Scrolled down past current item
1382 while ( ++newIndex < len ) {
1383 if ( isVisible( this.items[ newIndex ] ) ) {
1384 break;
1385 }
1386 }
1387 } else if ( currentRect.top > containerRect.bottom ) {
1388 // Scrolled up past current item
1389 while ( --newIndex >= 0 ) {
1390 if ( isVisible( this.items[ newIndex ] ) ) {
1391 break;
1392 }
1393 }
1394 }
1395
1396 if ( newIndex !== currentIndex ) {
1397 this.emit( 'visibleItemChange', this.items[ newIndex ] );
1398 }
1399 };
1400
1401 /**
1402 * Get the current panel.
1403 *
1404 * @return {OO.ui.Layout|null}
1405 */
1406 OO.ui.StackLayout.prototype.getCurrentItem = function () {
1407 return this.currentItem;
1408 };
1409
1410 /**
1411 * Unset the current item.
1412 *
1413 * @private
1414 * @param {OO.ui.StackLayout} layout
1415 * @fires set
1416 */
1417 OO.ui.StackLayout.prototype.unsetCurrentItem = function () {
1418 var prevItem = this.currentItem;
1419 if ( prevItem === null ) {
1420 return;
1421 }
1422
1423 this.currentItem = null;
1424 this.emit( 'set', null );
1425 };
1426
1427 /**
1428 * Add panel layouts to the stack layout.
1429 *
1430 * Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different
1431 * insertion point. Adding a panel that is already in the stack will move it to the end of the array or the point specified
1432 * by the index.
1433 *
1434 * @param {OO.ui.Layout[]} items Panels to add
1435 * @param {number} [index] Index of the insertion point
1436 * @chainable
1437 */
1438 OO.ui.StackLayout.prototype.addItems = function ( items, index ) {
1439 // Update the visibility
1440 this.updateHiddenState( items, this.currentItem );
1441
1442 // Mixin method
1443 OO.ui.mixin.GroupElement.prototype.addItems.call( this, items, index );
1444
1445 if ( !this.currentItem && items.length ) {
1446 this.setItem( items[ 0 ] );
1447 }
1448
1449 return this;
1450 };
1451
1452 /**
1453 * Remove the specified panels from the stack layout.
1454 *
1455 * Removed panels are detached from the DOM, not removed, so that they may be reused. To remove all panels,
1456 * you may wish to use the #clearItems method instead.
1457 *
1458 * @param {OO.ui.Layout[]} items Panels to remove
1459 * @chainable
1460 * @fires set
1461 */
1462 OO.ui.StackLayout.prototype.removeItems = function ( items ) {
1463 // Mixin method
1464 OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items );
1465
1466 if ( items.indexOf( this.currentItem ) !== -1 ) {
1467 if ( this.items.length ) {
1468 this.setItem( this.items[ 0 ] );
1469 } else {
1470 this.unsetCurrentItem();
1471 }
1472 }
1473
1474 return this;
1475 };
1476
1477 /**
1478 * Clear all panels from the stack layout.
1479 *
1480 * Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only
1481 * a subset of panels, use the #removeItems method.
1482 *
1483 * @chainable
1484 * @fires set
1485 */
1486 OO.ui.StackLayout.prototype.clearItems = function () {
1487 this.unsetCurrentItem();
1488 OO.ui.mixin.GroupElement.prototype.clearItems.call( this );
1489
1490 return this;
1491 };
1492
1493 /**
1494 * Show the specified panel.
1495 *
1496 * If another panel is currently displayed, it will be hidden.
1497 *
1498 * @param {OO.ui.Layout} item Panel to show
1499 * @chainable
1500 * @fires set
1501 */
1502 OO.ui.StackLayout.prototype.setItem = function ( item ) {
1503 if ( item !== this.currentItem ) {
1504 this.updateHiddenState( this.items, item );
1505
1506 if ( this.items.indexOf( item ) !== -1 ) {
1507 this.currentItem = item;
1508 this.emit( 'set', item );
1509 } else {
1510 this.unsetCurrentItem();
1511 }
1512 }
1513
1514 return this;
1515 };
1516
1517 /**
1518 * Update the visibility of all items in case of non-continuous view.
1519 *
1520 * Ensure all items are hidden except for the selected one.
1521 * This method does nothing when the stack is continuous.
1522 *
1523 * @private
1524 * @param {OO.ui.Layout[]} items Item list iterate over
1525 * @param {OO.ui.Layout} [selectedItem] Selected item to show
1526 */
1527 OO.ui.StackLayout.prototype.updateHiddenState = function ( items, selectedItem ) {
1528 var i, len;
1529
1530 if ( !this.continuous ) {
1531 for ( i = 0, len = items.length; i < len; i++ ) {
1532 if ( !selectedItem || selectedItem !== items[ i ] ) {
1533 items[ i ].$element.addClass( 'oo-ui-element-hidden' );
1534 items[ i ].$element.attr( 'aria-hidden', 'true' );
1535 }
1536 }
1537 if ( selectedItem ) {
1538 selectedItem.$element.removeClass( 'oo-ui-element-hidden' );
1539 selectedItem.$element.removeAttr( 'aria-hidden' );
1540 }
1541 }
1542 };
1543
1544 /**
1545 * 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)
1546 * and its size is customized with the #menuSize config. The content area will fill all remaining space.
1547 *
1548 * @example
1549 * var menuLayout = new OO.ui.MenuLayout( {
1550 * position: 'top'
1551 * } ),
1552 * menuPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
1553 * contentPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
1554 * select = new OO.ui.SelectWidget( {
1555 * items: [
1556 * new OO.ui.OptionWidget( {
1557 * data: 'before',
1558 * label: 'Before',
1559 * } ),
1560 * new OO.ui.OptionWidget( {
1561 * data: 'after',
1562 * label: 'After',
1563 * } ),
1564 * new OO.ui.OptionWidget( {
1565 * data: 'top',
1566 * label: 'Top',
1567 * } ),
1568 * new OO.ui.OptionWidget( {
1569 * data: 'bottom',
1570 * label: 'Bottom',
1571 * } )
1572 * ]
1573 * } ).on( 'select', function ( item ) {
1574 * menuLayout.setMenuPosition( item.getData() );
1575 * } );
1576 *
1577 * menuLayout.$menu.append(
1578 * menuPanel.$element.append( '<b>Menu panel</b>', select.$element )
1579 * );
1580 * menuLayout.$content.append(
1581 * contentPanel.$element.append( '<b>Content panel</b>', '<p>Note that the menu is positioned relative to the content panel: top, bottom, after, before.</p>')
1582 * );
1583 * $( 'body' ).append( menuLayout.$element );
1584 *
1585 * If menu size needs to be overridden, it can be accomplished using CSS similar to the snippet
1586 * below. MenuLayout's CSS will override the appropriate values with 'auto' or '0' to display the
1587 * menu correctly. If `menuPosition` is known beforehand, CSS rules corresponding to other positions
1588 * may be omitted.
1589 *
1590 * .oo-ui-menuLayout-menu {
1591 * height: 200px;
1592 * width: 200px;
1593 * }
1594 * .oo-ui-menuLayout-content {
1595 * top: 200px;
1596 * left: 200px;
1597 * right: 200px;
1598 * bottom: 200px;
1599 * }
1600 *
1601 * @class
1602 * @extends OO.ui.Layout
1603 *
1604 * @constructor
1605 * @param {Object} [config] Configuration options
1606 * @cfg {boolean} [showMenu=true] Show menu
1607 * @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before`
1608 */
1609 OO.ui.MenuLayout = function OoUiMenuLayout( config ) {
1610 // Configuration initialization
1611 config = $.extend( {
1612 showMenu: true,
1613 menuPosition: 'before'
1614 }, config );
1615
1616 // Parent constructor
1617 OO.ui.MenuLayout.parent.call( this, config );
1618
1619 /**
1620 * Menu DOM node
1621 *
1622 * @property {jQuery}
1623 */
1624 this.$menu = $( '<div>' );
1625 /**
1626 * Content DOM node
1627 *
1628 * @property {jQuery}
1629 */
1630 this.$content = $( '<div>' );
1631
1632 // Initialization
1633 this.$menu
1634 .addClass( 'oo-ui-menuLayout-menu' );
1635 this.$content.addClass( 'oo-ui-menuLayout-content' );
1636 this.$element
1637 .addClass( 'oo-ui-menuLayout' )
1638 .append( this.$content, this.$menu );
1639 this.setMenuPosition( config.menuPosition );
1640 this.toggleMenu( config.showMenu );
1641 };
1642
1643 /* Setup */
1644
1645 OO.inheritClass( OO.ui.MenuLayout, OO.ui.Layout );
1646
1647 /* Methods */
1648
1649 /**
1650 * Toggle menu.
1651 *
1652 * @param {boolean} showMenu Show menu, omit to toggle
1653 * @chainable
1654 */
1655 OO.ui.MenuLayout.prototype.toggleMenu = function ( showMenu ) {
1656 showMenu = showMenu === undefined ? !this.showMenu : !!showMenu;
1657
1658 if ( this.showMenu !== showMenu ) {
1659 this.showMenu = showMenu;
1660 this.$element
1661 .toggleClass( 'oo-ui-menuLayout-showMenu', this.showMenu )
1662 .toggleClass( 'oo-ui-menuLayout-hideMenu', !this.showMenu );
1663 this.$menu.attr( 'aria-hidden', this.showMenu ? 'false' : 'true' );
1664 }
1665
1666 return this;
1667 };
1668
1669 /**
1670 * Check if menu is visible
1671 *
1672 * @return {boolean} Menu is visible
1673 */
1674 OO.ui.MenuLayout.prototype.isMenuVisible = function () {
1675 return this.showMenu;
1676 };
1677
1678 /**
1679 * Set menu position.
1680 *
1681 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
1682 * @throws {Error} If position value is not supported
1683 * @chainable
1684 */
1685 OO.ui.MenuLayout.prototype.setMenuPosition = function ( position ) {
1686 this.$element.removeClass( 'oo-ui-menuLayout-' + this.menuPosition );
1687 this.menuPosition = position;
1688 this.$element.addClass( 'oo-ui-menuLayout-' + position );
1689
1690 return this;
1691 };
1692
1693 /**
1694 * Get menu position.
1695 *
1696 * @return {string} Menu position
1697 */
1698 OO.ui.MenuLayout.prototype.getMenuPosition = function () {
1699 return this.menuPosition;
1700 };
1701
1702 /**
1703 * BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as
1704 * an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate
1705 * through the pages and select which one to display. By default, only one page is
1706 * displayed at a time and the outline is hidden. When a user navigates to a new page,
1707 * the booklet layout automatically focuses on the first focusable element, unless the
1708 * default setting is changed. Optionally, booklets can be configured to show
1709 * {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items.
1710 *
1711 * @example
1712 * // Example of a BookletLayout that contains two PageLayouts.
1713 *
1714 * function PageOneLayout( name, config ) {
1715 * PageOneLayout.parent.call( this, name, config );
1716 * this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' );
1717 * }
1718 * OO.inheritClass( PageOneLayout, OO.ui.PageLayout );
1719 * PageOneLayout.prototype.setupOutlineItem = function () {
1720 * this.outlineItem.setLabel( 'Page One' );
1721 * };
1722 *
1723 * function PageTwoLayout( name, config ) {
1724 * PageTwoLayout.parent.call( this, name, config );
1725 * this.$element.append( '<p>Second page</p>' );
1726 * }
1727 * OO.inheritClass( PageTwoLayout, OO.ui.PageLayout );
1728 * PageTwoLayout.prototype.setupOutlineItem = function () {
1729 * this.outlineItem.setLabel( 'Page Two' );
1730 * };
1731 *
1732 * var page1 = new PageOneLayout( 'one' ),
1733 * page2 = new PageTwoLayout( 'two' );
1734 *
1735 * var booklet = new OO.ui.BookletLayout( {
1736 * outlined: true
1737 * } );
1738 *
1739 * booklet.addPages ( [ page1, page2 ] );
1740 * $( 'body' ).append( booklet.$element );
1741 *
1742 * @class
1743 * @extends OO.ui.MenuLayout
1744 *
1745 * @constructor
1746 * @param {Object} [config] Configuration options
1747 * @cfg {boolean} [continuous=false] Show all pages, one after another
1748 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed. Disabled on mobile.
1749 * @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet.
1750 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
1751 */
1752 OO.ui.BookletLayout = function OoUiBookletLayout( config ) {
1753 // Configuration initialization
1754 config = config || {};
1755
1756 // Parent constructor
1757 OO.ui.BookletLayout.parent.call( this, config );
1758
1759 // Properties
1760 this.currentPageName = null;
1761 this.pages = {};
1762 this.ignoreFocus = false;
1763 this.stackLayout = new OO.ui.StackLayout( { continuous: !!config.continuous } );
1764 this.$content.append( this.stackLayout.$element );
1765 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
1766 this.outlineVisible = false;
1767 this.outlined = !!config.outlined;
1768 if ( this.outlined ) {
1769 this.editable = !!config.editable;
1770 this.outlineControlsWidget = null;
1771 this.outlineSelectWidget = new OO.ui.OutlineSelectWidget();
1772 this.outlinePanel = new OO.ui.PanelLayout( { scrollable: true } );
1773 this.$menu.append( this.outlinePanel.$element );
1774 this.outlineVisible = true;
1775 if ( this.editable ) {
1776 this.outlineControlsWidget = new OO.ui.OutlineControlsWidget(
1777 this.outlineSelectWidget
1778 );
1779 }
1780 }
1781 this.toggleMenu( this.outlined );
1782
1783 // Events
1784 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
1785 if ( this.outlined ) {
1786 this.outlineSelectWidget.connect( this, { select: 'onOutlineSelectWidgetSelect' } );
1787 this.scrolling = false;
1788 this.stackLayout.connect( this, { visibleItemChange: 'onStackLayoutVisibleItemChange' } );
1789 }
1790 if ( this.autoFocus ) {
1791 // Event 'focus' does not bubble, but 'focusin' does
1792 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
1793 }
1794
1795 // Initialization
1796 this.$element.addClass( 'oo-ui-bookletLayout' );
1797 this.stackLayout.$element.addClass( 'oo-ui-bookletLayout-stackLayout' );
1798 if ( this.outlined ) {
1799 this.outlinePanel.$element
1800 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
1801 .append( this.outlineSelectWidget.$element );
1802 if ( this.editable ) {
1803 this.outlinePanel.$element
1804 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
1805 .append( this.outlineControlsWidget.$element );
1806 }
1807 }
1808 };
1809
1810 /* Setup */
1811
1812 OO.inheritClass( OO.ui.BookletLayout, OO.ui.MenuLayout );
1813
1814 /* Events */
1815
1816 /**
1817 * A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout.
1818 * @event set
1819 * @param {OO.ui.PageLayout} page Current page
1820 */
1821
1822 /**
1823 * An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout.
1824 *
1825 * @event add
1826 * @param {OO.ui.PageLayout[]} page Added pages
1827 * @param {number} index Index pages were added at
1828 */
1829
1830 /**
1831 * A 'remove' event is emitted when pages are {@link #clearPages cleared} or
1832 * {@link #removePages removed} from the booklet.
1833 *
1834 * @event remove
1835 * @param {OO.ui.PageLayout[]} pages Removed pages
1836 */
1837
1838 /* Methods */
1839
1840 /**
1841 * Handle stack layout focus.
1842 *
1843 * @private
1844 * @param {jQuery.Event} e Focusin event
1845 */
1846 OO.ui.BookletLayout.prototype.onStackLayoutFocus = function ( e ) {
1847 var name, $target;
1848
1849 // Find the page that an element was focused within
1850 $target = $( e.target ).closest( '.oo-ui-pageLayout' );
1851 for ( name in this.pages ) {
1852 // Check for page match, exclude current page to find only page changes
1853 if ( this.pages[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentPageName ) {
1854 this.setPage( name );
1855 break;
1856 }
1857 }
1858 };
1859
1860 /**
1861 * Handle visibleItemChange events from the stackLayout
1862 *
1863 * The next visible page is set as the current page by selecting it
1864 * in the outline
1865 *
1866 * @param {OO.ui.PageLayout} page The next visible page in the layout
1867 */
1868 OO.ui.BookletLayout.prototype.onStackLayoutVisibleItemChange = function ( page ) {
1869 // Set a flag to so that the resulting call to #onStackLayoutSet doesn't
1870 // try and scroll the item into view again.
1871 this.scrolling = true;
1872 this.outlineSelectWidget.selectItemByData( page.getName() );
1873 this.scrolling = false;
1874 };
1875
1876 /**
1877 * Handle stack layout set events.
1878 *
1879 * @private
1880 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
1881 */
1882 OO.ui.BookletLayout.prototype.onStackLayoutSet = function ( page ) {
1883 var layout = this;
1884 if ( !this.scrolling && page ) {
1885 page.scrollElementIntoView().done( function () {
1886 if ( layout.autoFocus && !OO.ui.isMobile() ) {
1887 layout.focus();
1888 }
1889 } );
1890 }
1891 };
1892
1893 /**
1894 * Focus the first input in the current page.
1895 *
1896 * If no page is selected, the first selectable page will be selected.
1897 * If the focus is already in an element on the current page, nothing will happen.
1898 *
1899 * @param {number} [itemIndex] A specific item to focus on
1900 */
1901 OO.ui.BookletLayout.prototype.focus = function ( itemIndex ) {
1902 var page,
1903 items = this.stackLayout.getItems();
1904
1905 if ( itemIndex !== undefined && items[ itemIndex ] ) {
1906 page = items[ itemIndex ];
1907 } else {
1908 page = this.stackLayout.getCurrentItem();
1909 }
1910
1911 if ( !page && this.outlined ) {
1912 this.selectFirstSelectablePage();
1913 page = this.stackLayout.getCurrentItem();
1914 }
1915 if ( !page ) {
1916 return;
1917 }
1918 // Only change the focus if is not already in the current page
1919 if ( !OO.ui.contains( page.$element[ 0 ], this.getElementDocument().activeElement, true ) ) {
1920 page.focus();
1921 }
1922 };
1923
1924 /**
1925 * Find the first focusable input in the booklet layout and focus
1926 * on it.
1927 */
1928 OO.ui.BookletLayout.prototype.focusFirstFocusable = function () {
1929 OO.ui.findFocusable( this.stackLayout.$element ).focus();
1930 };
1931
1932 /**
1933 * Handle outline widget select events.
1934 *
1935 * @private
1936 * @param {OO.ui.OptionWidget|null} item Selected item
1937 */
1938 OO.ui.BookletLayout.prototype.onOutlineSelectWidgetSelect = function ( item ) {
1939 if ( item ) {
1940 this.setPage( item.getData() );
1941 }
1942 };
1943
1944 /**
1945 * Check if booklet has an outline.
1946 *
1947 * @return {boolean} Booklet has an outline
1948 */
1949 OO.ui.BookletLayout.prototype.isOutlined = function () {
1950 return this.outlined;
1951 };
1952
1953 /**
1954 * Check if booklet has editing controls.
1955 *
1956 * @return {boolean} Booklet is editable
1957 */
1958 OO.ui.BookletLayout.prototype.isEditable = function () {
1959 return this.editable;
1960 };
1961
1962 /**
1963 * Check if booklet has a visible outline.
1964 *
1965 * @return {boolean} Outline is visible
1966 */
1967 OO.ui.BookletLayout.prototype.isOutlineVisible = function () {
1968 return this.outlined && this.outlineVisible;
1969 };
1970
1971 /**
1972 * Hide or show the outline.
1973 *
1974 * @param {boolean} [show] Show outline, omit to invert current state
1975 * @chainable
1976 */
1977 OO.ui.BookletLayout.prototype.toggleOutline = function ( show ) {
1978 var booklet = this;
1979
1980 if ( this.outlined ) {
1981 show = show === undefined ? !this.outlineVisible : !!show;
1982 this.outlineVisible = show;
1983 this.toggleMenu( show );
1984 if ( show && this.editable ) {
1985 // HACK: When the sidebar stops animating, kill dumb scrollbars (T161798). Only necessary when
1986 // outline controls are present, The delay matches transition on `.oo-ui-menuLayout-menu`.
1987 setTimeout( function () {
1988 OO.ui.Element.static.reconsiderScrollbars( booklet.outlinePanel.$element[ 0 ] );
1989 }, 200 );
1990 }
1991 }
1992
1993 return this;
1994 };
1995
1996 /**
1997 * Get the page closest to the specified page.
1998 *
1999 * @param {OO.ui.PageLayout} page Page to use as a reference point
2000 * @return {OO.ui.PageLayout|null} Page closest to the specified page
2001 */
2002 OO.ui.BookletLayout.prototype.getClosestPage = function ( page ) {
2003 var next, prev, level,
2004 pages = this.stackLayout.getItems(),
2005 index = pages.indexOf( page );
2006
2007 if ( index !== -1 ) {
2008 next = pages[ index + 1 ];
2009 prev = pages[ index - 1 ];
2010 // Prefer adjacent pages at the same level
2011 if ( this.outlined ) {
2012 level = this.outlineSelectWidget.getItemFromData( page.getName() ).getLevel();
2013 if (
2014 prev &&
2015 level === this.outlineSelectWidget.getItemFromData( prev.getName() ).getLevel()
2016 ) {
2017 return prev;
2018 }
2019 if (
2020 next &&
2021 level === this.outlineSelectWidget.getItemFromData( next.getName() ).getLevel()
2022 ) {
2023 return next;
2024 }
2025 }
2026 }
2027 return prev || next || null;
2028 };
2029
2030 /**
2031 * Get the outline widget.
2032 *
2033 * If the booklet is not outlined, the method will return `null`.
2034 *
2035 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
2036 */
2037 OO.ui.BookletLayout.prototype.getOutline = function () {
2038 return this.outlineSelectWidget;
2039 };
2040
2041 /**
2042 * Get the outline controls widget.
2043 *
2044 * If the outline is not editable, the method will return `null`.
2045 *
2046 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
2047 */
2048 OO.ui.BookletLayout.prototype.getOutlineControls = function () {
2049 return this.outlineControlsWidget;
2050 };
2051
2052 /**
2053 * Get a page by its symbolic name.
2054 *
2055 * @param {string} name Symbolic name of page
2056 * @return {OO.ui.PageLayout|undefined} Page, if found
2057 */
2058 OO.ui.BookletLayout.prototype.getPage = function ( name ) {
2059 return this.pages[ name ];
2060 };
2061
2062 /**
2063 * Get the current page.
2064 *
2065 * @return {OO.ui.PageLayout|undefined} Current page, if found
2066 */
2067 OO.ui.BookletLayout.prototype.getCurrentPage = function () {
2068 var name = this.getCurrentPageName();
2069 return name ? this.getPage( name ) : undefined;
2070 };
2071
2072 /**
2073 * Get the symbolic name of the current page.
2074 *
2075 * @return {string|null} Symbolic name of the current page
2076 */
2077 OO.ui.BookletLayout.prototype.getCurrentPageName = function () {
2078 return this.currentPageName;
2079 };
2080
2081 /**
2082 * Add pages to the booklet layout
2083 *
2084 * When pages are added with the same names as existing pages, the existing pages will be
2085 * automatically removed before the new pages are added.
2086 *
2087 * @param {OO.ui.PageLayout[]} pages Pages to add
2088 * @param {number} index Index of the insertion point
2089 * @fires add
2090 * @chainable
2091 */
2092 OO.ui.BookletLayout.prototype.addPages = function ( pages, index ) {
2093 var i, len, name, page, item, currentIndex,
2094 stackLayoutPages = this.stackLayout.getItems(),
2095 remove = [],
2096 items = [];
2097
2098 // Remove pages with same names
2099 for ( i = 0, len = pages.length; i < len; i++ ) {
2100 page = pages[ i ];
2101 name = page.getName();
2102
2103 if ( Object.prototype.hasOwnProperty.call( this.pages, name ) ) {
2104 // Correct the insertion index
2105 currentIndex = stackLayoutPages.indexOf( this.pages[ name ] );
2106 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
2107 index--;
2108 }
2109 remove.push( this.pages[ name ] );
2110 }
2111 }
2112 if ( remove.length ) {
2113 this.removePages( remove );
2114 }
2115
2116 // Add new pages
2117 for ( i = 0, len = pages.length; i < len; i++ ) {
2118 page = pages[ i ];
2119 name = page.getName();
2120 this.pages[ page.getName() ] = page;
2121 if ( this.outlined ) {
2122 item = new OO.ui.OutlineOptionWidget( { data: name } );
2123 page.setOutlineItem( item );
2124 items.push( item );
2125 }
2126 }
2127
2128 if ( this.outlined && items.length ) {
2129 this.outlineSelectWidget.addItems( items, index );
2130 this.selectFirstSelectablePage();
2131 }
2132 this.stackLayout.addItems( pages, index );
2133 this.emit( 'add', pages, index );
2134
2135 return this;
2136 };
2137
2138 /**
2139 * Remove the specified pages from the booklet layout.
2140 *
2141 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
2142 *
2143 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
2144 * @fires remove
2145 * @chainable
2146 */
2147 OO.ui.BookletLayout.prototype.removePages = function ( pages ) {
2148 var i, len, name, page,
2149 items = [];
2150
2151 for ( i = 0, len = pages.length; i < len; i++ ) {
2152 page = pages[ i ];
2153 name = page.getName();
2154 delete this.pages[ name ];
2155 if ( this.outlined ) {
2156 items.push( this.outlineSelectWidget.getItemFromData( name ) );
2157 page.setOutlineItem( null );
2158 }
2159 }
2160 if ( this.outlined && items.length ) {
2161 this.outlineSelectWidget.removeItems( items );
2162 this.selectFirstSelectablePage();
2163 }
2164 this.stackLayout.removeItems( pages );
2165 this.emit( 'remove', pages );
2166
2167 return this;
2168 };
2169
2170 /**
2171 * Clear all pages from the booklet layout.
2172 *
2173 * To remove only a subset of pages from the booklet, use the #removePages method.
2174 *
2175 * @fires remove
2176 * @chainable
2177 */
2178 OO.ui.BookletLayout.prototype.clearPages = function () {
2179 var i, len,
2180 pages = this.stackLayout.getItems();
2181
2182 this.pages = {};
2183 this.currentPageName = null;
2184 if ( this.outlined ) {
2185 this.outlineSelectWidget.clearItems();
2186 for ( i = 0, len = pages.length; i < len; i++ ) {
2187 pages[ i ].setOutlineItem( null );
2188 }
2189 }
2190 this.stackLayout.clearItems();
2191
2192 this.emit( 'remove', pages );
2193
2194 return this;
2195 };
2196
2197 /**
2198 * Set the current page by symbolic name.
2199 *
2200 * @fires set
2201 * @param {string} name Symbolic name of page
2202 */
2203 OO.ui.BookletLayout.prototype.setPage = function ( name ) {
2204 var selectedItem,
2205 $focused,
2206 page = this.pages[ name ],
2207 previousPage = this.currentPageName && this.pages[ this.currentPageName ];
2208
2209 if ( name !== this.currentPageName ) {
2210 if ( this.outlined ) {
2211 selectedItem = this.outlineSelectWidget.getSelectedItem();
2212 if ( selectedItem && selectedItem.getData() !== name ) {
2213 this.outlineSelectWidget.selectItemByData( name );
2214 }
2215 }
2216 if ( page ) {
2217 if ( previousPage ) {
2218 previousPage.setActive( false );
2219 // Blur anything focused if the next page doesn't have anything focusable.
2220 // This is not needed if the next page has something focusable (because once it is focused
2221 // this blur happens automatically). If the layout is non-continuous, this check is
2222 // meaningless because the next page is not visible yet and thus can't hold focus.
2223 if (
2224 this.autoFocus &&
2225 !OO.ui.isMobile() &&
2226 this.stackLayout.continuous &&
2227 OO.ui.findFocusable( page.$element ).length !== 0
2228 ) {
2229 $focused = previousPage.$element.find( ':focus' );
2230 if ( $focused.length ) {
2231 $focused[ 0 ].blur();
2232 }
2233 }
2234 }
2235 this.currentPageName = name;
2236 page.setActive( true );
2237 this.stackLayout.setItem( page );
2238 if ( !this.stackLayout.continuous && previousPage ) {
2239 // This should not be necessary, since any inputs on the previous page should have been
2240 // blurred when it was hidden, but browsers are not very consistent about this.
2241 $focused = previousPage.$element.find( ':focus' );
2242 if ( $focused.length ) {
2243 $focused[ 0 ].blur();
2244 }
2245 }
2246 this.emit( 'set', page );
2247 }
2248 }
2249 };
2250
2251 /**
2252 * Select the first selectable page.
2253 *
2254 * @chainable
2255 */
2256 OO.ui.BookletLayout.prototype.selectFirstSelectablePage = function () {
2257 if ( !this.outlineSelectWidget.getSelectedItem() ) {
2258 this.outlineSelectWidget.selectItem( this.outlineSelectWidget.getFirstSelectableItem() );
2259 }
2260
2261 return this;
2262 };
2263
2264 /**
2265 * IndexLayouts contain {@link OO.ui.TabPanelLayout tab panel layouts} as well as
2266 * {@link OO.ui.TabSelectWidget tabs} that allow users to easily navigate through the tab panels and
2267 * select which one to display. By default, only one tab panel is displayed at a time. When a user
2268 * navigates to a new tab panel, the index layout automatically focuses on the first focusable element,
2269 * unless the default setting is changed.
2270 *
2271 * TODO: This class is similar to BookletLayout, we may want to refactor to reduce duplication
2272 *
2273 * @example
2274 * // Example of a IndexLayout that contains two TabPanelLayouts.
2275 *
2276 * function TabPanelOneLayout( name, config ) {
2277 * TabPanelOneLayout.parent.call( this, name, config );
2278 * this.$element.append( '<p>First tab panel</p>' );
2279 * }
2280 * OO.inheritClass( TabPanelOneLayout, OO.ui.TabPanelLayout );
2281 * TabPanelOneLayout.prototype.setupTabItem = function () {
2282 * this.tabItem.setLabel( 'Tab panel one' );
2283 * };
2284 *
2285 * var tabPanel1 = new TabPanelOneLayout( 'one' ),
2286 * tabPanel2 = new OO.ui.TabPanelLayout( 'two', { label: 'Tab panel two' } );
2287 *
2288 * tabPanel2.$element.append( '<p>Second tab panel</p>' );
2289 *
2290 * var index = new OO.ui.IndexLayout();
2291 *
2292 * index.addTabPanels ( [ tabPanel1, tabPanel2 ] );
2293 * $( 'body' ).append( index.$element );
2294 *
2295 * @class
2296 * @extends OO.ui.MenuLayout
2297 *
2298 * @constructor
2299 * @param {Object} [config] Configuration options
2300 * @cfg {boolean} [continuous=false] Show all tab panels, one after another
2301 * @cfg {boolean} [expanded=true] Expand the content panel to fill the entire parent element.
2302 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new tab panel is displayed. Disabled on mobile.
2303 */
2304 OO.ui.IndexLayout = function OoUiIndexLayout( config ) {
2305 // Configuration initialization
2306 config = $.extend( {}, config, { menuPosition: 'top' } );
2307
2308 // Parent constructor
2309 OO.ui.IndexLayout.parent.call( this, config );
2310
2311 // Properties
2312 this.currentTabPanelName = null;
2313 this.tabPanels = {};
2314
2315 Object.defineProperty( this, 'currentCardName', {
2316 // TODO: read documentation
2317 configurable: true,
2318 enumerable: true,
2319 get: function () {
2320 OO.ui.warnDeprecation( 'IndexLayout\'s currentCardName property is deprecated. Use currentTabPanelName instead. See T155152' );
2321 return this.currentTabPanelName;
2322 },
2323 set: function ( value ) {
2324 OO.ui.warnDeprecation( 'IndexLayout\'s currentCardName property is deprecated. Use currentTabPanelName instead. See T155152' );
2325 this.currentTabPanelName = value;
2326 }
2327 } );
2328
2329 Object.defineProperty( this, 'cards', {
2330 // TODO: read documentation
2331 configurable: true,
2332 enumerable: true,
2333 get: function () {
2334 OO.ui.warnDeprecation( 'IndexLayout\'s cards property is deprecated. Use tabPanels instead. See T155152' );
2335 return this.tabPanels;
2336 },
2337 set: function ( value ) {
2338 OO.ui.warnDeprecation( 'IndexLayout\'s cards property is deprecated. Use tabPanels instead. See T155152' );
2339 this.tabPanels = value;
2340 }
2341 } );
2342
2343 this.ignoreFocus = false;
2344 this.stackLayout = new OO.ui.StackLayout( {
2345 continuous: !!config.continuous,
2346 expanded: config.expanded
2347 } );
2348 this.$content.append( this.stackLayout.$element );
2349 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
2350
2351 this.tabSelectWidget = new OO.ui.TabSelectWidget();
2352 this.tabPanel = new OO.ui.PanelLayout();
2353 this.$menu.append( this.tabPanel.$element );
2354
2355 this.toggleMenu( true );
2356
2357 // Events
2358 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
2359 this.tabSelectWidget.connect( this, { select: 'onTabSelectWidgetSelect' } );
2360 if ( this.autoFocus ) {
2361 // Event 'focus' does not bubble, but 'focusin' does
2362 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
2363 }
2364
2365 // Initialization
2366 this.$element.addClass( 'oo-ui-indexLayout' );
2367 this.stackLayout.$element.addClass( 'oo-ui-indexLayout-stackLayout' );
2368 this.tabPanel.$element
2369 .addClass( 'oo-ui-indexLayout-tabPanel' )
2370 .append( this.tabSelectWidget.$element );
2371 };
2372
2373 /* Setup */
2374
2375 OO.inheritClass( OO.ui.IndexLayout, OO.ui.MenuLayout );
2376
2377 /* Events */
2378
2379 /**
2380 * A 'set' event is emitted when a tab panel is {@link #setTabPanel set} to be displayed by the index layout.
2381 * @event set
2382 * @param {OO.ui.TabPanelLayout} tabPanel Current tab panel
2383 */
2384
2385 /**
2386 * An 'add' event is emitted when tab panels are {@link #addTabPanels added} to the index layout.
2387 *
2388 * @event add
2389 * @param {OO.ui.TabPanelLayout[]} tabPanel Added tab panels
2390 * @param {number} index Index tab panels were added at
2391 */
2392
2393 /**
2394 * A 'remove' event is emitted when tab panels are {@link #clearTabPanels cleared} or
2395 * {@link #removeTabPanels removed} from the index.
2396 *
2397 * @event remove
2398 * @param {OO.ui.TabPanelLayout[]} tabPanel Removed tab panels
2399 */
2400
2401 /* Methods */
2402
2403 /**
2404 * Handle stack layout focus.
2405 *
2406 * @private
2407 * @param {jQuery.Event} e Focusing event
2408 */
2409 OO.ui.IndexLayout.prototype.onStackLayoutFocus = function ( e ) {
2410 var name, $target;
2411
2412 // Find the tab panel that an element was focused within
2413 $target = $( e.target ).closest( '.oo-ui-tabPanelLayout' );
2414 for ( name in this.tabPanels ) {
2415 // Check for tab panel match, exclude current tab panel to find only tab panel changes
2416 if ( this.tabPanels[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentTabPanelName ) {
2417 this.setTabPanel( name );
2418 break;
2419 }
2420 }
2421 };
2422
2423 /**
2424 * Handle stack layout set events.
2425 *
2426 * @private
2427 * @param {OO.ui.PanelLayout|null} tabPanel The tab panel that is now the current panel
2428 */
2429 OO.ui.IndexLayout.prototype.onStackLayoutSet = function ( tabPanel ) {
2430 var layout = this;
2431 if ( tabPanel ) {
2432 tabPanel.scrollElementIntoView().done( function () {
2433 if ( layout.autoFocus && !OO.ui.isMobile() ) {
2434 layout.focus();
2435 }
2436 } );
2437 }
2438 };
2439
2440 /**
2441 * Focus the first input in the current tab panel.
2442 *
2443 * If no tab panel is selected, the first selectable tab panel will be selected.
2444 * If the focus is already in an element on the current tab panel, nothing will happen.
2445 *
2446 * @param {number} [itemIndex] A specific item to focus on
2447 */
2448 OO.ui.IndexLayout.prototype.focus = function ( itemIndex ) {
2449 var tabPanel,
2450 items = this.stackLayout.getItems();
2451
2452 if ( itemIndex !== undefined && items[ itemIndex ] ) {
2453 tabPanel = items[ itemIndex ];
2454 } else {
2455 tabPanel = this.stackLayout.getCurrentItem();
2456 }
2457
2458 if ( !tabPanel ) {
2459 this.selectFirstSelectableTabPanel();
2460 tabPanel = this.stackLayout.getCurrentItem();
2461 }
2462 if ( !tabPanel ) {
2463 return;
2464 }
2465 // Only change the focus if is not already in the current page
2466 if ( !OO.ui.contains( tabPanel.$element[ 0 ], this.getElementDocument().activeElement, true ) ) {
2467 tabPanel.focus();
2468 }
2469 };
2470
2471 /**
2472 * Find the first focusable input in the index layout and focus
2473 * on it.
2474 */
2475 OO.ui.IndexLayout.prototype.focusFirstFocusable = function () {
2476 OO.ui.findFocusable( this.stackLayout.$element ).focus();
2477 };
2478
2479 /**
2480 * Handle tab widget select events.
2481 *
2482 * @private
2483 * @param {OO.ui.OptionWidget|null} item Selected item
2484 */
2485 OO.ui.IndexLayout.prototype.onTabSelectWidgetSelect = function ( item ) {
2486 if ( item ) {
2487 this.setTabPanel( item.getData() );
2488 }
2489 };
2490
2491 /**
2492 * Get the tab panel closest to the specified tab panel.
2493 *
2494 * @param {OO.ui.TabPanelLayout} tabPanel Tab panel to use as a reference point
2495 * @return {OO.ui.TabPanelLayout|null} Tab panel closest to the specified
2496 */
2497 OO.ui.IndexLayout.prototype.getClosestTabPanel = function ( tabPanel ) {
2498 var next, prev, level,
2499 tabPanels = this.stackLayout.getItems(),
2500 index = tabPanels.indexOf( tabPanel );
2501
2502 if ( index !== -1 ) {
2503 next = tabPanels[ index + 1 ];
2504 prev = tabPanels[ index - 1 ];
2505 // Prefer adjacent tab panels at the same level
2506 level = this.tabSelectWidget.getItemFromData( tabPanel.getName() ).getLevel();
2507 if (
2508 prev &&
2509 level === this.tabSelectWidget.getItemFromData( prev.getName() ).getLevel()
2510 ) {
2511 return prev;
2512 }
2513 if (
2514 next &&
2515 level === this.tabSelectWidget.getItemFromData( next.getName() ).getLevel()
2516 ) {
2517 return next;
2518 }
2519 }
2520 return prev || next || null;
2521 };
2522
2523 /**
2524 * Get the tab panel closest to the specified tab panel.
2525 *
2526 * @param {OO.ui.TabPanelLayout} tabPanel Tab panel to use as a reference point
2527 * @return {OO.ui.TabPanelLayout|null} Tab panel closest to the specified
2528 * @deprecated since v0.21.3, use `getClosestTabPanel` instead
2529 */
2530 OO.ui.IndexLayout.prototype.getClosestCard = function ( tabPanel ) {
2531 OO.ui.warnDeprecation( 'IndexLayout\'s getClosestCard method is deprecated. Use getClosestTabPanel instead. See T155152' );
2532 return this.getClosestTabPanel( tabPanel );
2533 };
2534
2535 /**
2536 * Get the tabs widget.
2537 *
2538 * @return {OO.ui.TabSelectWidget} Tabs widget
2539 */
2540 OO.ui.IndexLayout.prototype.getTabs = function () {
2541 return this.tabSelectWidget;
2542 };
2543
2544 /**
2545 * Get a tab panel by its symbolic name.
2546 *
2547 * @param {string} name Symbolic name of tab panel
2548 * @return {OO.ui.TabPanelLayout|undefined} Tab panel, if found
2549 */
2550 OO.ui.IndexLayout.prototype.getTabPanel = function ( name ) {
2551 return this.tabPanels[ name ];
2552 };
2553
2554 /**
2555 * Get a tab panel by its symbolic name.
2556 *
2557 * @param {string} name Symbolic name of tab panel
2558 * @return {OO.ui.TabPanelLayout|undefined} Tab panel, if found
2559 * @deprecated since v0.21.3, use `getTabPanel` instead
2560 */
2561 OO.ui.IndexLayout.prototype.getCard = function ( name ) {
2562 OO.ui.warnDeprecation( 'IndexLayout\'s getCard method is deprecated. Use getTabPanel instead. See T155152' );
2563 return this.getTabPanel( name );
2564 };
2565
2566 /**
2567 * Get the current tab panel.
2568 *
2569 * @return {OO.ui.TabPanelLayout|undefined} Current tab panel, if found
2570 */
2571 OO.ui.IndexLayout.prototype.getCurrentTabPanel = function () {
2572 var name = this.getCurrentTabPanelName();
2573 return name ? this.getTabPanel( name ) : undefined;
2574 };
2575
2576 /**
2577 * Get the current tab panel.
2578 *
2579 * @return {OO.ui.TabPanelLayout|undefined} Current tab panel, if found
2580 * @deprecated since v0.21.3, use `getCurrentTabPanel` instead
2581 */
2582 OO.ui.IndexLayout.prototype.getCurrentCard = function () {
2583 OO.ui.warnDeprecation( 'IndexLayout\'s getCurrentCard method is deprecated. Use getCurrentTabPanel instead. See T155152' );
2584 return this.getCurrentTabPanel();
2585 };
2586
2587 /**
2588 * Get the symbolic name of the current tab panel.
2589 *
2590 * @return {string|null} Symbolic name of the current tab panel
2591 */
2592 OO.ui.IndexLayout.prototype.getCurrentTabPanelName = function () {
2593 return this.currentTabPanelName;
2594 };
2595
2596 /**
2597 * Get the symbolic name of the current tab panel.
2598 *
2599 * @return {string|null} Symbolic name of the current tab panel
2600 * @deprecated since v0.21.3, use `getCurrentTabPanelName` instead
2601 */
2602 OO.ui.IndexLayout.prototype.getCurrentCardName = function () {
2603 OO.ui.warnDeprecation( 'IndexLayout\'s getCurrentCardName method is deprecated. Use getCurrentTabPanelName instead. See T155152' );
2604 return this.getCurrentTabPanelName();
2605 };
2606
2607 /**
2608 * Add tab panels to the index layout
2609 *
2610 * When tab panels are added with the same names as existing tab panels, the existing tab panels
2611 * will be automatically removed before the new tab panels are added.
2612 *
2613 * @param {OO.ui.TabPanelLayout[]} tabPanels Tab panels to add
2614 * @param {number} index Index of the insertion point
2615 * @fires add
2616 * @chainable
2617 */
2618 OO.ui.IndexLayout.prototype.addTabPanels = function ( tabPanels, index ) {
2619 var i, len, name, tabPanel, item, currentIndex,
2620 stackLayoutTabPanels = this.stackLayout.getItems(),
2621 remove = [],
2622 items = [];
2623
2624 // Remove tab panels with same names
2625 for ( i = 0, len = tabPanels.length; i < len; i++ ) {
2626 tabPanel = tabPanels[ i ];
2627 name = tabPanel.getName();
2628
2629 if ( Object.prototype.hasOwnProperty.call( this.tabPanels, name ) ) {
2630 // Correct the insertion index
2631 currentIndex = stackLayoutTabPanels.indexOf( this.tabPanels[ name ] );
2632 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
2633 index--;
2634 }
2635 remove.push( this.tabPanels[ name ] );
2636 }
2637 }
2638 if ( remove.length ) {
2639 this.removeTabPanels( remove );
2640 }
2641
2642 // Add new tab panels
2643 for ( i = 0, len = tabPanels.length; i < len; i++ ) {
2644 tabPanel = tabPanels[ i ];
2645 name = tabPanel.getName();
2646 this.tabPanels[ tabPanel.getName() ] = tabPanel;
2647 item = new OO.ui.TabOptionWidget( { data: name } );
2648 tabPanel.setTabItem( item );
2649 items.push( item );
2650 }
2651
2652 if ( items.length ) {
2653 this.tabSelectWidget.addItems( items, index );
2654 this.selectFirstSelectableTabPanel();
2655 }
2656 this.stackLayout.addItems( tabPanels, index );
2657 this.emit( 'add', tabPanels, index );
2658
2659 return this;
2660 };
2661
2662 /**
2663 * Add tab panels to the index layout
2664 *
2665 * When tab panels are added with the same names as existing tab panels, the existing tab panels
2666 * will be automatically removed before the new tab panels are added.
2667 *
2668 * @param {OO.ui.TabPanelLayout[]} tabPanels Tab panels to add
2669 * @param {number} index Index of the insertion point
2670 * @fires add
2671 * @chainable
2672 * @deprecated since v0.21.3, use `addTabPanels` instead
2673 */
2674 OO.ui.IndexLayout.prototype.addCards = function ( tabPanels, index ) {
2675 OO.ui.warnDeprecation( 'IndexLayout\'s addCards method is deprecated. Use addTabPanels instead. See T155152' );
2676 return this.addTabPanels( tabPanels, index );
2677 };
2678
2679 /**
2680 * Remove the specified tab panels from the index layout.
2681 *
2682 * To remove all tab panels from the index, you may wish to use the #clearTabPanels method instead.
2683 *
2684 * @param {OO.ui.TabPanelLayout[]} tabPanels An array of tab panels to remove
2685 * @fires remove
2686 * @chainable
2687 */
2688 OO.ui.IndexLayout.prototype.removeTabPanels = function ( tabPanels ) {
2689 var i, len, name, tabPanel,
2690 items = [];
2691
2692 for ( i = 0, len = tabPanels.length; i < len; i++ ) {
2693 tabPanel = tabPanels[ i ];
2694 name = tabPanel.getName();
2695 delete this.tabPanels[ name ];
2696 items.push( this.tabSelectWidget.getItemFromData( name ) );
2697 tabPanel.setTabItem( null );
2698 }
2699 if ( items.length ) {
2700 this.tabSelectWidget.removeItems( items );
2701 this.selectFirstSelectableTabPanel();
2702 }
2703 this.stackLayout.removeItems( tabPanels );
2704 this.emit( 'remove', tabPanels );
2705
2706 return this;
2707 };
2708
2709 /**
2710 * Remove the specified tab panels from the index layout.
2711 *
2712 * To remove all tab panels from the index, you may wish to use the #clearTabPanels method instead.
2713 *
2714 * @param {OO.ui.TabPanelLayout[]} tabPanels An array of tab panels to remove
2715 * @fires remove
2716 * @chainable
2717 * @deprecated since v0.21.3, use `removeTabPanels` instead
2718 */
2719 OO.ui.IndexLayout.prototype.removeCards = function ( tabPanels ) {
2720 OO.ui.warnDeprecation( 'IndexLayout\'s removeCards method is deprecated. Use removeTabPanels instead. See T155152.' );
2721 return this.removeTabPanels( tabPanels );
2722 };
2723
2724 /**
2725 * Clear all tab panels from the index layout.
2726 *
2727 * To remove only a subset of tab panels from the index, use the #removeTabPanels method.
2728 *
2729 * @fires remove
2730 * @chainable
2731 */
2732 OO.ui.IndexLayout.prototype.clearTabPanels = function () {
2733 var i, len,
2734 tabPanels = this.stackLayout.getItems();
2735
2736 this.tabPanels = {};
2737 this.currentTabPanelName = null;
2738 this.tabSelectWidget.clearItems();
2739 for ( i = 0, len = tabPanels.length; i < len; i++ ) {
2740 tabPanels[ i ].setTabItem( null );
2741 }
2742 this.stackLayout.clearItems();
2743
2744 this.emit( 'remove', tabPanels );
2745
2746 return this;
2747 };
2748
2749 /**
2750 * Clear all tab panels from the index layout.
2751 *
2752 * To remove only a subset of tab panels from the index, use the #removeTabPanels method.
2753 *
2754 * @fires remove
2755 * @chainable
2756 * @deprecated since v0.21.3, use `clearTabPanels` instead
2757 */
2758 OO.ui.IndexLayout.prototype.clearCards = function () {
2759 OO.ui.warnDeprecation( 'IndexLayout\'s clearCards method is deprecated. Use clearTabPanels instead. See T155152.' );
2760 return this.clearTabPanels();
2761 };
2762
2763 /**
2764 * Set the current tab panel by symbolic name.
2765 *
2766 * @fires set
2767 * @param {string} name Symbolic name of tab panel
2768 */
2769 OO.ui.IndexLayout.prototype.setTabPanel = function ( name ) {
2770 var selectedItem,
2771 $focused,
2772 tabPanel = this.tabPanels[ name ],
2773 previousTabPanel = this.currentTabPanelName && this.tabPanels[ this.currentTabPanelName ];
2774
2775 if ( name !== this.currentTabPanelName ) {
2776 selectedItem = this.tabSelectWidget.getSelectedItem();
2777 if ( selectedItem && selectedItem.getData() !== name ) {
2778 this.tabSelectWidget.selectItemByData( name );
2779 }
2780 if ( tabPanel ) {
2781 if ( previousTabPanel ) {
2782 previousTabPanel.setActive( false );
2783 // Blur anything focused if the next tab panel doesn't have anything focusable.
2784 // This is not needed if the next tab panel has something focusable (because once it is focused
2785 // this blur happens automatically). If the layout is non-continuous, this check is
2786 // meaningless because the next tab panel is not visible yet and thus can't hold focus.
2787 if (
2788 this.autoFocus &&
2789 !OO.ui.isMobile() &&
2790 this.stackLayout.continuous &&
2791 OO.ui.findFocusable( tabPanel.$element ).length !== 0
2792 ) {
2793 $focused = previousTabPanel.$element.find( ':focus' );
2794 if ( $focused.length ) {
2795 $focused[ 0 ].blur();
2796 }
2797 }
2798 }
2799 this.currentTabPanelName = name;
2800 tabPanel.setActive( true );
2801 this.stackLayout.setItem( tabPanel );
2802 if ( !this.stackLayout.continuous && previousTabPanel ) {
2803 // This should not be necessary, since any inputs on the previous tab panel should have been
2804 // blurred when it was hidden, but browsers are not very consistent about this.
2805 $focused = previousTabPanel.$element.find( ':focus' );
2806 if ( $focused.length ) {
2807 $focused[ 0 ].blur();
2808 }
2809 }
2810 this.emit( 'set', tabPanel );
2811 }
2812 }
2813 };
2814
2815 /**
2816 * Set the current tab panel by symbolic name.
2817 *
2818 * @fires set
2819 * @param {string} name Symbolic name of tab panel
2820 * @deprecated since v0.21.3, use `setTabPanel` instead
2821 */
2822 OO.ui.IndexLayout.prototype.setCard = function ( name ) {
2823 OO.ui.warnDeprecation( 'IndexLayout\'s setCard method is deprecated. Use setTabPanel instead. See T155152.' );
2824 return this.setTabPanel( name );
2825 };
2826
2827 /**
2828 * Select the first selectable tab panel.
2829 *
2830 * @chainable
2831 */
2832 OO.ui.IndexLayout.prototype.selectFirstSelectableTabPanel = function () {
2833 if ( !this.tabSelectWidget.getSelectedItem() ) {
2834 this.tabSelectWidget.selectItem( this.tabSelectWidget.getFirstSelectableItem() );
2835 }
2836
2837 return this;
2838 };
2839
2840 /**
2841 * Select the first selectable tab panel.
2842 *
2843 * @chainable
2844 * @deprecated since v0.21.3, use `selectFirstSelectableTabPanel` instead
2845 */
2846 OO.ui.IndexLayout.prototype.selectFirstSelectableCard = function () {
2847 OO.ui.warnDeprecation( 'IndexLayout\'s selectFirstSelectableCard method is deprecated. Use selectFirestSelectableTabPanel instead. See T155152.' );
2848 return this.selectFirstSelectableTabPanel();
2849 };
2850
2851 /**
2852 * ToggleWidget implements basic behavior of widgets with an on/off state.
2853 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
2854 *
2855 * @abstract
2856 * @class
2857 * @extends OO.ui.Widget
2858 *
2859 * @constructor
2860 * @param {Object} [config] Configuration options
2861 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
2862 * By default, the toggle is in the 'off' state.
2863 */
2864 OO.ui.ToggleWidget = function OoUiToggleWidget( config ) {
2865 // Configuration initialization
2866 config = config || {};
2867
2868 // Parent constructor
2869 OO.ui.ToggleWidget.parent.call( this, config );
2870
2871 // Properties
2872 this.value = null;
2873
2874 // Initialization
2875 this.$element.addClass( 'oo-ui-toggleWidget' );
2876 this.setValue( !!config.value );
2877 };
2878
2879 /* Setup */
2880
2881 OO.inheritClass( OO.ui.ToggleWidget, OO.ui.Widget );
2882
2883 /* Events */
2884
2885 /**
2886 * @event change
2887 *
2888 * A change event is emitted when the on/off state of the toggle changes.
2889 *
2890 * @param {boolean} value Value representing the new state of the toggle
2891 */
2892
2893 /* Methods */
2894
2895 /**
2896 * Get the value representing the toggle’s state.
2897 *
2898 * @return {boolean} The on/off state of the toggle
2899 */
2900 OO.ui.ToggleWidget.prototype.getValue = function () {
2901 return this.value;
2902 };
2903
2904 /**
2905 * Set the state of the toggle: `true` for 'on', `false` for 'off'.
2906 *
2907 * @param {boolean} value The state of the toggle
2908 * @fires change
2909 * @chainable
2910 */
2911 OO.ui.ToggleWidget.prototype.setValue = function ( value ) {
2912 value = !!value;
2913 if ( this.value !== value ) {
2914 this.value = value;
2915 this.emit( 'change', value );
2916 this.$element.toggleClass( 'oo-ui-toggleWidget-on', value );
2917 this.$element.toggleClass( 'oo-ui-toggleWidget-off', !value );
2918 }
2919 return this;
2920 };
2921
2922 /**
2923 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
2924 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
2925 * configured with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators},
2926 * {@link OO.ui.mixin.TitledElement titles}, {@link OO.ui.mixin.FlaggedElement styling flags},
2927 * and {@link OO.ui.mixin.LabelElement labels}. Please see
2928 * the [OOjs UI documentation][1] on MediaWiki for more information.
2929 *
2930 * @example
2931 * // Toggle buttons in the 'off' and 'on' state.
2932 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
2933 * label: 'Toggle Button off'
2934 * } );
2935 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
2936 * label: 'Toggle Button on',
2937 * value: true
2938 * } );
2939 * // Append the buttons to the DOM.
2940 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
2941 *
2942 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
2943 *
2944 * @class
2945 * @extends OO.ui.ToggleWidget
2946 * @mixins OO.ui.mixin.ButtonElement
2947 * @mixins OO.ui.mixin.IconElement
2948 * @mixins OO.ui.mixin.IndicatorElement
2949 * @mixins OO.ui.mixin.LabelElement
2950 * @mixins OO.ui.mixin.TitledElement
2951 * @mixins OO.ui.mixin.FlaggedElement
2952 * @mixins OO.ui.mixin.TabIndexedElement
2953 *
2954 * @constructor
2955 * @param {Object} [config] Configuration options
2956 * @cfg {boolean} [value=false] The toggle button’s initial on/off
2957 * state. By default, the button is in the 'off' state.
2958 */
2959 OO.ui.ToggleButtonWidget = function OoUiToggleButtonWidget( config ) {
2960 // Configuration initialization
2961 config = config || {};
2962
2963 // Parent constructor
2964 OO.ui.ToggleButtonWidget.parent.call( this, config );
2965
2966 // Mixin constructors
2967 OO.ui.mixin.ButtonElement.call( this, $.extend( {}, config, { active: this.active } ) );
2968 OO.ui.mixin.IconElement.call( this, config );
2969 OO.ui.mixin.IndicatorElement.call( this, config );
2970 OO.ui.mixin.LabelElement.call( this, config );
2971 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
2972 OO.ui.mixin.FlaggedElement.call( this, config );
2973 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
2974
2975 // Events
2976 this.connect( this, { click: 'onAction' } );
2977
2978 // Initialization
2979 this.$button.append( this.$icon, this.$label, this.$indicator );
2980 this.$element
2981 .addClass( 'oo-ui-toggleButtonWidget' )
2982 .append( this.$button );
2983 };
2984
2985 /* Setup */
2986
2987 OO.inheritClass( OO.ui.ToggleButtonWidget, OO.ui.ToggleWidget );
2988 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.ButtonElement );
2989 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IconElement );
2990 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IndicatorElement );
2991 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.LabelElement );
2992 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TitledElement );
2993 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.FlaggedElement );
2994 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TabIndexedElement );
2995
2996 /* Static Properties */
2997
2998 /**
2999 * @static
3000 * @inheritdoc
3001 */
3002 OO.ui.ToggleButtonWidget.static.tagName = 'span';
3003
3004 /* Methods */
3005
3006 /**
3007 * Handle the button action being triggered.
3008 *
3009 * @private
3010 */
3011 OO.ui.ToggleButtonWidget.prototype.onAction = function () {
3012 this.setValue( !this.value );
3013 };
3014
3015 /**
3016 * @inheritdoc
3017 */
3018 OO.ui.ToggleButtonWidget.prototype.setValue = function ( value ) {
3019 value = !!value;
3020 if ( value !== this.value ) {
3021 // Might be called from parent constructor before ButtonElement constructor
3022 if ( this.$button ) {
3023 this.$button.attr( 'aria-pressed', value.toString() );
3024 }
3025 this.setActive( value );
3026 }
3027
3028 // Parent method
3029 OO.ui.ToggleButtonWidget.parent.prototype.setValue.call( this, value );
3030
3031 return this;
3032 };
3033
3034 /**
3035 * @inheritdoc
3036 */
3037 OO.ui.ToggleButtonWidget.prototype.setButtonElement = function ( $button ) {
3038 if ( this.$button ) {
3039 this.$button.removeAttr( 'aria-pressed' );
3040 }
3041 OO.ui.mixin.ButtonElement.prototype.setButtonElement.call( this, $button );
3042 this.$button.attr( 'aria-pressed', this.value.toString() );
3043 };
3044
3045 /**
3046 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
3047 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
3048 * visually by a slider in the leftmost position.
3049 *
3050 * @example
3051 * // Toggle switches in the 'off' and 'on' position.
3052 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
3053 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
3054 * value: true
3055 * } );
3056 *
3057 * // Create a FieldsetLayout to layout and label switches
3058 * var fieldset = new OO.ui.FieldsetLayout( {
3059 * label: 'Toggle switches'
3060 * } );
3061 * fieldset.addItems( [
3062 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
3063 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
3064 * ] );
3065 * $( 'body' ).append( fieldset.$element );
3066 *
3067 * @class
3068 * @extends OO.ui.ToggleWidget
3069 * @mixins OO.ui.mixin.TabIndexedElement
3070 *
3071 * @constructor
3072 * @param {Object} [config] Configuration options
3073 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
3074 * By default, the toggle switch is in the 'off' position.
3075 */
3076 OO.ui.ToggleSwitchWidget = function OoUiToggleSwitchWidget( config ) {
3077 // Parent constructor
3078 OO.ui.ToggleSwitchWidget.parent.call( this, config );
3079
3080 // Mixin constructors
3081 OO.ui.mixin.TabIndexedElement.call( this, config );
3082
3083 // Properties
3084 this.dragging = false;
3085 this.dragStart = null;
3086 this.sliding = false;
3087 this.$glow = $( '<span>' );
3088 this.$grip = $( '<span>' );
3089
3090 // Events
3091 this.$element.on( {
3092 click: this.onClick.bind( this ),
3093 keypress: this.onKeyPress.bind( this )
3094 } );
3095
3096 // Initialization
3097 this.$glow.addClass( 'oo-ui-toggleSwitchWidget-glow' );
3098 this.$grip.addClass( 'oo-ui-toggleSwitchWidget-grip' );
3099 this.$element
3100 .addClass( 'oo-ui-toggleSwitchWidget' )
3101 .attr( 'role', 'checkbox' )
3102 .append( this.$glow, this.$grip );
3103 };
3104
3105 /* Setup */
3106
3107 OO.inheritClass( OO.ui.ToggleSwitchWidget, OO.ui.ToggleWidget );
3108 OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.mixin.TabIndexedElement );
3109
3110 /* Methods */
3111
3112 /**
3113 * Handle mouse click events.
3114 *
3115 * @private
3116 * @param {jQuery.Event} e Mouse click event
3117 */
3118 OO.ui.ToggleSwitchWidget.prototype.onClick = function ( e ) {
3119 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
3120 this.setValue( !this.value );
3121 }
3122 return false;
3123 };
3124
3125 /**
3126 * Handle key press events.
3127 *
3128 * @private
3129 * @param {jQuery.Event} e Key press event
3130 */
3131 OO.ui.ToggleSwitchWidget.prototype.onKeyPress = function ( e ) {
3132 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
3133 this.setValue( !this.value );
3134 return false;
3135 }
3136 };
3137
3138 /**
3139 * @inheritdoc
3140 */
3141 OO.ui.ToggleSwitchWidget.prototype.setValue = function ( value ) {
3142 OO.ui.ToggleSwitchWidget.parent.prototype.setValue.call( this, value );
3143 this.$element.attr( 'aria-checked', this.value.toString() );
3144 return this;
3145 };
3146
3147 /**
3148 * @inheritdoc
3149 */
3150 OO.ui.ToggleSwitchWidget.prototype.simulateLabelClick = function () {
3151 if ( !this.isDisabled() ) {
3152 this.setValue( !this.value );
3153 }
3154 this.focus();
3155 };
3156
3157 /**
3158 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
3159 * Controls include moving items up and down, removing items, and adding different kinds of items.
3160 *
3161 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
3162 *
3163 * @class
3164 * @extends OO.ui.Widget
3165 * @mixins OO.ui.mixin.GroupElement
3166 * @mixins OO.ui.mixin.IconElement
3167 *
3168 * @constructor
3169 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
3170 * @param {Object} [config] Configuration options
3171 * @cfg {Object} [abilities] List of abilties
3172 * @cfg {boolean} [abilities.move=true] Allow moving movable items
3173 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
3174 */
3175 OO.ui.OutlineControlsWidget = function OoUiOutlineControlsWidget( outline, config ) {
3176 // Allow passing positional parameters inside the config object
3177 if ( OO.isPlainObject( outline ) && config === undefined ) {
3178 config = outline;
3179 outline = config.outline;
3180 }
3181
3182 // Configuration initialization
3183 config = $.extend( { icon: 'add' }, config );
3184
3185 // Parent constructor
3186 OO.ui.OutlineControlsWidget.parent.call( this, config );
3187
3188 // Mixin constructors
3189 OO.ui.mixin.GroupElement.call( this, config );
3190 OO.ui.mixin.IconElement.call( this, config );
3191
3192 // Properties
3193 this.outline = outline;
3194 this.$movers = $( '<div>' );
3195 this.upButton = new OO.ui.ButtonWidget( {
3196 framed: false,
3197 icon: 'collapse',
3198 title: OO.ui.msg( 'ooui-outline-control-move-up' )
3199 } );
3200 this.downButton = new OO.ui.ButtonWidget( {
3201 framed: false,
3202 icon: 'expand',
3203 title: OO.ui.msg( 'ooui-outline-control-move-down' )
3204 } );
3205 this.removeButton = new OO.ui.ButtonWidget( {
3206 framed: false,
3207 icon: 'trash',
3208 title: OO.ui.msg( 'ooui-outline-control-remove' )
3209 } );
3210 this.abilities = { move: true, remove: true };
3211
3212 // Events
3213 outline.connect( this, {
3214 select: 'onOutlineChange',
3215 add: 'onOutlineChange',
3216 remove: 'onOutlineChange'
3217 } );
3218 this.upButton.connect( this, { click: [ 'emit', 'move', -1 ] } );
3219 this.downButton.connect( this, { click: [ 'emit', 'move', 1 ] } );
3220 this.removeButton.connect( this, { click: [ 'emit', 'remove' ] } );
3221
3222 // Initialization
3223 this.$element.addClass( 'oo-ui-outlineControlsWidget' );
3224 this.$group.addClass( 'oo-ui-outlineControlsWidget-items' );
3225 this.$movers
3226 .addClass( 'oo-ui-outlineControlsWidget-movers' )
3227 .append( this.removeButton.$element, this.upButton.$element, this.downButton.$element );
3228 this.$element.append( this.$icon, this.$group, this.$movers );
3229 this.setAbilities( config.abilities || {} );
3230 };
3231
3232 /* Setup */
3233
3234 OO.inheritClass( OO.ui.OutlineControlsWidget, OO.ui.Widget );
3235 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.GroupElement );
3236 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.IconElement );
3237
3238 /* Events */
3239
3240 /**
3241 * @event move
3242 * @param {number} places Number of places to move
3243 */
3244
3245 /**
3246 * @event remove
3247 */
3248
3249 /* Methods */
3250
3251 /**
3252 * Set abilities.
3253 *
3254 * @param {Object} abilities List of abilties
3255 * @param {boolean} [abilities.move] Allow moving movable items
3256 * @param {boolean} [abilities.remove] Allow removing removable items
3257 */
3258 OO.ui.OutlineControlsWidget.prototype.setAbilities = function ( abilities ) {
3259 var ability;
3260
3261 for ( ability in this.abilities ) {
3262 if ( abilities[ ability ] !== undefined ) {
3263 this.abilities[ ability ] = !!abilities[ ability ];
3264 }
3265 }
3266
3267 this.onOutlineChange();
3268 };
3269
3270 /**
3271 * Handle outline change events.
3272 *
3273 * @private
3274 */
3275 OO.ui.OutlineControlsWidget.prototype.onOutlineChange = function () {
3276 var i, len, firstMovable, lastMovable,
3277 items = this.outline.getItems(),
3278 selectedItem = this.outline.getSelectedItem(),
3279 movable = this.abilities.move && selectedItem && selectedItem.isMovable(),
3280 removable = this.abilities.remove && selectedItem && selectedItem.isRemovable();
3281
3282 if ( movable ) {
3283 i = -1;
3284 len = items.length;
3285 while ( ++i < len ) {
3286 if ( items[ i ].isMovable() ) {
3287 firstMovable = items[ i ];
3288 break;
3289 }
3290 }
3291 i = len;
3292 while ( i-- ) {
3293 if ( items[ i ].isMovable() ) {
3294 lastMovable = items[ i ];
3295 break;
3296 }
3297 }
3298 }
3299 this.upButton.setDisabled( !movable || selectedItem === firstMovable );
3300 this.downButton.setDisabled( !movable || selectedItem === lastMovable );
3301 this.removeButton.setDisabled( !removable );
3302 };
3303
3304 /**
3305 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
3306 *
3307 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
3308 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
3309 * for an example.
3310 *
3311 * @class
3312 * @extends OO.ui.DecoratedOptionWidget
3313 *
3314 * @constructor
3315 * @param {Object} [config] Configuration options
3316 * @cfg {number} [level] Indentation level
3317 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
3318 */
3319 OO.ui.OutlineOptionWidget = function OoUiOutlineOptionWidget( config ) {
3320 // Configuration initialization
3321 config = config || {};
3322
3323 // Parent constructor
3324 OO.ui.OutlineOptionWidget.parent.call( this, config );
3325
3326 // Properties
3327 this.level = 0;
3328 this.movable = !!config.movable;
3329 this.removable = !!config.removable;
3330
3331 // Initialization
3332 this.$element.addClass( 'oo-ui-outlineOptionWidget' );
3333 this.setLevel( config.level );
3334 };
3335
3336 /* Setup */
3337
3338 OO.inheritClass( OO.ui.OutlineOptionWidget, OO.ui.DecoratedOptionWidget );
3339
3340 /* Static Properties */
3341
3342 /**
3343 * @static
3344 * @inheritdoc
3345 */
3346 OO.ui.OutlineOptionWidget.static.highlightable = true;
3347
3348 /**
3349 * @static
3350 * @inheritdoc
3351 */
3352 OO.ui.OutlineOptionWidget.static.scrollIntoViewOnSelect = true;
3353
3354 /**
3355 * @static
3356 * @inheritable
3357 * @property {string}
3358 */
3359 OO.ui.OutlineOptionWidget.static.levelClass = 'oo-ui-outlineOptionWidget-level-';
3360
3361 /**
3362 * @static
3363 * @inheritable
3364 * @property {number}
3365 */
3366 OO.ui.OutlineOptionWidget.static.levels = 3;
3367
3368 /* Methods */
3369
3370 /**
3371 * Check if item is movable.
3372 *
3373 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
3374 *
3375 * @return {boolean} Item is movable
3376 */
3377 OO.ui.OutlineOptionWidget.prototype.isMovable = function () {
3378 return this.movable;
3379 };
3380
3381 /**
3382 * Check if item is removable.
3383 *
3384 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
3385 *
3386 * @return {boolean} Item is removable
3387 */
3388 OO.ui.OutlineOptionWidget.prototype.isRemovable = function () {
3389 return this.removable;
3390 };
3391
3392 /**
3393 * Get indentation level.
3394 *
3395 * @return {number} Indentation level
3396 */
3397 OO.ui.OutlineOptionWidget.prototype.getLevel = function () {
3398 return this.level;
3399 };
3400
3401 /**
3402 * @inheritdoc
3403 */
3404 OO.ui.OutlineOptionWidget.prototype.setPressed = function ( state ) {
3405 OO.ui.OutlineOptionWidget.parent.prototype.setPressed.call( this, state );
3406 if ( this.pressed ) {
3407 this.setFlags( { progressive: true } );
3408 } else if ( !this.selected ) {
3409 this.setFlags( { progressive: false } );
3410 }
3411 return this;
3412 };
3413
3414 /**
3415 * Set movability.
3416 *
3417 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
3418 *
3419 * @param {boolean} movable Item is movable
3420 * @chainable
3421 */
3422 OO.ui.OutlineOptionWidget.prototype.setMovable = function ( movable ) {
3423 this.movable = !!movable;
3424 this.updateThemeClasses();
3425 return this;
3426 };
3427
3428 /**
3429 * Set removability.
3430 *
3431 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
3432 *
3433 * @param {boolean} removable Item is removable
3434 * @chainable
3435 */
3436 OO.ui.OutlineOptionWidget.prototype.setRemovable = function ( removable ) {
3437 this.removable = !!removable;
3438 this.updateThemeClasses();
3439 return this;
3440 };
3441
3442 /**
3443 * @inheritdoc
3444 */
3445 OO.ui.OutlineOptionWidget.prototype.setSelected = function ( state ) {
3446 OO.ui.OutlineOptionWidget.parent.prototype.setSelected.call( this, state );
3447 if ( this.selected ) {
3448 this.setFlags( { progressive: true } );
3449 } else {
3450 this.setFlags( { progressive: false } );
3451 }
3452 return this;
3453 };
3454
3455 /**
3456 * Set indentation level.
3457 *
3458 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
3459 * @chainable
3460 */
3461 OO.ui.OutlineOptionWidget.prototype.setLevel = function ( level ) {
3462 var levels = this.constructor.static.levels,
3463 levelClass = this.constructor.static.levelClass,
3464 i = levels;
3465
3466 this.level = level ? Math.max( 0, Math.min( levels - 1, level ) ) : 0;
3467 while ( i-- ) {
3468 if ( this.level === i ) {
3469 this.$element.addClass( levelClass + i );
3470 } else {
3471 this.$element.removeClass( levelClass + i );
3472 }
3473 }
3474 this.updateThemeClasses();
3475
3476 return this;
3477 };
3478
3479 /**
3480 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
3481 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
3482 *
3483 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
3484 *
3485 * @class
3486 * @extends OO.ui.SelectWidget
3487 * @mixins OO.ui.mixin.TabIndexedElement
3488 *
3489 * @constructor
3490 * @param {Object} [config] Configuration options
3491 */
3492 OO.ui.OutlineSelectWidget = function OoUiOutlineSelectWidget( config ) {
3493 // Parent constructor
3494 OO.ui.OutlineSelectWidget.parent.call( this, config );
3495
3496 // Mixin constructors
3497 OO.ui.mixin.TabIndexedElement.call( this, config );
3498
3499 // Events
3500 this.$element.on( {
3501 focus: this.bindKeyDownListener.bind( this ),
3502 blur: this.unbindKeyDownListener.bind( this )
3503 } );
3504
3505 // Initialization
3506 this.$element.addClass( 'oo-ui-outlineSelectWidget' );
3507 };
3508
3509 /* Setup */
3510
3511 OO.inheritClass( OO.ui.OutlineSelectWidget, OO.ui.SelectWidget );
3512 OO.mixinClass( OO.ui.OutlineSelectWidget, OO.ui.mixin.TabIndexedElement );
3513
3514 /**
3515 * ButtonOptionWidget is a special type of {@link OO.ui.mixin.ButtonElement button element} that
3516 * can be selected and configured with data. The class is
3517 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
3518 * [OOjs UI documentation on MediaWiki] [1] for more information.
3519 *
3520 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
3521 *
3522 * @class
3523 * @extends OO.ui.OptionWidget
3524 * @mixins OO.ui.mixin.ButtonElement
3525 * @mixins OO.ui.mixin.IconElement
3526 * @mixins OO.ui.mixin.IndicatorElement
3527 * @mixins OO.ui.mixin.TitledElement
3528 *
3529 * @constructor
3530 * @param {Object} [config] Configuration options
3531 */
3532 OO.ui.ButtonOptionWidget = function OoUiButtonOptionWidget( config ) {
3533 // Configuration initialization
3534 config = config || {};
3535
3536 // Parent constructor
3537 OO.ui.ButtonOptionWidget.parent.call( this, config );
3538
3539 // Mixin constructors
3540 OO.ui.mixin.ButtonElement.call( this, config );
3541 OO.ui.mixin.IconElement.call( this, config );
3542 OO.ui.mixin.IndicatorElement.call( this, config );
3543 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
3544
3545 // Initialization
3546 this.$element.addClass( 'oo-ui-buttonOptionWidget' );
3547 this.$button.append( this.$icon, this.$label, this.$indicator );
3548 this.$element.append( this.$button );
3549 };
3550
3551 /* Setup */
3552
3553 OO.inheritClass( OO.ui.ButtonOptionWidget, OO.ui.OptionWidget );
3554 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.ButtonElement );
3555 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.IconElement );
3556 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.IndicatorElement );
3557 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.TitledElement );
3558
3559 /* Static Properties */
3560
3561 /**
3562 * Allow button mouse down events to pass through so they can be handled by the parent select widget
3563 *
3564 * @static
3565 * @inheritdoc
3566 */
3567 OO.ui.ButtonOptionWidget.static.cancelButtonMouseDownEvents = false;
3568
3569 /**
3570 * @static
3571 * @inheritdoc
3572 */
3573 OO.ui.ButtonOptionWidget.static.highlightable = false;
3574
3575 /* Methods */
3576
3577 /**
3578 * @inheritdoc
3579 */
3580 OO.ui.ButtonOptionWidget.prototype.setSelected = function ( state ) {
3581 OO.ui.ButtonOptionWidget.parent.prototype.setSelected.call( this, state );
3582
3583 if ( this.constructor.static.selectable ) {
3584 this.setActive( state );
3585 }
3586
3587 return this;
3588 };
3589
3590 /**
3591 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
3592 * button options and is used together with
3593 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
3594 * highlighting, choosing, and selecting mutually exclusive options. Please see
3595 * the [OOjs UI documentation on MediaWiki] [1] for more information.
3596 *
3597 * @example
3598 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
3599 * var option1 = new OO.ui.ButtonOptionWidget( {
3600 * data: 1,
3601 * label: 'Option 1',
3602 * title: 'Button option 1'
3603 * } );
3604 *
3605 * var option2 = new OO.ui.ButtonOptionWidget( {
3606 * data: 2,
3607 * label: 'Option 2',
3608 * title: 'Button option 2'
3609 * } );
3610 *
3611 * var option3 = new OO.ui.ButtonOptionWidget( {
3612 * data: 3,
3613 * label: 'Option 3',
3614 * title: 'Button option 3'
3615 * } );
3616 *
3617 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
3618 * items: [ option1, option2, option3 ]
3619 * } );
3620 * $( 'body' ).append( buttonSelect.$element );
3621 *
3622 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
3623 *
3624 * @class
3625 * @extends OO.ui.SelectWidget
3626 * @mixins OO.ui.mixin.TabIndexedElement
3627 *
3628 * @constructor
3629 * @param {Object} [config] Configuration options
3630 */
3631 OO.ui.ButtonSelectWidget = function OoUiButtonSelectWidget( config ) {
3632 // Parent constructor
3633 OO.ui.ButtonSelectWidget.parent.call( this, config );
3634
3635 // Mixin constructors
3636 OO.ui.mixin.TabIndexedElement.call( this, config );
3637
3638 // Events
3639 this.$element.on( {
3640 focus: this.bindKeyDownListener.bind( this ),
3641 blur: this.unbindKeyDownListener.bind( this )
3642 } );
3643
3644 // Initialization
3645 this.$element.addClass( 'oo-ui-buttonSelectWidget' );
3646 };
3647
3648 /* Setup */
3649
3650 OO.inheritClass( OO.ui.ButtonSelectWidget, OO.ui.SelectWidget );
3651 OO.mixinClass( OO.ui.ButtonSelectWidget, OO.ui.mixin.TabIndexedElement );
3652
3653 /**
3654 * TabOptionWidget is an item in a {@link OO.ui.TabSelectWidget TabSelectWidget}.
3655 *
3656 * Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}, which contain
3657 * {@link OO.ui.TabPanelLayout tab panel layouts}. See {@link OO.ui.IndexLayout IndexLayout}
3658 * for an example.
3659 *
3660 * @class
3661 * @extends OO.ui.OptionWidget
3662 *
3663 * @constructor
3664 * @param {Object} [config] Configuration options
3665 */
3666 OO.ui.TabOptionWidget = function OoUiTabOptionWidget( config ) {
3667 // Configuration initialization
3668 config = config || {};
3669
3670 // Parent constructor
3671 OO.ui.TabOptionWidget.parent.call( this, config );
3672
3673 // Initialization
3674 this.$element.addClass( 'oo-ui-tabOptionWidget' );
3675 };
3676
3677 /* Setup */
3678
3679 OO.inheritClass( OO.ui.TabOptionWidget, OO.ui.OptionWidget );
3680
3681 /* Static Properties */
3682
3683 /**
3684 * @static
3685 * @inheritdoc
3686 */
3687 OO.ui.TabOptionWidget.static.highlightable = false;
3688
3689 /**
3690 * TabSelectWidget is a list that contains {@link OO.ui.TabOptionWidget tab options}
3691 *
3692 * **Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}.**
3693 *
3694 * @class
3695 * @extends OO.ui.SelectWidget
3696 * @mixins OO.ui.mixin.TabIndexedElement
3697 *
3698 * @constructor
3699 * @param {Object} [config] Configuration options
3700 */
3701 OO.ui.TabSelectWidget = function OoUiTabSelectWidget( config ) {
3702 // Parent constructor
3703 OO.ui.TabSelectWidget.parent.call( this, config );
3704
3705 // Mixin constructors
3706 OO.ui.mixin.TabIndexedElement.call( this, config );
3707
3708 // Events
3709 this.$element.on( {
3710 focus: this.bindKeyDownListener.bind( this ),
3711 blur: this.unbindKeyDownListener.bind( this )
3712 } );
3713
3714 // Initialization
3715 this.$element.addClass( 'oo-ui-tabSelectWidget' );
3716 };
3717
3718 /* Setup */
3719
3720 OO.inheritClass( OO.ui.TabSelectWidget, OO.ui.SelectWidget );
3721 OO.mixinClass( OO.ui.TabSelectWidget, OO.ui.mixin.TabIndexedElement );
3722
3723 /**
3724 * CapsuleItemWidgets are used within a {@link OO.ui.CapsuleMultiselectWidget
3725 * CapsuleMultiselectWidget} to display the selected items.
3726 *
3727 * @class
3728 * @extends OO.ui.Widget
3729 * @mixins OO.ui.mixin.ItemWidget
3730 * @mixins OO.ui.mixin.LabelElement
3731 * @mixins OO.ui.mixin.FlaggedElement
3732 * @mixins OO.ui.mixin.TabIndexedElement
3733 *
3734 * @constructor
3735 * @param {Object} [config] Configuration options
3736 */
3737 OO.ui.CapsuleItemWidget = function OoUiCapsuleItemWidget( config ) {
3738 // Configuration initialization
3739 config = config || {};
3740
3741 // Parent constructor
3742 OO.ui.CapsuleItemWidget.parent.call( this, config );
3743
3744 // Mixin constructors
3745 OO.ui.mixin.ItemWidget.call( this );
3746 OO.ui.mixin.LabelElement.call( this, config );
3747 OO.ui.mixin.FlaggedElement.call( this, config );
3748 OO.ui.mixin.TabIndexedElement.call( this, config );
3749
3750 // Events
3751 this.closeButton = new OO.ui.ButtonWidget( {
3752 framed: false,
3753 icon: 'close',
3754 tabIndex: -1
3755 } ).on( 'click', this.onCloseClick.bind( this ) );
3756
3757 this.on( 'disable', function ( disabled ) {
3758 this.closeButton.setDisabled( disabled );
3759 }.bind( this ) );
3760
3761 // Initialization
3762 this.$element
3763 .on( {
3764 click: this.onClick.bind( this ),
3765 keydown: this.onKeyDown.bind( this )
3766 } )
3767 .addClass( 'oo-ui-capsuleItemWidget' )
3768 .append( this.$label, this.closeButton.$element );
3769 };
3770
3771 /* Setup */
3772
3773 OO.inheritClass( OO.ui.CapsuleItemWidget, OO.ui.Widget );
3774 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.ItemWidget );
3775 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.LabelElement );
3776 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.FlaggedElement );
3777 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.TabIndexedElement );
3778
3779 /* Methods */
3780
3781 /**
3782 * Handle close icon clicks
3783 */
3784 OO.ui.CapsuleItemWidget.prototype.onCloseClick = function () {
3785 var element = this.getElementGroup();
3786
3787 if ( element && $.isFunction( element.removeItems ) ) {
3788 element.removeItems( [ this ] );
3789 element.focus();
3790 }
3791 };
3792
3793 /**
3794 * Handle click event for the entire capsule
3795 */
3796 OO.ui.CapsuleItemWidget.prototype.onClick = function () {
3797 var element = this.getElementGroup();
3798
3799 if ( !this.isDisabled() && element && $.isFunction( element.editItem ) ) {
3800 element.editItem( this );
3801 }
3802 };
3803
3804 /**
3805 * Handle keyDown event for the entire capsule
3806 *
3807 * @param {jQuery.Event} e Key down event
3808 */
3809 OO.ui.CapsuleItemWidget.prototype.onKeyDown = function ( e ) {
3810 var element = this.getElementGroup();
3811
3812 if ( e.keyCode === OO.ui.Keys.BACKSPACE || e.keyCode === OO.ui.Keys.DELETE ) {
3813 element.removeItems( [ this ] );
3814 element.focus();
3815 return false;
3816 } else if ( e.keyCode === OO.ui.Keys.ENTER ) {
3817 element.editItem( this );
3818 return false;
3819 } else if ( e.keyCode === OO.ui.Keys.LEFT ) {
3820 element.getPreviousItem( this ).focus();
3821 } else if ( e.keyCode === OO.ui.Keys.RIGHT ) {
3822 element.getNextItem( this ).focus();
3823 }
3824 };
3825
3826 /**
3827 * CapsuleMultiselectWidgets are something like a {@link OO.ui.ComboBoxInputWidget combo box widget}
3828 * that allows for selecting multiple values.
3829 *
3830 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
3831 *
3832 * @example
3833 * // Example: A CapsuleMultiselectWidget.
3834 * var capsule = new OO.ui.CapsuleMultiselectWidget( {
3835 * label: 'CapsuleMultiselectWidget',
3836 * selected: [ 'Option 1', 'Option 3' ],
3837 * menu: {
3838 * items: [
3839 * new OO.ui.MenuOptionWidget( {
3840 * data: 'Option 1',
3841 * label: 'Option One'
3842 * } ),
3843 * new OO.ui.MenuOptionWidget( {
3844 * data: 'Option 2',
3845 * label: 'Option Two'
3846 * } ),
3847 * new OO.ui.MenuOptionWidget( {
3848 * data: 'Option 3',
3849 * label: 'Option Three'
3850 * } ),
3851 * new OO.ui.MenuOptionWidget( {
3852 * data: 'Option 4',
3853 * label: 'Option Four'
3854 * } ),
3855 * new OO.ui.MenuOptionWidget( {
3856 * data: 'Option 5',
3857 * label: 'Option Five'
3858 * } )
3859 * ]
3860 * }
3861 * } );
3862 * $( 'body' ).append( capsule.$element );
3863 *
3864 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
3865 *
3866 * @class
3867 * @extends OO.ui.Widget
3868 * @mixins OO.ui.mixin.GroupElement
3869 * @mixins OO.ui.mixin.PopupElement
3870 * @mixins OO.ui.mixin.TabIndexedElement
3871 * @mixins OO.ui.mixin.IndicatorElement
3872 * @mixins OO.ui.mixin.IconElement
3873 * @uses OO.ui.CapsuleItemWidget
3874 * @uses OO.ui.MenuSelectWidget
3875 *
3876 * @constructor
3877 * @param {Object} [config] Configuration options
3878 * @cfg {string} [placeholder] Placeholder text
3879 * @cfg {boolean} [allowArbitrary=false] Allow data items to be added even if not present in the menu.
3880 * @cfg {boolean} [allowDuplicates=false] Allow duplicate items to be added.
3881 * @cfg {Object} [menu] (required) Configuration options to pass to the
3882 * {@link OO.ui.MenuSelectWidget menu select widget}.
3883 * @cfg {Object} [popup] Configuration options to pass to the {@link OO.ui.PopupWidget popup widget}.
3884 * If specified, this popup will be shown instead of the menu (but the menu
3885 * will still be used for item labels and allowArbitrary=false). The widgets
3886 * in the popup should use {@link #addItemsFromData} or {@link #addItems} as necessary.
3887 * @cfg {jQuery} [$overlay=this.$element] Render the menu or popup into a separate layer.
3888 * This configuration is useful in cases where the expanded menu is larger than
3889 * its containing `<div>`. The specified overlay layer is usually on top of
3890 * the containing `<div>` and has a larger area. By default, the menu uses
3891 * relative positioning.
3892 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
3893 */
3894 OO.ui.CapsuleMultiselectWidget = function OoUiCapsuleMultiselectWidget( config ) {
3895 var $tabFocus;
3896
3897 // Parent constructor
3898 OO.ui.CapsuleMultiselectWidget.parent.call( this, config );
3899
3900 // Configuration initialization
3901 config = $.extend( {
3902 allowArbitrary: false,
3903 allowDuplicates: false,
3904 $overlay: this.$element
3905 }, config );
3906
3907 // Properties (must be set before mixin constructor calls)
3908 this.$handle = $( '<div>' );
3909 this.$input = config.popup ? null : $( '<input>' );
3910 if ( config.placeholder !== undefined && config.placeholder !== '' ) {
3911 this.$input.attr( 'placeholder', config.placeholder );
3912 }
3913
3914 // Mixin constructors
3915 OO.ui.mixin.GroupElement.call( this, config );
3916 if ( config.popup ) {
3917 config.popup = $.extend( {}, config.popup, {
3918 align: 'forwards',
3919 anchor: false
3920 } );
3921 OO.ui.mixin.PopupElement.call( this, config );
3922 $tabFocus = $( '<span>' );
3923 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: $tabFocus } ) );
3924 } else {
3925 this.popup = null;
3926 $tabFocus = null;
3927 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
3928 }
3929 OO.ui.mixin.IndicatorElement.call( this, config );
3930 OO.ui.mixin.IconElement.call( this, config );
3931
3932 // Properties
3933 this.$content = $( '<div>' );
3934 this.allowArbitrary = config.allowArbitrary;
3935 this.allowDuplicates = config.allowDuplicates;
3936 this.$overlay = config.$overlay;
3937 this.menu = new OO.ui.MenuSelectWidget( $.extend(
3938 {
3939 widget: this,
3940 $input: this.$input,
3941 $floatableContainer: this.$element,
3942 filterFromInput: true,
3943 disabled: this.isDisabled()
3944 },
3945 config.menu
3946 ) );
3947
3948 // Events
3949 if ( this.popup ) {
3950 $tabFocus.on( {
3951 focus: this.focus.bind( this )
3952 } );
3953 this.popup.$element.on( 'focusout', this.onPopupFocusOut.bind( this ) );
3954 if ( this.popup.$autoCloseIgnore ) {
3955 this.popup.$autoCloseIgnore.on( 'focusout', this.onPopupFocusOut.bind( this ) );
3956 }
3957 this.popup.connect( this, {
3958 toggle: function ( visible ) {
3959 $tabFocus.toggle( !visible );
3960 }
3961 } );
3962 } else {
3963 this.$input.on( {
3964 focus: this.onInputFocus.bind( this ),
3965 blur: this.onInputBlur.bind( this ),
3966 'propertychange change click mouseup keydown keyup input cut paste select focus':
3967 OO.ui.debounce( this.updateInputSize.bind( this ) ),
3968 keydown: this.onKeyDown.bind( this ),
3969 keypress: this.onKeyPress.bind( this )
3970 } );
3971 }
3972 this.menu.connect( this, {
3973 choose: 'onMenuChoose',
3974 toggle: 'onMenuToggle',
3975 add: 'onMenuItemsChange',
3976 remove: 'onMenuItemsChange'
3977 } );
3978 this.$handle.on( {
3979 mousedown: this.onMouseDown.bind( this )
3980 } );
3981
3982 // Initialization
3983 if ( this.$input ) {
3984 this.$input.prop( 'disabled', this.isDisabled() );
3985 this.$input.attr( {
3986 role: 'combobox',
3987 'aria-owns': this.menu.getElementId(),
3988 'aria-autocomplete': 'list'
3989 } );
3990 }
3991 if ( config.data ) {
3992 this.setItemsFromData( config.data );
3993 }
3994 this.$content.addClass( 'oo-ui-capsuleMultiselectWidget-content' )
3995 .append( this.$group );
3996 this.$group.addClass( 'oo-ui-capsuleMultiselectWidget-group' );
3997 this.$handle.addClass( 'oo-ui-capsuleMultiselectWidget-handle' )
3998 .append( this.$indicator, this.$icon, this.$content );
3999 this.$element.addClass( 'oo-ui-capsuleMultiselectWidget' )
4000 .append( this.$handle );
4001 if ( this.popup ) {
4002 this.popup.$element.addClass( 'oo-ui-capsuleMultiselectWidget-popup' );
4003 this.$content.append( $tabFocus );
4004 this.$overlay.append( this.popup.$element );
4005 } else {
4006 this.$content.append( this.$input );
4007 this.$overlay.append( this.menu.$element );
4008 }
4009 if ( $tabFocus ) {
4010 $tabFocus.addClass( 'oo-ui-capsuleMultiselectWidget-focusTrap' );
4011 }
4012
4013 // Input size needs to be calculated after everything else is rendered
4014 setTimeout( function () {
4015 if ( this.$input ) {
4016 this.updateInputSize();
4017 }
4018 }.bind( this ) );
4019
4020 this.onMenuItemsChange();
4021 };
4022
4023 /* Setup */
4024
4025 OO.inheritClass( OO.ui.CapsuleMultiselectWidget, OO.ui.Widget );
4026 OO.mixinClass( OO.ui.CapsuleMultiselectWidget, OO.ui.mixin.GroupElement );
4027 OO.mixinClass( OO.ui.CapsuleMultiselectWidget, OO.ui.mixin.PopupElement );
4028 OO.mixinClass( OO.ui.CapsuleMultiselectWidget, OO.ui.mixin.TabIndexedElement );
4029 OO.mixinClass( OO.ui.CapsuleMultiselectWidget, OO.ui.mixin.IndicatorElement );
4030 OO.mixinClass( OO.ui.CapsuleMultiselectWidget, OO.ui.mixin.IconElement );
4031
4032 /* Events */
4033
4034 /**
4035 * @event change
4036 *
4037 * A change event is emitted when the set of selected items changes.
4038 *
4039 * @param {Mixed[]} datas Data of the now-selected items
4040 */
4041
4042 /**
4043 * @event resize
4044 *
4045 * A resize event is emitted when the widget's dimensions change to accomodate newly added items or
4046 * current user input.
4047 */
4048
4049 /* Methods */
4050
4051 /**
4052 * Construct a OO.ui.CapsuleItemWidget (or a subclass thereof) from given label and data.
4053 * May return `null` if the given label and data are not valid.
4054 *
4055 * @protected
4056 * @param {Mixed} data Custom data of any type.
4057 * @param {string} label The label text.
4058 * @return {OO.ui.CapsuleItemWidget|null}
4059 */
4060 OO.ui.CapsuleMultiselectWidget.prototype.createItemWidget = function ( data, label ) {
4061 if ( label === '' ) {
4062 return null;
4063 }
4064 return new OO.ui.CapsuleItemWidget( { data: data, label: label } );
4065 };
4066
4067 /**
4068 * @inheritdoc
4069 */
4070 OO.ui.CapsuleMultiselectWidget.prototype.getInputId = function () {
4071 if ( !this.$input ) {
4072 return null;
4073 }
4074 return OO.ui.mixin.TabIndexedElement.prototype.getInputId.call( this );
4075 };
4076
4077 /**
4078 * Get the data of the items in the capsule
4079 *
4080 * @return {Mixed[]}
4081 */
4082 OO.ui.CapsuleMultiselectWidget.prototype.getItemsData = function () {
4083 return this.getItems().map( function ( item ) {
4084 return item.data;
4085 } );
4086 };
4087
4088 /**
4089 * Set the items in the capsule by providing data
4090 *
4091 * @chainable
4092 * @param {Mixed[]} datas
4093 * @return {OO.ui.CapsuleMultiselectWidget}
4094 */
4095 OO.ui.CapsuleMultiselectWidget.prototype.setItemsFromData = function ( datas ) {
4096 var widget = this,
4097 menu = this.menu,
4098 items = this.getItems();
4099
4100 $.each( datas, function ( i, data ) {
4101 var j, label,
4102 item = menu.getItemFromData( data );
4103
4104 if ( item ) {
4105 label = item.label;
4106 } else if ( widget.allowArbitrary ) {
4107 label = String( data );
4108 } else {
4109 return;
4110 }
4111
4112 item = null;
4113 for ( j = 0; j < items.length; j++ ) {
4114 if ( items[ j ].data === data && items[ j ].label === label ) {
4115 item = items[ j ];
4116 items.splice( j, 1 );
4117 break;
4118 }
4119 }
4120 if ( !item ) {
4121 item = widget.createItemWidget( data, label );
4122 }
4123 if ( item ) {
4124 widget.addItems( [ item ], i );
4125 }
4126 } );
4127
4128 if ( items.length ) {
4129 widget.removeItems( items );
4130 }
4131
4132 return this;
4133 };
4134
4135 /**
4136 * Add items to the capsule by providing their data
4137 *
4138 * @chainable
4139 * @param {Mixed[]} datas
4140 * @return {OO.ui.CapsuleMultiselectWidget}
4141 */
4142 OO.ui.CapsuleMultiselectWidget.prototype.addItemsFromData = function ( datas ) {
4143 var widget = this,
4144 menu = this.menu,
4145 items = [];
4146
4147 $.each( datas, function ( i, data ) {
4148 var item;
4149
4150 if ( !widget.getItemFromData( data ) || widget.allowDuplicates ) {
4151 item = menu.getItemFromData( data );
4152 if ( item ) {
4153 item = widget.createItemWidget( data, item.label );
4154 } else if ( widget.allowArbitrary ) {
4155 item = widget.createItemWidget( data, String( data ) );
4156 }
4157 if ( item ) {
4158 items.push( item );
4159 }
4160 }
4161 } );
4162
4163 if ( items.length ) {
4164 this.addItems( items );
4165 }
4166
4167 return this;
4168 };
4169
4170 /**
4171 * Add items to the capsule by providing a label
4172 *
4173 * @param {string} label
4174 * @return {boolean} Whether the item was added or not
4175 */
4176 OO.ui.CapsuleMultiselectWidget.prototype.addItemFromLabel = function ( label ) {
4177 var item, items;
4178 item = this.menu.getItemFromLabel( label, true );
4179 if ( item ) {
4180 this.addItemsFromData( [ item.data ] );
4181 return true;
4182 } else if ( this.allowArbitrary ) {
4183 items = this.getItems();
4184 this.addItemsFromData( [ label ] );
4185 return !OO.compare( this.getItems(), items );
4186 }
4187 return false;
4188 };
4189
4190 /**
4191 * Remove items by data
4192 *
4193 * @chainable
4194 * @param {Mixed[]} datas
4195 * @return {OO.ui.CapsuleMultiselectWidget}
4196 */
4197 OO.ui.CapsuleMultiselectWidget.prototype.removeItemsFromData = function ( datas ) {
4198 var widget = this,
4199 items = [];
4200
4201 $.each( datas, function ( i, data ) {
4202 var item = widget.getItemFromData( data );
4203 if ( item ) {
4204 items.push( item );
4205 }
4206 } );
4207
4208 if ( items.length ) {
4209 this.removeItems( items );
4210 }
4211
4212 return this;
4213 };
4214
4215 /**
4216 * @inheritdoc
4217 */
4218 OO.ui.CapsuleMultiselectWidget.prototype.addItems = function ( items ) {
4219 var same, i, l,
4220 oldItems = this.items.slice();
4221
4222 OO.ui.mixin.GroupElement.prototype.addItems.call( this, items );
4223
4224 if ( this.items.length !== oldItems.length ) {
4225 same = false;
4226 } else {
4227 same = true;
4228 for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
4229 same = same && this.items[ i ] === oldItems[ i ];
4230 }
4231 }
4232 if ( !same ) {
4233 this.emit( 'change', this.getItemsData() );
4234 this.updateInputSize();
4235 }
4236
4237 return this;
4238 };
4239
4240 /**
4241 * Removes the item from the list and copies its label to `this.$input`.
4242 *
4243 * @param {Object} item
4244 */
4245 OO.ui.CapsuleMultiselectWidget.prototype.editItem = function ( item ) {
4246 this.addItemFromLabel( this.$input.val() );
4247 this.clearInput();
4248 this.$input.val( item.label );
4249 this.updateInputSize();
4250 this.focus();
4251 this.menu.updateItemVisibility(); // Hack, we shouldn't be calling this method directly
4252 this.removeItems( [ item ] );
4253 };
4254
4255 /**
4256 * @inheritdoc
4257 */
4258 OO.ui.CapsuleMultiselectWidget.prototype.removeItems = function ( items ) {
4259 var same, i, l,
4260 oldItems = this.items.slice();
4261
4262 OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items );
4263
4264 if ( this.items.length !== oldItems.length ) {
4265 same = false;
4266 } else {
4267 same = true;
4268 for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
4269 same = same && this.items[ i ] === oldItems[ i ];
4270 }
4271 }
4272 if ( !same ) {
4273 this.emit( 'change', this.getItemsData() );
4274 this.updateInputSize();
4275 }
4276
4277 return this;
4278 };
4279
4280 /**
4281 * @inheritdoc
4282 */
4283 OO.ui.CapsuleMultiselectWidget.prototype.clearItems = function () {
4284 if ( this.items.length ) {
4285 OO.ui.mixin.GroupElement.prototype.clearItems.call( this );
4286 this.emit( 'change', this.getItemsData() );
4287 this.updateInputSize();
4288 }
4289 return this;
4290 };
4291
4292 /**
4293 * Given an item, returns the item after it. If its the last item,
4294 * returns `this.$input`. If no item is passed, returns the very first
4295 * item.
4296 *
4297 * @param {OO.ui.CapsuleItemWidget} [item]
4298 * @return {OO.ui.CapsuleItemWidget|jQuery|boolean}
4299 */
4300 OO.ui.CapsuleMultiselectWidget.prototype.getNextItem = function ( item ) {
4301 var itemIndex;
4302
4303 if ( item === undefined ) {
4304 return this.items[ 0 ];
4305 }
4306
4307 itemIndex = this.items.indexOf( item );
4308 if ( itemIndex < 0 ) { // Item not in list
4309 return false;
4310 } else if ( itemIndex === this.items.length - 1 ) { // Last item
4311 return this.$input;
4312 } else {
4313 return this.items[ itemIndex + 1 ];
4314 }
4315 };
4316
4317 /**
4318 * Given an item, returns the item before it. If its the first item,
4319 * returns `this.$input`. If no item is passed, returns the very last
4320 * item.
4321 *
4322 * @param {OO.ui.CapsuleItemWidget} [item]
4323 * @return {OO.ui.CapsuleItemWidget|jQuery|boolean}
4324 */
4325 OO.ui.CapsuleMultiselectWidget.prototype.getPreviousItem = function ( item ) {
4326 var itemIndex;
4327
4328 if ( item === undefined ) {
4329 return this.items[ this.items.length - 1 ];
4330 }
4331
4332 itemIndex = this.items.indexOf( item );
4333 if ( itemIndex < 0 ) { // Item not in list
4334 return false;
4335 } else if ( itemIndex === 0 ) { // First item
4336 return this.$input;
4337 } else {
4338 return this.items[ itemIndex - 1 ];
4339 }
4340 };
4341
4342 /**
4343 * Get the capsule widget's menu.
4344 *
4345 * @return {OO.ui.MenuSelectWidget} Menu widget
4346 */
4347 OO.ui.CapsuleMultiselectWidget.prototype.getMenu = function () {
4348 return this.menu;
4349 };
4350
4351 /**
4352 * Handle focus events
4353 *
4354 * @private
4355 * @param {jQuery.Event} event
4356 */
4357 OO.ui.CapsuleMultiselectWidget.prototype.onInputFocus = function () {
4358 if ( !this.isDisabled() ) {
4359 this.updateInputSize();
4360 this.menu.toggle( true );
4361 }
4362 };
4363
4364 /**
4365 * Handle blur events
4366 *
4367 * @private
4368 * @param {jQuery.Event} event
4369 */
4370 OO.ui.CapsuleMultiselectWidget.prototype.onInputBlur = function () {
4371 this.addItemFromLabel( this.$input.val() );
4372 this.clearInput();
4373 };
4374
4375 /**
4376 * Handles popup focus out events.
4377 *
4378 * @private
4379 * @param {jQuery.Event} e Focus out event
4380 */
4381 OO.ui.CapsuleMultiselectWidget.prototype.onPopupFocusOut = function () {
4382 var widget = this.popup;
4383
4384 setTimeout( function () {
4385 if (
4386 widget.isVisible() &&
4387 !OO.ui.contains( widget.$element.add( widget.$autoCloseIgnore ).get(), document.activeElement, true )
4388 ) {
4389 widget.toggle( false );
4390 }
4391 } );
4392 };
4393
4394 /**
4395 * Handle mouse down events.
4396 *
4397 * @private
4398 * @param {jQuery.Event} e Mouse down event
4399 */
4400 OO.ui.CapsuleMultiselectWidget.prototype.onMouseDown = function ( e ) {
4401 if ( e.which === OO.ui.MouseButtons.LEFT ) {
4402 this.focus();
4403 return false;
4404 } else {
4405 this.updateInputSize();
4406 }
4407 };
4408
4409 /**
4410 * Handle key press events.
4411 *
4412 * @private
4413 * @param {jQuery.Event} e Key press event
4414 */
4415 OO.ui.CapsuleMultiselectWidget.prototype.onKeyPress = function ( e ) {
4416 if ( !this.isDisabled() ) {
4417 if ( e.which === OO.ui.Keys.ESCAPE ) {
4418 this.clearInput();
4419 return false;
4420 }
4421
4422 if ( !this.popup ) {
4423 this.menu.toggle( true );
4424 if ( e.which === OO.ui.Keys.ENTER ) {
4425 if ( this.addItemFromLabel( this.$input.val() ) ) {
4426 this.clearInput();
4427 }
4428 return false;
4429 }
4430
4431 // Make sure the input gets resized.
4432 setTimeout( this.updateInputSize.bind( this ), 0 );
4433 }
4434 }
4435 };
4436
4437 /**
4438 * Handle key down events.
4439 *
4440 * @private
4441 * @param {jQuery.Event} e Key down event
4442 */
4443 OO.ui.CapsuleMultiselectWidget.prototype.onKeyDown = function ( e ) {
4444 if (
4445 !this.isDisabled() &&
4446 this.$input.val() === '' &&
4447 this.items.length
4448 ) {
4449 // 'keypress' event is not triggered for Backspace
4450 if ( e.keyCode === OO.ui.Keys.BACKSPACE ) {
4451 if ( e.metaKey || e.ctrlKey ) {
4452 this.removeItems( this.items.slice( -1 ) );
4453 } else {
4454 this.editItem( this.items[ this.items.length - 1 ] );
4455 }
4456 return false;
4457 } else if ( e.keyCode === OO.ui.Keys.LEFT ) {
4458 this.getPreviousItem().focus();
4459 } else if ( e.keyCode === OO.ui.Keys.RIGHT ) {
4460 this.getNextItem().focus();
4461 }
4462 }
4463 };
4464
4465 /**
4466 * Update the dimensions of the text input field to encompass all available area.
4467 *
4468 * @private
4469 * @param {jQuery.Event} e Event of some sort
4470 */
4471 OO.ui.CapsuleMultiselectWidget.prototype.updateInputSize = function () {
4472 var $lastItem, direction, contentWidth, currentWidth, bestWidth;
4473 if ( this.$input && !this.isDisabled() ) {
4474 this.$input.css( 'width', '1em' );
4475 $lastItem = this.$group.children().last();
4476 direction = OO.ui.Element.static.getDir( this.$handle );
4477
4478 // Get the width of the input with the placeholder text as
4479 // the value and save it so that we don't keep recalculating
4480 if (
4481 this.contentWidthWithPlaceholder === undefined &&
4482 this.$input.val() === '' &&
4483 this.$input.attr( 'placeholder' ) !== undefined
4484 ) {
4485 this.$input.val( this.$input.attr( 'placeholder' ) );
4486 this.contentWidthWithPlaceholder = this.$input[ 0 ].scrollWidth;
4487 this.$input.val( '' );
4488
4489 }
4490
4491 // Always keep the input wide enough for the placeholder text
4492 contentWidth = Math.max(
4493 this.$input[ 0 ].scrollWidth,
4494 // undefined arguments in Math.max lead to NaN
4495 ( this.contentWidthWithPlaceholder === undefined ) ?
4496 0 : this.contentWidthWithPlaceholder
4497 );
4498 currentWidth = this.$input.width();
4499
4500 if ( contentWidth < currentWidth ) {
4501 this.updateIfHeightChanged();
4502 // All is fine, don't perform expensive calculations
4503 return;
4504 }
4505
4506 if ( $lastItem.length === 0 ) {
4507 bestWidth = this.$content.innerWidth();
4508 } else {
4509 bestWidth = direction === 'ltr' ?
4510 this.$content.innerWidth() - $lastItem.position().left - $lastItem.outerWidth() :
4511 $lastItem.position().left;
4512 }
4513
4514 // Some safety margin for sanity, because I *really* don't feel like finding out where the few
4515 // pixels this is off by are coming from.
4516 bestWidth -= 10;
4517 if ( contentWidth > bestWidth ) {
4518 // This will result in the input getting shifted to the next line
4519 bestWidth = this.$content.innerWidth() - 10;
4520 }
4521 this.$input.width( Math.floor( bestWidth ) );
4522 this.updateIfHeightChanged();
4523 } else {
4524 this.updateIfHeightChanged();
4525 }
4526 };
4527
4528 /**
4529 * Determine if widget height changed, and if so, update menu position and emit 'resize' event.
4530 *
4531 * @private
4532 */
4533 OO.ui.CapsuleMultiselectWidget.prototype.updateIfHeightChanged = function () {
4534 var height = this.$element.height();
4535 if ( height !== this.height ) {
4536 this.height = height;
4537 this.menu.position();
4538 if ( this.popup ) {
4539 this.popup.updateDimensions();
4540 }
4541 this.emit( 'resize' );
4542 }
4543 };
4544
4545 /**
4546 * Handle menu choose events.
4547 *
4548 * @private
4549 * @param {OO.ui.OptionWidget} item Chosen item
4550 */
4551 OO.ui.CapsuleMultiselectWidget.prototype.onMenuChoose = function ( item ) {
4552 if ( item && item.isVisible() ) {
4553 this.addItemsFromData( [ item.getData() ] );
4554 this.clearInput();
4555 }
4556 };
4557
4558 /**
4559 * Handle menu toggle events.
4560 *
4561 * @private
4562 * @param {boolean} isVisible Menu toggle event
4563 */
4564 OO.ui.CapsuleMultiselectWidget.prototype.onMenuToggle = function ( isVisible ) {
4565 this.$element.toggleClass( 'oo-ui-capsuleMultiselectWidget-open', isVisible );
4566 };
4567
4568 /**
4569 * Handle menu item change events.
4570 *
4571 * @private
4572 */
4573 OO.ui.CapsuleMultiselectWidget.prototype.onMenuItemsChange = function () {
4574 this.setItemsFromData( this.getItemsData() );
4575 this.$element.toggleClass( 'oo-ui-capsuleMultiselectWidget-empty', this.menu.isEmpty() );
4576 };
4577
4578 /**
4579 * Clear the input field
4580 *
4581 * @private
4582 */
4583 OO.ui.CapsuleMultiselectWidget.prototype.clearInput = function () {
4584 if ( this.$input ) {
4585 this.$input.val( '' );
4586 this.updateInputSize();
4587 }
4588 if ( this.popup ) {
4589 this.popup.toggle( false );
4590 }
4591 this.menu.toggle( false );
4592 this.menu.selectItem();
4593 this.menu.highlightItem();
4594 };
4595
4596 /**
4597 * @inheritdoc
4598 */
4599 OO.ui.CapsuleMultiselectWidget.prototype.setDisabled = function ( disabled ) {
4600 var i, len;
4601
4602 // Parent method
4603 OO.ui.CapsuleMultiselectWidget.parent.prototype.setDisabled.call( this, disabled );
4604
4605 if ( this.$input ) {
4606 this.$input.prop( 'disabled', this.isDisabled() );
4607 }
4608 if ( this.menu ) {
4609 this.menu.setDisabled( this.isDisabled() );
4610 }
4611 if ( this.popup ) {
4612 this.popup.setDisabled( this.isDisabled() );
4613 }
4614
4615 if ( this.items ) {
4616 for ( i = 0, len = this.items.length; i < len; i++ ) {
4617 this.items[ i ].updateDisabled();
4618 }
4619 }
4620
4621 return this;
4622 };
4623
4624 /**
4625 * Focus the widget
4626 *
4627 * @chainable
4628 */
4629 OO.ui.CapsuleMultiselectWidget.prototype.focus = function () {
4630 if ( !this.isDisabled() ) {
4631 if ( this.popup ) {
4632 this.popup.setSize( this.$handle.outerWidth() );
4633 this.popup.toggle( true );
4634 OO.ui.findFocusable( this.popup.$element ).focus();
4635 } else {
4636 OO.ui.mixin.TabIndexedElement.prototype.focus.call( this );
4637 }
4638 }
4639 return this;
4640 };
4641
4642 /**
4643 * TagItemWidgets are used within a {@link OO.ui.TagMultiselectWidget
4644 * TagMultiselectWidget} to display the selected items.
4645 *
4646 * @class
4647 * @extends OO.ui.Widget
4648 * @mixins OO.ui.mixin.ItemWidget
4649 * @mixins OO.ui.mixin.LabelElement
4650 * @mixins OO.ui.mixin.FlaggedElement
4651 * @mixins OO.ui.mixin.TabIndexedElement
4652 * @mixins OO.ui.mixin.DraggableElement
4653 *
4654 * @constructor
4655 * @param {Object} [config] Configuration object
4656 * @cfg {boolean} [valid=true] Item is valid
4657 */
4658 OO.ui.TagItemWidget = function OoUiTagItemWidget( config ) {
4659 config = config || {};
4660
4661 // Parent constructor
4662 OO.ui.TagItemWidget.parent.call( this, config );
4663
4664 // Mixin constructors
4665 OO.ui.mixin.ItemWidget.call( this );
4666 OO.ui.mixin.LabelElement.call( this, config );
4667 OO.ui.mixin.FlaggedElement.call( this, config );
4668 OO.ui.mixin.TabIndexedElement.call( this, config );
4669 OO.ui.mixin.DraggableElement.call( this, config );
4670
4671 this.valid = config.valid === undefined ? true : !!config.valid;
4672
4673 this.closeButton = new OO.ui.ButtonWidget( {
4674 framed: false,
4675 icon: 'close',
4676 tabIndex: -1
4677 } );
4678 this.closeButton.setDisabled( this.isDisabled() );
4679
4680 // Events
4681 this.closeButton
4682 .connect( this, { click: 'remove' } );
4683 this.$element
4684 .on( 'click', this.select.bind( this ) )
4685 .on( 'keydown', this.onKeyDown.bind( this ) )
4686 // Prevent propagation of mousedown; the tag item "lives" in the
4687 // clickable area of the TagMultiselectWidget, which listens to
4688 // mousedown to open the menu or popup. We want to prevent that
4689 // for clicks specifically on the tag itself, so the actions taken
4690 // are more deliberate. When the tag is clicked, it will emit the
4691 // selection event (similar to how #OO.ui.MultioptionWidget emits 'change')
4692 // and can be handled separately.
4693 .on( 'mousedown', function ( e ) { e.stopPropagation(); } );
4694
4695 // Initialization
4696 this.$element
4697 .addClass( 'oo-ui-tagItemWidget' )
4698 .append( this.$label, this.closeButton.$element );
4699 };
4700
4701 /* Initialization */
4702
4703 OO.inheritClass( OO.ui.TagItemWidget, OO.ui.Widget );
4704 OO.mixinClass( OO.ui.TagItemWidget, OO.ui.mixin.ItemWidget );
4705 OO.mixinClass( OO.ui.TagItemWidget, OO.ui.mixin.LabelElement );
4706 OO.mixinClass( OO.ui.TagItemWidget, OO.ui.mixin.FlaggedElement );
4707 OO.mixinClass( OO.ui.TagItemWidget, OO.ui.mixin.TabIndexedElement );
4708 OO.mixinClass( OO.ui.TagItemWidget, OO.ui.mixin.DraggableElement );
4709
4710 /* Events */
4711
4712 /**
4713 * @event remove
4714 *
4715 * A remove action was performed on the item
4716 */
4717
4718 /**
4719 * @event navigate
4720 * @param {string} direction Direction of the movement, forward or backwards
4721 *
4722 * A navigate action was performed on the item
4723 */
4724
4725 /**
4726 * @event select
4727 *
4728 * The tag widget was selected. This can occur when the widget
4729 * is either clicked or enter was pressed on it.
4730 */
4731
4732 /**
4733 * @event valid
4734 * @param {boolean} isValid Item is valid
4735 *
4736 * Item validity has changed
4737 */
4738
4739 /* Methods */
4740
4741 /**
4742 * @inheritdoc
4743 */
4744 OO.ui.TagItemWidget.prototype.setDisabled = function ( state ) {
4745 // Parent method
4746 OO.ui.TagItemWidget.parent.prototype.setDisabled.call( this, state );
4747
4748 if ( this.closeButton ) {
4749 this.closeButton.setDisabled( state );
4750 }
4751 return this;
4752 };
4753
4754 /**
4755 * Handle removal of the item
4756 *
4757 * This is mainly for extensibility concerns, so other children
4758 * of this class can change the behavior if they need to. This
4759 * is called by both clicking the 'remove' button but also
4760 * on keypress, which is harder to override if needed.
4761 *
4762 * @fires remove
4763 */
4764 OO.ui.TagItemWidget.prototype.remove = function () {
4765 if ( !this.isDisabled() ) {
4766 this.emit( 'remove' );
4767 }
4768 };
4769
4770 /**
4771 * Handle a keydown event on the widget
4772 *
4773 * @fires navigate
4774 * @fires remove
4775 * @param {jQuery.Event} e Key down event
4776 * @return {boolean|undefined} false to stop the operation
4777 */
4778 OO.ui.TagItemWidget.prototype.onKeyDown = function ( e ) {
4779 var movement;
4780
4781 if ( e.keyCode === OO.ui.Keys.BACKSPACE || e.keyCode === OO.ui.Keys.DELETE ) {
4782 this.remove();
4783 return false;
4784 } else if ( e.keyCode === OO.ui.Keys.ENTER ) {
4785 this.select();
4786 return false;
4787 } else if (
4788 e.keyCode === OO.ui.Keys.LEFT ||
4789 e.keyCode === OO.ui.Keys.RIGHT
4790 ) {
4791 if ( OO.ui.Element.static.getDir( this.$element ) === 'rtl' ) {
4792 movement = {
4793 left: 'forwards',
4794 right: 'backwards'
4795 };
4796 } else {
4797 movement = {
4798 left: 'backwards',
4799 right: 'forwards'
4800 };
4801 }
4802
4803 this.emit(
4804 'navigate',
4805 e.keyCode === OO.ui.Keys.LEFT ?
4806 movement.left : movement.right
4807 );
4808 }
4809 };
4810
4811 /**
4812 * Select this item
4813 *
4814 * @fires select
4815 */
4816 OO.ui.TagItemWidget.prototype.select = function () {
4817 if ( !this.isDisabled() ) {
4818 this.emit( 'select' );
4819 }
4820 };
4821
4822 /**
4823 * Set the valid state of this item
4824 *
4825 * @param {boolean} [valid] Item is valid
4826 * @fires valid
4827 */
4828 OO.ui.TagItemWidget.prototype.toggleValid = function ( valid ) {
4829 valid = valid === undefined ? !this.valid : !!valid;
4830
4831 if ( this.valid !== valid ) {
4832 this.valid = valid;
4833
4834 this.setFlags( { invalid: !this.valid } );
4835
4836 this.emit( 'valid', this.valid );
4837 }
4838 };
4839
4840 /**
4841 * Check whether the item is valid
4842 *
4843 * @return {boolean} Item is valid
4844 */
4845 OO.ui.TagItemWidget.prototype.isValid = function () {
4846 return this.valid;
4847 };
4848
4849 /**
4850 * A basic tag multiselect widget, similar in concept to {@link OO.ui.ComboBoxInputWidget combo box widget}
4851 * that allows the user to add multiple values that are displayed in a tag area.
4852 *
4853 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
4854 *
4855 * This widget is a base widget; see {@link OO.ui.MenuTagMultiselectWidget MenuTagMultiselectWidget} and
4856 * {@link OO.ui.PopupTagMultiselectWidget PopupTagMultiselectWidget} for the implementations that use
4857 * a menu and a popup respectively.
4858 *
4859 * @example
4860 * // Example: A basic TagMultiselectWidget.
4861 * var widget = new OO.ui.TagMultiselectWidget( {
4862 * inputPosition: 'outline',
4863 * allowedValues: [ 'Option 1', 'Option 2', 'Option 3' ],
4864 * selected: [ 'Option 1' ]
4865 * } );
4866 * $( 'body' ).append( widget.$element );
4867 *
4868 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
4869 *
4870 * @class
4871 * @extends OO.ui.Widget
4872 * @mixins OO.ui.mixin.GroupWidget
4873 * @mixins OO.ui.mixin.DraggableGroupElement
4874 * @mixins OO.ui.mixin.IndicatorElement
4875 * @mixins OO.ui.mixin.IconElement
4876 * @mixins OO.ui.mixin.TabIndexedElement
4877 * @mixins OO.ui.mixin.FlaggedElement
4878 *
4879 * @constructor
4880 * @param {Object} config Configuration object
4881 * @cfg {Object} [input] Configuration options for the input widget
4882 * @cfg {OO.ui.InputWidget} [inputWidget] An optional input widget. If given, it will
4883 * replace the input widget used in the TagMultiselectWidget. If not given,
4884 * TagMultiselectWidget creates its own.
4885 * @cfg {boolean} [inputPosition='inline'] Position of the input. Options are:
4886 * - inline: The input is invisible, but exists inside the tag list, so
4887 * the user types into the tag groups to add tags.
4888 * - outline: The input is underneath the tag area.
4889 * - none: No input supplied
4890 * @cfg {boolean} [allowEditTags=true] Allow editing of the tags by clicking them
4891 * @cfg {boolean} [allowArbitrary=false] Allow data items to be added even if
4892 * not present in the menu.
4893 * @cfg {Object[]} [allowedValues] An array representing the allowed items
4894 * by their datas.
4895 * @cfg {boolean} [allowDuplicates=false] Allow duplicate items to be added
4896 * @cfg {boolean} [allowDisplayInvalidTags=false] Allow the display of
4897 * invalid tags. These tags will display with an invalid state, and
4898 * the widget as a whole will have an invalid state if any invalid tags
4899 * are present.
4900 * @cfg {boolean} [allowReordering=true] Allow reordering of the items
4901 * @cfg {Object[]|String[]} [selected] A set of selected tags. If given,
4902 * these will appear in the tag list on initialization, as long as they
4903 * pass the validity tests.
4904 */
4905 OO.ui.TagMultiselectWidget = function OoUiTagMultiselectWidget( config ) {
4906 var inputEvents,
4907 rAF = window.requestAnimationFrame || setTimeout,
4908 widget = this,
4909 $tabFocus = $( '<span>' )
4910 .addClass( 'oo-ui-tagMultiselectWidget-focusTrap' );
4911
4912 config = config || {};
4913
4914 // Parent constructor
4915 OO.ui.TagMultiselectWidget.parent.call( this, config );
4916
4917 // Mixin constructors
4918 OO.ui.mixin.GroupWidget.call( this, config );
4919 OO.ui.mixin.IndicatorElement.call( this, config );
4920 OO.ui.mixin.IconElement.call( this, config );
4921 OO.ui.mixin.TabIndexedElement.call( this, config );
4922 OO.ui.mixin.FlaggedElement.call( this, config );
4923 OO.ui.mixin.DraggableGroupElement.call( this, config );
4924
4925 this.toggleDraggable(
4926 config.allowReordering === undefined ?
4927 true : !!config.allowReordering
4928 );
4929
4930 this.inputPosition = this.constructor.static.allowedInputPositions.indexOf( config.inputPosition ) > -1 ?
4931 config.inputPosition : 'inline';
4932 this.allowEditTags = config.allowEditTags === undefined ? true : !!config.allowEditTags;
4933 this.allowArbitrary = !!config.allowArbitrary;
4934 this.allowDuplicates = !!config.allowDuplicates;
4935 this.allowedValues = config.allowedValues || [];
4936 this.allowDisplayInvalidTags = config.allowDisplayInvalidTags;
4937 this.hasInput = this.inputPosition !== 'none';
4938 this.height = null;
4939 this.valid = true;
4940
4941 this.$content = $( '<div>' )
4942 .addClass( 'oo-ui-tagMultiselectWidget-content' );
4943 this.$handle = $( '<div>' )
4944 .addClass( 'oo-ui-tagMultiselectWidget-handle' )
4945 .append(
4946 this.$indicator,
4947 this.$icon,
4948 this.$content
4949 .append(
4950 this.$group
4951 .addClass( 'oo-ui-tagMultiselectWidget-group' )
4952 )
4953 );
4954
4955 // Events
4956 this.aggregate( {
4957 remove: 'itemRemove',
4958 navigate: 'itemNavigate',
4959 select: 'itemSelect'
4960 } );
4961 this.connect( this, {
4962 itemRemove: 'onTagRemove',
4963 itemSelect: 'onTagSelect',
4964 itemNavigate: 'onTagNavigate',
4965 change: 'onChangeTags'
4966 } );
4967 this.$handle.on( {
4968 mousedown: this.onMouseDown.bind( this )
4969 } );
4970
4971 // Initialize
4972 this.$element
4973 .addClass( 'oo-ui-tagMultiselectWidget' )
4974 .append( this.$handle );
4975
4976 if ( this.hasInput ) {
4977 if ( config.inputWidget ) {
4978 this.input = config.inputWidget;
4979 } else {
4980 this.input = new OO.ui.TextInputWidget( $.extend( {
4981 placeholder: config.placeholder,
4982 classes: [ 'oo-ui-tagMultiselectWidget-input' ]
4983 }, config.input ) );
4984 }
4985 this.input.setDisabled( this.isDisabled() );
4986
4987 inputEvents = {
4988 focus: this.onInputFocus.bind( this ),
4989 blur: this.onInputBlur.bind( this ),
4990 'propertychange change click mouseup keydown keyup input cut paste select focus':
4991 OO.ui.debounce( this.updateInputSize.bind( this ) ),
4992 keydown: this.onInputKeyDown.bind( this ),
4993 keypress: this.onInputKeyPress.bind( this )
4994 };
4995
4996 this.input.$input.on( inputEvents );
4997
4998 if ( this.inputPosition === 'outline' ) {
4999 // Override max-height for the input widget
5000 // in the case the widget is outline so it can
5001 // stretch all the way if the widet is wide
5002 this.input.$element.css( 'max-width', 'inherit' );
5003 this.$element
5004 .addClass( 'oo-ui-tagMultiselectWidget-outlined' )
5005 .append( this.input.$element );
5006 } else {
5007 this.$element.addClass( 'oo-ui-tagMultiselectWidget-inlined' );
5008 // HACK: When the widget is using 'inline' input, the
5009 // behavior needs to only use the $input itself
5010 // so we style and size it accordingly (otherwise
5011 // the styling and sizing can get very convoluted
5012 // when the wrapping divs and other elements)
5013 // We are taking advantage of still being able to
5014 // call the widget itself for operations like
5015 // .getValue() and setDisabled() and .focus() but
5016 // having only the $input attached to the DOM
5017 this.$content.append( this.input.$input );
5018 }
5019 } else {
5020 this.$content.append( $tabFocus );
5021 }
5022
5023 this.setTabIndexedElement(
5024 this.hasInput ?
5025 this.input.$input :
5026 $tabFocus
5027 );
5028
5029 if ( config.selected ) {
5030 this.setValue( config.selected );
5031 }
5032
5033 // HACK: Input size needs to be calculated after everything
5034 // else is rendered
5035 rAF( function () {
5036 if ( widget.hasInput ) {
5037 widget.updateInputSize();
5038 }
5039 } );
5040 };
5041
5042 /* Initialization */
5043
5044 OO.inheritClass( OO.ui.TagMultiselectWidget, OO.ui.Widget );
5045 OO.mixinClass( OO.ui.TagMultiselectWidget, OO.ui.mixin.GroupWidget );
5046 OO.mixinClass( OO.ui.TagMultiselectWidget, OO.ui.mixin.DraggableGroupElement );
5047 OO.mixinClass( OO.ui.TagMultiselectWidget, OO.ui.mixin.IndicatorElement );
5048 OO.mixinClass( OO.ui.TagMultiselectWidget, OO.ui.mixin.IconElement );
5049 OO.mixinClass( OO.ui.TagMultiselectWidget, OO.ui.mixin.TabIndexedElement );
5050 OO.mixinClass( OO.ui.TagMultiselectWidget, OO.ui.mixin.FlaggedElement );
5051
5052 /* Static properties */
5053
5054 /**
5055 * Allowed input positions.
5056 * - inline: The input is inside the tag list
5057 * - outline: The input is under the tag list
5058 * - none: There is no input
5059 *
5060 * @property {Array}
5061 */
5062 OO.ui.TagMultiselectWidget.static.allowedInputPositions = [ 'inline', 'outline', 'none' ];
5063
5064 /* Methods */
5065
5066 /**
5067 * Handle mouse down events.
5068 *
5069 * @private
5070 * @param {jQuery.Event} e Mouse down event
5071 * @return {boolean} False to prevent defaults
5072 */
5073 OO.ui.TagMultiselectWidget.prototype.onMouseDown = function ( e ) {
5074 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
5075 this.focus();
5076 return false;
5077 }
5078 };
5079
5080 /**
5081 * Handle key press events.
5082 *
5083 * @private
5084 * @param {jQuery.Event} e Key press event
5085 * @return {boolean} Whether to prevent defaults
5086 */
5087 OO.ui.TagMultiselectWidget.prototype.onInputKeyPress = function ( e ) {
5088 var stopOrContinue,
5089 withMetaKey = e.metaKey || e.ctrlKey;
5090
5091 if ( !this.isDisabled() ) {
5092 if ( e.which === OO.ui.Keys.ENTER ) {
5093 stopOrContinue = this.doInputEnter( e, withMetaKey );
5094 }
5095
5096 // Make sure the input gets resized.
5097 setTimeout( this.updateInputSize.bind( this ), 0 );
5098 return stopOrContinue;
5099 }
5100 };
5101
5102 /**
5103 * Handle key down events.
5104 *
5105 * @private
5106 * @param {jQuery.Event} e Key down event
5107 * @return {boolean}
5108 */
5109 OO.ui.TagMultiselectWidget.prototype.onInputKeyDown = function ( e ) {
5110 var movement, direction,
5111 withMetaKey = e.metaKey || e.ctrlKey;
5112
5113 if ( !this.isDisabled() ) {
5114 // 'keypress' event is not triggered for Backspace
5115 if ( e.keyCode === OO.ui.Keys.BACKSPACE ) {
5116 return this.doInputBackspace( e, withMetaKey );
5117 } else if ( e.keyCode === OO.ui.Keys.ESCAPE ) {
5118 return this.doInputEscape( e );
5119 } else if (
5120 e.keyCode === OO.ui.Keys.LEFT ||
5121 e.keyCode === OO.ui.Keys.RIGHT
5122 ) {
5123 if ( OO.ui.Element.static.getDir( this.$element ) === 'rtl' ) {
5124 movement = {
5125 left: 'forwards',
5126 right: 'backwards'
5127 };
5128 } else {
5129 movement = {
5130 left: 'backwards',
5131 right: 'forwards'
5132 };
5133 }
5134 direction = e.keyCode === OO.ui.Keys.LEFT ?
5135 movement.left : movement.right;
5136
5137 return this.doInputArrow( e, direction, withMetaKey );
5138 }
5139 }
5140 };
5141
5142 /**
5143 * Respond to input focus event
5144 */
5145 OO.ui.TagMultiselectWidget.prototype.onInputFocus = function () {
5146 this.$element.addClass( 'oo-ui-tagMultiselectWidget-focus' );
5147 };
5148
5149 /**
5150 * Respond to input blur event
5151 */
5152 OO.ui.TagMultiselectWidget.prototype.onInputBlur = function () {
5153 this.$element.removeClass( 'oo-ui-tagMultiselectWidget-focus' );
5154 };
5155
5156 /**
5157 * Perform an action after the enter key on the input
5158 *
5159 * @param {jQuery.Event} e Event data
5160 * @param {boolean} [withMetaKey] Whether this key was pressed with
5161 * a meta key like 'ctrl'
5162 * @return {boolean} Whether to prevent defaults
5163 */
5164 OO.ui.TagMultiselectWidget.prototype.doInputEnter = function () {
5165 this.addTagFromInput();
5166 return false;
5167 };
5168
5169 /**
5170 * Perform an action responding to the enter key on the input
5171 *
5172 * @param {jQuery.Event} e Event data
5173 * @param {boolean} [withMetaKey] Whether this key was pressed with
5174 * a meta key like 'ctrl'
5175 * @return {boolean} Whether to prevent defaults
5176 */
5177 OO.ui.TagMultiselectWidget.prototype.doInputBackspace = function ( e, withMetaKey ) {
5178 var items, item;
5179
5180 if (
5181 this.inputPosition === 'inline' &&
5182 this.input.getValue() === '' &&
5183 !this.isEmpty()
5184 ) {
5185 // Delete the last item
5186 items = this.getItems();
5187 item = items[ items.length - 1 ];
5188 this.removeItems( [ item ] );
5189 // If Ctrl/Cmd was pressed, delete item entirely.
5190 // Otherwise put it into the text field for editing.
5191 if ( !withMetaKey ) {
5192 this.input.setValue( item.getData() );
5193 }
5194
5195 return false;
5196 }
5197 };
5198
5199 /**
5200 * Perform an action after the escape key on the input
5201 *
5202 * @param {jQuery.Event} e Event data
5203 */
5204 OO.ui.TagMultiselectWidget.prototype.doInputEscape = function () {
5205 this.clearInput();
5206 };
5207
5208 /**
5209 * Perform an action after the arrow key on the input, select the previous
5210 * or next item from the input.
5211 * See #getPreviousItem and #getNextItem
5212 *
5213 * @param {jQuery.Event} e Event data
5214 * @param {string} direction Direction of the movement; forwards or backwards
5215 * @param {boolean} [withMetaKey] Whether this key was pressed with
5216 * a meta key like 'ctrl'
5217 */
5218 OO.ui.TagMultiselectWidget.prototype.doInputArrow = function ( e, direction ) {
5219 if (
5220 this.inputPosition === 'inline' &&
5221 !this.isEmpty()
5222 ) {
5223 if ( direction === 'backwards' ) {
5224 // Get previous item
5225 this.getPreviousItem().focus();
5226 } else {
5227 // Get next item
5228 this.getNextItem().focus();
5229 }
5230 }
5231 };
5232
5233 /**
5234 * Respond to item select event
5235 *
5236 * @param {OO.ui.TagItemWidget} item Selected item
5237 */
5238 OO.ui.TagMultiselectWidget.prototype.onTagSelect = function ( item ) {
5239 if ( this.hasInput && this.allowEditTags ) {
5240 if ( this.input.getValue() ) {
5241 this.addTagFromInput();
5242 }
5243 // 1. Get the label of the tag into the input
5244 this.input.setValue( item.getData() );
5245 // 2. Remove the tag
5246 this.removeItems( [ item ] );
5247 // 3. Focus the input
5248 this.focus();
5249 }
5250 };
5251
5252 /**
5253 * Respond to change event, where items were added, removed, or cleared.
5254 */
5255 OO.ui.TagMultiselectWidget.prototype.onChangeTags = function () {
5256 this.toggleValid( this.checkValidity() );
5257 if ( this.hasInput ) {
5258 this.updateInputSize();
5259 }
5260 this.updateIfHeightChanged();
5261 };
5262
5263 /**
5264 * @inheritdoc
5265 */
5266 OO.ui.TagMultiselectWidget.prototype.setDisabled = function ( isDisabled ) {
5267 // Parent method
5268 OO.ui.TagMultiselectWidget.parent.prototype.setDisabled.call( this, isDisabled );
5269
5270 if ( this.hasInput && this.input ) {
5271 this.input.setDisabled( !!isDisabled );
5272 }
5273
5274 if ( this.items ) {
5275 this.getItems().forEach( function ( item ) {
5276 item.setDisabled( !!isDisabled );
5277 } );
5278 }
5279 };
5280
5281 /**
5282 * Respond to tag remove event
5283 * @param {OO.ui.TagItemWidget} item Removed tag
5284 */
5285 OO.ui.TagMultiselectWidget.prototype.onTagRemove = function ( item ) {
5286 this.removeTagByData( item.getData() );
5287 };
5288
5289 /**
5290 * Respond to navigate event on the tag
5291 *
5292 * @param {OO.ui.TagItemWidget} item Removed tag
5293 * @param {string} direction Direction of movement; 'forwards' or 'backwards'
5294 */
5295 OO.ui.TagMultiselectWidget.prototype.onTagNavigate = function ( item, direction ) {
5296 if ( direction === 'forwards' ) {
5297 this.getNextItem( item ).focus();
5298 } else {
5299 this.getPreviousItem( item ).focus();
5300 }
5301 };
5302
5303 /**
5304 * Add tag from input value
5305 */
5306 OO.ui.TagMultiselectWidget.prototype.addTagFromInput = function () {
5307 var val = this.input.getValue(),
5308 isValid = this.isAllowedData( val );
5309
5310 if ( !val ) {
5311 return;
5312 }
5313
5314 if ( isValid || this.allowDisplayInvalidTags ) {
5315 this.addTag( val );
5316 this.clearInput();
5317 this.focus();
5318 }
5319 };
5320
5321 /**
5322 * Clear the input
5323 */
5324 OO.ui.TagMultiselectWidget.prototype.clearInput = function () {
5325 this.input.setValue( '' );
5326 };
5327
5328 /**
5329 * Check whether the given value is a duplicate of an existing
5330 * tag already in the list.
5331 *
5332 * @param {string|Object} data Requested value
5333 * @return {boolean} Value is duplicate
5334 */
5335 OO.ui.TagMultiselectWidget.prototype.isDuplicateData = function ( data ) {
5336 return !!this.getItemFromData( data );
5337 };
5338
5339 /**
5340 * Check whether a given value is allowed to be added
5341 *
5342 * @param {string|Object} data Requested value
5343 * @return {boolean} Value is allowed
5344 */
5345 OO.ui.TagMultiselectWidget.prototype.isAllowedData = function ( data ) {
5346 if (
5347 !this.allowDuplicates &&
5348 this.isDuplicateData( data )
5349 ) {
5350 return false;
5351 }
5352
5353 if ( this.allowArbitrary ) {
5354 return true;
5355 }
5356
5357 // Check with allowed values
5358 if (
5359 this.getAllowedValues().some( function ( value ) {
5360 return data === value;
5361 } )
5362 ) {
5363 return true;
5364 }
5365
5366 return false;
5367 };
5368
5369 /**
5370 * Get the allowed values list
5371 *
5372 * @return {string[]} Allowed data values
5373 */
5374 OO.ui.TagMultiselectWidget.prototype.getAllowedValues = function () {
5375 return this.allowedValues;
5376 };
5377
5378 /**
5379 * Add a value to the allowed values list
5380 *
5381 * @param {string} value Allowed data value
5382 */
5383 OO.ui.TagMultiselectWidget.prototype.addAllowedValue = function ( value ) {
5384 if ( this.allowedValues.indexOf( value ) === -1 ) {
5385 this.allowedValues.push( value );
5386 }
5387 };
5388
5389 /**
5390 * Get the datas of the currently selected items
5391 *
5392 * @return {string[]|Object[]} Datas of currently selected items
5393 */
5394 OO.ui.TagMultiselectWidget.prototype.getValue = function () {
5395 return this.getItems()
5396 .filter( function ( item ) {
5397 return item.isValid();
5398 } )
5399 .map( function ( item ) {
5400 return item.getData();
5401 } );
5402 };
5403
5404 /**
5405 * Set the value of this widget by datas.
5406 *
5407 * @param {string|string[]|Object|Object[]} valueObject An object representing the data
5408 * and label of the value. If the widget allows arbitrary values,
5409 * the items will be added as-is. Otherwise, the data value will
5410 * be checked against allowedValues.
5411 * This object must contain at least a data key. Example:
5412 * { data: 'foo', label: 'Foo item' }
5413 * For multiple items, use an array of objects. For example:
5414 * [
5415 * { data: 'foo', label: 'Foo item' },
5416 * { data: 'bar', label: 'Bar item' }
5417 * ]
5418 * Value can also be added with plaintext array, for example:
5419 * [ 'foo', 'bar', 'bla' ] or a single string, like 'foo'
5420 */
5421 OO.ui.TagMultiselectWidget.prototype.setValue = function ( valueObject ) {
5422 valueObject = Array.isArray( valueObject ) ? valueObject : [ valueObject ];
5423
5424 this.clearItems();
5425 valueObject.forEach( function ( obj ) {
5426 if ( typeof obj === 'string' ) {
5427 this.addTag( obj );
5428 } else {
5429 this.addTag( obj.data, obj.label );
5430 }
5431 }.bind( this ) );
5432 };
5433
5434 /**
5435 * Add tag to the display area
5436 *
5437 * @param {string|Object} data Tag data
5438 * @param {string} [label] Tag label. If no label is provided, the
5439 * stringified version of the data will be used instead.
5440 * @return {boolean} Item was added successfully
5441 */
5442 OO.ui.TagMultiselectWidget.prototype.addTag = function ( data, label ) {
5443 var newItemWidget,
5444 isValid = this.isAllowedData( data );
5445
5446 if ( isValid || this.allowDisplayInvalidTags ) {
5447 newItemWidget = this.createTagItemWidget( data, label );
5448 newItemWidget.toggleValid( isValid );
5449 this.addItems( [ newItemWidget ] );
5450 return true;
5451 }
5452 return false;
5453 };
5454
5455 /**
5456 * Remove tag by its data property.
5457 *
5458 * @param {string|Object} data Tag data
5459 */
5460 OO.ui.TagMultiselectWidget.prototype.removeTagByData = function ( data ) {
5461 var item = this.getItemFromData( data );
5462
5463 this.removeItems( [ item ] );
5464 };
5465
5466 /**
5467 * Construct a OO.ui.TagItemWidget (or a subclass thereof) from given label and data.
5468 *
5469 * @protected
5470 * @param {string} data Item data
5471 * @param {string} label The label text.
5472 * @return {OO.ui.TagItemWidget}
5473 */
5474 OO.ui.TagMultiselectWidget.prototype.createTagItemWidget = function ( data, label ) {
5475 label = label || data;
5476
5477 return new OO.ui.TagItemWidget( { data: data, label: label } );
5478 };
5479
5480 /**
5481 * Given an item, returns the item after it. If the item is already the
5482 * last item, return `this.input`. If no item is passed, returns the
5483 * very first item.
5484 *
5485 * @protected
5486 * @param {OO.ui.TagItemWidget} [item] Tag item
5487 * @return {OO.ui.Widget} The next widget available.
5488 */
5489 OO.ui.TagMultiselectWidget.prototype.getNextItem = function ( item ) {
5490 var itemIndex = this.items.indexOf( item );
5491
5492 if ( item === undefined || itemIndex === -1 ) {
5493 return this.items[ 0 ];
5494 }
5495
5496 if ( itemIndex === this.items.length - 1 ) { // Last item
5497 if ( this.hasInput ) {
5498 return this.input;
5499 } else {
5500 // Return first item
5501 return this.items[ 0 ];
5502 }
5503 } else {
5504 return this.items[ itemIndex + 1 ];
5505 }
5506 };
5507
5508 /**
5509 * Given an item, returns the item before it. If the item is already the
5510 * first item, return `this.input`. If no item is passed, returns the
5511 * very last item.
5512 *
5513 * @protected
5514 * @param {OO.ui.TagItemWidget} [item] Tag item
5515 * @return {OO.ui.Widget} The previous widget available.
5516 */
5517 OO.ui.TagMultiselectWidget.prototype.getPreviousItem = function ( item ) {
5518 var itemIndex = this.items.indexOf( item );
5519
5520 if ( item === undefined || itemIndex === -1 ) {
5521 return this.items[ this.items.length - 1 ];
5522 }
5523
5524 if ( itemIndex === 0 ) {
5525 if ( this.hasInput ) {
5526 return this.input;
5527 } else {
5528 // Return the last item
5529 return this.items[ this.items.length - 1 ];
5530 }
5531 } else {
5532 return this.items[ itemIndex - 1 ];
5533 }
5534 };
5535
5536 /**
5537 * Update the dimensions of the text input field to encompass all available area.
5538 * This is especially relevant for when the input is at the edge of a line
5539 * and should get smaller. The usual operation (as an inline-block with min-width)
5540 * does not work in that case, pushing the input downwards to the next line.
5541 *
5542 * @private
5543 */
5544 OO.ui.TagMultiselectWidget.prototype.updateInputSize = function () {
5545 var $lastItem, direction, contentWidth, currentWidth, bestWidth;
5546 if ( this.inputPosition === 'inline' && !this.isDisabled() ) {
5547 if ( this.input.$input[ 0 ].scrollWidth === 0 ) {
5548 // Input appears to be attached but not visible.
5549 // Don't attempt to adjust its size, because our measurements
5550 // are going to fail anyway.
5551 return;
5552 }
5553 this.input.$input.css( 'width', '1em' );
5554 $lastItem = this.$group.children().last();
5555 direction = OO.ui.Element.static.getDir( this.$handle );
5556
5557 // Get the width of the input with the placeholder text as
5558 // the value and save it so that we don't keep recalculating
5559 if (
5560 this.contentWidthWithPlaceholder === undefined &&
5561 this.input.getValue() === '' &&
5562 this.input.$input.attr( 'placeholder' ) !== undefined
5563 ) {
5564 this.input.setValue( this.input.$input.attr( 'placeholder' ) );
5565 this.contentWidthWithPlaceholder = this.input.$input[ 0 ].scrollWidth;
5566 this.input.setValue( '' );
5567
5568 }
5569
5570 // Always keep the input wide enough for the placeholder text
5571 contentWidth = Math.max(
5572 this.input.$input[ 0 ].scrollWidth,
5573 // undefined arguments in Math.max lead to NaN
5574 ( this.contentWidthWithPlaceholder === undefined ) ?
5575 0 : this.contentWidthWithPlaceholder
5576 );
5577 currentWidth = this.input.$input.width();
5578
5579 if ( contentWidth < currentWidth ) {
5580 this.updateIfHeightChanged();
5581 // All is fine, don't perform expensive calculations
5582 return;
5583 }
5584
5585 if ( $lastItem.length === 0 ) {
5586 bestWidth = this.$content.innerWidth();
5587 } else {
5588 bestWidth = direction === 'ltr' ?
5589 this.$content.innerWidth() - $lastItem.position().left - $lastItem.outerWidth() :
5590 $lastItem.position().left;
5591 }
5592
5593 // Some safety margin for sanity, because I *really* don't feel like finding out where the few
5594 // pixels this is off by are coming from.
5595 bestWidth -= 10;
5596 if ( contentWidth > bestWidth ) {
5597 // This will result in the input getting shifted to the next line
5598 bestWidth = this.$content.innerWidth() - 10;
5599 }
5600 this.input.$input.width( Math.floor( bestWidth ) );
5601 this.updateIfHeightChanged();
5602 } else {
5603 this.updateIfHeightChanged();
5604 }
5605 };
5606
5607 /**
5608 * Determine if widget height changed, and if so,
5609 * emit the resize event. This is useful for when there are either
5610 * menus or popups attached to the bottom of the widget, to allow
5611 * them to change their positioning in case the widget moved down
5612 * or up.
5613 *
5614 * @private
5615 */
5616 OO.ui.TagMultiselectWidget.prototype.updateIfHeightChanged = function () {
5617 var height = this.$element.height();
5618 if ( height !== this.height ) {
5619 this.height = height;
5620 this.emit( 'resize' );
5621 }
5622 };
5623
5624 /**
5625 * Check whether all items in the widget are valid
5626 *
5627 * @return {boolean} Widget is valid
5628 */
5629 OO.ui.TagMultiselectWidget.prototype.checkValidity = function () {
5630 return this.getItems().every( function ( item ) {
5631 return item.isValid();
5632 } );
5633 };
5634
5635 /**
5636 * Set the valid state of this item
5637 *
5638 * @param {boolean} [valid] Item is valid
5639 * @fires valid
5640 */
5641 OO.ui.TagMultiselectWidget.prototype.toggleValid = function ( valid ) {
5642 valid = valid === undefined ? !this.valid : !!valid;
5643
5644 if ( this.valid !== valid ) {
5645 this.valid = valid;
5646
5647 this.setFlags( { invalid: !this.valid } );
5648
5649 this.emit( 'valid', this.valid );
5650 }
5651 };
5652
5653 /**
5654 * Get the current valid state of the widget
5655 *
5656 * @return {boolean} Widget is valid
5657 */
5658 OO.ui.TagMultiselectWidget.prototype.isValid = function () {
5659 return this.valid;
5660 };
5661
5662 /**
5663 * PopupTagMultiselectWidget is a {@link OO.ui.TagMultiselectWidget OO.ui.TagMultiselectWidget} intended
5664 * to use a popup. The popup can be configured to have a default input to insert values into the widget.
5665 *
5666 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
5667 *
5668 * @example
5669 * // Example: A basic PopupTagMultiselectWidget.
5670 * var widget = new OO.ui.PopupTagMultiselectWidget();
5671 * $( 'body' ).append( widget.$element );
5672 *
5673 * // Example: A PopupTagMultiselectWidget with an external popup.
5674 * var popupInput = new OO.ui.TextInputWidget(),
5675 * widget = new OO.ui.PopupTagMultiselectWidget( {
5676 * popupInput: popupInput,
5677 * popup: {
5678 * $content: popupInput.$element
5679 * }
5680 * } );
5681 * $( 'body' ).append( widget.$element );
5682 *
5683 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
5684 *
5685 * @class
5686 * @extends OO.ui.TagMultiselectWidget
5687 * @mixins OO.ui.mixin.PopupElement
5688 *
5689 * @param {Object} config Configuration object
5690 * @cfg {jQuery} [$overlay] An overlay for the popup.
5691 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
5692 * @cfg {Object} [popup] Configuration options for the popup
5693 * @cfg {OO.ui.InputWidget} [popupInput] An input widget inside the popup that will be
5694 * focused when the popup is opened and will be used as replacement for the
5695 * general input in the widget.
5696 */
5697 OO.ui.PopupTagMultiselectWidget = function OoUiPopupTagMultiselectWidget( config ) {
5698 var defaultInput,
5699 defaultConfig = { popup: {} };
5700
5701 config = config || {};
5702
5703 // Parent constructor
5704 OO.ui.PopupTagMultiselectWidget.parent.call( this, $.extend( { inputPosition: 'none' }, config ) );
5705
5706 this.$overlay = config.$overlay || this.$element;
5707
5708 if ( !config.popup ) {
5709 // For the default base implementation, we give a popup
5710 // with an input widget inside it. For any other use cases
5711 // the popup needs to be populated externally and the
5712 // event handled to add tags separately and manually
5713 defaultInput = new OO.ui.TextInputWidget();
5714
5715 defaultConfig.popupInput = defaultInput;
5716 defaultConfig.popup.$content = defaultInput.$element;
5717
5718 this.$element.addClass( 'oo-ui-popupTagMultiselectWidget-defaultPopup' );
5719 }
5720
5721 // Add overlay, and add that to the autoCloseIgnore
5722 defaultConfig.popup.$overlay = this.$overlay;
5723 defaultConfig.popup.$autoCloseIgnore = this.hasInput ?
5724 this.input.$element.add( this.$overlay ) : this.$overlay;
5725
5726 // Allow extending any of the above
5727 config = $.extend( defaultConfig, config );
5728
5729 // Mixin constructors
5730 OO.ui.mixin.PopupElement.call( this, config );
5731
5732 if ( this.hasInput ) {
5733 this.input.$input.on( 'focus', this.popup.toggle.bind( this.popup, true ) );
5734 }
5735
5736 // Configuration options
5737 this.popupInput = config.popupInput;
5738 if ( this.popupInput ) {
5739 this.popupInput.connect( this, {
5740 enter: 'onPopupInputEnter'
5741 } );
5742 }
5743
5744 // Events
5745 this.on( 'resize', this.popup.updateDimensions.bind( this.popup ) );
5746 this.popup.connect( this, { toggle: 'onPopupToggle' } );
5747 this.$tabIndexed
5748 .on( 'focus', this.onFocus.bind( this ) );
5749
5750 // Initialize
5751 this.$element
5752 .append( this.popup.$element )
5753 .addClass( 'oo-ui-popupTagMultiselectWidget' );
5754 };
5755
5756 /* Initialization */
5757
5758 OO.inheritClass( OO.ui.PopupTagMultiselectWidget, OO.ui.TagMultiselectWidget );
5759 OO.mixinClass( OO.ui.PopupTagMultiselectWidget, OO.ui.mixin.PopupElement );
5760
5761 /* Methods */
5762
5763 /**
5764 * Focus event handler.
5765 *
5766 * @private
5767 */
5768 OO.ui.PopupTagMultiselectWidget.prototype.onFocus = function () {
5769 this.popup.toggle( true );
5770 };
5771
5772 /**
5773 * Respond to popup toggle event
5774 *
5775 * @param {boolean} isVisible Popup is visible
5776 */
5777 OO.ui.PopupTagMultiselectWidget.prototype.onPopupToggle = function ( isVisible ) {
5778 if ( isVisible && this.popupInput ) {
5779 this.popupInput.focus();
5780 }
5781 };
5782
5783 /**
5784 * Respond to popup input enter event
5785 */
5786 OO.ui.PopupTagMultiselectWidget.prototype.onPopupInputEnter = function () {
5787 if ( this.popupInput ) {
5788 this.addTagByPopupValue( this.popupInput.getValue() );
5789 this.popupInput.setValue( '' );
5790 }
5791 };
5792
5793 /**
5794 * @inheritdoc
5795 */
5796 OO.ui.PopupTagMultiselectWidget.prototype.onTagSelect = function ( item ) {
5797 if ( this.popupInput && this.allowEditTags ) {
5798 this.popupInput.setValue( item.getData() );
5799 this.removeItems( [ item ] );
5800
5801 this.popup.toggle( true );
5802 this.popupInput.focus();
5803 } else {
5804 // Parent
5805 OO.ui.PopupTagMultiselectWidget.parent.prototype.onTagSelect.call( this, item );
5806 }
5807 };
5808
5809 /**
5810 * Add a tag by the popup value.
5811 * Whatever is responsible for setting the value in the popup should call
5812 * this method to add a tag, or use the regular methods like #addTag or
5813 * #setValue directly.
5814 *
5815 * @param {string} data The value of item
5816 * @param {string} [label] The label of the tag. If not given, the data is used.
5817 */
5818 OO.ui.PopupTagMultiselectWidget.prototype.addTagByPopupValue = function ( data, label ) {
5819 this.addTag( data, label );
5820 };
5821
5822 /**
5823 * MenuTagMultiselectWidget is a {@link OO.ui.TagMultiselectWidget OO.ui.TagMultiselectWidget} intended
5824 * to use a menu of selectable options.
5825 *
5826 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
5827 *
5828 * @example
5829 * // Example: A basic MenuTagMultiselectWidget.
5830 * var widget = new OO.ui.MenuTagMultiselectWidget( {
5831 * inputPosition: 'outline',
5832 * options: [
5833 * { data: 'option1', label: 'Option 1' },
5834 * { data: 'option2', label: 'Option 2' },
5835 * { data: 'option3', label: 'Option 3' },
5836 * ],
5837 * selected: [ 'option1', 'option2' ]
5838 * } );
5839 * $( 'body' ).append( widget.$element );
5840 *
5841 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
5842 *
5843 * @class
5844 * @extends OO.ui.TagMultiselectWidget
5845 *
5846 * @constructor
5847 * @param {Object} [config] Configuration object
5848 * @cfg {Object} [menu] Configuration object for the menu widget
5849 * @cfg {jQuery} [$overlay] An overlay for the menu.
5850 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
5851 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
5852 */
5853 OO.ui.MenuTagMultiselectWidget = function OoUiMenuTagMultiselectWidget( config ) {
5854 config = config || {};
5855
5856 // Parent constructor
5857 OO.ui.MenuTagMultiselectWidget.parent.call( this, config );
5858
5859 this.$overlay = config.$overlay || this.$element;
5860
5861 this.menu = this.createMenuWidget( $.extend( {
5862 widget: this,
5863 input: this.hasInput ? this.input : null,
5864 $input: this.hasInput ? this.input.$input : null,
5865 filterFromInput: !!this.hasInput,
5866 $autoCloseIgnore: this.hasInput ?
5867 this.input.$element.add( this.$overlay ) : this.$overlay,
5868 $floatableContainer: this.hasInput && this.inputPosition === 'outline' ?
5869 this.input.$element : this.$element,
5870 $overlay: this.$overlay,
5871 disabled: this.isDisabled()
5872 }, config.menu ) );
5873 this.addOptions( config.options || [] );
5874
5875 // Events
5876 this.menu.connect( this, {
5877 choose: 'onMenuChoose',
5878 toggle: 'onMenuToggle'
5879 } );
5880 if ( this.hasInput ) {
5881 this.input.connect( this, { change: 'onInputChange' } );
5882 }
5883 this.connect( this, { resize: 'onResize' } );
5884
5885 // Initialization
5886 this.$overlay
5887 .append( this.menu.$element );
5888 this.$element
5889 .addClass( 'oo-ui-menuTagMultiselectWidget' );
5890 // TagMultiselectWidget already does this, but it doesn't work right because this.menu is not yet
5891 // set up while the parent constructor runs, and #getAllowedValues rejects everything.
5892 if ( config.selected ) {
5893 this.setValue( config.selected );
5894 }
5895 };
5896
5897 /* Initialization */
5898
5899 OO.inheritClass( OO.ui.MenuTagMultiselectWidget, OO.ui.TagMultiselectWidget );
5900
5901 /* Methods */
5902
5903 /**
5904 * Respond to resize event
5905 */
5906 OO.ui.MenuTagMultiselectWidget.prototype.onResize = function () {
5907 // Reposition the menu
5908 this.menu.position();
5909 };
5910
5911 /**
5912 * @inheritdoc
5913 */
5914 OO.ui.MenuTagMultiselectWidget.prototype.onInputFocus = function () {
5915 // Parent method
5916 OO.ui.MenuTagMultiselectWidget.parent.prototype.onInputFocus.call( this );
5917
5918 this.menu.toggle( true );
5919 };
5920
5921 /**
5922 * Respond to input change event
5923 */
5924 OO.ui.MenuTagMultiselectWidget.prototype.onInputChange = function () {
5925 this.menu.toggle( true );
5926 };
5927
5928 /**
5929 * Respond to menu choose event
5930 *
5931 * @param {OO.ui.OptionWidget} menuItem Chosen menu item
5932 */
5933 OO.ui.MenuTagMultiselectWidget.prototype.onMenuChoose = function ( menuItem ) {
5934 // Add tag
5935 this.addTag( menuItem.getData(), menuItem.getLabel() );
5936 };
5937
5938 /**
5939 * Respond to menu toggle event. Reset item highlights on hide.
5940 *
5941 * @param {boolean} isVisible The menu is visible
5942 */
5943 OO.ui.MenuTagMultiselectWidget.prototype.onMenuToggle = function ( isVisible ) {
5944 if ( !isVisible ) {
5945 this.menu.selectItem( null );
5946 this.menu.highlightItem( null );
5947 }
5948 };
5949
5950 /**
5951 * @inheritdoc
5952 */
5953 OO.ui.MenuTagMultiselectWidget.prototype.onTagSelect = function ( tagItem ) {
5954 var menuItem = this.menu.getItemFromData( tagItem.getData() );
5955 // Override the base behavior from TagMultiselectWidget; the base behavior
5956 // in TagMultiselectWidget is to remove the tag to edit it in the input,
5957 // but in our case, we want to utilize the menu selection behavior, and
5958 // definitely not remove the item.
5959
5960 // Select the menu item
5961 this.menu.selectItem( menuItem );
5962
5963 this.focus();
5964 };
5965
5966 /**
5967 * @inheritdoc
5968 */
5969 OO.ui.MenuTagMultiselectWidget.prototype.addTagFromInput = function () {
5970 var inputValue = this.input.getValue(),
5971 validated = false,
5972 highlightedItem = this.menu.getHighlightedItem(),
5973 item = this.menu.getItemFromData( inputValue );
5974
5975 // Override the parent method so we add from the menu
5976 // rather than directly from the input
5977
5978 // Look for a highlighted item first
5979 if ( highlightedItem ) {
5980 validated = this.addTag( highlightedItem.getData(), highlightedItem.getLabel() );
5981 } else if ( item ) {
5982 // Look for the element that fits the data
5983 validated = this.addTag( item.getData(), item.getLabel() );
5984 } else {
5985 // Otherwise, add the tag - the method will only add if the
5986 // tag is valid or if invalid tags are allowed
5987 validated = this.addTag( inputValue );
5988 }
5989
5990 if ( validated ) {
5991 this.clearInput();
5992 this.focus();
5993 }
5994 };
5995
5996 /**
5997 * Return the visible items in the menu. This is mainly used for when
5998 * the menu is filtering results.
5999 *
6000 * @return {OO.ui.MenuOptionWidget[]} Visible results
6001 */
6002 OO.ui.MenuTagMultiselectWidget.prototype.getMenuVisibleItems = function () {
6003 return this.menu.getItems().filter( function ( menuItem ) {
6004 return menuItem.isVisible();
6005 } );
6006 };
6007
6008 /**
6009 * Create the menu for this widget. This is in a separate method so that
6010 * child classes can override this without polluting the constructor with
6011 * unnecessary extra objects that will be overidden.
6012 *
6013 * @param {Object} menuConfig Configuration options
6014 * @return {OO.ui.MenuSelectWidget} Menu widget
6015 */
6016 OO.ui.MenuTagMultiselectWidget.prototype.createMenuWidget = function ( menuConfig ) {
6017 return new OO.ui.MenuSelectWidget( menuConfig );
6018 };
6019
6020 /**
6021 * Add options to the menu
6022 *
6023 * @param {Object[]} menuOptions Object defining options
6024 */
6025 OO.ui.MenuTagMultiselectWidget.prototype.addOptions = function ( menuOptions ) {
6026 var widget = this,
6027 items = menuOptions.map( function ( obj ) {
6028 return widget.createMenuOptionWidget( obj.data, obj.label );
6029 } );
6030
6031 this.menu.addItems( items );
6032 };
6033
6034 /**
6035 * Create a menu option widget.
6036 *
6037 * @param {string} data Item data
6038 * @param {string} [label] Item label
6039 * @return {OO.ui.OptionWidget} Option widget
6040 */
6041 OO.ui.MenuTagMultiselectWidget.prototype.createMenuOptionWidget = function ( data, label ) {
6042 return new OO.ui.MenuOptionWidget( {
6043 data: data,
6044 label: label || data
6045 } );
6046 };
6047
6048 /**
6049 * Get the menu
6050 *
6051 * @return {OO.ui.MenuSelectWidget} Menu
6052 */
6053 OO.ui.MenuTagMultiselectWidget.prototype.getMenu = function () {
6054 return this.menu;
6055 };
6056
6057 /**
6058 * Get the allowed values list
6059 *
6060 * @return {string[]} Allowed data values
6061 */
6062 OO.ui.MenuTagMultiselectWidget.prototype.getAllowedValues = function () {
6063 var menuDatas = [];
6064 if ( this.menu ) {
6065 // If the parent constructor is calling us, we're not ready yet, this.menu is not set up.
6066 menuDatas = this.menu.getItems().map( function ( menuItem ) {
6067 return menuItem.getData();
6068 } );
6069 }
6070 return this.allowedValues.concat( menuDatas );
6071 };
6072
6073 /**
6074 * SelectFileWidgets allow for selecting files, using the HTML5 File API. These
6075 * widgets can be configured with {@link OO.ui.mixin.IconElement icons} and {@link
6076 * OO.ui.mixin.IndicatorElement indicators}.
6077 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
6078 *
6079 * @example
6080 * // Example of a file select widget
6081 * var selectFile = new OO.ui.SelectFileWidget();
6082 * $( 'body' ).append( selectFile.$element );
6083 *
6084 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets
6085 *
6086 * @class
6087 * @extends OO.ui.Widget
6088 * @mixins OO.ui.mixin.IconElement
6089 * @mixins OO.ui.mixin.IndicatorElement
6090 * @mixins OO.ui.mixin.PendingElement
6091 * @mixins OO.ui.mixin.LabelElement
6092 *
6093 * @constructor
6094 * @param {Object} [config] Configuration options
6095 * @cfg {string[]|null} [accept=null] MIME types to accept. null accepts all types.
6096 * @cfg {string} [placeholder] Text to display when no file is selected.
6097 * @cfg {string} [notsupported] Text to display when file support is missing in the browser.
6098 * @cfg {boolean} [droppable=true] Whether to accept files by drag and drop.
6099 * @cfg {boolean} [showDropTarget=false] Whether to show a drop target. Requires droppable to be true.
6100 * @cfg {number} [thumbnailSizeLimit=20] File size limit in MiB above which to not try and show a
6101 * preview (for performance)
6102 */
6103 OO.ui.SelectFileWidget = function OoUiSelectFileWidget( config ) {
6104 var dragHandler;
6105
6106 // Configuration initialization
6107 config = $.extend( {
6108 accept: null,
6109 placeholder: OO.ui.msg( 'ooui-selectfile-placeholder' ),
6110 notsupported: OO.ui.msg( 'ooui-selectfile-not-supported' ),
6111 droppable: true,
6112 showDropTarget: false,
6113 thumbnailSizeLimit: 20
6114 }, config );
6115
6116 // Parent constructor
6117 OO.ui.SelectFileWidget.parent.call( this, config );
6118
6119 // Mixin constructors
6120 OO.ui.mixin.IconElement.call( this, config );
6121 OO.ui.mixin.IndicatorElement.call( this, config );
6122 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$info } ) );
6123 OO.ui.mixin.LabelElement.call( this, config );
6124
6125 // Properties
6126 this.$info = $( '<span>' );
6127 this.showDropTarget = config.showDropTarget;
6128 this.thumbnailSizeLimit = config.thumbnailSizeLimit;
6129 this.isSupported = this.constructor.static.isSupported();
6130 this.currentFile = null;
6131 if ( Array.isArray( config.accept ) ) {
6132 this.accept = config.accept;
6133 } else {
6134 this.accept = null;
6135 }
6136 this.placeholder = config.placeholder;
6137 this.notsupported = config.notsupported;
6138 this.onFileSelectedHandler = this.onFileSelected.bind( this );
6139
6140 this.selectButton = new OO.ui.ButtonWidget( {
6141 classes: [ 'oo-ui-selectFileWidget-selectButton' ],
6142 label: OO.ui.msg( 'ooui-selectfile-button-select' ),
6143 disabled: this.disabled || !this.isSupported
6144 } );
6145
6146 this.clearButton = new OO.ui.ButtonWidget( {
6147 classes: [ 'oo-ui-selectFileWidget-clearButton' ],
6148 framed: false,
6149 icon: 'close',
6150 disabled: this.disabled
6151 } );
6152
6153 // Events
6154 this.selectButton.$button.on( {
6155 keypress: this.onKeyPress.bind( this )
6156 } );
6157 this.clearButton.connect( this, {
6158 click: 'onClearClick'
6159 } );
6160 if ( config.droppable ) {
6161 dragHandler = this.onDragEnterOrOver.bind( this );
6162 this.$element.on( {
6163 dragenter: dragHandler,
6164 dragover: dragHandler,
6165 dragleave: this.onDragLeave.bind( this ),
6166 drop: this.onDrop.bind( this )
6167 } );
6168 }
6169
6170 // Initialization
6171 this.addInput();
6172 this.$label.addClass( 'oo-ui-selectFileWidget-label' );
6173 this.$info
6174 .addClass( 'oo-ui-selectFileWidget-info' )
6175 .append( this.$icon, this.$label, this.clearButton.$element, this.$indicator );
6176
6177 if ( config.droppable && config.showDropTarget ) {
6178 this.selectButton.setIcon( 'upload' );
6179 this.$thumbnail = $( '<div>' ).addClass( 'oo-ui-selectFileWidget-thumbnail' );
6180 this.setPendingElement( this.$thumbnail );
6181 this.$element
6182 .addClass( 'oo-ui-selectFileWidget-dropTarget oo-ui-selectFileWidget' )
6183 .on( {
6184 click: this.onDropTargetClick.bind( this )
6185 } )
6186 .append(
6187 this.$thumbnail,
6188 this.$info,
6189 this.selectButton.$element,
6190 $( '<span>' )
6191 .addClass( 'oo-ui-selectFileWidget-dropLabel' )
6192 .text( OO.ui.msg( 'ooui-selectfile-dragdrop-placeholder' ) )
6193 );
6194 } else {
6195 this.$element
6196 .addClass( 'oo-ui-selectFileWidget' )
6197 .append( this.$info, this.selectButton.$element );
6198 }
6199 this.updateUI();
6200 };
6201
6202 /* Setup */
6203
6204 OO.inheritClass( OO.ui.SelectFileWidget, OO.ui.Widget );
6205 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IconElement );
6206 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IndicatorElement );
6207 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.PendingElement );
6208 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.LabelElement );
6209
6210 /* Static Properties */
6211
6212 /**
6213 * Check if this widget is supported
6214 *
6215 * @static
6216 * @return {boolean}
6217 */
6218 OO.ui.SelectFileWidget.static.isSupported = function () {
6219 var $input;
6220 if ( OO.ui.SelectFileWidget.static.isSupportedCache === null ) {
6221 $input = $( '<input>' ).attr( 'type', 'file' );
6222 OO.ui.SelectFileWidget.static.isSupportedCache = $input[ 0 ].files !== undefined;
6223 }
6224 return OO.ui.SelectFileWidget.static.isSupportedCache;
6225 };
6226
6227 OO.ui.SelectFileWidget.static.isSupportedCache = null;
6228
6229 /* Events */
6230
6231 /**
6232 * @event change
6233 *
6234 * A change event is emitted when the on/off state of the toggle changes.
6235 *
6236 * @param {File|null} value New value
6237 */
6238
6239 /* Methods */
6240
6241 /**
6242 * Get the current value of the field
6243 *
6244 * @return {File|null}
6245 */
6246 OO.ui.SelectFileWidget.prototype.getValue = function () {
6247 return this.currentFile;
6248 };
6249
6250 /**
6251 * Set the current value of the field
6252 *
6253 * @param {File|null} file File to select
6254 */
6255 OO.ui.SelectFileWidget.prototype.setValue = function ( file ) {
6256 if ( this.currentFile !== file ) {
6257 this.currentFile = file;
6258 this.updateUI();
6259 this.emit( 'change', this.currentFile );
6260 }
6261 };
6262
6263 /**
6264 * Focus the widget.
6265 *
6266 * Focusses the select file button.
6267 *
6268 * @chainable
6269 */
6270 OO.ui.SelectFileWidget.prototype.focus = function () {
6271 this.selectButton.focus();
6272 return this;
6273 };
6274
6275 /**
6276 * Blur the widget.
6277 *
6278 * @chainable
6279 */
6280 OO.ui.SelectFileWidget.prototype.blur = function () {
6281 this.selectButton.blur();
6282 return this;
6283 };
6284
6285 /**
6286 * @inheritdoc
6287 */
6288 OO.ui.SelectFileWidget.prototype.simulateLabelClick = function () {
6289 this.focus();
6290 };
6291
6292 /**
6293 * Update the user interface when a file is selected or unselected
6294 *
6295 * @protected
6296 */
6297 OO.ui.SelectFileWidget.prototype.updateUI = function () {
6298 var $label;
6299 if ( !this.isSupported ) {
6300 this.$element.addClass( 'oo-ui-selectFileWidget-notsupported' );
6301 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
6302 this.setLabel( this.notsupported );
6303 } else {
6304 this.$element.addClass( 'oo-ui-selectFileWidget-supported' );
6305 if ( this.currentFile ) {
6306 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
6307 $label = $( [] );
6308 $label = $label.add(
6309 $( '<span>' )
6310 .addClass( 'oo-ui-selectFileWidget-fileName' )
6311 .text( this.currentFile.name )
6312 );
6313 this.setLabel( $label );
6314
6315 if ( this.showDropTarget ) {
6316 this.pushPending();
6317 this.loadAndGetImageUrl().done( function ( url ) {
6318 this.$thumbnail.css( 'background-image', 'url( ' + url + ' )' );
6319 }.bind( this ) ).fail( function () {
6320 this.$thumbnail.append(
6321 new OO.ui.IconWidget( {
6322 icon: 'attachment',
6323 classes: [ 'oo-ui-selectFileWidget-noThumbnail-icon' ]
6324 } ).$element
6325 );
6326 }.bind( this ) ).always( function () {
6327 this.popPending();
6328 }.bind( this ) );
6329 this.$element.off( 'click' );
6330 }
6331 } else {
6332 if ( this.showDropTarget ) {
6333 this.$element.off( 'click' );
6334 this.$element.on( {
6335 click: this.onDropTargetClick.bind( this )
6336 } );
6337 this.$thumbnail
6338 .empty()
6339 .css( 'background-image', '' );
6340 }
6341 this.$element.addClass( 'oo-ui-selectFileWidget-empty' );
6342 this.setLabel( this.placeholder );
6343 }
6344 }
6345 };
6346
6347 /**
6348 * If the selected file is an image, get its URL and load it.
6349 *
6350 * @return {jQuery.Promise} Promise resolves with the image URL after it has loaded
6351 */
6352 OO.ui.SelectFileWidget.prototype.loadAndGetImageUrl = function () {
6353 var deferred = $.Deferred(),
6354 file = this.currentFile,
6355 reader = new FileReader();
6356
6357 if (
6358 file &&
6359 ( OO.getProp( file, 'type' ) || '' ).indexOf( 'image/' ) === 0 &&
6360 file.size < this.thumbnailSizeLimit * 1024 * 1024
6361 ) {
6362 reader.onload = function ( event ) {
6363 var img = document.createElement( 'img' );
6364 img.addEventListener( 'load', function () {
6365 if (
6366 img.naturalWidth === 0 ||
6367 img.naturalHeight === 0 ||
6368 img.complete === false
6369 ) {
6370 deferred.reject();
6371 } else {
6372 deferred.resolve( event.target.result );
6373 }
6374 } );
6375 img.src = event.target.result;
6376 };
6377 reader.readAsDataURL( file );
6378 } else {
6379 deferred.reject();
6380 }
6381
6382 return deferred.promise();
6383 };
6384
6385 /**
6386 * Add the input to the widget
6387 *
6388 * @private
6389 */
6390 OO.ui.SelectFileWidget.prototype.addInput = function () {
6391 if ( this.$input ) {
6392 this.$input.remove();
6393 }
6394
6395 if ( !this.isSupported ) {
6396 this.$input = null;
6397 return;
6398 }
6399
6400 this.$input = $( '<input>' ).attr( 'type', 'file' );
6401 this.$input.on( 'change', this.onFileSelectedHandler );
6402 this.$input.on( 'click', function ( e ) {
6403 // Prevents dropTarget to get clicked which calls
6404 // a click on this input
6405 e.stopPropagation();
6406 } );
6407 this.$input.attr( {
6408 tabindex: -1
6409 } );
6410 if ( this.accept ) {
6411 this.$input.attr( 'accept', this.accept.join( ', ' ) );
6412 }
6413 this.selectButton.$button.append( this.$input );
6414 };
6415
6416 /**
6417 * Determine if we should accept this file
6418 *
6419 * @private
6420 * @param {string} mimeType File MIME type
6421 * @return {boolean}
6422 */
6423 OO.ui.SelectFileWidget.prototype.isAllowedType = function ( mimeType ) {
6424 var i, mimeTest;
6425
6426 if ( !this.accept || !mimeType ) {
6427 return true;
6428 }
6429
6430 for ( i = 0; i < this.accept.length; i++ ) {
6431 mimeTest = this.accept[ i ];
6432 if ( mimeTest === mimeType ) {
6433 return true;
6434 } else if ( mimeTest.substr( -2 ) === '/*' ) {
6435 mimeTest = mimeTest.substr( 0, mimeTest.length - 1 );
6436 if ( mimeType.substr( 0, mimeTest.length ) === mimeTest ) {
6437 return true;
6438 }
6439 }
6440 }
6441
6442 return false;
6443 };
6444
6445 /**
6446 * Handle file selection from the input
6447 *
6448 * @private
6449 * @param {jQuery.Event} e
6450 */
6451 OO.ui.SelectFileWidget.prototype.onFileSelected = function ( e ) {
6452 var file = OO.getProp( e.target, 'files', 0 ) || null;
6453
6454 if ( file && !this.isAllowedType( file.type ) ) {
6455 file = null;
6456 }
6457
6458 this.setValue( file );
6459 this.addInput();
6460 };
6461
6462 /**
6463 * Handle clear button click events.
6464 *
6465 * @private
6466 */
6467 OO.ui.SelectFileWidget.prototype.onClearClick = function () {
6468 this.setValue( null );
6469 return false;
6470 };
6471
6472 /**
6473 * Handle key press events.
6474 *
6475 * @private
6476 * @param {jQuery.Event} e Key press event
6477 */
6478 OO.ui.SelectFileWidget.prototype.onKeyPress = function ( e ) {
6479 if ( this.isSupported && !this.isDisabled() && this.$input &&
6480 ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
6481 ) {
6482 this.$input.click();
6483 return false;
6484 }
6485 };
6486
6487 /**
6488 * Handle drop target click events.
6489 *
6490 * @private
6491 * @param {jQuery.Event} e Key press event
6492 */
6493 OO.ui.SelectFileWidget.prototype.onDropTargetClick = function () {
6494 if ( this.isSupported && !this.isDisabled() && this.$input ) {
6495 this.$input.click();
6496 return false;
6497 }
6498 };
6499
6500 /**
6501 * Handle drag enter and over events
6502 *
6503 * @private
6504 * @param {jQuery.Event} e Drag event
6505 */
6506 OO.ui.SelectFileWidget.prototype.onDragEnterOrOver = function ( e ) {
6507 var itemOrFile,
6508 droppableFile = false,
6509 dt = e.originalEvent.dataTransfer;
6510
6511 e.preventDefault();
6512 e.stopPropagation();
6513
6514 if ( this.isDisabled() || !this.isSupported ) {
6515 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
6516 dt.dropEffect = 'none';
6517 return false;
6518 }
6519
6520 // DataTransferItem and File both have a type property, but in Chrome files
6521 // have no information at this point.
6522 itemOrFile = OO.getProp( dt, 'items', 0 ) || OO.getProp( dt, 'files', 0 );
6523 if ( itemOrFile ) {
6524 if ( this.isAllowedType( itemOrFile.type ) ) {
6525 droppableFile = true;
6526 }
6527 // dt.types is Array-like, but not an Array
6528 } else if ( Array.prototype.indexOf.call( OO.getProp( dt, 'types' ) || [], 'Files' ) !== -1 ) {
6529 // File information is not available at this point for security so just assume
6530 // it is acceptable for now.
6531 // https://bugzilla.mozilla.org/show_bug.cgi?id=640534
6532 droppableFile = true;
6533 }
6534
6535 this.$element.toggleClass( 'oo-ui-selectFileWidget-canDrop', droppableFile );
6536 if ( !droppableFile ) {
6537 dt.dropEffect = 'none';
6538 }
6539
6540 return false;
6541 };
6542
6543 /**
6544 * Handle drag leave events
6545 *
6546 * @private
6547 * @param {jQuery.Event} e Drag event
6548 */
6549 OO.ui.SelectFileWidget.prototype.onDragLeave = function () {
6550 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
6551 };
6552
6553 /**
6554 * Handle drop events
6555 *
6556 * @private
6557 * @param {jQuery.Event} e Drop event
6558 */
6559 OO.ui.SelectFileWidget.prototype.onDrop = function ( e ) {
6560 var file = null,
6561 dt = e.originalEvent.dataTransfer;
6562
6563 e.preventDefault();
6564 e.stopPropagation();
6565 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
6566
6567 if ( this.isDisabled() || !this.isSupported ) {
6568 return false;
6569 }
6570
6571 file = OO.getProp( dt, 'files', 0 );
6572 if ( file && !this.isAllowedType( file.type ) ) {
6573 file = null;
6574 }
6575 if ( file ) {
6576 this.setValue( file );
6577 }
6578
6579 return false;
6580 };
6581
6582 /**
6583 * @inheritdoc
6584 */
6585 OO.ui.SelectFileWidget.prototype.setDisabled = function ( disabled ) {
6586 OO.ui.SelectFileWidget.parent.prototype.setDisabled.call( this, disabled );
6587 if ( this.selectButton ) {
6588 this.selectButton.setDisabled( disabled );
6589 }
6590 if ( this.clearButton ) {
6591 this.clearButton.setDisabled( disabled );
6592 }
6593 return this;
6594 };
6595
6596 /**
6597 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
6598 * and a menu of search results, which is displayed beneath the query
6599 * field. Unlike {@link OO.ui.mixin.LookupElement lookup menus}, search result menus are always visible to the user.
6600 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
6601 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
6602 *
6603 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
6604 * the [OOjs UI demos][1] for an example.
6605 *
6606 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
6607 *
6608 * @class
6609 * @extends OO.ui.Widget
6610 *
6611 * @constructor
6612 * @param {Object} [config] Configuration options
6613 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
6614 * @cfg {string} [value] Initial query value
6615 */
6616 OO.ui.SearchWidget = function OoUiSearchWidget( config ) {
6617 // Configuration initialization
6618 config = config || {};
6619
6620 // Parent constructor
6621 OO.ui.SearchWidget.parent.call( this, config );
6622
6623 // Properties
6624 this.query = new OO.ui.TextInputWidget( {
6625 icon: 'search',
6626 placeholder: config.placeholder,
6627 value: config.value
6628 } );
6629 this.results = new OO.ui.SelectWidget();
6630 this.$query = $( '<div>' );
6631 this.$results = $( '<div>' );
6632
6633 // Events
6634 this.query.connect( this, {
6635 change: 'onQueryChange',
6636 enter: 'onQueryEnter'
6637 } );
6638 this.query.$input.on( 'keydown', this.onQueryKeydown.bind( this ) );
6639
6640 // Initialization
6641 this.$query
6642 .addClass( 'oo-ui-searchWidget-query' )
6643 .append( this.query.$element );
6644 this.$results
6645 .addClass( 'oo-ui-searchWidget-results' )
6646 .append( this.results.$element );
6647 this.$element
6648 .addClass( 'oo-ui-searchWidget' )
6649 .append( this.$results, this.$query );
6650 };
6651
6652 /* Setup */
6653
6654 OO.inheritClass( OO.ui.SearchWidget, OO.ui.Widget );
6655
6656 /* Methods */
6657
6658 /**
6659 * Handle query key down events.
6660 *
6661 * @private
6662 * @param {jQuery.Event} e Key down event
6663 */
6664 OO.ui.SearchWidget.prototype.onQueryKeydown = function ( e ) {
6665 var highlightedItem, nextItem,
6666 dir = e.which === OO.ui.Keys.DOWN ? 1 : ( e.which === OO.ui.Keys.UP ? -1 : 0 );
6667
6668 if ( dir ) {
6669 highlightedItem = this.results.getHighlightedItem();
6670 if ( !highlightedItem ) {
6671 highlightedItem = this.results.getSelectedItem();
6672 }
6673 nextItem = this.results.getRelativeSelectableItem( highlightedItem, dir );
6674 this.results.highlightItem( nextItem );
6675 nextItem.scrollElementIntoView();
6676 }
6677 };
6678
6679 /**
6680 * Handle select widget select events.
6681 *
6682 * Clears existing results. Subclasses should repopulate items according to new query.
6683 *
6684 * @private
6685 * @param {string} value New value
6686 */
6687 OO.ui.SearchWidget.prototype.onQueryChange = function () {
6688 // Reset
6689 this.results.clearItems();
6690 };
6691
6692 /**
6693 * Handle select widget enter key events.
6694 *
6695 * Chooses highlighted item.
6696 *
6697 * @private
6698 * @param {string} value New value
6699 */
6700 OO.ui.SearchWidget.prototype.onQueryEnter = function () {
6701 var highlightedItem = this.results.getHighlightedItem();
6702 if ( highlightedItem ) {
6703 this.results.chooseItem( highlightedItem );
6704 }
6705 };
6706
6707 /**
6708 * Get the query input.
6709 *
6710 * @return {OO.ui.TextInputWidget} Query input
6711 */
6712 OO.ui.SearchWidget.prototype.getQuery = function () {
6713 return this.query;
6714 };
6715
6716 /**
6717 * Get the search results menu.
6718 *
6719 * @return {OO.ui.SelectWidget} Menu of search results
6720 */
6721 OO.ui.SearchWidget.prototype.getResults = function () {
6722 return this.results;
6723 };
6724
6725 /**
6726 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
6727 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
6728 * (to adjust the value in increments) to allow the user to enter a number.
6729 *
6730 * @example
6731 * // Example: A NumberInputWidget.
6732 * var numberInput = new OO.ui.NumberInputWidget( {
6733 * label: 'NumberInputWidget',
6734 * input: { value: 5 },
6735 * min: 1,
6736 * max: 10
6737 * } );
6738 * $( 'body' ).append( numberInput.$element );
6739 *
6740 * @class
6741 * @extends OO.ui.TextInputWidget
6742 *
6743 * @constructor
6744 * @param {Object} [config] Configuration options
6745 * @cfg {Object} [minusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget decrementing button widget}.
6746 * @cfg {Object} [plusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget incrementing button widget}.
6747 * @cfg {boolean} [allowInteger=false] Whether the field accepts only integer values.
6748 * @cfg {number} [min=-Infinity] Minimum allowed value
6749 * @cfg {number} [max=Infinity] Maximum allowed value
6750 * @cfg {number} [step=1] Delta when using the buttons or up/down arrow keys
6751 * @cfg {number|null} [pageStep] Delta when using the page-up/page-down keys. Defaults to 10 times #step.
6752 * @cfg {boolean} [showButtons=true] Whether to show the plus and minus buttons.
6753 */
6754 OO.ui.NumberInputWidget = function OoUiNumberInputWidget( config ) {
6755 var $field = $( '<div>' )
6756 .addClass( 'oo-ui-numberInputWidget-field' );
6757
6758 // Configuration initialization
6759 config = $.extend( {
6760 allowInteger: false,
6761 min: -Infinity,
6762 max: Infinity,
6763 step: 1,
6764 pageStep: null,
6765 showButtons: true
6766 }, config );
6767
6768 // For backward compatibility
6769 $.extend( config, config.input );
6770 this.input = this;
6771
6772 // Parent constructor
6773 OO.ui.NumberInputWidget.parent.call( this, $.extend( config, {
6774 type: 'number'
6775 } ) );
6776
6777 if ( config.showButtons ) {
6778 this.minusButton = new OO.ui.ButtonWidget( $.extend(
6779 {
6780 disabled: this.isDisabled(),
6781 tabIndex: -1,
6782 classes: [ 'oo-ui-numberInputWidget-minusButton' ],
6783 icon: 'subtract'
6784 },
6785 config.minusButton
6786 ) );
6787 this.plusButton = new OO.ui.ButtonWidget( $.extend(
6788 {
6789 disabled: this.isDisabled(),
6790 tabIndex: -1,
6791 classes: [ 'oo-ui-numberInputWidget-plusButton' ],
6792 icon: 'add'
6793 },
6794 config.plusButton
6795 ) );
6796 }
6797
6798 // Events
6799 this.$input.on( {
6800 keydown: this.onKeyDown.bind( this ),
6801 'wheel mousewheel DOMMouseScroll': this.onWheel.bind( this )
6802 } );
6803 if ( config.showButtons ) {
6804 this.plusButton.connect( this, {
6805 click: [ 'onButtonClick', +1 ]
6806 } );
6807 this.minusButton.connect( this, {
6808 click: [ 'onButtonClick', -1 ]
6809 } );
6810 }
6811
6812 // Build the field
6813 $field.append( this.$input );
6814 if ( config.showButtons ) {
6815 $field
6816 .prepend( this.minusButton.$element )
6817 .append( this.plusButton.$element );
6818 }
6819
6820 // Initialization
6821 this.setAllowInteger( config.allowInteger || config.isInteger );
6822 this.setRange( config.min, config.max );
6823 this.setStep( config.step, config.pageStep );
6824 // Set the validation method after we set allowInteger and range
6825 // so that it doesn't immediately call setValidityFlag
6826 this.setValidation( this.validateNumber.bind( this ) );
6827
6828 this.$element
6829 .addClass( 'oo-ui-numberInputWidget' )
6830 .toggleClass( 'oo-ui-numberInputWidget-buttoned', config.showButtons )
6831 .append( $field );
6832 };
6833
6834 /* Setup */
6835
6836 OO.inheritClass( OO.ui.NumberInputWidget, OO.ui.TextInputWidget );
6837
6838 /* Methods */
6839
6840 /**
6841 * Set whether only integers are allowed
6842 *
6843 * @param {boolean} flag
6844 */
6845 OO.ui.NumberInputWidget.prototype.setAllowInteger = function ( flag ) {
6846 this.allowInteger = !!flag;
6847 this.setValidityFlag();
6848 };
6849 // Backward compatibility
6850 OO.ui.NumberInputWidget.prototype.setIsInteger = OO.ui.NumberInputWidget.prototype.setAllowInteger;
6851
6852 /**
6853 * Get whether only integers are allowed
6854 *
6855 * @return {boolean} Flag value
6856 */
6857 OO.ui.NumberInputWidget.prototype.getAllowInteger = function () {
6858 return this.allowInteger;
6859 };
6860 // Backward compatibility
6861 OO.ui.NumberInputWidget.prototype.getIsInteger = OO.ui.NumberInputWidget.prototype.getAllowInteger;
6862
6863 /**
6864 * Set the range of allowed values
6865 *
6866 * @param {number} min Minimum allowed value
6867 * @param {number} max Maximum allowed value
6868 */
6869 OO.ui.NumberInputWidget.prototype.setRange = function ( min, max ) {
6870 if ( min > max ) {
6871 throw new Error( 'Minimum (' + min + ') must not be greater than maximum (' + max + ')' );
6872 }
6873 this.min = min;
6874 this.max = max;
6875 this.setValidityFlag();
6876 };
6877
6878 /**
6879 * Get the current range
6880 *
6881 * @return {number[]} Minimum and maximum values
6882 */
6883 OO.ui.NumberInputWidget.prototype.getRange = function () {
6884 return [ this.min, this.max ];
6885 };
6886
6887 /**
6888 * Set the stepping deltas
6889 *
6890 * @param {number} step Normal step
6891 * @param {number|null} pageStep Page step. If null, 10 * step will be used.
6892 */
6893 OO.ui.NumberInputWidget.prototype.setStep = function ( step, pageStep ) {
6894 if ( step <= 0 ) {
6895 throw new Error( 'Step value must be positive' );
6896 }
6897 if ( pageStep === null ) {
6898 pageStep = step * 10;
6899 } else if ( pageStep <= 0 ) {
6900 throw new Error( 'Page step value must be positive' );
6901 }
6902 this.step = step;
6903 this.pageStep = pageStep;
6904 };
6905
6906 /**
6907 * Get the current stepping values
6908 *
6909 * @return {number[]} Step and page step
6910 */
6911 OO.ui.NumberInputWidget.prototype.getStep = function () {
6912 return [ this.step, this.pageStep ];
6913 };
6914
6915 /**
6916 * Get the current value of the widget as a number
6917 *
6918 * @return {number} May be NaN, or an invalid number
6919 */
6920 OO.ui.NumberInputWidget.prototype.getNumericValue = function () {
6921 return +this.getValue();
6922 };
6923
6924 /**
6925 * Adjust the value of the widget
6926 *
6927 * @param {number} delta Adjustment amount
6928 */
6929 OO.ui.NumberInputWidget.prototype.adjustValue = function ( delta ) {
6930 var n, v = this.getNumericValue();
6931
6932 delta = +delta;
6933 if ( isNaN( delta ) || !isFinite( delta ) ) {
6934 throw new Error( 'Delta must be a finite number' );
6935 }
6936
6937 if ( isNaN( v ) ) {
6938 n = 0;
6939 } else {
6940 n = v + delta;
6941 n = Math.max( Math.min( n, this.max ), this.min );
6942 if ( this.allowInteger ) {
6943 n = Math.round( n );
6944 }
6945 }
6946
6947 if ( n !== v ) {
6948 this.setValue( n );
6949 }
6950 };
6951 /**
6952 * Validate input
6953 *
6954 * @private
6955 * @param {string} value Field value
6956 * @return {boolean}
6957 */
6958 OO.ui.NumberInputWidget.prototype.validateNumber = function ( value ) {
6959 var n = +value;
6960 if ( value === '' ) {
6961 return !this.isRequired();
6962 }
6963
6964 if ( isNaN( n ) || !isFinite( n ) ) {
6965 return false;
6966 }
6967
6968 if ( this.allowInteger && Math.floor( n ) !== n ) {
6969 return false;
6970 }
6971
6972 if ( n < this.min || n > this.max ) {
6973 return false;
6974 }
6975
6976 return true;
6977 };
6978
6979 /**
6980 * Handle mouse click events.
6981 *
6982 * @private
6983 * @param {number} dir +1 or -1
6984 */
6985 OO.ui.NumberInputWidget.prototype.onButtonClick = function ( dir ) {
6986 this.adjustValue( dir * this.step );
6987 };
6988
6989 /**
6990 * Handle mouse wheel events.
6991 *
6992 * @private
6993 * @param {jQuery.Event} event
6994 */
6995 OO.ui.NumberInputWidget.prototype.onWheel = function ( event ) {
6996 var delta = 0;
6997
6998 if ( !this.isDisabled() && this.$input.is( ':focus' ) ) {
6999 // Standard 'wheel' event
7000 if ( event.originalEvent.deltaMode !== undefined ) {
7001 this.sawWheelEvent = true;
7002 }
7003 if ( event.originalEvent.deltaY ) {
7004 delta = -event.originalEvent.deltaY;
7005 } else if ( event.originalEvent.deltaX ) {
7006 delta = event.originalEvent.deltaX;
7007 }
7008
7009 // Non-standard events
7010 if ( !this.sawWheelEvent ) {
7011 if ( event.originalEvent.wheelDeltaX ) {
7012 delta = -event.originalEvent.wheelDeltaX;
7013 } else if ( event.originalEvent.wheelDeltaY ) {
7014 delta = event.originalEvent.wheelDeltaY;
7015 } else if ( event.originalEvent.wheelDelta ) {
7016 delta = event.originalEvent.wheelDelta;
7017 } else if ( event.originalEvent.detail ) {
7018 delta = -event.originalEvent.detail;
7019 }
7020 }
7021
7022 if ( delta ) {
7023 delta = delta < 0 ? -1 : 1;
7024 this.adjustValue( delta * this.step );
7025 }
7026
7027 return false;
7028 }
7029 };
7030
7031 /**
7032 * Handle key down events.
7033 *
7034 * @private
7035 * @param {jQuery.Event} e Key down event
7036 */
7037 OO.ui.NumberInputWidget.prototype.onKeyDown = function ( e ) {
7038 if ( !this.isDisabled() ) {
7039 switch ( e.which ) {
7040 case OO.ui.Keys.UP:
7041 this.adjustValue( this.step );
7042 return false;
7043 case OO.ui.Keys.DOWN:
7044 this.adjustValue( -this.step );
7045 return false;
7046 case OO.ui.Keys.PAGEUP:
7047 this.adjustValue( this.pageStep );
7048 return false;
7049 case OO.ui.Keys.PAGEDOWN:
7050 this.adjustValue( -this.pageStep );
7051 return false;
7052 }
7053 }
7054 };
7055
7056 /**
7057 * @inheritdoc
7058 */
7059 OO.ui.NumberInputWidget.prototype.setDisabled = function ( disabled ) {
7060 // Parent method
7061 OO.ui.NumberInputWidget.parent.prototype.setDisabled.call( this, disabled );
7062
7063 if ( this.minusButton ) {
7064 this.minusButton.setDisabled( this.isDisabled() );
7065 }
7066 if ( this.plusButton ) {
7067 this.plusButton.setDisabled( this.isDisabled() );
7068 }
7069
7070 return this;
7071 };
7072
7073 }( OO ) );
7074
7075 //# sourceMappingURL=oojs-ui-widgets.js.map