Merge "Increase Opera minimum for Grades A and C to 15"
[lhc/web/wiklou.git] / resources / lib / oojs-ui / oojs-ui-widgets.js
1 /*!
2 * OOjs UI v0.24.3
3 * https://www.mediawiki.org/wiki/OOjs_UI
4 *
5 * Copyright 2011–2017 OOjs UI Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
8 *
9 * Date: 2017-11-28T23:28:05Z
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 || 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 $overlay: this.$element
3787 }, config );
3788
3789 // Properties (must be set before mixin constructor calls)
3790 this.$handle = $( '<div>' );
3791 this.$input = config.popup ? null : $( '<input>' );
3792 if ( config.placeholder !== undefined && config.placeholder !== '' ) {
3793 this.$input.attr( 'placeholder', config.placeholder );
3794 }
3795
3796 // Mixin constructors
3797 OO.ui.mixin.GroupElement.call( this, config );
3798 if ( config.popup ) {
3799 config.popup = $.extend( {}, config.popup, {
3800 align: 'forwards',
3801 anchor: false
3802 } );
3803 OO.ui.mixin.PopupElement.call( this, config );
3804 $tabFocus = $( '<span>' );
3805 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: $tabFocus } ) );
3806 } else {
3807 this.popup = null;
3808 $tabFocus = null;
3809 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
3810 }
3811 OO.ui.mixin.IndicatorElement.call( this, config );
3812 OO.ui.mixin.IconElement.call( this, config );
3813
3814 // Properties
3815 this.$content = $( '<div>' );
3816 this.allowArbitrary = config.allowArbitrary;
3817 this.allowDuplicates = config.allowDuplicates;
3818 this.$overlay = config.$overlay;
3819 this.menu = new OO.ui.MenuSelectWidget( $.extend(
3820 {
3821 widget: this,
3822 $input: this.$input,
3823 $floatableContainer: this.$element,
3824 filterFromInput: true,
3825 disabled: this.isDisabled()
3826 },
3827 config.menu
3828 ) );
3829
3830 // Events
3831 if ( this.popup ) {
3832 $tabFocus.on( {
3833 focus: this.focus.bind( this )
3834 } );
3835 this.popup.$element.on( 'focusout', this.onPopupFocusOut.bind( this ) );
3836 if ( this.popup.$autoCloseIgnore ) {
3837 this.popup.$autoCloseIgnore.on( 'focusout', this.onPopupFocusOut.bind( this ) );
3838 }
3839 this.popup.connect( this, {
3840 toggle: function ( visible ) {
3841 $tabFocus.toggle( !visible );
3842 }
3843 } );
3844 } else {
3845 this.$input.on( {
3846 focus: this.onInputFocus.bind( this ),
3847 blur: this.onInputBlur.bind( this ),
3848 'propertychange change click mouseup keydown keyup input cut paste select focus':
3849 OO.ui.debounce( this.updateInputSize.bind( this ) ),
3850 keydown: this.onKeyDown.bind( this ),
3851 keypress: this.onKeyPress.bind( this )
3852 } );
3853 }
3854 this.menu.connect( this, {
3855 choose: 'onMenuChoose',
3856 toggle: 'onMenuToggle',
3857 add: 'onMenuItemsChange',
3858 remove: 'onMenuItemsChange'
3859 } );
3860 this.$handle.on( {
3861 mousedown: this.onMouseDown.bind( this )
3862 } );
3863
3864 // Initialization
3865 if ( this.$input ) {
3866 this.$input.prop( 'disabled', this.isDisabled() );
3867 this.$input.attr( {
3868 role: 'combobox',
3869 'aria-owns': this.menu.getElementId(),
3870 'aria-autocomplete': 'list'
3871 } );
3872 }
3873 if ( config.data ) {
3874 this.setItemsFromData( config.data );
3875 }
3876 this.$content.addClass( 'oo-ui-capsuleMultiselectWidget-content' )
3877 .append( this.$group );
3878 this.$group.addClass( 'oo-ui-capsuleMultiselectWidget-group' );
3879 this.$handle.addClass( 'oo-ui-capsuleMultiselectWidget-handle' )
3880 .append( this.$indicator, this.$icon, this.$content );
3881 this.$element.addClass( 'oo-ui-capsuleMultiselectWidget' )
3882 .append( this.$handle );
3883 if ( this.popup ) {
3884 this.popup.$element.addClass( 'oo-ui-capsuleMultiselectWidget-popup' );
3885 this.$content.append( $tabFocus );
3886 this.$overlay.append( this.popup.$element );
3887 } else {
3888 this.$content.append( this.$input );
3889 this.$overlay.append( this.menu.$element );
3890 }
3891 if ( $tabFocus ) {
3892 $tabFocus.addClass( 'oo-ui-capsuleMultiselectWidget-focusTrap' );
3893 }
3894
3895 // Input size needs to be calculated after everything else is rendered
3896 setTimeout( function () {
3897 if ( this.$input ) {
3898 this.updateInputSize();
3899 }
3900 }.bind( this ) );
3901
3902 this.onMenuItemsChange();
3903 };
3904
3905 /* Setup */
3906
3907 OO.inheritClass( OO.ui.CapsuleMultiselectWidget, OO.ui.Widget );
3908 OO.mixinClass( OO.ui.CapsuleMultiselectWidget, OO.ui.mixin.GroupElement );
3909 OO.mixinClass( OO.ui.CapsuleMultiselectWidget, OO.ui.mixin.PopupElement );
3910 OO.mixinClass( OO.ui.CapsuleMultiselectWidget, OO.ui.mixin.TabIndexedElement );
3911 OO.mixinClass( OO.ui.CapsuleMultiselectWidget, OO.ui.mixin.IndicatorElement );
3912 OO.mixinClass( OO.ui.CapsuleMultiselectWidget, OO.ui.mixin.IconElement );
3913
3914 /* Events */
3915
3916 /**
3917 * @event change
3918 *
3919 * A change event is emitted when the set of selected items changes.
3920 *
3921 * @param {Mixed[]} datas Data of the now-selected items
3922 */
3923
3924 /**
3925 * @event resize
3926 *
3927 * A resize event is emitted when the widget's dimensions change to accomodate newly added items or
3928 * current user input.
3929 */
3930
3931 /* Methods */
3932
3933 /**
3934 * Construct a OO.ui.CapsuleItemWidget (or a subclass thereof) from given label and data.
3935 * May return `null` if the given label and data are not valid.
3936 *
3937 * @protected
3938 * @param {Mixed} data Custom data of any type.
3939 * @param {string} label The label text.
3940 * @return {OO.ui.CapsuleItemWidget|null}
3941 */
3942 OO.ui.CapsuleMultiselectWidget.prototype.createItemWidget = function ( data, label ) {
3943 if ( label === '' ) {
3944 return null;
3945 }
3946 return new OO.ui.CapsuleItemWidget( { data: data, label: label } );
3947 };
3948
3949 /**
3950 * @inheritdoc
3951 */
3952 OO.ui.CapsuleMultiselectWidget.prototype.getInputId = function () {
3953 if ( !this.$input ) {
3954 return null;
3955 }
3956 return OO.ui.mixin.TabIndexedElement.prototype.getInputId.call( this );
3957 };
3958
3959 /**
3960 * Get the data of the items in the capsule
3961 *
3962 * @return {Mixed[]}
3963 */
3964 OO.ui.CapsuleMultiselectWidget.prototype.getItemsData = function () {
3965 return this.getItems().map( function ( item ) {
3966 return item.data;
3967 } );
3968 };
3969
3970 /**
3971 * Set the items in the capsule by providing data
3972 *
3973 * @chainable
3974 * @param {Mixed[]} datas
3975 * @return {OO.ui.CapsuleMultiselectWidget}
3976 */
3977 OO.ui.CapsuleMultiselectWidget.prototype.setItemsFromData = function ( datas ) {
3978 var widget = this,
3979 menu = this.menu,
3980 items = this.getItems();
3981
3982 $.each( datas, function ( i, data ) {
3983 var j, label,
3984 item = menu.getItemFromData( data );
3985
3986 if ( item ) {
3987 label = item.label;
3988 } else if ( widget.allowArbitrary ) {
3989 label = String( data );
3990 } else {
3991 return;
3992 }
3993
3994 item = null;
3995 for ( j = 0; j < items.length; j++ ) {
3996 if ( items[ j ].data === data && items[ j ].label === label ) {
3997 item = items[ j ];
3998 items.splice( j, 1 );
3999 break;
4000 }
4001 }
4002 if ( !item ) {
4003 item = widget.createItemWidget( data, label );
4004 }
4005 if ( item ) {
4006 widget.addItems( [ item ], i );
4007 }
4008 } );
4009
4010 if ( items.length ) {
4011 widget.removeItems( items );
4012 }
4013
4014 return this;
4015 };
4016
4017 /**
4018 * Add items to the capsule by providing their data
4019 *
4020 * @chainable
4021 * @param {Mixed[]} datas
4022 * @return {OO.ui.CapsuleMultiselectWidget}
4023 */
4024 OO.ui.CapsuleMultiselectWidget.prototype.addItemsFromData = function ( datas ) {
4025 var widget = this,
4026 menu = this.menu,
4027 items = [];
4028
4029 $.each( datas, function ( i, data ) {
4030 var item;
4031
4032 if ( !widget.getItemFromData( data ) || widget.allowDuplicates ) {
4033 item = menu.getItemFromData( data );
4034 if ( item ) {
4035 item = widget.createItemWidget( data, item.label );
4036 } else if ( widget.allowArbitrary ) {
4037 item = widget.createItemWidget( data, String( data ) );
4038 }
4039 if ( item ) {
4040 items.push( item );
4041 }
4042 }
4043 } );
4044
4045 if ( items.length ) {
4046 this.addItems( items );
4047 }
4048
4049 return this;
4050 };
4051
4052 /**
4053 * Add items to the capsule by providing a label
4054 *
4055 * @param {string} label
4056 * @return {boolean} Whether the item was added or not
4057 */
4058 OO.ui.CapsuleMultiselectWidget.prototype.addItemFromLabel = function ( label ) {
4059 var item, items;
4060 item = this.menu.getItemFromLabel( label, true );
4061 if ( item ) {
4062 this.addItemsFromData( [ item.data ] );
4063 return true;
4064 } else if ( this.allowArbitrary ) {
4065 items = this.getItems();
4066 this.addItemsFromData( [ label ] );
4067 return !OO.compare( this.getItems(), items );
4068 }
4069 return false;
4070 };
4071
4072 /**
4073 * Remove items by data
4074 *
4075 * @chainable
4076 * @param {Mixed[]} datas
4077 * @return {OO.ui.CapsuleMultiselectWidget}
4078 */
4079 OO.ui.CapsuleMultiselectWidget.prototype.removeItemsFromData = function ( datas ) {
4080 var widget = this,
4081 items = [];
4082
4083 $.each( datas, function ( i, data ) {
4084 var item = widget.getItemFromData( data );
4085 if ( item ) {
4086 items.push( item );
4087 }
4088 } );
4089
4090 if ( items.length ) {
4091 this.removeItems( items );
4092 }
4093
4094 return this;
4095 };
4096
4097 /**
4098 * @inheritdoc
4099 */
4100 OO.ui.CapsuleMultiselectWidget.prototype.addItems = function ( items ) {
4101 var same, i, l,
4102 oldItems = this.items.slice();
4103
4104 OO.ui.mixin.GroupElement.prototype.addItems.call( this, items );
4105
4106 if ( this.items.length !== oldItems.length ) {
4107 same = false;
4108 } else {
4109 same = true;
4110 for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
4111 same = same && this.items[ i ] === oldItems[ i ];
4112 }
4113 }
4114 if ( !same ) {
4115 this.emit( 'change', this.getItemsData() );
4116 this.updateInputSize();
4117 }
4118
4119 return this;
4120 };
4121
4122 /**
4123 * Removes the item from the list and copies its label to `this.$input`.
4124 *
4125 * @param {Object} item
4126 */
4127 OO.ui.CapsuleMultiselectWidget.prototype.editItem = function ( item ) {
4128 this.addItemFromLabel( this.$input.val() );
4129 this.clearInput();
4130 this.$input.val( item.label );
4131 this.updateInputSize();
4132 this.focus();
4133 this.menu.updateItemVisibility(); // Hack, we shouldn't be calling this method directly
4134 this.removeItems( [ item ] );
4135 };
4136
4137 /**
4138 * @inheritdoc
4139 */
4140 OO.ui.CapsuleMultiselectWidget.prototype.removeItems = function ( items ) {
4141 var same, i, l,
4142 oldItems = this.items.slice();
4143
4144 OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items );
4145
4146 if ( this.items.length !== oldItems.length ) {
4147 same = false;
4148 } else {
4149 same = true;
4150 for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
4151 same = same && this.items[ i ] === oldItems[ i ];
4152 }
4153 }
4154 if ( !same ) {
4155 this.emit( 'change', this.getItemsData() );
4156 this.updateInputSize();
4157 }
4158
4159 return this;
4160 };
4161
4162 /**
4163 * @inheritdoc
4164 */
4165 OO.ui.CapsuleMultiselectWidget.prototype.clearItems = function () {
4166 if ( this.items.length ) {
4167 OO.ui.mixin.GroupElement.prototype.clearItems.call( this );
4168 this.emit( 'change', this.getItemsData() );
4169 this.updateInputSize();
4170 }
4171 return this;
4172 };
4173
4174 /**
4175 * Given an item, returns the item after it. If its the last item,
4176 * returns `this.$input`. If no item is passed, returns the very first
4177 * item.
4178 *
4179 * @param {OO.ui.CapsuleItemWidget} [item]
4180 * @return {OO.ui.CapsuleItemWidget|jQuery|boolean}
4181 */
4182 OO.ui.CapsuleMultiselectWidget.prototype.getNextItem = function ( item ) {
4183 var itemIndex;
4184
4185 if ( item === undefined ) {
4186 return this.items[ 0 ];
4187 }
4188
4189 itemIndex = this.items.indexOf( item );
4190 if ( itemIndex < 0 ) { // Item not in list
4191 return false;
4192 } else if ( itemIndex === this.items.length - 1 ) { // Last item
4193 return this.$input;
4194 } else {
4195 return this.items[ itemIndex + 1 ];
4196 }
4197 };
4198
4199 /**
4200 * Given an item, returns the item before it. If its the first item,
4201 * returns `this.$input`. If no item is passed, returns the very last
4202 * item.
4203 *
4204 * @param {OO.ui.CapsuleItemWidget} [item]
4205 * @return {OO.ui.CapsuleItemWidget|jQuery|boolean}
4206 */
4207 OO.ui.CapsuleMultiselectWidget.prototype.getPreviousItem = function ( item ) {
4208 var itemIndex;
4209
4210 if ( item === undefined ) {
4211 return this.items[ this.items.length - 1 ];
4212 }
4213
4214 itemIndex = this.items.indexOf( item );
4215 if ( itemIndex < 0 ) { // Item not in list
4216 return false;
4217 } else if ( itemIndex === 0 ) { // First item
4218 return this.$input;
4219 } else {
4220 return this.items[ itemIndex - 1 ];
4221 }
4222 };
4223
4224 /**
4225 * Get the capsule widget's menu.
4226 *
4227 * @return {OO.ui.MenuSelectWidget} Menu widget
4228 */
4229 OO.ui.CapsuleMultiselectWidget.prototype.getMenu = function () {
4230 return this.menu;
4231 };
4232
4233 /**
4234 * Handle focus events
4235 *
4236 * @private
4237 * @param {jQuery.Event} event
4238 */
4239 OO.ui.CapsuleMultiselectWidget.prototype.onInputFocus = function () {
4240 if ( !this.isDisabled() ) {
4241 this.updateInputSize();
4242 this.menu.toggle( true );
4243 }
4244 };
4245
4246 /**
4247 * Handle blur events
4248 *
4249 * @private
4250 * @param {jQuery.Event} event
4251 */
4252 OO.ui.CapsuleMultiselectWidget.prototype.onInputBlur = function () {
4253 this.addItemFromLabel( this.$input.val() );
4254 this.clearInput();
4255 };
4256
4257 /**
4258 * Handles popup focus out events.
4259 *
4260 * @private
4261 * @param {jQuery.Event} e Focus out event
4262 */
4263 OO.ui.CapsuleMultiselectWidget.prototype.onPopupFocusOut = function () {
4264 var widget = this.popup;
4265
4266 setTimeout( function () {
4267 if (
4268 widget.isVisible() &&
4269 !OO.ui.contains( widget.$element.add( widget.$autoCloseIgnore ).get(), document.activeElement, true )
4270 ) {
4271 widget.toggle( false );
4272 }
4273 } );
4274 };
4275
4276 /**
4277 * Handle mouse down events.
4278 *
4279 * @private
4280 * @param {jQuery.Event} e Mouse down event
4281 */
4282 OO.ui.CapsuleMultiselectWidget.prototype.onMouseDown = function ( e ) {
4283 if ( e.which === OO.ui.MouseButtons.LEFT ) {
4284 this.focus();
4285 return false;
4286 } else {
4287 this.updateInputSize();
4288 }
4289 };
4290
4291 /**
4292 * Handle key press events.
4293 *
4294 * @private
4295 * @param {jQuery.Event} e Key press event
4296 */
4297 OO.ui.CapsuleMultiselectWidget.prototype.onKeyPress = function ( e ) {
4298 if ( !this.isDisabled() ) {
4299 if ( e.which === OO.ui.Keys.ESCAPE ) {
4300 this.clearInput();
4301 return false;
4302 }
4303
4304 if ( !this.popup ) {
4305 this.menu.toggle( true );
4306 if ( e.which === OO.ui.Keys.ENTER ) {
4307 if ( this.addItemFromLabel( this.$input.val() ) ) {
4308 this.clearInput();
4309 }
4310 return false;
4311 }
4312
4313 // Make sure the input gets resized.
4314 setTimeout( this.updateInputSize.bind( this ), 0 );
4315 }
4316 }
4317 };
4318
4319 /**
4320 * Handle key down events.
4321 *
4322 * @private
4323 * @param {jQuery.Event} e Key down event
4324 */
4325 OO.ui.CapsuleMultiselectWidget.prototype.onKeyDown = function ( e ) {
4326 if (
4327 !this.isDisabled() &&
4328 this.$input.val() === '' &&
4329 this.items.length
4330 ) {
4331 // 'keypress' event is not triggered for Backspace
4332 if ( e.keyCode === OO.ui.Keys.BACKSPACE ) {
4333 if ( e.metaKey || e.ctrlKey ) {
4334 this.removeItems( this.items.slice( -1 ) );
4335 } else {
4336 this.editItem( this.items[ this.items.length - 1 ] );
4337 }
4338 return false;
4339 } else if ( e.keyCode === OO.ui.Keys.LEFT ) {
4340 this.getPreviousItem().focus();
4341 } else if ( e.keyCode === OO.ui.Keys.RIGHT ) {
4342 this.getNextItem().focus();
4343 }
4344 }
4345 };
4346
4347 /**
4348 * Update the dimensions of the text input field to encompass all available area.
4349 *
4350 * @private
4351 * @param {jQuery.Event} e Event of some sort
4352 */
4353 OO.ui.CapsuleMultiselectWidget.prototype.updateInputSize = function () {
4354 var $lastItem, direction, contentWidth, currentWidth, bestWidth;
4355 if ( this.$input && !this.isDisabled() ) {
4356 this.$input.css( 'width', '1em' );
4357 $lastItem = this.$group.children().last();
4358 direction = OO.ui.Element.static.getDir( this.$handle );
4359
4360 // Get the width of the input with the placeholder text as
4361 // the value and save it so that we don't keep recalculating
4362 if (
4363 this.contentWidthWithPlaceholder === undefined &&
4364 this.$input.val() === '' &&
4365 this.$input.attr( 'placeholder' ) !== undefined
4366 ) {
4367 this.$input.val( this.$input.attr( 'placeholder' ) );
4368 this.contentWidthWithPlaceholder = this.$input[ 0 ].scrollWidth;
4369 this.$input.val( '' );
4370
4371 }
4372
4373 // Always keep the input wide enough for the placeholder text
4374 contentWidth = Math.max(
4375 this.$input[ 0 ].scrollWidth,
4376 // undefined arguments in Math.max lead to NaN
4377 ( this.contentWidthWithPlaceholder === undefined ) ?
4378 0 : this.contentWidthWithPlaceholder
4379 );
4380 currentWidth = this.$input.width();
4381
4382 if ( contentWidth < currentWidth ) {
4383 this.updateIfHeightChanged();
4384 // All is fine, don't perform expensive calculations
4385 return;
4386 }
4387
4388 if ( $lastItem.length === 0 ) {
4389 bestWidth = this.$content.innerWidth();
4390 } else {
4391 bestWidth = direction === 'ltr' ?
4392 this.$content.innerWidth() - $lastItem.position().left - $lastItem.outerWidth() :
4393 $lastItem.position().left;
4394 }
4395
4396 // Some safety margin for sanity, because I *really* don't feel like finding out where the few
4397 // pixels this is off by are coming from.
4398 bestWidth -= 10;
4399 if ( contentWidth > bestWidth ) {
4400 // This will result in the input getting shifted to the next line
4401 bestWidth = this.$content.innerWidth() - 10;
4402 }
4403 this.$input.width( Math.floor( bestWidth ) );
4404 this.updateIfHeightChanged();
4405 } else {
4406 this.updateIfHeightChanged();
4407 }
4408 };
4409
4410 /**
4411 * Determine if widget height changed, and if so, update menu position and emit 'resize' event.
4412 *
4413 * @private
4414 */
4415 OO.ui.CapsuleMultiselectWidget.prototype.updateIfHeightChanged = function () {
4416 var height = this.$element.height();
4417 if ( height !== this.height ) {
4418 this.height = height;
4419 this.menu.position();
4420 if ( this.popup ) {
4421 this.popup.updateDimensions();
4422 }
4423 this.emit( 'resize' );
4424 }
4425 };
4426
4427 /**
4428 * Handle menu choose events.
4429 *
4430 * @private
4431 * @param {OO.ui.OptionWidget} item Chosen item
4432 */
4433 OO.ui.CapsuleMultiselectWidget.prototype.onMenuChoose = function ( item ) {
4434 if ( item && item.isVisible() ) {
4435 this.addItemsFromData( [ item.getData() ] );
4436 this.clearInput();
4437 }
4438 };
4439
4440 /**
4441 * Handle menu toggle events.
4442 *
4443 * @private
4444 * @param {boolean} isVisible Open state of the menu
4445 */
4446 OO.ui.CapsuleMultiselectWidget.prototype.onMenuToggle = function ( isVisible ) {
4447 this.$element.toggleClass( 'oo-ui-capsuleMultiselectWidget-open', isVisible );
4448 };
4449
4450 /**
4451 * Handle menu item change events.
4452 *
4453 * @private
4454 */
4455 OO.ui.CapsuleMultiselectWidget.prototype.onMenuItemsChange = function () {
4456 this.setItemsFromData( this.getItemsData() );
4457 this.$element.toggleClass( 'oo-ui-capsuleMultiselectWidget-empty', this.menu.isEmpty() );
4458 };
4459
4460 /**
4461 * Clear the input field
4462 *
4463 * @private
4464 */
4465 OO.ui.CapsuleMultiselectWidget.prototype.clearInput = function () {
4466 if ( this.$input ) {
4467 this.$input.val( '' );
4468 this.updateInputSize();
4469 }
4470 if ( this.popup ) {
4471 this.popup.toggle( false );
4472 }
4473 this.menu.toggle( false );
4474 this.menu.selectItem();
4475 this.menu.highlightItem();
4476 };
4477
4478 /**
4479 * @inheritdoc
4480 */
4481 OO.ui.CapsuleMultiselectWidget.prototype.setDisabled = function ( disabled ) {
4482 var i, len;
4483
4484 // Parent method
4485 OO.ui.CapsuleMultiselectWidget.parent.prototype.setDisabled.call( this, disabled );
4486
4487 if ( this.$input ) {
4488 this.$input.prop( 'disabled', this.isDisabled() );
4489 }
4490 if ( this.menu ) {
4491 this.menu.setDisabled( this.isDisabled() );
4492 }
4493 if ( this.popup ) {
4494 this.popup.setDisabled( this.isDisabled() );
4495 }
4496
4497 if ( this.items ) {
4498 for ( i = 0, len = this.items.length; i < len; i++ ) {
4499 this.items[ i ].updateDisabled();
4500 }
4501 }
4502
4503 return this;
4504 };
4505
4506 /**
4507 * Focus the widget
4508 *
4509 * @chainable
4510 */
4511 OO.ui.CapsuleMultiselectWidget.prototype.focus = function () {
4512 if ( !this.isDisabled() ) {
4513 if ( this.popup ) {
4514 this.popup.setSize( this.$handle.outerWidth() );
4515 this.popup.toggle( true );
4516 OO.ui.findFocusable( this.popup.$element ).focus();
4517 } else {
4518 OO.ui.mixin.TabIndexedElement.prototype.focus.call( this );
4519 }
4520 }
4521 return this;
4522 };
4523
4524 /**
4525 * TagItemWidgets are used within a {@link OO.ui.TagMultiselectWidget
4526 * TagMultiselectWidget} to display the selected items.
4527 *
4528 * @class
4529 * @extends OO.ui.Widget
4530 * @mixins OO.ui.mixin.ItemWidget
4531 * @mixins OO.ui.mixin.LabelElement
4532 * @mixins OO.ui.mixin.FlaggedElement
4533 * @mixins OO.ui.mixin.TabIndexedElement
4534 * @mixins OO.ui.mixin.DraggableElement
4535 *
4536 * @constructor
4537 * @param {Object} [config] Configuration object
4538 * @cfg {boolean} [valid=true] Item is valid
4539 */
4540 OO.ui.TagItemWidget = function OoUiTagItemWidget( config ) {
4541 config = config || {};
4542
4543 // Parent constructor
4544 OO.ui.TagItemWidget.parent.call( this, config );
4545
4546 // Mixin constructors
4547 OO.ui.mixin.ItemWidget.call( this );
4548 OO.ui.mixin.LabelElement.call( this, config );
4549 OO.ui.mixin.FlaggedElement.call( this, config );
4550 OO.ui.mixin.TabIndexedElement.call( this, config );
4551 OO.ui.mixin.DraggableElement.call( this, config );
4552
4553 this.valid = config.valid === undefined ? true : !!config.valid;
4554
4555 this.closeButton = new OO.ui.ButtonWidget( {
4556 framed: false,
4557 icon: 'close',
4558 tabIndex: -1,
4559 title: OO.ui.msg( 'ooui-item-remove' )
4560 } );
4561 this.closeButton.setDisabled( this.isDisabled() );
4562
4563 // Events
4564 this.closeButton
4565 .connect( this, { click: 'remove' } );
4566 this.$element
4567 .on( 'click', this.select.bind( this ) )
4568 .on( 'keydown', this.onKeyDown.bind( this ) )
4569 // Prevent propagation of mousedown; the tag item "lives" in the
4570 // clickable area of the TagMultiselectWidget, which listens to
4571 // mousedown to open the menu or popup. We want to prevent that
4572 // for clicks specifically on the tag itself, so the actions taken
4573 // are more deliberate. When the tag is clicked, it will emit the
4574 // selection event (similar to how #OO.ui.MultioptionWidget emits 'change')
4575 // and can be handled separately.
4576 .on( 'mousedown', function ( e ) { e.stopPropagation(); } );
4577
4578 // Initialization
4579 this.$element
4580 .addClass( 'oo-ui-tagItemWidget' )
4581 .append( this.$label, this.closeButton.$element );
4582 };
4583
4584 /* Initialization */
4585
4586 OO.inheritClass( OO.ui.TagItemWidget, OO.ui.Widget );
4587 OO.mixinClass( OO.ui.TagItemWidget, OO.ui.mixin.ItemWidget );
4588 OO.mixinClass( OO.ui.TagItemWidget, OO.ui.mixin.LabelElement );
4589 OO.mixinClass( OO.ui.TagItemWidget, OO.ui.mixin.FlaggedElement );
4590 OO.mixinClass( OO.ui.TagItemWidget, OO.ui.mixin.TabIndexedElement );
4591 OO.mixinClass( OO.ui.TagItemWidget, OO.ui.mixin.DraggableElement );
4592
4593 /* Events */
4594
4595 /**
4596 * @event remove
4597 *
4598 * A remove action was performed on the item
4599 */
4600
4601 /**
4602 * @event navigate
4603 * @param {string} direction Direction of the movement, forward or backwards
4604 *
4605 * A navigate action was performed on the item
4606 */
4607
4608 /**
4609 * @event select
4610 *
4611 * The tag widget was selected. This can occur when the widget
4612 * is either clicked or enter was pressed on it.
4613 */
4614
4615 /**
4616 * @event valid
4617 * @param {boolean} isValid Item is valid
4618 *
4619 * Item validity has changed
4620 */
4621
4622 /* Methods */
4623
4624 /**
4625 * @inheritdoc
4626 */
4627 OO.ui.TagItemWidget.prototype.setDisabled = function ( state ) {
4628 // Parent method
4629 OO.ui.TagItemWidget.parent.prototype.setDisabled.call( this, state );
4630
4631 if ( this.closeButton ) {
4632 this.closeButton.setDisabled( state );
4633 }
4634 return this;
4635 };
4636
4637 /**
4638 * Handle removal of the item
4639 *
4640 * This is mainly for extensibility concerns, so other children
4641 * of this class can change the behavior if they need to. This
4642 * is called by both clicking the 'remove' button but also
4643 * on keypress, which is harder to override if needed.
4644 *
4645 * @fires remove
4646 */
4647 OO.ui.TagItemWidget.prototype.remove = function () {
4648 if ( !this.isDisabled() ) {
4649 this.emit( 'remove' );
4650 }
4651 };
4652
4653 /**
4654 * Handle a keydown event on the widget
4655 *
4656 * @fires navigate
4657 * @fires remove
4658 * @param {jQuery.Event} e Key down event
4659 * @return {boolean|undefined} false to stop the operation
4660 */
4661 OO.ui.TagItemWidget.prototype.onKeyDown = function ( e ) {
4662 var movement;
4663
4664 if ( e.keyCode === OO.ui.Keys.BACKSPACE || e.keyCode === OO.ui.Keys.DELETE ) {
4665 this.remove();
4666 return false;
4667 } else if ( e.keyCode === OO.ui.Keys.ENTER ) {
4668 this.select();
4669 return false;
4670 } else if (
4671 e.keyCode === OO.ui.Keys.LEFT ||
4672 e.keyCode === OO.ui.Keys.RIGHT
4673 ) {
4674 if ( OO.ui.Element.static.getDir( this.$element ) === 'rtl' ) {
4675 movement = {
4676 left: 'forwards',
4677 right: 'backwards'
4678 };
4679 } else {
4680 movement = {
4681 left: 'backwards',
4682 right: 'forwards'
4683 };
4684 }
4685
4686 this.emit(
4687 'navigate',
4688 e.keyCode === OO.ui.Keys.LEFT ?
4689 movement.left : movement.right
4690 );
4691 }
4692 };
4693
4694 /**
4695 * Select this item
4696 *
4697 * @fires select
4698 */
4699 OO.ui.TagItemWidget.prototype.select = function () {
4700 if ( !this.isDisabled() ) {
4701 this.emit( 'select' );
4702 }
4703 };
4704
4705 /**
4706 * Set the valid state of this item
4707 *
4708 * @param {boolean} [valid] Item is valid
4709 * @fires valid
4710 */
4711 OO.ui.TagItemWidget.prototype.toggleValid = function ( valid ) {
4712 valid = valid === undefined ? !this.valid : !!valid;
4713
4714 if ( this.valid !== valid ) {
4715 this.valid = valid;
4716
4717 this.setFlags( { invalid: !this.valid } );
4718
4719 this.emit( 'valid', this.valid );
4720 }
4721 };
4722
4723 /**
4724 * Check whether the item is valid
4725 *
4726 * @return {boolean} Item is valid
4727 */
4728 OO.ui.TagItemWidget.prototype.isValid = function () {
4729 return this.valid;
4730 };
4731
4732 /**
4733 * A basic tag multiselect widget, similar in concept to {@link OO.ui.ComboBoxInputWidget combo box widget}
4734 * that allows the user to add multiple values that are displayed in a tag area.
4735 *
4736 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
4737 *
4738 * This widget is a base widget; see {@link OO.ui.MenuTagMultiselectWidget MenuTagMultiselectWidget} and
4739 * {@link OO.ui.PopupTagMultiselectWidget PopupTagMultiselectWidget} for the implementations that use
4740 * a menu and a popup respectively.
4741 *
4742 * @example
4743 * // Example: A basic TagMultiselectWidget.
4744 * var widget = new OO.ui.TagMultiselectWidget( {
4745 * inputPosition: 'outline',
4746 * allowedValues: [ 'Option 1', 'Option 2', 'Option 3' ],
4747 * selected: [ 'Option 1' ]
4748 * } );
4749 * $( 'body' ).append( widget.$element );
4750 *
4751 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
4752 *
4753 * @class
4754 * @extends OO.ui.Widget
4755 * @mixins OO.ui.mixin.GroupWidget
4756 * @mixins OO.ui.mixin.DraggableGroupElement
4757 * @mixins OO.ui.mixin.IndicatorElement
4758 * @mixins OO.ui.mixin.IconElement
4759 * @mixins OO.ui.mixin.TabIndexedElement
4760 * @mixins OO.ui.mixin.FlaggedElement
4761 *
4762 * @constructor
4763 * @param {Object} config Configuration object
4764 * @cfg {Object} [input] Configuration options for the input widget
4765 * @cfg {OO.ui.InputWidget} [inputWidget] An optional input widget. If given, it will
4766 * replace the input widget used in the TagMultiselectWidget. If not given,
4767 * TagMultiselectWidget creates its own.
4768 * @cfg {boolean} [inputPosition='inline'] Position of the input. Options are:
4769 * - inline: The input is invisible, but exists inside the tag list, so
4770 * the user types into the tag groups to add tags.
4771 * - outline: The input is underneath the tag area.
4772 * - none: No input supplied
4773 * @cfg {boolean} [allowEditTags=true] Allow editing of the tags by clicking them
4774 * @cfg {boolean} [allowArbitrary=false] Allow data items to be added even if
4775 * not present in the menu.
4776 * @cfg {Object[]} [allowedValues] An array representing the allowed items
4777 * by their datas.
4778 * @cfg {boolean} [allowDuplicates=false] Allow duplicate items to be added
4779 * @cfg {boolean} [allowDisplayInvalidTags=false] Allow the display of
4780 * invalid tags. These tags will display with an invalid state, and
4781 * the widget as a whole will have an invalid state if any invalid tags
4782 * are present.
4783 * @cfg {boolean} [allowReordering=true] Allow reordering of the items
4784 * @cfg {Object[]|String[]} [selected] A set of selected tags. If given,
4785 * these will appear in the tag list on initialization, as long as they
4786 * pass the validity tests.
4787 */
4788 OO.ui.TagMultiselectWidget = function OoUiTagMultiselectWidget( config ) {
4789 var inputEvents,
4790 rAF = window.requestAnimationFrame || setTimeout,
4791 widget = this,
4792 $tabFocus = $( '<span>' )
4793 .addClass( 'oo-ui-tagMultiselectWidget-focusTrap' );
4794
4795 config = config || {};
4796
4797 // Parent constructor
4798 OO.ui.TagMultiselectWidget.parent.call( this, config );
4799
4800 // Mixin constructors
4801 OO.ui.mixin.GroupWidget.call( this, config );
4802 OO.ui.mixin.IndicatorElement.call( this, config );
4803 OO.ui.mixin.IconElement.call( this, config );
4804 OO.ui.mixin.TabIndexedElement.call( this, config );
4805 OO.ui.mixin.FlaggedElement.call( this, config );
4806 OO.ui.mixin.DraggableGroupElement.call( this, config );
4807
4808 this.toggleDraggable(
4809 config.allowReordering === undefined ?
4810 true : !!config.allowReordering
4811 );
4812
4813 this.inputPosition =
4814 this.constructor.static.allowedInputPositions.indexOf( config.inputPosition ) > -1 ?
4815 config.inputPosition : 'inline';
4816 this.allowEditTags = config.allowEditTags === undefined ? true : !!config.allowEditTags;
4817 this.allowArbitrary = !!config.allowArbitrary;
4818 this.allowDuplicates = !!config.allowDuplicates;
4819 this.allowedValues = config.allowedValues || [];
4820 this.allowDisplayInvalidTags = config.allowDisplayInvalidTags;
4821 this.hasInput = this.inputPosition !== 'none';
4822 this.height = null;
4823 this.valid = true;
4824
4825 this.$content = $( '<div>' )
4826 .addClass( 'oo-ui-tagMultiselectWidget-content' );
4827 this.$handle = $( '<div>' )
4828 .addClass( 'oo-ui-tagMultiselectWidget-handle' )
4829 .append(
4830 this.$indicator,
4831 this.$icon,
4832 this.$content
4833 .append(
4834 this.$group
4835 .addClass( 'oo-ui-tagMultiselectWidget-group' )
4836 )
4837 );
4838
4839 // Events
4840 this.aggregate( {
4841 remove: 'itemRemove',
4842 navigate: 'itemNavigate',
4843 select: 'itemSelect'
4844 } );
4845 this.connect( this, {
4846 itemRemove: 'onTagRemove',
4847 itemSelect: 'onTagSelect',
4848 itemNavigate: 'onTagNavigate',
4849 change: 'onChangeTags'
4850 } );
4851 this.$handle.on( {
4852 mousedown: this.onMouseDown.bind( this )
4853 } );
4854
4855 // Initialize
4856 this.$element
4857 .addClass( 'oo-ui-tagMultiselectWidget' )
4858 .append( this.$handle );
4859
4860 if ( this.hasInput ) {
4861 if ( config.inputWidget ) {
4862 this.input = config.inputWidget;
4863 } else {
4864 this.input = new OO.ui.TextInputWidget( $.extend( {
4865 placeholder: config.placeholder,
4866 classes: [ 'oo-ui-tagMultiselectWidget-input' ]
4867 }, config.input ) );
4868 }
4869 this.input.setDisabled( this.isDisabled() );
4870
4871 inputEvents = {
4872 focus: this.onInputFocus.bind( this ),
4873 blur: this.onInputBlur.bind( this ),
4874 'propertychange change click mouseup keydown keyup input cut paste select focus':
4875 OO.ui.debounce( this.updateInputSize.bind( this ) ),
4876 keydown: this.onInputKeyDown.bind( this ),
4877 keypress: this.onInputKeyPress.bind( this )
4878 };
4879
4880 this.input.$input.on( inputEvents );
4881
4882 if ( this.inputPosition === 'outline' ) {
4883 // Override max-height for the input widget
4884 // in the case the widget is outline so it can
4885 // stretch all the way if the widet is wide
4886 this.input.$element.css( 'max-width', 'inherit' );
4887 this.$element
4888 .addClass( 'oo-ui-tagMultiselectWidget-outlined' )
4889 .append( this.input.$element );
4890 } else {
4891 this.$element.addClass( 'oo-ui-tagMultiselectWidget-inlined' );
4892 // HACK: When the widget is using 'inline' input, the
4893 // behavior needs to only use the $input itself
4894 // so we style and size it accordingly (otherwise
4895 // the styling and sizing can get very convoluted
4896 // when the wrapping divs and other elements)
4897 // We are taking advantage of still being able to
4898 // call the widget itself for operations like
4899 // .getValue() and setDisabled() and .focus() but
4900 // having only the $input attached to the DOM
4901 this.$content.append( this.input.$input );
4902 }
4903 } else {
4904 this.$content.append( $tabFocus );
4905 }
4906
4907 this.setTabIndexedElement(
4908 this.hasInput ?
4909 this.input.$input :
4910 $tabFocus
4911 );
4912
4913 if ( config.selected ) {
4914 this.setValue( config.selected );
4915 }
4916
4917 // HACK: Input size needs to be calculated after everything
4918 // else is rendered
4919 rAF( function () {
4920 if ( widget.hasInput ) {
4921 widget.updateInputSize();
4922 }
4923 } );
4924 };
4925
4926 /* Initialization */
4927
4928 OO.inheritClass( OO.ui.TagMultiselectWidget, OO.ui.Widget );
4929 OO.mixinClass( OO.ui.TagMultiselectWidget, OO.ui.mixin.GroupWidget );
4930 OO.mixinClass( OO.ui.TagMultiselectWidget, OO.ui.mixin.DraggableGroupElement );
4931 OO.mixinClass( OO.ui.TagMultiselectWidget, OO.ui.mixin.IndicatorElement );
4932 OO.mixinClass( OO.ui.TagMultiselectWidget, OO.ui.mixin.IconElement );
4933 OO.mixinClass( OO.ui.TagMultiselectWidget, OO.ui.mixin.TabIndexedElement );
4934 OO.mixinClass( OO.ui.TagMultiselectWidget, OO.ui.mixin.FlaggedElement );
4935
4936 /* Static properties */
4937
4938 /**
4939 * Allowed input positions.
4940 * - inline: The input is inside the tag list
4941 * - outline: The input is under the tag list
4942 * - none: There is no input
4943 *
4944 * @property {Array}
4945 */
4946 OO.ui.TagMultiselectWidget.static.allowedInputPositions = [ 'inline', 'outline', 'none' ];
4947
4948 /* Methods */
4949
4950 /**
4951 * Handle mouse down events.
4952 *
4953 * @private
4954 * @param {jQuery.Event} e Mouse down event
4955 * @return {boolean} False to prevent defaults
4956 */
4957 OO.ui.TagMultiselectWidget.prototype.onMouseDown = function ( e ) {
4958 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
4959 this.focus();
4960 return false;
4961 }
4962 };
4963
4964 /**
4965 * Handle key press events.
4966 *
4967 * @private
4968 * @param {jQuery.Event} e Key press event
4969 * @return {boolean} Whether to prevent defaults
4970 */
4971 OO.ui.TagMultiselectWidget.prototype.onInputKeyPress = function ( e ) {
4972 var stopOrContinue,
4973 withMetaKey = e.metaKey || e.ctrlKey;
4974
4975 if ( !this.isDisabled() ) {
4976 if ( e.which === OO.ui.Keys.ENTER ) {
4977 stopOrContinue = this.doInputEnter( e, withMetaKey );
4978 }
4979
4980 // Make sure the input gets resized.
4981 setTimeout( this.updateInputSize.bind( this ), 0 );
4982 return stopOrContinue;
4983 }
4984 };
4985
4986 /**
4987 * Handle key down events.
4988 *
4989 * @private
4990 * @param {jQuery.Event} e Key down event
4991 * @return {boolean}
4992 */
4993 OO.ui.TagMultiselectWidget.prototype.onInputKeyDown = function ( e ) {
4994 var movement, direction,
4995 withMetaKey = e.metaKey || e.ctrlKey;
4996
4997 if ( !this.isDisabled() ) {
4998 // 'keypress' event is not triggered for Backspace
4999 if ( e.keyCode === OO.ui.Keys.BACKSPACE ) {
5000 return this.doInputBackspace( e, withMetaKey );
5001 } else if ( e.keyCode === OO.ui.Keys.ESCAPE ) {
5002 return this.doInputEscape( e );
5003 } else if (
5004 e.keyCode === OO.ui.Keys.LEFT ||
5005 e.keyCode === OO.ui.Keys.RIGHT
5006 ) {
5007 if ( OO.ui.Element.static.getDir( this.$element ) === 'rtl' ) {
5008 movement = {
5009 left: 'forwards',
5010 right: 'backwards'
5011 };
5012 } else {
5013 movement = {
5014 left: 'backwards',
5015 right: 'forwards'
5016 };
5017 }
5018 direction = e.keyCode === OO.ui.Keys.LEFT ?
5019 movement.left : movement.right;
5020
5021 return this.doInputArrow( e, direction, withMetaKey );
5022 }
5023 }
5024 };
5025
5026 /**
5027 * Respond to input focus event
5028 */
5029 OO.ui.TagMultiselectWidget.prototype.onInputFocus = function () {
5030 this.$element.addClass( 'oo-ui-tagMultiselectWidget-focus' );
5031 };
5032
5033 /**
5034 * Respond to input blur event
5035 */
5036 OO.ui.TagMultiselectWidget.prototype.onInputBlur = function () {
5037 this.$element.removeClass( 'oo-ui-tagMultiselectWidget-focus' );
5038 };
5039
5040 /**
5041 * Perform an action after the enter key on the input
5042 *
5043 * @param {jQuery.Event} e Event data
5044 * @param {boolean} [withMetaKey] Whether this key was pressed with
5045 * a meta key like 'ctrl'
5046 * @return {boolean} Whether to prevent defaults
5047 */
5048 OO.ui.TagMultiselectWidget.prototype.doInputEnter = function () {
5049 this.addTagFromInput();
5050 return false;
5051 };
5052
5053 /**
5054 * Perform an action responding to the enter key on the input
5055 *
5056 * @param {jQuery.Event} e Event data
5057 * @param {boolean} [withMetaKey] Whether this key was pressed with
5058 * a meta key like 'ctrl'
5059 * @return {boolean} Whether to prevent defaults
5060 */
5061 OO.ui.TagMultiselectWidget.prototype.doInputBackspace = function ( e, withMetaKey ) {
5062 var items, item;
5063
5064 if (
5065 this.inputPosition === 'inline' &&
5066 this.input.getValue() === '' &&
5067 !this.isEmpty()
5068 ) {
5069 // Delete the last item
5070 items = this.getItems();
5071 item = items[ items.length - 1 ];
5072 this.removeItems( [ item ] );
5073 // If Ctrl/Cmd was pressed, delete item entirely.
5074 // Otherwise put it into the text field for editing.
5075 if ( !withMetaKey ) {
5076 this.input.setValue( item.getData() );
5077 }
5078
5079 return false;
5080 }
5081 };
5082
5083 /**
5084 * Perform an action after the escape key on the input
5085 *
5086 * @param {jQuery.Event} e Event data
5087 */
5088 OO.ui.TagMultiselectWidget.prototype.doInputEscape = function () {
5089 this.clearInput();
5090 };
5091
5092 /**
5093 * Perform an action after the arrow key on the input, select the previous
5094 * or next item from the input.
5095 * See #getPreviousItem and #getNextItem
5096 *
5097 * @param {jQuery.Event} e Event data
5098 * @param {string} direction Direction of the movement; forwards or backwards
5099 * @param {boolean} [withMetaKey] Whether this key was pressed with
5100 * a meta key like 'ctrl'
5101 */
5102 OO.ui.TagMultiselectWidget.prototype.doInputArrow = function ( e, direction ) {
5103 if (
5104 this.inputPosition === 'inline' &&
5105 !this.isEmpty()
5106 ) {
5107 if ( direction === 'backwards' ) {
5108 // Get previous item
5109 this.getPreviousItem().focus();
5110 } else {
5111 // Get next item
5112 this.getNextItem().focus();
5113 }
5114 }
5115 };
5116
5117 /**
5118 * Respond to item select event
5119 *
5120 * @param {OO.ui.TagItemWidget} item Selected item
5121 */
5122 OO.ui.TagMultiselectWidget.prototype.onTagSelect = function ( item ) {
5123 if ( this.hasInput && this.allowEditTags ) {
5124 if ( this.input.getValue() ) {
5125 this.addTagFromInput();
5126 }
5127 // 1. Get the label of the tag into the input
5128 this.input.setValue( item.getData() );
5129 // 2. Remove the tag
5130 this.removeItems( [ item ] );
5131 // 3. Focus the input
5132 this.focus();
5133 }
5134 };
5135
5136 /**
5137 * Respond to change event, where items were added, removed, or cleared.
5138 */
5139 OO.ui.TagMultiselectWidget.prototype.onChangeTags = function () {
5140 this.toggleValid( this.checkValidity() );
5141 if ( this.hasInput ) {
5142 this.updateInputSize();
5143 }
5144 this.updateIfHeightChanged();
5145 };
5146
5147 /**
5148 * @inheritdoc
5149 */
5150 OO.ui.TagMultiselectWidget.prototype.setDisabled = function ( isDisabled ) {
5151 // Parent method
5152 OO.ui.TagMultiselectWidget.parent.prototype.setDisabled.call( this, isDisabled );
5153
5154 if ( this.hasInput && this.input ) {
5155 this.input.setDisabled( !!isDisabled );
5156 }
5157
5158 if ( this.items ) {
5159 this.getItems().forEach( function ( item ) {
5160 item.setDisabled( !!isDisabled );
5161 } );
5162 }
5163 };
5164
5165 /**
5166 * Respond to tag remove event
5167 * @param {OO.ui.TagItemWidget} item Removed tag
5168 */
5169 OO.ui.TagMultiselectWidget.prototype.onTagRemove = function ( item ) {
5170 this.removeTagByData( item.getData() );
5171 };
5172
5173 /**
5174 * Respond to navigate event on the tag
5175 *
5176 * @param {OO.ui.TagItemWidget} item Removed tag
5177 * @param {string} direction Direction of movement; 'forwards' or 'backwards'
5178 */
5179 OO.ui.TagMultiselectWidget.prototype.onTagNavigate = function ( item, direction ) {
5180 if ( direction === 'forwards' ) {
5181 this.getNextItem( item ).focus();
5182 } else {
5183 this.getPreviousItem( item ).focus();
5184 }
5185 };
5186
5187 /**
5188 * Add tag from input value
5189 */
5190 OO.ui.TagMultiselectWidget.prototype.addTagFromInput = function () {
5191 var val = this.input.getValue(),
5192 isValid = this.isAllowedData( val );
5193
5194 if ( !val ) {
5195 return;
5196 }
5197
5198 if ( isValid || this.allowDisplayInvalidTags ) {
5199 this.addTag( val );
5200 this.clearInput();
5201 this.focus();
5202 }
5203 };
5204
5205 /**
5206 * Clear the input
5207 */
5208 OO.ui.TagMultiselectWidget.prototype.clearInput = function () {
5209 this.input.setValue( '' );
5210 };
5211
5212 /**
5213 * Check whether the given value is a duplicate of an existing
5214 * tag already in the list.
5215 *
5216 * @param {string|Object} data Requested value
5217 * @return {boolean} Value is duplicate
5218 */
5219 OO.ui.TagMultiselectWidget.prototype.isDuplicateData = function ( data ) {
5220 return !!this.getItemFromData( data );
5221 };
5222
5223 /**
5224 * Check whether a given value is allowed to be added
5225 *
5226 * @param {string|Object} data Requested value
5227 * @return {boolean} Value is allowed
5228 */
5229 OO.ui.TagMultiselectWidget.prototype.isAllowedData = function ( data ) {
5230 if (
5231 !this.allowDuplicates &&
5232 this.isDuplicateData( data )
5233 ) {
5234 return false;
5235 }
5236
5237 if ( this.allowArbitrary ) {
5238 return true;
5239 }
5240
5241 // Check with allowed values
5242 if (
5243 this.getAllowedValues().some( function ( value ) {
5244 return data === value;
5245 } )
5246 ) {
5247 return true;
5248 }
5249
5250 return false;
5251 };
5252
5253 /**
5254 * Get the allowed values list
5255 *
5256 * @return {string[]} Allowed data values
5257 */
5258 OO.ui.TagMultiselectWidget.prototype.getAllowedValues = function () {
5259 return this.allowedValues;
5260 };
5261
5262 /**
5263 * Add a value to the allowed values list
5264 *
5265 * @param {string} value Allowed data value
5266 */
5267 OO.ui.TagMultiselectWidget.prototype.addAllowedValue = function ( value ) {
5268 if ( this.allowedValues.indexOf( value ) === -1 ) {
5269 this.allowedValues.push( value );
5270 }
5271 };
5272
5273 /**
5274 * Get the datas of the currently selected items
5275 *
5276 * @return {string[]|Object[]} Datas of currently selected items
5277 */
5278 OO.ui.TagMultiselectWidget.prototype.getValue = function () {
5279 return this.getItems()
5280 .filter( function ( item ) {
5281 return item.isValid();
5282 } )
5283 .map( function ( item ) {
5284 return item.getData();
5285 } );
5286 };
5287
5288 /**
5289 * Set the value of this widget by datas.
5290 *
5291 * @param {string|string[]|Object|Object[]} valueObject An object representing the data
5292 * and label of the value. If the widget allows arbitrary values,
5293 * the items will be added as-is. Otherwise, the data value will
5294 * be checked against allowedValues.
5295 * This object must contain at least a data key. Example:
5296 * { data: 'foo', label: 'Foo item' }
5297 * For multiple items, use an array of objects. For example:
5298 * [
5299 * { data: 'foo', label: 'Foo item' },
5300 * { data: 'bar', label: 'Bar item' }
5301 * ]
5302 * Value can also be added with plaintext array, for example:
5303 * [ 'foo', 'bar', 'bla' ] or a single string, like 'foo'
5304 */
5305 OO.ui.TagMultiselectWidget.prototype.setValue = function ( valueObject ) {
5306 valueObject = Array.isArray( valueObject ) ? valueObject : [ valueObject ];
5307
5308 this.clearItems();
5309 valueObject.forEach( function ( obj ) {
5310 if ( typeof obj === 'string' ) {
5311 this.addTag( obj );
5312 } else {
5313 this.addTag( obj.data, obj.label );
5314 }
5315 }.bind( this ) );
5316 };
5317
5318 /**
5319 * Add tag to the display area
5320 *
5321 * @param {string|Object} data Tag data
5322 * @param {string} [label] Tag label. If no label is provided, the
5323 * stringified version of the data will be used instead.
5324 * @return {boolean} Item was added successfully
5325 */
5326 OO.ui.TagMultiselectWidget.prototype.addTag = function ( data, label ) {
5327 var newItemWidget,
5328 isValid = this.isAllowedData( data );
5329
5330 if ( isValid || this.allowDisplayInvalidTags ) {
5331 newItemWidget = this.createTagItemWidget( data, label );
5332 newItemWidget.toggleValid( isValid );
5333 this.addItems( [ newItemWidget ] );
5334 return true;
5335 }
5336 return false;
5337 };
5338
5339 /**
5340 * Remove tag by its data property.
5341 *
5342 * @param {string|Object} data Tag data
5343 */
5344 OO.ui.TagMultiselectWidget.prototype.removeTagByData = function ( data ) {
5345 var item = this.getItemFromData( data );
5346
5347 this.removeItems( [ item ] );
5348 };
5349
5350 /**
5351 * Construct a OO.ui.TagItemWidget (or a subclass thereof) from given label and data.
5352 *
5353 * @protected
5354 * @param {string} data Item data
5355 * @param {string} label The label text.
5356 * @return {OO.ui.TagItemWidget}
5357 */
5358 OO.ui.TagMultiselectWidget.prototype.createTagItemWidget = function ( data, label ) {
5359 label = label || data;
5360
5361 return new OO.ui.TagItemWidget( { data: data, label: label } );
5362 };
5363
5364 /**
5365 * Given an item, returns the item after it. If the item is already the
5366 * last item, return `this.input`. If no item is passed, returns the
5367 * very first item.
5368 *
5369 * @protected
5370 * @param {OO.ui.TagItemWidget} [item] Tag item
5371 * @return {OO.ui.Widget} The next widget available.
5372 */
5373 OO.ui.TagMultiselectWidget.prototype.getNextItem = function ( item ) {
5374 var itemIndex = this.items.indexOf( item );
5375
5376 if ( item === undefined || itemIndex === -1 ) {
5377 return this.items[ 0 ];
5378 }
5379
5380 if ( itemIndex === this.items.length - 1 ) { // Last item
5381 if ( this.hasInput ) {
5382 return this.input;
5383 } else {
5384 // Return first item
5385 return this.items[ 0 ];
5386 }
5387 } else {
5388 return this.items[ itemIndex + 1 ];
5389 }
5390 };
5391
5392 /**
5393 * Given an item, returns the item before it. If the item is already the
5394 * first item, return `this.input`. If no item is passed, returns the
5395 * very last item.
5396 *
5397 * @protected
5398 * @param {OO.ui.TagItemWidget} [item] Tag item
5399 * @return {OO.ui.Widget} The previous widget available.
5400 */
5401 OO.ui.TagMultiselectWidget.prototype.getPreviousItem = function ( item ) {
5402 var itemIndex = this.items.indexOf( item );
5403
5404 if ( item === undefined || itemIndex === -1 ) {
5405 return this.items[ this.items.length - 1 ];
5406 }
5407
5408 if ( itemIndex === 0 ) {
5409 if ( this.hasInput ) {
5410 return this.input;
5411 } else {
5412 // Return the last item
5413 return this.items[ this.items.length - 1 ];
5414 }
5415 } else {
5416 return this.items[ itemIndex - 1 ];
5417 }
5418 };
5419
5420 /**
5421 * Update the dimensions of the text input field to encompass all available area.
5422 * This is especially relevant for when the input is at the edge of a line
5423 * and should get smaller. The usual operation (as an inline-block with min-width)
5424 * does not work in that case, pushing the input downwards to the next line.
5425 *
5426 * @private
5427 */
5428 OO.ui.TagMultiselectWidget.prototype.updateInputSize = function () {
5429 var $lastItem, direction, contentWidth, currentWidth, bestWidth;
5430 if ( this.inputPosition === 'inline' && !this.isDisabled() ) {
5431 if ( this.input.$input[ 0 ].scrollWidth === 0 ) {
5432 // Input appears to be attached but not visible.
5433 // Don't attempt to adjust its size, because our measurements
5434 // are going to fail anyway.
5435 return;
5436 }
5437 this.input.$input.css( 'width', '1em' );
5438 $lastItem = this.$group.children().last();
5439 direction = OO.ui.Element.static.getDir( this.$handle );
5440
5441 // Get the width of the input with the placeholder text as
5442 // the value and save it so that we don't keep recalculating
5443 if (
5444 this.contentWidthWithPlaceholder === undefined &&
5445 this.input.getValue() === '' &&
5446 this.input.$input.attr( 'placeholder' ) !== undefined
5447 ) {
5448 this.input.setValue( this.input.$input.attr( 'placeholder' ) );
5449 this.contentWidthWithPlaceholder = this.input.$input[ 0 ].scrollWidth;
5450 this.input.setValue( '' );
5451
5452 }
5453
5454 // Always keep the input wide enough for the placeholder text
5455 contentWidth = Math.max(
5456 this.input.$input[ 0 ].scrollWidth,
5457 // undefined arguments in Math.max lead to NaN
5458 ( this.contentWidthWithPlaceholder === undefined ) ?
5459 0 : this.contentWidthWithPlaceholder
5460 );
5461 currentWidth = this.input.$input.width();
5462
5463 if ( contentWidth < currentWidth ) {
5464 this.updateIfHeightChanged();
5465 // All is fine, don't perform expensive calculations
5466 return;
5467 }
5468
5469 if ( $lastItem.length === 0 ) {
5470 bestWidth = this.$content.innerWidth();
5471 } else {
5472 bestWidth = direction === 'ltr' ?
5473 this.$content.innerWidth() - $lastItem.position().left - $lastItem.outerWidth() :
5474 $lastItem.position().left;
5475 }
5476
5477 // Some safety margin for sanity, because I *really* don't feel like finding out where the few
5478 // pixels this is off by are coming from.
5479 bestWidth -= 10;
5480 if ( contentWidth > bestWidth ) {
5481 // This will result in the input getting shifted to the next line
5482 bestWidth = this.$content.innerWidth() - 10;
5483 }
5484 this.input.$input.width( Math.floor( bestWidth ) );
5485 this.updateIfHeightChanged();
5486 } else {
5487 this.updateIfHeightChanged();
5488 }
5489 };
5490
5491 /**
5492 * Determine if widget height changed, and if so,
5493 * emit the resize event. This is useful for when there are either
5494 * menus or popups attached to the bottom of the widget, to allow
5495 * them to change their positioning in case the widget moved down
5496 * or up.
5497 *
5498 * @private
5499 */
5500 OO.ui.TagMultiselectWidget.prototype.updateIfHeightChanged = function () {
5501 var height = this.$element.height();
5502 if ( height !== this.height ) {
5503 this.height = height;
5504 this.emit( 'resize' );
5505 }
5506 };
5507
5508 /**
5509 * Check whether all items in the widget are valid
5510 *
5511 * @return {boolean} Widget is valid
5512 */
5513 OO.ui.TagMultiselectWidget.prototype.checkValidity = function () {
5514 return this.getItems().every( function ( item ) {
5515 return item.isValid();
5516 } );
5517 };
5518
5519 /**
5520 * Set the valid state of this item
5521 *
5522 * @param {boolean} [valid] Item is valid
5523 * @fires valid
5524 */
5525 OO.ui.TagMultiselectWidget.prototype.toggleValid = function ( valid ) {
5526 valid = valid === undefined ? !this.valid : !!valid;
5527
5528 if ( this.valid !== valid ) {
5529 this.valid = valid;
5530
5531 this.setFlags( { invalid: !this.valid } );
5532
5533 this.emit( 'valid', this.valid );
5534 }
5535 };
5536
5537 /**
5538 * Get the current valid state of the widget
5539 *
5540 * @return {boolean} Widget is valid
5541 */
5542 OO.ui.TagMultiselectWidget.prototype.isValid = function () {
5543 return this.valid;
5544 };
5545
5546 /**
5547 * PopupTagMultiselectWidget is a {@link OO.ui.TagMultiselectWidget OO.ui.TagMultiselectWidget} intended
5548 * to use a popup. The popup can be configured to have a default input to insert values into the widget.
5549 *
5550 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
5551 *
5552 * @example
5553 * // Example: A basic PopupTagMultiselectWidget.
5554 * var widget = new OO.ui.PopupTagMultiselectWidget();
5555 * $( 'body' ).append( widget.$element );
5556 *
5557 * // Example: A PopupTagMultiselectWidget with an external popup.
5558 * var popupInput = new OO.ui.TextInputWidget(),
5559 * widget = new OO.ui.PopupTagMultiselectWidget( {
5560 * popupInput: popupInput,
5561 * popup: {
5562 * $content: popupInput.$element
5563 * }
5564 * } );
5565 * $( 'body' ).append( widget.$element );
5566 *
5567 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
5568 *
5569 * @class
5570 * @extends OO.ui.TagMultiselectWidget
5571 * @mixins OO.ui.mixin.PopupElement
5572 *
5573 * @param {Object} config Configuration object
5574 * @cfg {jQuery} [$overlay] An overlay for the popup.
5575 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
5576 * @cfg {Object} [popup] Configuration options for the popup
5577 * @cfg {OO.ui.InputWidget} [popupInput] An input widget inside the popup that will be
5578 * focused when the popup is opened and will be used as replacement for the
5579 * general input in the widget.
5580 */
5581 OO.ui.PopupTagMultiselectWidget = function OoUiPopupTagMultiselectWidget( config ) {
5582 var defaultInput,
5583 defaultConfig = { popup: {} };
5584
5585 config = config || {};
5586
5587 // Parent constructor
5588 OO.ui.PopupTagMultiselectWidget.parent.call( this, $.extend( { inputPosition: 'none' }, config ) );
5589
5590 this.$overlay = config.$overlay || this.$element;
5591
5592 if ( !config.popup ) {
5593 // For the default base implementation, we give a popup
5594 // with an input widget inside it. For any other use cases
5595 // the popup needs to be populated externally and the
5596 // event handled to add tags separately and manually
5597 defaultInput = new OO.ui.TextInputWidget();
5598
5599 defaultConfig.popupInput = defaultInput;
5600 defaultConfig.popup.$content = defaultInput.$element;
5601
5602 this.$element.addClass( 'oo-ui-popupTagMultiselectWidget-defaultPopup' );
5603 }
5604
5605 // Add overlay, and add that to the autoCloseIgnore
5606 defaultConfig.popup.$overlay = this.$overlay;
5607 defaultConfig.popup.$autoCloseIgnore = this.hasInput ?
5608 this.input.$element.add( this.$overlay ) : this.$overlay;
5609
5610 // Allow extending any of the above
5611 config = $.extend( defaultConfig, config );
5612
5613 // Mixin constructors
5614 OO.ui.mixin.PopupElement.call( this, config );
5615
5616 if ( this.hasInput ) {
5617 this.input.$input.on( 'focus', this.popup.toggle.bind( this.popup, true ) );
5618 }
5619
5620 // Configuration options
5621 this.popupInput = config.popupInput;
5622 if ( this.popupInput ) {
5623 this.popupInput.connect( this, {
5624 enter: 'onPopupInputEnter'
5625 } );
5626 }
5627
5628 // Events
5629 this.on( 'resize', this.popup.updateDimensions.bind( this.popup ) );
5630 this.popup.connect( this, { toggle: 'onPopupToggle' } );
5631 this.$tabIndexed
5632 .on( 'focus', this.onFocus.bind( this ) );
5633
5634 // Initialize
5635 this.$element
5636 .append( this.popup.$element )
5637 .addClass( 'oo-ui-popupTagMultiselectWidget' );
5638 };
5639
5640 /* Initialization */
5641
5642 OO.inheritClass( OO.ui.PopupTagMultiselectWidget, OO.ui.TagMultiselectWidget );
5643 OO.mixinClass( OO.ui.PopupTagMultiselectWidget, OO.ui.mixin.PopupElement );
5644
5645 /* Methods */
5646
5647 /**
5648 * Focus event handler.
5649 *
5650 * @private
5651 */
5652 OO.ui.PopupTagMultiselectWidget.prototype.onFocus = function () {
5653 this.popup.toggle( true );
5654 };
5655
5656 /**
5657 * Respond to popup toggle event
5658 *
5659 * @param {boolean} isVisible Popup is visible
5660 */
5661 OO.ui.PopupTagMultiselectWidget.prototype.onPopupToggle = function ( isVisible ) {
5662 if ( isVisible && this.popupInput ) {
5663 this.popupInput.focus();
5664 }
5665 };
5666
5667 /**
5668 * Respond to popup input enter event
5669 */
5670 OO.ui.PopupTagMultiselectWidget.prototype.onPopupInputEnter = function () {
5671 if ( this.popupInput ) {
5672 this.addTagByPopupValue( this.popupInput.getValue() );
5673 this.popupInput.setValue( '' );
5674 }
5675 };
5676
5677 /**
5678 * @inheritdoc
5679 */
5680 OO.ui.PopupTagMultiselectWidget.prototype.onTagSelect = function ( item ) {
5681 if ( this.popupInput && this.allowEditTags ) {
5682 this.popupInput.setValue( item.getData() );
5683 this.removeItems( [ item ] );
5684
5685 this.popup.toggle( true );
5686 this.popupInput.focus();
5687 } else {
5688 // Parent
5689 OO.ui.PopupTagMultiselectWidget.parent.prototype.onTagSelect.call( this, item );
5690 }
5691 };
5692
5693 /**
5694 * Add a tag by the popup value.
5695 * Whatever is responsible for setting the value in the popup should call
5696 * this method to add a tag, or use the regular methods like #addTag or
5697 * #setValue directly.
5698 *
5699 * @param {string} data The value of item
5700 * @param {string} [label] The label of the tag. If not given, the data is used.
5701 */
5702 OO.ui.PopupTagMultiselectWidget.prototype.addTagByPopupValue = function ( data, label ) {
5703 this.addTag( data, label );
5704 };
5705
5706 /**
5707 * MenuTagMultiselectWidget is a {@link OO.ui.TagMultiselectWidget OO.ui.TagMultiselectWidget} intended
5708 * to use a menu of selectable options.
5709 *
5710 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
5711 *
5712 * @example
5713 * // Example: A basic MenuTagMultiselectWidget.
5714 * var widget = new OO.ui.MenuTagMultiselectWidget( {
5715 * inputPosition: 'outline',
5716 * options: [
5717 * { data: 'option1', label: 'Option 1' },
5718 * { data: 'option2', label: 'Option 2' },
5719 * { data: 'option3', label: 'Option 3' },
5720 * ],
5721 * selected: [ 'option1', 'option2' ]
5722 * } );
5723 * $( 'body' ).append( widget.$element );
5724 *
5725 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
5726 *
5727 * @class
5728 * @extends OO.ui.TagMultiselectWidget
5729 *
5730 * @constructor
5731 * @param {Object} [config] Configuration object
5732 * @cfg {Object} [menu] Configuration object for the menu widget
5733 * @cfg {jQuery} [$overlay] An overlay for the menu.
5734 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
5735 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
5736 */
5737 OO.ui.MenuTagMultiselectWidget = function OoUiMenuTagMultiselectWidget( config ) {
5738 config = config || {};
5739
5740 // Parent constructor
5741 OO.ui.MenuTagMultiselectWidget.parent.call( this, config );
5742
5743 this.$overlay = config.$overlay || this.$element;
5744
5745 this.menu = this.createMenuWidget( $.extend( {
5746 widget: this,
5747 input: this.hasInput ? this.input : null,
5748 $input: this.hasInput ? this.input.$input : null,
5749 filterFromInput: !!this.hasInput,
5750 $autoCloseIgnore: this.hasInput ?
5751 this.input.$element.add( this.$overlay ) : this.$overlay,
5752 $floatableContainer: this.hasInput && this.inputPosition === 'outline' ?
5753 this.input.$element : this.$element,
5754 $overlay: this.$overlay,
5755 disabled: this.isDisabled()
5756 }, config.menu ) );
5757 this.addOptions( config.options || [] );
5758
5759 // Events
5760 this.menu.connect( this, {
5761 choose: 'onMenuChoose',
5762 toggle: 'onMenuToggle'
5763 } );
5764 if ( this.hasInput ) {
5765 this.input.connect( this, { change: 'onInputChange' } );
5766 }
5767 this.connect( this, { resize: 'onResize' } );
5768
5769 // Initialization
5770 this.$overlay
5771 .append( this.menu.$element );
5772 this.$element
5773 .addClass( 'oo-ui-menuTagMultiselectWidget' );
5774 // TagMultiselectWidget already does this, but it doesn't work right because this.menu is not yet
5775 // set up while the parent constructor runs, and #getAllowedValues rejects everything.
5776 if ( config.selected ) {
5777 this.setValue( config.selected );
5778 }
5779 };
5780
5781 /* Initialization */
5782
5783 OO.inheritClass( OO.ui.MenuTagMultiselectWidget, OO.ui.TagMultiselectWidget );
5784
5785 /* Methods */
5786
5787 /**
5788 * Respond to resize event
5789 */
5790 OO.ui.MenuTagMultiselectWidget.prototype.onResize = function () {
5791 // Reposition the menu
5792 this.menu.position();
5793 };
5794
5795 /**
5796 * @inheritdoc
5797 */
5798 OO.ui.MenuTagMultiselectWidget.prototype.onInputFocus = function () {
5799 // Parent method
5800 OO.ui.MenuTagMultiselectWidget.parent.prototype.onInputFocus.call( this );
5801
5802 this.menu.toggle( true );
5803 };
5804
5805 /**
5806 * Respond to input change event
5807 */
5808 OO.ui.MenuTagMultiselectWidget.prototype.onInputChange = function () {
5809 this.menu.toggle( true );
5810 };
5811
5812 /**
5813 * Respond to menu choose event
5814 *
5815 * @param {OO.ui.OptionWidget} menuItem Chosen menu item
5816 */
5817 OO.ui.MenuTagMultiselectWidget.prototype.onMenuChoose = function ( menuItem ) {
5818 // Add tag
5819 this.addTag( menuItem.getData(), menuItem.getLabel() );
5820 };
5821
5822 /**
5823 * Respond to menu toggle event. Reset item highlights on hide.
5824 *
5825 * @param {boolean} isVisible The menu is visible
5826 */
5827 OO.ui.MenuTagMultiselectWidget.prototype.onMenuToggle = function ( isVisible ) {
5828 if ( !isVisible ) {
5829 this.menu.selectItem( null );
5830 this.menu.highlightItem( null );
5831 }
5832 };
5833
5834 /**
5835 * @inheritdoc
5836 */
5837 OO.ui.MenuTagMultiselectWidget.prototype.onTagSelect = function ( tagItem ) {
5838 var menuItem = this.menu.getItemFromData( tagItem.getData() );
5839 // Override the base behavior from TagMultiselectWidget; the base behavior
5840 // in TagMultiselectWidget is to remove the tag to edit it in the input,
5841 // but in our case, we want to utilize the menu selection behavior, and
5842 // definitely not remove the item.
5843
5844 // Select the menu item
5845 this.menu.selectItem( menuItem );
5846
5847 this.focus();
5848 };
5849
5850 /**
5851 * @inheritdoc
5852 */
5853 OO.ui.MenuTagMultiselectWidget.prototype.addTagFromInput = function () {
5854 var inputValue = this.input.getValue(),
5855 validated = false,
5856 highlightedItem = this.menu.findHighlightedItem(),
5857 item = this.menu.getItemFromData( inputValue );
5858
5859 // Override the parent method so we add from the menu
5860 // rather than directly from the input
5861
5862 // Look for a highlighted item first
5863 if ( highlightedItem ) {
5864 validated = this.addTag( highlightedItem.getData(), highlightedItem.getLabel() );
5865 } else if ( item ) {
5866 // Look for the element that fits the data
5867 validated = this.addTag( item.getData(), item.getLabel() );
5868 } else {
5869 // Otherwise, add the tag - the method will only add if the
5870 // tag is valid or if invalid tags are allowed
5871 validated = this.addTag( inputValue );
5872 }
5873
5874 if ( validated ) {
5875 this.clearInput();
5876 this.focus();
5877 }
5878 };
5879
5880 /**
5881 * Return the visible items in the menu. This is mainly used for when
5882 * the menu is filtering results.
5883 *
5884 * @return {OO.ui.MenuOptionWidget[]} Visible results
5885 */
5886 OO.ui.MenuTagMultiselectWidget.prototype.getMenuVisibleItems = function () {
5887 return this.menu.getItems().filter( function ( menuItem ) {
5888 return menuItem.isVisible();
5889 } );
5890 };
5891
5892 /**
5893 * Create the menu for this widget. This is in a separate method so that
5894 * child classes can override this without polluting the constructor with
5895 * unnecessary extra objects that will be overidden.
5896 *
5897 * @param {Object} menuConfig Configuration options
5898 * @return {OO.ui.MenuSelectWidget} Menu widget
5899 */
5900 OO.ui.MenuTagMultiselectWidget.prototype.createMenuWidget = function ( menuConfig ) {
5901 return new OO.ui.MenuSelectWidget( menuConfig );
5902 };
5903
5904 /**
5905 * Add options to the menu
5906 *
5907 * @param {Object[]} menuOptions Object defining options
5908 */
5909 OO.ui.MenuTagMultiselectWidget.prototype.addOptions = function ( menuOptions ) {
5910 var widget = this,
5911 items = menuOptions.map( function ( obj ) {
5912 return widget.createMenuOptionWidget( obj.data, obj.label );
5913 } );
5914
5915 this.menu.addItems( items );
5916 };
5917
5918 /**
5919 * Create a menu option widget.
5920 *
5921 * @param {string} data Item data
5922 * @param {string} [label] Item label
5923 * @return {OO.ui.OptionWidget} Option widget
5924 */
5925 OO.ui.MenuTagMultiselectWidget.prototype.createMenuOptionWidget = function ( data, label ) {
5926 return new OO.ui.MenuOptionWidget( {
5927 data: data,
5928 label: label || data
5929 } );
5930 };
5931
5932 /**
5933 * Get the menu
5934 *
5935 * @return {OO.ui.MenuSelectWidget} Menu
5936 */
5937 OO.ui.MenuTagMultiselectWidget.prototype.getMenu = function () {
5938 return this.menu;
5939 };
5940
5941 /**
5942 * Get the allowed values list
5943 *
5944 * @return {string[]} Allowed data values
5945 */
5946 OO.ui.MenuTagMultiselectWidget.prototype.getAllowedValues = function () {
5947 var menuDatas = [];
5948 if ( this.menu ) {
5949 // If the parent constructor is calling us, we're not ready yet, this.menu is not set up.
5950 menuDatas = this.menu.getItems().map( function ( menuItem ) {
5951 return menuItem.getData();
5952 } );
5953 }
5954 return this.allowedValues.concat( menuDatas );
5955 };
5956
5957 /**
5958 * SelectFileWidgets allow for selecting files, using the HTML5 File API. These
5959 * widgets can be configured with {@link OO.ui.mixin.IconElement icons} and {@link
5960 * OO.ui.mixin.IndicatorElement indicators}.
5961 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
5962 *
5963 * @example
5964 * // Example of a file select widget
5965 * var selectFile = new OO.ui.SelectFileWidget();
5966 * $( 'body' ).append( selectFile.$element );
5967 *
5968 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets
5969 *
5970 * @class
5971 * @extends OO.ui.Widget
5972 * @mixins OO.ui.mixin.IconElement
5973 * @mixins OO.ui.mixin.IndicatorElement
5974 * @mixins OO.ui.mixin.PendingElement
5975 * @mixins OO.ui.mixin.LabelElement
5976 *
5977 * @constructor
5978 * @param {Object} [config] Configuration options
5979 * @cfg {string[]|null} [accept=null] MIME types to accept. null accepts all types.
5980 * @cfg {string} [placeholder] Text to display when no file is selected.
5981 * @cfg {string} [notsupported] Text to display when file support is missing in the browser.
5982 * @cfg {boolean} [droppable=true] Whether to accept files by drag and drop.
5983 * @cfg {boolean} [showDropTarget=false] Whether to show a drop target. Requires droppable to be true.
5984 * @cfg {number} [thumbnailSizeLimit=20] File size limit in MiB above which to not try and show a
5985 * preview (for performance)
5986 */
5987 OO.ui.SelectFileWidget = function OoUiSelectFileWidget( config ) {
5988 var dragHandler;
5989
5990 // Configuration initialization
5991 config = $.extend( {
5992 accept: null,
5993 placeholder: OO.ui.msg( 'ooui-selectfile-placeholder' ),
5994 notsupported: OO.ui.msg( 'ooui-selectfile-not-supported' ),
5995 droppable: true,
5996 showDropTarget: false,
5997 thumbnailSizeLimit: 20
5998 }, config );
5999
6000 // Parent constructor
6001 OO.ui.SelectFileWidget.parent.call( this, config );
6002
6003 // Mixin constructors
6004 OO.ui.mixin.IconElement.call( this, config );
6005 OO.ui.mixin.IndicatorElement.call( this, config );
6006 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$info } ) );
6007 OO.ui.mixin.LabelElement.call( this, config );
6008
6009 // Properties
6010 this.$info = $( '<span>' );
6011 this.showDropTarget = config.showDropTarget;
6012 this.thumbnailSizeLimit = config.thumbnailSizeLimit;
6013 this.isSupported = this.constructor.static.isSupported();
6014 this.currentFile = null;
6015 if ( Array.isArray( config.accept ) ) {
6016 this.accept = config.accept;
6017 } else {
6018 this.accept = null;
6019 }
6020 this.placeholder = config.placeholder;
6021 this.notsupported = config.notsupported;
6022 this.onFileSelectedHandler = this.onFileSelected.bind( this );
6023
6024 this.selectButton = new OO.ui.ButtonWidget( {
6025 classes: [ 'oo-ui-selectFileWidget-selectButton' ],
6026 label: OO.ui.msg( 'ooui-selectfile-button-select' ),
6027 disabled: this.disabled || !this.isSupported
6028 } );
6029
6030 this.clearButton = new OO.ui.ButtonWidget( {
6031 classes: [ 'oo-ui-selectFileWidget-clearButton' ],
6032 framed: false,
6033 icon: 'close',
6034 disabled: this.disabled
6035 } );
6036
6037 // Events
6038 this.selectButton.$button.on( {
6039 keypress: this.onKeyPress.bind( this )
6040 } );
6041 this.clearButton.connect( this, {
6042 click: 'onClearClick'
6043 } );
6044 if ( config.droppable ) {
6045 dragHandler = this.onDragEnterOrOver.bind( this );
6046 this.$element.on( {
6047 dragenter: dragHandler,
6048 dragover: dragHandler,
6049 dragleave: this.onDragLeave.bind( this ),
6050 drop: this.onDrop.bind( this )
6051 } );
6052 }
6053
6054 // Initialization
6055 this.addInput();
6056 this.$label.addClass( 'oo-ui-selectFileWidget-label' );
6057 this.$info
6058 .addClass( 'oo-ui-selectFileWidget-info' )
6059 .append( this.$icon, this.$label, this.clearButton.$element, this.$indicator );
6060
6061 if ( config.droppable && config.showDropTarget ) {
6062 this.selectButton.setIcon( 'upload' );
6063 this.$thumbnail = $( '<div>' ).addClass( 'oo-ui-selectFileWidget-thumbnail' );
6064 this.setPendingElement( this.$thumbnail );
6065 this.$element
6066 .addClass( 'oo-ui-selectFileWidget-dropTarget oo-ui-selectFileWidget' )
6067 .on( {
6068 click: this.onDropTargetClick.bind( this )
6069 } )
6070 .append(
6071 this.$thumbnail,
6072 this.$info,
6073 this.selectButton.$element,
6074 $( '<span>' )
6075 .addClass( 'oo-ui-selectFileWidget-dropLabel' )
6076 .text( OO.ui.msg( 'ooui-selectfile-dragdrop-placeholder' ) )
6077 );
6078 } else {
6079 this.$element
6080 .addClass( 'oo-ui-selectFileWidget' )
6081 .append( this.$info, this.selectButton.$element );
6082 }
6083 this.updateUI();
6084 };
6085
6086 /* Setup */
6087
6088 OO.inheritClass( OO.ui.SelectFileWidget, OO.ui.Widget );
6089 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IconElement );
6090 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IndicatorElement );
6091 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.PendingElement );
6092 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.LabelElement );
6093
6094 /* Static Properties */
6095
6096 /**
6097 * Check if this widget is supported
6098 *
6099 * @static
6100 * @return {boolean}
6101 */
6102 OO.ui.SelectFileWidget.static.isSupported = function () {
6103 var $input;
6104 if ( OO.ui.SelectFileWidget.static.isSupportedCache === null ) {
6105 $input = $( '<input>' ).attr( 'type', 'file' );
6106 OO.ui.SelectFileWidget.static.isSupportedCache = $input[ 0 ].files !== undefined;
6107 }
6108 return OO.ui.SelectFileWidget.static.isSupportedCache;
6109 };
6110
6111 OO.ui.SelectFileWidget.static.isSupportedCache = null;
6112
6113 /* Events */
6114
6115 /**
6116 * @event change
6117 *
6118 * A change event is emitted when the on/off state of the toggle changes.
6119 *
6120 * @param {File|null} value New value
6121 */
6122
6123 /* Methods */
6124
6125 /**
6126 * Get the current value of the field
6127 *
6128 * @return {File|null}
6129 */
6130 OO.ui.SelectFileWidget.prototype.getValue = function () {
6131 return this.currentFile;
6132 };
6133
6134 /**
6135 * Set the current value of the field
6136 *
6137 * @param {File|null} file File to select
6138 */
6139 OO.ui.SelectFileWidget.prototype.setValue = function ( file ) {
6140 if ( this.currentFile !== file ) {
6141 this.currentFile = file;
6142 this.updateUI();
6143 this.emit( 'change', this.currentFile );
6144 }
6145 };
6146
6147 /**
6148 * Focus the widget.
6149 *
6150 * Focusses the select file button.
6151 *
6152 * @chainable
6153 */
6154 OO.ui.SelectFileWidget.prototype.focus = function () {
6155 this.selectButton.focus();
6156 return this;
6157 };
6158
6159 /**
6160 * Blur the widget.
6161 *
6162 * @chainable
6163 */
6164 OO.ui.SelectFileWidget.prototype.blur = function () {
6165 this.selectButton.blur();
6166 return this;
6167 };
6168
6169 /**
6170 * @inheritdoc
6171 */
6172 OO.ui.SelectFileWidget.prototype.simulateLabelClick = function () {
6173 this.focus();
6174 };
6175
6176 /**
6177 * Update the user interface when a file is selected or unselected
6178 *
6179 * @protected
6180 */
6181 OO.ui.SelectFileWidget.prototype.updateUI = function () {
6182 var $label;
6183 if ( !this.isSupported ) {
6184 this.$element.addClass( 'oo-ui-selectFileWidget-notsupported' );
6185 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
6186 this.setLabel( this.notsupported );
6187 } else {
6188 this.$element.addClass( 'oo-ui-selectFileWidget-supported' );
6189 if ( this.currentFile ) {
6190 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
6191 $label = $( [] );
6192 $label = $label.add(
6193 $( '<span>' )
6194 .addClass( 'oo-ui-selectFileWidget-fileName' )
6195 .text( this.currentFile.name )
6196 );
6197 this.setLabel( $label );
6198
6199 if ( this.showDropTarget ) {
6200 this.pushPending();
6201 this.loadAndGetImageUrl().done( function ( url ) {
6202 this.$thumbnail.css( 'background-image', 'url( ' + url + ' )' );
6203 }.bind( this ) ).fail( function () {
6204 this.$thumbnail.append(
6205 new OO.ui.IconWidget( {
6206 icon: 'attachment',
6207 classes: [ 'oo-ui-selectFileWidget-noThumbnail-icon' ]
6208 } ).$element
6209 );
6210 }.bind( this ) ).always( function () {
6211 this.popPending();
6212 }.bind( this ) );
6213 this.$element.off( 'click' );
6214 }
6215 } else {
6216 if ( this.showDropTarget ) {
6217 this.$element.off( 'click' );
6218 this.$element.on( {
6219 click: this.onDropTargetClick.bind( this )
6220 } );
6221 this.$thumbnail
6222 .empty()
6223 .css( 'background-image', '' );
6224 }
6225 this.$element.addClass( 'oo-ui-selectFileWidget-empty' );
6226 this.setLabel( this.placeholder );
6227 }
6228 }
6229 };
6230
6231 /**
6232 * If the selected file is an image, get its URL and load it.
6233 *
6234 * @return {jQuery.Promise} Promise resolves with the image URL after it has loaded
6235 */
6236 OO.ui.SelectFileWidget.prototype.loadAndGetImageUrl = function () {
6237 var deferred = $.Deferred(),
6238 file = this.currentFile,
6239 reader = new FileReader();
6240
6241 if (
6242 file &&
6243 ( OO.getProp( file, 'type' ) || '' ).indexOf( 'image/' ) === 0 &&
6244 file.size < this.thumbnailSizeLimit * 1024 * 1024
6245 ) {
6246 reader.onload = function ( event ) {
6247 var img = document.createElement( 'img' );
6248 img.addEventListener( 'load', function () {
6249 if (
6250 img.naturalWidth === 0 ||
6251 img.naturalHeight === 0 ||
6252 img.complete === false
6253 ) {
6254 deferred.reject();
6255 } else {
6256 deferred.resolve( event.target.result );
6257 }
6258 } );
6259 img.src = event.target.result;
6260 };
6261 reader.readAsDataURL( file );
6262 } else {
6263 deferred.reject();
6264 }
6265
6266 return deferred.promise();
6267 };
6268
6269 /**
6270 * Add the input to the widget
6271 *
6272 * @private
6273 */
6274 OO.ui.SelectFileWidget.prototype.addInput = function () {
6275 if ( this.$input ) {
6276 this.$input.remove();
6277 }
6278
6279 if ( !this.isSupported ) {
6280 this.$input = null;
6281 return;
6282 }
6283
6284 this.$input = $( '<input>' ).attr( 'type', 'file' );
6285 this.$input.on( 'change', this.onFileSelectedHandler );
6286 this.$input.on( 'click', function ( e ) {
6287 // Prevents dropTarget to get clicked which calls
6288 // a click on this input
6289 e.stopPropagation();
6290 } );
6291 this.$input.attr( {
6292 tabindex: -1
6293 } );
6294 if ( this.accept ) {
6295 this.$input.attr( 'accept', this.accept.join( ', ' ) );
6296 }
6297 this.selectButton.$button.append( this.$input );
6298 };
6299
6300 /**
6301 * Determine if we should accept this file
6302 *
6303 * @private
6304 * @param {string} mimeType File MIME type
6305 * @return {boolean}
6306 */
6307 OO.ui.SelectFileWidget.prototype.isAllowedType = function ( mimeType ) {
6308 var i, mimeTest;
6309
6310 if ( !this.accept || !mimeType ) {
6311 return true;
6312 }
6313
6314 for ( i = 0; i < this.accept.length; i++ ) {
6315 mimeTest = this.accept[ i ];
6316 if ( mimeTest === mimeType ) {
6317 return true;
6318 } else if ( mimeTest.substr( -2 ) === '/*' ) {
6319 mimeTest = mimeTest.substr( 0, mimeTest.length - 1 );
6320 if ( mimeType.substr( 0, mimeTest.length ) === mimeTest ) {
6321 return true;
6322 }
6323 }
6324 }
6325
6326 return false;
6327 };
6328
6329 /**
6330 * Handle file selection from the input
6331 *
6332 * @private
6333 * @param {jQuery.Event} e
6334 */
6335 OO.ui.SelectFileWidget.prototype.onFileSelected = function ( e ) {
6336 var file = OO.getProp( e.target, 'files', 0 ) || null;
6337
6338 if ( file && !this.isAllowedType( file.type ) ) {
6339 file = null;
6340 }
6341
6342 this.setValue( file );
6343 this.addInput();
6344 };
6345
6346 /**
6347 * Handle clear button click events.
6348 *
6349 * @private
6350 */
6351 OO.ui.SelectFileWidget.prototype.onClearClick = function () {
6352 this.setValue( null );
6353 return false;
6354 };
6355
6356 /**
6357 * Handle key press events.
6358 *
6359 * @private
6360 * @param {jQuery.Event} e Key press event
6361 */
6362 OO.ui.SelectFileWidget.prototype.onKeyPress = function ( e ) {
6363 if ( this.isSupported && !this.isDisabled() && this.$input &&
6364 ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
6365 ) {
6366 this.$input.click();
6367 return false;
6368 }
6369 };
6370
6371 /**
6372 * Handle drop target click events.
6373 *
6374 * @private
6375 * @param {jQuery.Event} e Key press event
6376 */
6377 OO.ui.SelectFileWidget.prototype.onDropTargetClick = function () {
6378 if ( this.isSupported && !this.isDisabled() && this.$input ) {
6379 this.$input.click();
6380 return false;
6381 }
6382 };
6383
6384 /**
6385 * Handle drag enter and over events
6386 *
6387 * @private
6388 * @param {jQuery.Event} e Drag event
6389 */
6390 OO.ui.SelectFileWidget.prototype.onDragEnterOrOver = function ( e ) {
6391 var itemOrFile,
6392 droppableFile = false,
6393 dt = e.originalEvent.dataTransfer;
6394
6395 e.preventDefault();
6396 e.stopPropagation();
6397
6398 if ( this.isDisabled() || !this.isSupported ) {
6399 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
6400 dt.dropEffect = 'none';
6401 return false;
6402 }
6403
6404 // DataTransferItem and File both have a type property, but in Chrome files
6405 // have no information at this point.
6406 itemOrFile = OO.getProp( dt, 'items', 0 ) || OO.getProp( dt, 'files', 0 );
6407 if ( itemOrFile ) {
6408 if ( this.isAllowedType( itemOrFile.type ) ) {
6409 droppableFile = true;
6410 }
6411 // dt.types is Array-like, but not an Array
6412 } else if ( Array.prototype.indexOf.call( OO.getProp( dt, 'types' ) || [], 'Files' ) !== -1 ) {
6413 // File information is not available at this point for security so just assume
6414 // it is acceptable for now.
6415 // https://bugzilla.mozilla.org/show_bug.cgi?id=640534
6416 droppableFile = true;
6417 }
6418
6419 this.$element.toggleClass( 'oo-ui-selectFileWidget-canDrop', droppableFile );
6420 if ( !droppableFile ) {
6421 dt.dropEffect = 'none';
6422 }
6423
6424 return false;
6425 };
6426
6427 /**
6428 * Handle drag leave events
6429 *
6430 * @private
6431 * @param {jQuery.Event} e Drag event
6432 */
6433 OO.ui.SelectFileWidget.prototype.onDragLeave = function () {
6434 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
6435 };
6436
6437 /**
6438 * Handle drop events
6439 *
6440 * @private
6441 * @param {jQuery.Event} e Drop event
6442 */
6443 OO.ui.SelectFileWidget.prototype.onDrop = function ( e ) {
6444 var file = null,
6445 dt = e.originalEvent.dataTransfer;
6446
6447 e.preventDefault();
6448 e.stopPropagation();
6449 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
6450
6451 if ( this.isDisabled() || !this.isSupported ) {
6452 return false;
6453 }
6454
6455 file = OO.getProp( dt, 'files', 0 );
6456 if ( file && !this.isAllowedType( file.type ) ) {
6457 file = null;
6458 }
6459 if ( file ) {
6460 this.setValue( file );
6461 }
6462
6463 return false;
6464 };
6465
6466 /**
6467 * @inheritdoc
6468 */
6469 OO.ui.SelectFileWidget.prototype.setDisabled = function ( disabled ) {
6470 OO.ui.SelectFileWidget.parent.prototype.setDisabled.call( this, disabled );
6471 if ( this.selectButton ) {
6472 this.selectButton.setDisabled( disabled );
6473 }
6474 if ( this.clearButton ) {
6475 this.clearButton.setDisabled( disabled );
6476 }
6477 return this;
6478 };
6479
6480 /**
6481 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
6482 * and a menu of search results, which is displayed beneath the query
6483 * field. Unlike {@link OO.ui.mixin.LookupElement lookup menus}, search result menus are always visible to the user.
6484 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
6485 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
6486 *
6487 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
6488 * the [OOjs UI demos][1] for an example.
6489 *
6490 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
6491 *
6492 * @class
6493 * @extends OO.ui.Widget
6494 *
6495 * @constructor
6496 * @param {Object} [config] Configuration options
6497 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
6498 * @cfg {string} [value] Initial query value
6499 */
6500 OO.ui.SearchWidget = function OoUiSearchWidget( config ) {
6501 // Configuration initialization
6502 config = config || {};
6503
6504 // Parent constructor
6505 OO.ui.SearchWidget.parent.call( this, config );
6506
6507 // Properties
6508 this.query = new OO.ui.TextInputWidget( {
6509 icon: 'search',
6510 placeholder: config.placeholder,
6511 value: config.value
6512 } );
6513 this.results = new OO.ui.SelectWidget();
6514 this.$query = $( '<div>' );
6515 this.$results = $( '<div>' );
6516
6517 // Events
6518 this.query.connect( this, {
6519 change: 'onQueryChange',
6520 enter: 'onQueryEnter'
6521 } );
6522 this.query.$input.on( 'keydown', this.onQueryKeydown.bind( this ) );
6523
6524 // Initialization
6525 this.$query
6526 .addClass( 'oo-ui-searchWidget-query' )
6527 .append( this.query.$element );
6528 this.$results
6529 .addClass( 'oo-ui-searchWidget-results' )
6530 .append( this.results.$element );
6531 this.$element
6532 .addClass( 'oo-ui-searchWidget' )
6533 .append( this.$results, this.$query );
6534 };
6535
6536 /* Setup */
6537
6538 OO.inheritClass( OO.ui.SearchWidget, OO.ui.Widget );
6539
6540 /* Methods */
6541
6542 /**
6543 * Handle query key down events.
6544 *
6545 * @private
6546 * @param {jQuery.Event} e Key down event
6547 */
6548 OO.ui.SearchWidget.prototype.onQueryKeydown = function ( e ) {
6549 var highlightedItem, nextItem,
6550 dir = e.which === OO.ui.Keys.DOWN ? 1 : ( e.which === OO.ui.Keys.UP ? -1 : 0 );
6551
6552 if ( dir ) {
6553 highlightedItem = this.results.findHighlightedItem();
6554 if ( !highlightedItem ) {
6555 highlightedItem = this.results.getSelectedItem();
6556 }
6557 nextItem = this.results.findRelativeSelectableItem( highlightedItem, dir );
6558 this.results.highlightItem( nextItem );
6559 nextItem.scrollElementIntoView();
6560 }
6561 };
6562
6563 /**
6564 * Handle select widget select events.
6565 *
6566 * Clears existing results. Subclasses should repopulate items according to new query.
6567 *
6568 * @private
6569 * @param {string} value New value
6570 */
6571 OO.ui.SearchWidget.prototype.onQueryChange = function () {
6572 // Reset
6573 this.results.clearItems();
6574 };
6575
6576 /**
6577 * Handle select widget enter key events.
6578 *
6579 * Chooses highlighted item.
6580 *
6581 * @private
6582 * @param {string} value New value
6583 */
6584 OO.ui.SearchWidget.prototype.onQueryEnter = function () {
6585 var highlightedItem = this.results.findHighlightedItem();
6586 if ( highlightedItem ) {
6587 this.results.chooseItem( highlightedItem );
6588 }
6589 };
6590
6591 /**
6592 * Get the query input.
6593 *
6594 * @return {OO.ui.TextInputWidget} Query input
6595 */
6596 OO.ui.SearchWidget.prototype.getQuery = function () {
6597 return this.query;
6598 };
6599
6600 /**
6601 * Get the search results menu.
6602 *
6603 * @return {OO.ui.SelectWidget} Menu of search results
6604 */
6605 OO.ui.SearchWidget.prototype.getResults = function () {
6606 return this.results;
6607 };
6608
6609 /**
6610 * NumberInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
6611 * can be entered manually) and two {@link OO.ui.ButtonWidget button widgets}
6612 * (to adjust the value in increments) to allow the user to enter a number.
6613 *
6614 * @example
6615 * // Example: A NumberInputWidget.
6616 * var numberInput = new OO.ui.NumberInputWidget( {
6617 * label: 'NumberInputWidget',
6618 * input: { value: 5 },
6619 * min: 1,
6620 * max: 10
6621 * } );
6622 * $( 'body' ).append( numberInput.$element );
6623 *
6624 * @class
6625 * @extends OO.ui.TextInputWidget
6626 *
6627 * @constructor
6628 * @param {Object} [config] Configuration options
6629 * @cfg {Object} [minusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget decrementing button widget}.
6630 * @cfg {Object} [plusButton] Configuration options to pass to the {@link OO.ui.ButtonWidget incrementing button widget}.
6631 * @cfg {boolean} [allowInteger=false] Whether the field accepts only integer values.
6632 * @cfg {number} [min=-Infinity] Minimum allowed value
6633 * @cfg {number} [max=Infinity] Maximum allowed value
6634 * @cfg {number} [step=1] Delta when using the buttons or up/down arrow keys
6635 * @cfg {number|null} [pageStep] Delta when using the page-up/page-down keys. Defaults to 10 times #step.
6636 * @cfg {boolean} [showButtons=true] Whether to show the plus and minus buttons.
6637 */
6638 OO.ui.NumberInputWidget = function OoUiNumberInputWidget( config ) {
6639 var $field = $( '<div>' )
6640 .addClass( 'oo-ui-numberInputWidget-field' );
6641
6642 // Configuration initialization
6643 config = $.extend( {
6644 allowInteger: false,
6645 min: -Infinity,
6646 max: Infinity,
6647 step: 1,
6648 pageStep: null,
6649 showButtons: true
6650 }, config );
6651
6652 // For backward compatibility
6653 $.extend( config, config.input );
6654 this.input = this;
6655
6656 // Parent constructor
6657 OO.ui.NumberInputWidget.parent.call( this, $.extend( config, {
6658 type: 'number'
6659 } ) );
6660
6661 if ( config.showButtons ) {
6662 this.minusButton = new OO.ui.ButtonWidget( $.extend(
6663 {
6664 disabled: this.isDisabled(),
6665 tabIndex: -1,
6666 classes: [ 'oo-ui-numberInputWidget-minusButton' ],
6667 icon: 'subtract'
6668 },
6669 config.minusButton
6670 ) );
6671 this.plusButton = new OO.ui.ButtonWidget( $.extend(
6672 {
6673 disabled: this.isDisabled(),
6674 tabIndex: -1,
6675 classes: [ 'oo-ui-numberInputWidget-plusButton' ],
6676 icon: 'add'
6677 },
6678 config.plusButton
6679 ) );
6680 }
6681
6682 // Events
6683 this.$input.on( {
6684 keydown: this.onKeyDown.bind( this ),
6685 'wheel mousewheel DOMMouseScroll': this.onWheel.bind( this )
6686 } );
6687 if ( config.showButtons ) {
6688 this.plusButton.connect( this, {
6689 click: [ 'onButtonClick', +1 ]
6690 } );
6691 this.minusButton.connect( this, {
6692 click: [ 'onButtonClick', -1 ]
6693 } );
6694 }
6695
6696 // Build the field
6697 $field.append( this.$input );
6698 if ( config.showButtons ) {
6699 $field
6700 .prepend( this.minusButton.$element )
6701 .append( this.plusButton.$element );
6702 }
6703
6704 // Initialization
6705 this.setAllowInteger( config.allowInteger || config.isInteger );
6706 this.setRange( config.min, config.max );
6707 this.setStep( config.step, config.pageStep );
6708 // Set the validation method after we set allowInteger and range
6709 // so that it doesn't immediately call setValidityFlag
6710 this.setValidation( this.validateNumber.bind( this ) );
6711
6712 this.$element
6713 .addClass( 'oo-ui-numberInputWidget' )
6714 .toggleClass( 'oo-ui-numberInputWidget-buttoned', config.showButtons )
6715 .append( $field );
6716 };
6717
6718 /* Setup */
6719
6720 OO.inheritClass( OO.ui.NumberInputWidget, OO.ui.TextInputWidget );
6721
6722 /* Methods */
6723
6724 /**
6725 * Set whether only integers are allowed
6726 *
6727 * @param {boolean} flag
6728 */
6729 OO.ui.NumberInputWidget.prototype.setAllowInteger = function ( flag ) {
6730 this.allowInteger = !!flag;
6731 this.setValidityFlag();
6732 };
6733 // Backward compatibility
6734 OO.ui.NumberInputWidget.prototype.setIsInteger = OO.ui.NumberInputWidget.prototype.setAllowInteger;
6735
6736 /**
6737 * Get whether only integers are allowed
6738 *
6739 * @return {boolean} Flag value
6740 */
6741 OO.ui.NumberInputWidget.prototype.getAllowInteger = function () {
6742 return this.allowInteger;
6743 };
6744 // Backward compatibility
6745 OO.ui.NumberInputWidget.prototype.getIsInteger = OO.ui.NumberInputWidget.prototype.getAllowInteger;
6746
6747 /**
6748 * Set the range of allowed values
6749 *
6750 * @param {number} min Minimum allowed value
6751 * @param {number} max Maximum allowed value
6752 */
6753 OO.ui.NumberInputWidget.prototype.setRange = function ( min, max ) {
6754 if ( min > max ) {
6755 throw new Error( 'Minimum (' + min + ') must not be greater than maximum (' + max + ')' );
6756 }
6757 this.min = min;
6758 this.max = max;
6759 this.setValidityFlag();
6760 };
6761
6762 /**
6763 * Get the current range
6764 *
6765 * @return {number[]} Minimum and maximum values
6766 */
6767 OO.ui.NumberInputWidget.prototype.getRange = function () {
6768 return [ this.min, this.max ];
6769 };
6770
6771 /**
6772 * Set the stepping deltas
6773 *
6774 * @param {number} step Normal step
6775 * @param {number|null} pageStep Page step. If null, 10 * step will be used.
6776 */
6777 OO.ui.NumberInputWidget.prototype.setStep = function ( step, pageStep ) {
6778 if ( step <= 0 ) {
6779 throw new Error( 'Step value must be positive' );
6780 }
6781 if ( pageStep === null ) {
6782 pageStep = step * 10;
6783 } else if ( pageStep <= 0 ) {
6784 throw new Error( 'Page step value must be positive' );
6785 }
6786 this.step = step;
6787 this.pageStep = pageStep;
6788 };
6789
6790 /**
6791 * Get the current stepping values
6792 *
6793 * @return {number[]} Step and page step
6794 */
6795 OO.ui.NumberInputWidget.prototype.getStep = function () {
6796 return [ this.step, this.pageStep ];
6797 };
6798
6799 /**
6800 * Get the current value of the widget as a number
6801 *
6802 * @return {number} May be NaN, or an invalid number
6803 */
6804 OO.ui.NumberInputWidget.prototype.getNumericValue = function () {
6805 return +this.getValue();
6806 };
6807
6808 /**
6809 * Adjust the value of the widget
6810 *
6811 * @param {number} delta Adjustment amount
6812 */
6813 OO.ui.NumberInputWidget.prototype.adjustValue = function ( delta ) {
6814 var n, v = this.getNumericValue();
6815
6816 delta = +delta;
6817 if ( isNaN( delta ) || !isFinite( delta ) ) {
6818 throw new Error( 'Delta must be a finite number' );
6819 }
6820
6821 if ( isNaN( v ) ) {
6822 n = 0;
6823 } else {
6824 n = v + delta;
6825 n = Math.max( Math.min( n, this.max ), this.min );
6826 if ( this.allowInteger ) {
6827 n = Math.round( n );
6828 }
6829 }
6830
6831 if ( n !== v ) {
6832 this.setValue( n );
6833 }
6834 };
6835 /**
6836 * Validate input
6837 *
6838 * @private
6839 * @param {string} value Field value
6840 * @return {boolean}
6841 */
6842 OO.ui.NumberInputWidget.prototype.validateNumber = function ( value ) {
6843 var n = +value;
6844 if ( value === '' ) {
6845 return !this.isRequired();
6846 }
6847
6848 if ( isNaN( n ) || !isFinite( n ) ) {
6849 return false;
6850 }
6851
6852 if ( this.allowInteger && Math.floor( n ) !== n ) {
6853 return false;
6854 }
6855
6856 if ( n < this.min || n > this.max ) {
6857 return false;
6858 }
6859
6860 return true;
6861 };
6862
6863 /**
6864 * Handle mouse click events.
6865 *
6866 * @private
6867 * @param {number} dir +1 or -1
6868 */
6869 OO.ui.NumberInputWidget.prototype.onButtonClick = function ( dir ) {
6870 this.adjustValue( dir * this.step );
6871 };
6872
6873 /**
6874 * Handle mouse wheel events.
6875 *
6876 * @private
6877 * @param {jQuery.Event} event
6878 */
6879 OO.ui.NumberInputWidget.prototype.onWheel = function ( event ) {
6880 var delta = 0;
6881
6882 if ( !this.isDisabled() && this.$input.is( ':focus' ) ) {
6883 // Standard 'wheel' event
6884 if ( event.originalEvent.deltaMode !== undefined ) {
6885 this.sawWheelEvent = true;
6886 }
6887 if ( event.originalEvent.deltaY ) {
6888 delta = -event.originalEvent.deltaY;
6889 } else if ( event.originalEvent.deltaX ) {
6890 delta = event.originalEvent.deltaX;
6891 }
6892
6893 // Non-standard events
6894 if ( !this.sawWheelEvent ) {
6895 if ( event.originalEvent.wheelDeltaX ) {
6896 delta = -event.originalEvent.wheelDeltaX;
6897 } else if ( event.originalEvent.wheelDeltaY ) {
6898 delta = event.originalEvent.wheelDeltaY;
6899 } else if ( event.originalEvent.wheelDelta ) {
6900 delta = event.originalEvent.wheelDelta;
6901 } else if ( event.originalEvent.detail ) {
6902 delta = -event.originalEvent.detail;
6903 }
6904 }
6905
6906 if ( delta ) {
6907 delta = delta < 0 ? -1 : 1;
6908 this.adjustValue( delta * this.step );
6909 }
6910
6911 return false;
6912 }
6913 };
6914
6915 /**
6916 * Handle key down events.
6917 *
6918 * @private
6919 * @param {jQuery.Event} e Key down event
6920 */
6921 OO.ui.NumberInputWidget.prototype.onKeyDown = function ( e ) {
6922 if ( !this.isDisabled() ) {
6923 switch ( e.which ) {
6924 case OO.ui.Keys.UP:
6925 this.adjustValue( this.step );
6926 return false;
6927 case OO.ui.Keys.DOWN:
6928 this.adjustValue( -this.step );
6929 return false;
6930 case OO.ui.Keys.PAGEUP:
6931 this.adjustValue( this.pageStep );
6932 return false;
6933 case OO.ui.Keys.PAGEDOWN:
6934 this.adjustValue( -this.pageStep );
6935 return false;
6936 }
6937 }
6938 };
6939
6940 /**
6941 * @inheritdoc
6942 */
6943 OO.ui.NumberInputWidget.prototype.setDisabled = function ( disabled ) {
6944 // Parent method
6945 OO.ui.NumberInputWidget.parent.prototype.setDisabled.call( this, disabled );
6946
6947 if ( this.minusButton ) {
6948 this.minusButton.setDisabled( this.isDisabled() );
6949 }
6950 if ( this.plusButton ) {
6951 this.plusButton.setDisabled( this.isDisabled() );
6952 }
6953
6954 return this;
6955 };
6956
6957 }( OO ) );
6958
6959 //# sourceMappingURL=oojs-ui-widgets.js.map