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