Merge "Use {{int:}} on MediaWiki:Blockedtext and MediaWiki:Autoblockedtext"
[lhc/web/wiklou.git] / resources / lib / oojs-ui / oojs-ui-widgets.js
1 /*!
2 * OOUI v0.27.0
3 * https://www.mediawiki.org/wiki/OOUI
4 *
5 * Copyright 2011–2018 OOUI Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
8 *
9 * Date: 2018-05-09T00:44:45Z
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/OOUI-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 [OOUI demos][1] for an example.
622 *
623 * [1]: https://doc.wikimedia.org/oojs-ui/master/demos/#LookupElement-try-inputting-an-integer
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/OOUI/Concepts#Overlays>.
633 * @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element.
634 * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty.
635 * By default, the lookup menu is not generated and displayed until the user begins to type.
636 * @cfg {boolean} [highlightFirst=true] Whether the first lookup result should be highlighted (so, that the user can
637 * take it over into the input with simply pressing return) automatically or not.
638 */
639 OO.ui.mixin.LookupElement = function OoUiMixinLookupElement( config ) {
640 // Configuration initialization
641 config = $.extend( { highlightFirst: true }, config );
642
643 // Mixin constructors
644 OO.ui.mixin.RequestManager.call( this, config );
645
646 // Properties
647 this.$overlay = ( config.$overlay === true ? OO.ui.getDefaultOverlay() : config.$overlay ) || this.$element;
648 this.lookupMenu = new OO.ui.MenuSelectWidget( {
649 widget: this,
650 input: this,
651 $floatableContainer: config.$container || this.$element
652 } );
653
654 this.allowSuggestionsWhenEmpty = config.allowSuggestionsWhenEmpty || false;
655
656 this.lookupsDisabled = false;
657 this.lookupInputFocused = false;
658 this.lookupHighlightFirstItem = config.highlightFirst;
659
660 // Events
661 this.$input.on( {
662 focus: this.onLookupInputFocus.bind( this ),
663 blur: this.onLookupInputBlur.bind( this ),
664 mousedown: this.onLookupInputMouseDown.bind( this )
665 } );
666 this.connect( this, { change: 'onLookupInputChange' } );
667 this.lookupMenu.connect( this, {
668 toggle: 'onLookupMenuToggle',
669 choose: 'onLookupMenuItemChoose'
670 } );
671
672 // Initialization
673 this.$input.attr( {
674 role: 'combobox',
675 'aria-owns': this.lookupMenu.getElementId(),
676 'aria-autocomplete': 'list'
677 } );
678 this.$element.addClass( 'oo-ui-lookupElement' );
679 this.lookupMenu.$element.addClass( 'oo-ui-lookupElement-menu' );
680 this.$overlay.append( this.lookupMenu.$element );
681 };
682
683 /* Setup */
684
685 OO.mixinClass( OO.ui.mixin.LookupElement, OO.ui.mixin.RequestManager );
686
687 /* Methods */
688
689 /**
690 * Handle input focus event.
691 *
692 * @protected
693 * @param {jQuery.Event} e Input focus event
694 */
695 OO.ui.mixin.LookupElement.prototype.onLookupInputFocus = function () {
696 this.lookupInputFocused = true;
697 this.populateLookupMenu();
698 };
699
700 /**
701 * Handle input blur event.
702 *
703 * @protected
704 * @param {jQuery.Event} e Input blur event
705 */
706 OO.ui.mixin.LookupElement.prototype.onLookupInputBlur = function () {
707 this.closeLookupMenu();
708 this.lookupInputFocused = false;
709 };
710
711 /**
712 * Handle input mouse down event.
713 *
714 * @protected
715 * @param {jQuery.Event} e Input mouse down event
716 */
717 OO.ui.mixin.LookupElement.prototype.onLookupInputMouseDown = function () {
718 // Only open the menu if the input was already focused.
719 // This way we allow the user to open the menu again after closing it with Esc
720 // by clicking in the input. Opening (and populating) the menu when initially
721 // clicking into the input is handled by the focus handler.
722 if ( this.lookupInputFocused && !this.lookupMenu.isVisible() ) {
723 this.populateLookupMenu();
724 }
725 };
726
727 /**
728 * Handle input change event.
729 *
730 * @protected
731 * @param {string} value New input value
732 */
733 OO.ui.mixin.LookupElement.prototype.onLookupInputChange = function () {
734 if ( this.lookupInputFocused ) {
735 this.populateLookupMenu();
736 }
737 };
738
739 /**
740 * Handle the lookup menu being shown/hidden.
741 *
742 * @protected
743 * @param {boolean} visible Whether the lookup menu is now visible.
744 */
745 OO.ui.mixin.LookupElement.prototype.onLookupMenuToggle = function ( visible ) {
746 if ( !visible ) {
747 // When the menu is hidden, abort any active request and clear the menu.
748 // This has to be done here in addition to closeLookupMenu(), because
749 // MenuSelectWidget will close itself when the user presses Esc.
750 this.abortLookupRequest();
751 this.lookupMenu.clearItems();
752 }
753 };
754
755 /**
756 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
757 *
758 * @protected
759 * @param {OO.ui.MenuOptionWidget} item Selected item
760 */
761 OO.ui.mixin.LookupElement.prototype.onLookupMenuItemChoose = function ( item ) {
762 this.setValue( item.getData() );
763 };
764
765 /**
766 * Get lookup menu.
767 *
768 * @private
769 * @return {OO.ui.MenuSelectWidget}
770 */
771 OO.ui.mixin.LookupElement.prototype.getLookupMenu = function () {
772 return this.lookupMenu;
773 };
774
775 /**
776 * Disable or re-enable lookups.
777 *
778 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
779 *
780 * @param {boolean} disabled Disable lookups
781 */
782 OO.ui.mixin.LookupElement.prototype.setLookupsDisabled = function ( disabled ) {
783 this.lookupsDisabled = !!disabled;
784 };
785
786 /**
787 * Open the menu. If there are no entries in the menu, this does nothing.
788 *
789 * @private
790 * @chainable
791 */
792 OO.ui.mixin.LookupElement.prototype.openLookupMenu = function () {
793 if ( !this.lookupMenu.isEmpty() ) {
794 this.lookupMenu.toggle( true );
795 }
796 return this;
797 };
798
799 /**
800 * Close the menu, empty it, and abort any pending request.
801 *
802 * @private
803 * @chainable
804 */
805 OO.ui.mixin.LookupElement.prototype.closeLookupMenu = function () {
806 this.lookupMenu.toggle( false );
807 this.abortLookupRequest();
808 this.lookupMenu.clearItems();
809 return this;
810 };
811
812 /**
813 * Request menu items based on the input's current value, and when they arrive,
814 * populate the menu with these items and show the menu.
815 *
816 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
817 *
818 * @private
819 * @chainable
820 */
821 OO.ui.mixin.LookupElement.prototype.populateLookupMenu = function () {
822 var widget = this,
823 value = this.getValue();
824
825 if ( this.lookupsDisabled || this.isReadOnly() ) {
826 return;
827 }
828
829 // If the input is empty, clear the menu, unless suggestions when empty are allowed.
830 if ( !this.allowSuggestionsWhenEmpty && value === '' ) {
831 this.closeLookupMenu();
832 // Skip population if there is already a request pending for the current value
833 } else if ( value !== this.lookupQuery ) {
834 this.getLookupMenuItems()
835 .done( function ( items ) {
836 widget.lookupMenu.clearItems();
837 if ( items.length ) {
838 widget.lookupMenu
839 .addItems( items )
840 .toggle( true );
841 widget.initializeLookupMenuSelection();
842 } else {
843 widget.lookupMenu.toggle( false );
844 }
845 } )
846 .fail( function () {
847 widget.lookupMenu.clearItems();
848 } );
849 }
850
851 return this;
852 };
853
854 /**
855 * Highlight the first selectable item in the menu, if configured.
856 *
857 * @private
858 * @chainable
859 */
860 OO.ui.mixin.LookupElement.prototype.initializeLookupMenuSelection = function () {
861 if ( this.lookupHighlightFirstItem && !this.lookupMenu.findSelectedItem() ) {
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.findItemFromData( page.getName() ).getLevel();
2024 if (
2025 prev &&
2026 level === this.outlineSelectWidget.findItemFromData( prev.getName() ).getLevel()
2027 ) {
2028 return prev;
2029 }
2030 if (
2031 next &&
2032 level === this.outlineSelectWidget.findItemFromData( next.getName() ).getLevel()
2033 ) {
2034 return next;
2035 }
2036 }
2037 }
2038 return prev || next || null;
2039 };
2040
2041 /**
2042 * Get the outline widget.
2043 *
2044 * If the booklet is not outlined, the method will return `null`.
2045 *
2046 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
2047 */
2048 OO.ui.BookletLayout.prototype.getOutline = function () {
2049 return this.outlineSelectWidget;
2050 };
2051
2052 /**
2053 * Get the outline controls widget.
2054 *
2055 * If the outline is not editable, the method will return `null`.
2056 *
2057 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
2058 */
2059 OO.ui.BookletLayout.prototype.getOutlineControls = function () {
2060 return this.outlineControlsWidget;
2061 };
2062
2063 /**
2064 * Get a page by its symbolic name.
2065 *
2066 * @param {string} name Symbolic name of page
2067 * @return {OO.ui.PageLayout|undefined} Page, if found
2068 */
2069 OO.ui.BookletLayout.prototype.getPage = function ( name ) {
2070 return this.pages[ name ];
2071 };
2072
2073 /**
2074 * Get the current page.
2075 *
2076 * @return {OO.ui.PageLayout|undefined} Current page, if found
2077 */
2078 OO.ui.BookletLayout.prototype.getCurrentPage = function () {
2079 var name = this.getCurrentPageName();
2080 return name ? this.getPage( name ) : undefined;
2081 };
2082
2083 /**
2084 * Get the symbolic name of the current page.
2085 *
2086 * @return {string|null} Symbolic name of the current page
2087 */
2088 OO.ui.BookletLayout.prototype.getCurrentPageName = function () {
2089 return this.currentPageName;
2090 };
2091
2092 /**
2093 * Add pages to the booklet layout
2094 *
2095 * When pages are added with the same names as existing pages, the existing pages will be
2096 * automatically removed before the new pages are added.
2097 *
2098 * @param {OO.ui.PageLayout[]} pages Pages to add
2099 * @param {number} index Index of the insertion point
2100 * @fires add
2101 * @chainable
2102 */
2103 OO.ui.BookletLayout.prototype.addPages = function ( pages, index ) {
2104 var i, len, name, page, item, currentIndex,
2105 stackLayoutPages = this.stackLayout.getItems(),
2106 remove = [],
2107 items = [];
2108
2109 // Remove pages with same names
2110 for ( i = 0, len = pages.length; i < len; i++ ) {
2111 page = pages[ i ];
2112 name = page.getName();
2113
2114 if ( Object.prototype.hasOwnProperty.call( this.pages, name ) ) {
2115 // Correct the insertion index
2116 currentIndex = stackLayoutPages.indexOf( this.pages[ name ] );
2117 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
2118 index--;
2119 }
2120 remove.push( this.pages[ name ] );
2121 }
2122 }
2123 if ( remove.length ) {
2124 this.removePages( remove );
2125 }
2126
2127 // Add new pages
2128 for ( i = 0, len = pages.length; i < len; i++ ) {
2129 page = pages[ i ];
2130 name = page.getName();
2131 this.pages[ page.getName() ] = page;
2132 if ( this.outlined ) {
2133 item = new OO.ui.OutlineOptionWidget( { data: name } );
2134 page.setOutlineItem( item );
2135 items.push( item );
2136 }
2137 }
2138
2139 if ( this.outlined && items.length ) {
2140 this.outlineSelectWidget.addItems( items, index );
2141 this.selectFirstSelectablePage();
2142 }
2143 this.stackLayout.addItems( pages, index );
2144 this.emit( 'add', pages, index );
2145
2146 return this;
2147 };
2148
2149 /**
2150 * Remove the specified pages from the booklet layout.
2151 *
2152 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
2153 *
2154 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
2155 * @fires remove
2156 * @chainable
2157 */
2158 OO.ui.BookletLayout.prototype.removePages = function ( pages ) {
2159 var i, len, name, page,
2160 items = [];
2161
2162 for ( i = 0, len = pages.length; i < len; i++ ) {
2163 page = pages[ i ];
2164 name = page.getName();
2165 delete this.pages[ name ];
2166 if ( this.outlined ) {
2167 items.push( this.outlineSelectWidget.findItemFromData( name ) );
2168 page.setOutlineItem( null );
2169 }
2170 }
2171 if ( this.outlined && items.length ) {
2172 this.outlineSelectWidget.removeItems( items );
2173 this.selectFirstSelectablePage();
2174 }
2175 this.stackLayout.removeItems( pages );
2176 this.emit( 'remove', pages );
2177
2178 return this;
2179 };
2180
2181 /**
2182 * Clear all pages from the booklet layout.
2183 *
2184 * To remove only a subset of pages from the booklet, use the #removePages method.
2185 *
2186 * @fires remove
2187 * @chainable
2188 */
2189 OO.ui.BookletLayout.prototype.clearPages = function () {
2190 var i, len,
2191 pages = this.stackLayout.getItems();
2192
2193 this.pages = {};
2194 this.currentPageName = null;
2195 if ( this.outlined ) {
2196 this.outlineSelectWidget.clearItems();
2197 for ( i = 0, len = pages.length; i < len; i++ ) {
2198 pages[ i ].setOutlineItem( null );
2199 }
2200 }
2201 this.stackLayout.clearItems();
2202
2203 this.emit( 'remove', pages );
2204
2205 return this;
2206 };
2207
2208 /**
2209 * Set the current page by symbolic name.
2210 *
2211 * @fires set
2212 * @param {string} name Symbolic name of page
2213 */
2214 OO.ui.BookletLayout.prototype.setPage = function ( name ) {
2215 var selectedItem,
2216 $focused,
2217 page = this.pages[ name ],
2218 previousPage = this.currentPageName && this.pages[ this.currentPageName ];
2219
2220 if ( name !== this.currentPageName ) {
2221 if ( this.outlined ) {
2222 selectedItem = this.outlineSelectWidget.findSelectedItem();
2223 if ( selectedItem && selectedItem.getData() !== name ) {
2224 this.outlineSelectWidget.selectItemByData( name );
2225 }
2226 }
2227 if ( page ) {
2228 if ( previousPage ) {
2229 previousPage.setActive( false );
2230 // Blur anything focused if the next page doesn't have anything focusable.
2231 // This is not needed if the next page has something focusable (because once it is focused
2232 // this blur happens automatically). If the layout is non-continuous, this check is
2233 // meaningless because the next page is not visible yet and thus can't hold focus.
2234 if (
2235 this.autoFocus &&
2236 !OO.ui.isMobile() &&
2237 this.stackLayout.continuous &&
2238 OO.ui.findFocusable( page.$element ).length !== 0
2239 ) {
2240 $focused = previousPage.$element.find( ':focus' );
2241 if ( $focused.length ) {
2242 $focused[ 0 ].blur();
2243 }
2244 }
2245 }
2246 this.currentPageName = name;
2247 page.setActive( true );
2248 this.stackLayout.setItem( page );
2249 if ( !this.stackLayout.continuous && previousPage ) {
2250 // This should not be necessary, since any inputs on the previous page should have been
2251 // blurred when it was hidden, but browsers are not very consistent about this.
2252 $focused = previousPage.$element.find( ':focus' );
2253 if ( $focused.length ) {
2254 $focused[ 0 ].blur();
2255 }
2256 }
2257 this.emit( 'set', page );
2258 }
2259 }
2260 };
2261
2262 /**
2263 * Select the first selectable page.
2264 *
2265 * @chainable
2266 */
2267 OO.ui.BookletLayout.prototype.selectFirstSelectablePage = function () {
2268 if ( !this.outlineSelectWidget.findSelectedItem() ) {
2269 this.outlineSelectWidget.selectItem( this.outlineSelectWidget.findFirstSelectableItem() );
2270 }
2271
2272 return this;
2273 };
2274
2275 /**
2276 * IndexLayouts contain {@link OO.ui.TabPanelLayout tab panel layouts} as well as
2277 * {@link OO.ui.TabSelectWidget tabs} that allow users to easily navigate through the tab panels and
2278 * select which one to display. By default, only one tab panel is displayed at a time. When a user
2279 * navigates to a new tab panel, the index layout automatically focuses on the first focusable element,
2280 * unless the default setting is changed.
2281 *
2282 * TODO: This class is similar to BookletLayout, we may want to refactor to reduce duplication
2283 *
2284 * @example
2285 * // Example of a IndexLayout that contains two TabPanelLayouts.
2286 *
2287 * function TabPanelOneLayout( name, config ) {
2288 * TabPanelOneLayout.parent.call( this, name, config );
2289 * this.$element.append( '<p>First tab panel</p>' );
2290 * }
2291 * OO.inheritClass( TabPanelOneLayout, OO.ui.TabPanelLayout );
2292 * TabPanelOneLayout.prototype.setupTabItem = function () {
2293 * this.tabItem.setLabel( 'Tab panel one' );
2294 * };
2295 *
2296 * var tabPanel1 = new TabPanelOneLayout( 'one' ),
2297 * tabPanel2 = new OO.ui.TabPanelLayout( 'two', { label: 'Tab panel two' } );
2298 *
2299 * tabPanel2.$element.append( '<p>Second tab panel</p>' );
2300 *
2301 * var index = new OO.ui.IndexLayout();
2302 *
2303 * index.addTabPanels ( [ tabPanel1, tabPanel2 ] );
2304 * $( 'body' ).append( index.$element );
2305 *
2306 * @class
2307 * @extends OO.ui.MenuLayout
2308 *
2309 * @constructor
2310 * @param {Object} [config] Configuration options
2311 * @cfg {boolean} [continuous=false] Show all tab panels, one after another
2312 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new tab panel is displayed. Disabled on mobile.
2313 */
2314 OO.ui.IndexLayout = function OoUiIndexLayout( config ) {
2315 // Configuration initialization
2316 config = $.extend( {}, config, { menuPosition: 'top' } );
2317
2318 // Parent constructor
2319 OO.ui.IndexLayout.parent.call( this, config );
2320
2321 // Properties
2322 this.currentTabPanelName = null;
2323 this.tabPanels = {};
2324
2325 this.ignoreFocus = false;
2326 this.stackLayout = new OO.ui.StackLayout( {
2327 continuous: !!config.continuous,
2328 expanded: this.expanded
2329 } );
2330 this.$content.append( this.stackLayout.$element );
2331 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
2332
2333 this.tabSelectWidget = new OO.ui.TabSelectWidget();
2334 this.tabPanel = new OO.ui.PanelLayout( {
2335 expanded: this.expanded
2336 } );
2337 this.$menu.append( this.tabPanel.$element );
2338
2339 this.toggleMenu( true );
2340
2341 // Events
2342 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
2343 this.tabSelectWidget.connect( this, { select: 'onTabSelectWidgetSelect' } );
2344 if ( this.autoFocus ) {
2345 // Event 'focus' does not bubble, but 'focusin' does
2346 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
2347 }
2348
2349 // Initialization
2350 this.$element.addClass( 'oo-ui-indexLayout' );
2351 this.stackLayout.$element.addClass( 'oo-ui-indexLayout-stackLayout' );
2352 this.tabPanel.$element
2353 .addClass( 'oo-ui-indexLayout-tabPanel' )
2354 .append( this.tabSelectWidget.$element );
2355 };
2356
2357 /* Setup */
2358
2359 OO.inheritClass( OO.ui.IndexLayout, OO.ui.MenuLayout );
2360
2361 /* Events */
2362
2363 /**
2364 * A 'set' event is emitted when a tab panel is {@link #setTabPanel set} to be displayed by the index layout.
2365 * @event set
2366 * @param {OO.ui.TabPanelLayout} tabPanel Current tab panel
2367 */
2368
2369 /**
2370 * An 'add' event is emitted when tab panels are {@link #addTabPanels added} to the index layout.
2371 *
2372 * @event add
2373 * @param {OO.ui.TabPanelLayout[]} tabPanel Added tab panels
2374 * @param {number} index Index tab panels were added at
2375 */
2376
2377 /**
2378 * A 'remove' event is emitted when tab panels are {@link #clearTabPanels cleared} or
2379 * {@link #removeTabPanels removed} from the index.
2380 *
2381 * @event remove
2382 * @param {OO.ui.TabPanelLayout[]} tabPanel Removed tab panels
2383 */
2384
2385 /* Methods */
2386
2387 /**
2388 * Handle stack layout focus.
2389 *
2390 * @private
2391 * @param {jQuery.Event} e Focusing event
2392 */
2393 OO.ui.IndexLayout.prototype.onStackLayoutFocus = function ( e ) {
2394 var name, $target;
2395
2396 // Find the tab panel that an element was focused within
2397 $target = $( e.target ).closest( '.oo-ui-tabPanelLayout' );
2398 for ( name in this.tabPanels ) {
2399 // Check for tab panel match, exclude current tab panel to find only tab panel changes
2400 if ( this.tabPanels[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentTabPanelName ) {
2401 this.setTabPanel( name );
2402 break;
2403 }
2404 }
2405 };
2406
2407 /**
2408 * Handle stack layout set events.
2409 *
2410 * @private
2411 * @param {OO.ui.PanelLayout|null} tabPanel The tab panel that is now the current panel
2412 */
2413 OO.ui.IndexLayout.prototype.onStackLayoutSet = function ( tabPanel ) {
2414 // If everything is unselected, do nothing
2415 if ( !tabPanel ) {
2416 return;
2417 }
2418 // Focus the first element on the newly selected panel
2419 if ( this.autoFocus && !OO.ui.isMobile() ) {
2420 this.focus();
2421 }
2422 };
2423
2424 /**
2425 * Focus the first input in the current tab panel.
2426 *
2427 * If no tab panel is selected, the first selectable tab panel will be selected.
2428 * If the focus is already in an element on the current tab panel, nothing will happen.
2429 *
2430 * @param {number} [itemIndex] A specific item to focus on
2431 */
2432 OO.ui.IndexLayout.prototype.focus = function ( itemIndex ) {
2433 var tabPanel,
2434 items = this.stackLayout.getItems();
2435
2436 if ( itemIndex !== undefined && items[ itemIndex ] ) {
2437 tabPanel = items[ itemIndex ];
2438 } else {
2439 tabPanel = this.stackLayout.getCurrentItem();
2440 }
2441
2442 if ( !tabPanel ) {
2443 this.selectFirstSelectableTabPanel();
2444 tabPanel = this.stackLayout.getCurrentItem();
2445 }
2446 if ( !tabPanel ) {
2447 return;
2448 }
2449 // Only change the focus if is not already in the current page
2450 if ( !OO.ui.contains( tabPanel.$element[ 0 ], this.getElementDocument().activeElement, true ) ) {
2451 tabPanel.focus();
2452 }
2453 };
2454
2455 /**
2456 * Find the first focusable input in the index layout and focus
2457 * on it.
2458 */
2459 OO.ui.IndexLayout.prototype.focusFirstFocusable = function () {
2460 OO.ui.findFocusable( this.stackLayout.$element ).focus();
2461 };
2462
2463 /**
2464 * Handle tab widget select events.
2465 *
2466 * @private
2467 * @param {OO.ui.OptionWidget|null} item Selected item
2468 */
2469 OO.ui.IndexLayout.prototype.onTabSelectWidgetSelect = function ( item ) {
2470 if ( item ) {
2471 this.setTabPanel( item.getData() );
2472 }
2473 };
2474
2475 /**
2476 * Get the tab panel closest to the specified tab panel.
2477 *
2478 * @param {OO.ui.TabPanelLayout} tabPanel Tab panel to use as a reference point
2479 * @return {OO.ui.TabPanelLayout|null} Tab panel closest to the specified
2480 */
2481 OO.ui.IndexLayout.prototype.getClosestTabPanel = function ( tabPanel ) {
2482 var next, prev, level,
2483 tabPanels = this.stackLayout.getItems(),
2484 index = tabPanels.indexOf( tabPanel );
2485
2486 if ( index !== -1 ) {
2487 next = tabPanels[ index + 1 ];
2488 prev = tabPanels[ index - 1 ];
2489 // Prefer adjacent tab panels at the same level
2490 level = this.tabSelectWidget.findItemFromData( tabPanel.getName() ).getLevel();
2491 if (
2492 prev &&
2493 level === this.tabSelectWidget.findItemFromData( prev.getName() ).getLevel()
2494 ) {
2495 return prev;
2496 }
2497 if (
2498 next &&
2499 level === this.tabSelectWidget.findItemFromData( next.getName() ).getLevel()
2500 ) {
2501 return next;
2502 }
2503 }
2504 return prev || next || null;
2505 };
2506
2507 /**
2508 * Get the tabs widget.
2509 *
2510 * @return {OO.ui.TabSelectWidget} Tabs widget
2511 */
2512 OO.ui.IndexLayout.prototype.getTabs = function () {
2513 return this.tabSelectWidget;
2514 };
2515
2516 /**
2517 * Get a tab panel by its symbolic name.
2518 *
2519 * @param {string} name Symbolic name of tab panel
2520 * @return {OO.ui.TabPanelLayout|undefined} Tab panel, if found
2521 */
2522 OO.ui.IndexLayout.prototype.getTabPanel = function ( name ) {
2523 return this.tabPanels[ name ];
2524 };
2525
2526 /**
2527 * Get the current tab panel.
2528 *
2529 * @return {OO.ui.TabPanelLayout|undefined} Current tab panel, if found
2530 */
2531 OO.ui.IndexLayout.prototype.getCurrentTabPanel = function () {
2532 var name = this.getCurrentTabPanelName();
2533 return name ? this.getTabPanel( name ) : undefined;
2534 };
2535
2536 /**
2537 * Get the symbolic name of the current tab panel.
2538 *
2539 * @return {string|null} Symbolic name of the current tab panel
2540 */
2541 OO.ui.IndexLayout.prototype.getCurrentTabPanelName = function () {
2542 return this.currentTabPanelName;
2543 };
2544
2545 /**
2546 * Add tab panels to the index layout
2547 *
2548 * When tab panels are added with the same names as existing tab panels, the existing tab panels
2549 * will be automatically removed before the new tab panels are added.
2550 *
2551 * @param {OO.ui.TabPanelLayout[]} tabPanels Tab panels to add
2552 * @param {number} index Index of the insertion point
2553 * @fires add
2554 * @chainable
2555 */
2556 OO.ui.IndexLayout.prototype.addTabPanels = function ( tabPanels, index ) {
2557 var i, len, name, tabPanel, item, currentIndex,
2558 stackLayoutTabPanels = this.stackLayout.getItems(),
2559 remove = [],
2560 items = [];
2561
2562 // Remove tab panels with same names
2563 for ( i = 0, len = tabPanels.length; i < len; i++ ) {
2564 tabPanel = tabPanels[ i ];
2565 name = tabPanel.getName();
2566
2567 if ( Object.prototype.hasOwnProperty.call( this.tabPanels, name ) ) {
2568 // Correct the insertion index
2569 currentIndex = stackLayoutTabPanels.indexOf( this.tabPanels[ name ] );
2570 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
2571 index--;
2572 }
2573 remove.push( this.tabPanels[ name ] );
2574 }
2575 }
2576 if ( remove.length ) {
2577 this.removeTabPanels( remove );
2578 }
2579
2580 // Add new tab panels
2581 for ( i = 0, len = tabPanels.length; i < len; i++ ) {
2582 tabPanel = tabPanels[ i ];
2583 name = tabPanel.getName();
2584 this.tabPanels[ tabPanel.getName() ] = tabPanel;
2585 item = new OO.ui.TabOptionWidget( { data: name } );
2586 tabPanel.setTabItem( item );
2587 items.push( item );
2588 }
2589
2590 if ( items.length ) {
2591 this.tabSelectWidget.addItems( items, index );
2592 this.selectFirstSelectableTabPanel();
2593 }
2594 this.stackLayout.addItems( tabPanels, index );
2595 this.emit( 'add', tabPanels, index );
2596
2597 return this;
2598 };
2599
2600 /**
2601 * Remove the specified tab panels from the index layout.
2602 *
2603 * To remove all tab panels from the index, you may wish to use the #clearTabPanels method instead.
2604 *
2605 * @param {OO.ui.TabPanelLayout[]} tabPanels An array of tab panels to remove
2606 * @fires remove
2607 * @chainable
2608 */
2609 OO.ui.IndexLayout.prototype.removeTabPanels = function ( tabPanels ) {
2610 var i, len, name, tabPanel,
2611 items = [];
2612
2613 for ( i = 0, len = tabPanels.length; i < len; i++ ) {
2614 tabPanel = tabPanels[ i ];
2615 name = tabPanel.getName();
2616 delete this.tabPanels[ name ];
2617 items.push( this.tabSelectWidget.findItemFromData( name ) );
2618 tabPanel.setTabItem( null );
2619 }
2620 if ( items.length ) {
2621 this.tabSelectWidget.removeItems( items );
2622 this.selectFirstSelectableTabPanel();
2623 }
2624 this.stackLayout.removeItems( tabPanels );
2625 this.emit( 'remove', tabPanels );
2626
2627 return this;
2628 };
2629
2630 /**
2631 * Clear all tab panels from the index layout.
2632 *
2633 * To remove only a subset of tab panels from the index, use the #removeTabPanels method.
2634 *
2635 * @fires remove
2636 * @chainable
2637 */
2638 OO.ui.IndexLayout.prototype.clearTabPanels = function () {
2639 var i, len,
2640 tabPanels = this.stackLayout.getItems();
2641
2642 this.tabPanels = {};
2643 this.currentTabPanelName = null;
2644 this.tabSelectWidget.clearItems();
2645 for ( i = 0, len = tabPanels.length; i < len; i++ ) {
2646 tabPanels[ i ].setTabItem( null );
2647 }
2648 this.stackLayout.clearItems();
2649
2650 this.emit( 'remove', tabPanels );
2651
2652 return this;
2653 };
2654
2655 /**
2656 * Set the current tab panel by symbolic name.
2657 *
2658 * @fires set
2659 * @param {string} name Symbolic name of tab panel
2660 */
2661 OO.ui.IndexLayout.prototype.setTabPanel = function ( name ) {
2662 var selectedItem,
2663 $focused,
2664 tabPanel = this.tabPanels[ name ],
2665 previousTabPanel = this.currentTabPanelName && this.tabPanels[ this.currentTabPanelName ];
2666
2667 if ( name !== this.currentTabPanelName ) {
2668 selectedItem = this.tabSelectWidget.findSelectedItem();
2669 if ( selectedItem && selectedItem.getData() !== name ) {
2670 this.tabSelectWidget.selectItemByData( name );
2671 }
2672 if ( tabPanel ) {
2673 if ( previousTabPanel ) {
2674 previousTabPanel.setActive( false );
2675 // Blur anything focused if the next tab panel doesn't have anything focusable.
2676 // This is not needed if the next tab panel has something focusable (because once it is focused
2677 // this blur happens automatically). If the layout is non-continuous, this check is
2678 // meaningless because the next tab panel is not visible yet and thus can't hold focus.
2679 if (
2680 this.autoFocus &&
2681 !OO.ui.isMobile() &&
2682 this.stackLayout.continuous &&
2683 OO.ui.findFocusable( tabPanel.$element ).length !== 0
2684 ) {
2685 $focused = previousTabPanel.$element.find( ':focus' );
2686 if ( $focused.length ) {
2687 $focused[ 0 ].blur();
2688 }
2689 }
2690 }
2691 this.currentTabPanelName = name;
2692 tabPanel.setActive( true );
2693 this.stackLayout.setItem( tabPanel );
2694 if ( !this.stackLayout.continuous && previousTabPanel ) {
2695 // This should not be necessary, since any inputs on the previous tab panel should have been
2696 // blurred when it was hidden, but browsers are not very consistent about this.
2697 $focused = previousTabPanel.$element.find( ':focus' );
2698 if ( $focused.length ) {
2699 $focused[ 0 ].blur();
2700 }
2701 }
2702 this.emit( 'set', tabPanel );
2703 }
2704 }
2705 };
2706
2707 /**
2708 * Select the first selectable tab panel.
2709 *
2710 * @chainable
2711 */
2712 OO.ui.IndexLayout.prototype.selectFirstSelectableTabPanel = function () {
2713 if ( !this.tabSelectWidget.findSelectedItem() ) {
2714 this.tabSelectWidget.selectItem( this.tabSelectWidget.findFirstSelectableItem() );
2715 }
2716
2717 return this;
2718 };
2719
2720 /**
2721 * ToggleWidget implements basic behavior of widgets with an on/off state.
2722 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
2723 *
2724 * @abstract
2725 * @class
2726 * @extends OO.ui.Widget
2727 *
2728 * @constructor
2729 * @param {Object} [config] Configuration options
2730 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
2731 * By default, the toggle is in the 'off' state.
2732 */
2733 OO.ui.ToggleWidget = function OoUiToggleWidget( config ) {
2734 // Configuration initialization
2735 config = config || {};
2736
2737 // Parent constructor
2738 OO.ui.ToggleWidget.parent.call( this, config );
2739
2740 // Properties
2741 this.value = null;
2742
2743 // Initialization
2744 this.$element.addClass( 'oo-ui-toggleWidget' );
2745 this.setValue( !!config.value );
2746 };
2747
2748 /* Setup */
2749
2750 OO.inheritClass( OO.ui.ToggleWidget, OO.ui.Widget );
2751
2752 /* Events */
2753
2754 /**
2755 * @event change
2756 *
2757 * A change event is emitted when the on/off state of the toggle changes.
2758 *
2759 * @param {boolean} value Value representing the new state of the toggle
2760 */
2761
2762 /* Methods */
2763
2764 /**
2765 * Get the value representing the toggle’s state.
2766 *
2767 * @return {boolean} The on/off state of the toggle
2768 */
2769 OO.ui.ToggleWidget.prototype.getValue = function () {
2770 return this.value;
2771 };
2772
2773 /**
2774 * Set the state of the toggle: `true` for 'on', `false` for 'off'.
2775 *
2776 * @param {boolean} value The state of the toggle
2777 * @fires change
2778 * @chainable
2779 */
2780 OO.ui.ToggleWidget.prototype.setValue = function ( value ) {
2781 value = !!value;
2782 if ( this.value !== value ) {
2783 this.value = value;
2784 this.emit( 'change', value );
2785 this.$element.toggleClass( 'oo-ui-toggleWidget-on', value );
2786 this.$element.toggleClass( 'oo-ui-toggleWidget-off', !value );
2787 }
2788 return this;
2789 };
2790
2791 /**
2792 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
2793 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
2794 * configured with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators},
2795 * {@link OO.ui.mixin.TitledElement titles}, {@link OO.ui.mixin.FlaggedElement styling flags},
2796 * and {@link OO.ui.mixin.LabelElement labels}. Please see
2797 * the [OOUI documentation][1] on MediaWiki for more information.
2798 *
2799 * @example
2800 * // Toggle buttons in the 'off' and 'on' state.
2801 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
2802 * label: 'Toggle Button off'
2803 * } );
2804 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
2805 * label: 'Toggle Button on',
2806 * value: true
2807 * } );
2808 * // Append the buttons to the DOM.
2809 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
2810 *
2811 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Buttons_and_Switches#Toggle_buttons
2812 *
2813 * @class
2814 * @extends OO.ui.ToggleWidget
2815 * @mixins OO.ui.mixin.ButtonElement
2816 * @mixins OO.ui.mixin.IconElement
2817 * @mixins OO.ui.mixin.IndicatorElement
2818 * @mixins OO.ui.mixin.LabelElement
2819 * @mixins OO.ui.mixin.TitledElement
2820 * @mixins OO.ui.mixin.FlaggedElement
2821 * @mixins OO.ui.mixin.TabIndexedElement
2822 *
2823 * @constructor
2824 * @param {Object} [config] Configuration options
2825 * @cfg {boolean} [value=false] The toggle button’s initial on/off
2826 * state. By default, the button is in the 'off' state.
2827 */
2828 OO.ui.ToggleButtonWidget = function OoUiToggleButtonWidget( config ) {
2829 // Configuration initialization
2830 config = config || {};
2831
2832 // Parent constructor
2833 OO.ui.ToggleButtonWidget.parent.call( this, config );
2834
2835 // Mixin constructors
2836 OO.ui.mixin.ButtonElement.call( this, $.extend( {}, config, { active: this.active } ) );
2837 OO.ui.mixin.IconElement.call( this, config );
2838 OO.ui.mixin.IndicatorElement.call( this, config );
2839 OO.ui.mixin.LabelElement.call( this, config );
2840 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
2841 OO.ui.mixin.FlaggedElement.call( this, config );
2842 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
2843
2844 // Events
2845 this.connect( this, { click: 'onAction' } );
2846
2847 // Initialization
2848 this.$button.append( this.$icon, this.$label, this.$indicator );
2849 this.$element
2850 .addClass( 'oo-ui-toggleButtonWidget' )
2851 .append( this.$button );
2852 };
2853
2854 /* Setup */
2855
2856 OO.inheritClass( OO.ui.ToggleButtonWidget, OO.ui.ToggleWidget );
2857 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.ButtonElement );
2858 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IconElement );
2859 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.IndicatorElement );
2860 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.LabelElement );
2861 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TitledElement );
2862 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.FlaggedElement );
2863 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.mixin.TabIndexedElement );
2864
2865 /* Static Properties */
2866
2867 /**
2868 * @static
2869 * @inheritdoc
2870 */
2871 OO.ui.ToggleButtonWidget.static.tagName = 'span';
2872
2873 /* Methods */
2874
2875 /**
2876 * Handle the button action being triggered.
2877 *
2878 * @private
2879 */
2880 OO.ui.ToggleButtonWidget.prototype.onAction = function () {
2881 this.setValue( !this.value );
2882 };
2883
2884 /**
2885 * @inheritdoc
2886 */
2887 OO.ui.ToggleButtonWidget.prototype.setValue = function ( value ) {
2888 value = !!value;
2889 if ( value !== this.value ) {
2890 // Might be called from parent constructor before ButtonElement constructor
2891 if ( this.$button ) {
2892 this.$button.attr( 'aria-pressed', value.toString() );
2893 }
2894 this.setActive( value );
2895 }
2896
2897 // Parent method
2898 OO.ui.ToggleButtonWidget.parent.prototype.setValue.call( this, value );
2899
2900 return this;
2901 };
2902
2903 /**
2904 * @inheritdoc
2905 */
2906 OO.ui.ToggleButtonWidget.prototype.setButtonElement = function ( $button ) {
2907 if ( this.$button ) {
2908 this.$button.removeAttr( 'aria-pressed' );
2909 }
2910 OO.ui.mixin.ButtonElement.prototype.setButtonElement.call( this, $button );
2911 this.$button.attr( 'aria-pressed', this.value.toString() );
2912 };
2913
2914 /**
2915 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
2916 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
2917 * visually by a slider in the leftmost position.
2918 *
2919 * @example
2920 * // Toggle switches in the 'off' and 'on' position.
2921 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
2922 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
2923 * value: true
2924 * } );
2925 *
2926 * // Create a FieldsetLayout to layout and label switches
2927 * var fieldset = new OO.ui.FieldsetLayout( {
2928 * label: 'Toggle switches'
2929 * } );
2930 * fieldset.addItems( [
2931 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
2932 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
2933 * ] );
2934 * $( 'body' ).append( fieldset.$element );
2935 *
2936 * @class
2937 * @extends OO.ui.ToggleWidget
2938 * @mixins OO.ui.mixin.TabIndexedElement
2939 *
2940 * @constructor
2941 * @param {Object} [config] Configuration options
2942 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
2943 * By default, the toggle switch is in the 'off' position.
2944 */
2945 OO.ui.ToggleSwitchWidget = function OoUiToggleSwitchWidget( config ) {
2946 // Parent constructor
2947 OO.ui.ToggleSwitchWidget.parent.call( this, config );
2948
2949 // Mixin constructors
2950 OO.ui.mixin.TabIndexedElement.call( this, config );
2951
2952 // Properties
2953 this.dragging = false;
2954 this.dragStart = null;
2955 this.sliding = false;
2956 this.$glow = $( '<span>' );
2957 this.$grip = $( '<span>' );
2958
2959 // Events
2960 this.$element.on( {
2961 click: this.onClick.bind( this ),
2962 keypress: this.onKeyPress.bind( this )
2963 } );
2964
2965 // Initialization
2966 this.$glow.addClass( 'oo-ui-toggleSwitchWidget-glow' );
2967 this.$grip.addClass( 'oo-ui-toggleSwitchWidget-grip' );
2968 this.$element
2969 .addClass( 'oo-ui-toggleSwitchWidget' )
2970 .attr( 'role', 'checkbox' )
2971 .append( this.$glow, this.$grip );
2972 };
2973
2974 /* Setup */
2975
2976 OO.inheritClass( OO.ui.ToggleSwitchWidget, OO.ui.ToggleWidget );
2977 OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.mixin.TabIndexedElement );
2978
2979 /* Methods */
2980
2981 /**
2982 * Handle mouse click events.
2983 *
2984 * @private
2985 * @param {jQuery.Event} e Mouse click event
2986 */
2987 OO.ui.ToggleSwitchWidget.prototype.onClick = function ( e ) {
2988 if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) {
2989 this.setValue( !this.value );
2990 }
2991 return false;
2992 };
2993
2994 /**
2995 * Handle key press events.
2996 *
2997 * @private
2998 * @param {jQuery.Event} e Key press event
2999 */
3000 OO.ui.ToggleSwitchWidget.prototype.onKeyPress = function ( e ) {
3001 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
3002 this.setValue( !this.value );
3003 return false;
3004 }
3005 };
3006
3007 /**
3008 * @inheritdoc
3009 */
3010 OO.ui.ToggleSwitchWidget.prototype.setValue = function ( value ) {
3011 OO.ui.ToggleSwitchWidget.parent.prototype.setValue.call( this, value );
3012 this.$element.attr( 'aria-checked', this.value.toString() );
3013 return this;
3014 };
3015
3016 /**
3017 * @inheritdoc
3018 */
3019 OO.ui.ToggleSwitchWidget.prototype.simulateLabelClick = function () {
3020 if ( !this.isDisabled() ) {
3021 this.setValue( !this.value );
3022 }
3023 this.focus();
3024 };
3025
3026 /**
3027 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
3028 * Controls include moving items up and down, removing items, and adding different kinds of items.
3029 *
3030 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
3031 *
3032 * @class
3033 * @extends OO.ui.Widget
3034 * @mixins OO.ui.mixin.GroupElement
3035 * @mixins OO.ui.mixin.IconElement
3036 *
3037 * @constructor
3038 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
3039 * @param {Object} [config] Configuration options
3040 * @cfg {Object} [abilities] List of abilties
3041 * @cfg {boolean} [abilities.move=true] Allow moving movable items
3042 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
3043 */
3044 OO.ui.OutlineControlsWidget = function OoUiOutlineControlsWidget( outline, config ) {
3045 // Allow passing positional parameters inside the config object
3046 if ( OO.isPlainObject( outline ) && config === undefined ) {
3047 config = outline;
3048 outline = config.outline;
3049 }
3050
3051 // Configuration initialization
3052 config = $.extend( { icon: 'add' }, config );
3053
3054 // Parent constructor
3055 OO.ui.OutlineControlsWidget.parent.call( this, config );
3056
3057 // Mixin constructors
3058 OO.ui.mixin.GroupElement.call( this, config );
3059 OO.ui.mixin.IconElement.call( this, config );
3060
3061 // Properties
3062 this.outline = outline;
3063 this.$movers = $( '<div>' );
3064 this.upButton = new OO.ui.ButtonWidget( {
3065 framed: false,
3066 icon: 'collapse',
3067 title: OO.ui.msg( 'ooui-outline-control-move-up' )
3068 } );
3069 this.downButton = new OO.ui.ButtonWidget( {
3070 framed: false,
3071 icon: 'expand',
3072 title: OO.ui.msg( 'ooui-outline-control-move-down' )
3073 } );
3074 this.removeButton = new OO.ui.ButtonWidget( {
3075 framed: false,
3076 icon: 'trash',
3077 title: OO.ui.msg( 'ooui-outline-control-remove' )
3078 } );
3079 this.abilities = { move: true, remove: true };
3080
3081 // Events
3082 outline.connect( this, {
3083 select: 'onOutlineChange',
3084 add: 'onOutlineChange',
3085 remove: 'onOutlineChange'
3086 } );
3087 this.upButton.connect( this, { click: [ 'emit', 'move', -1 ] } );
3088 this.downButton.connect( this, { click: [ 'emit', 'move', 1 ] } );
3089 this.removeButton.connect( this, { click: [ 'emit', 'remove' ] } );
3090
3091 // Initialization
3092 this.$element.addClass( 'oo-ui-outlineControlsWidget' );
3093 this.$group.addClass( 'oo-ui-outlineControlsWidget-items' );
3094 this.$movers
3095 .addClass( 'oo-ui-outlineControlsWidget-movers' )
3096 .append( this.removeButton.$element, this.upButton.$element, this.downButton.$element );
3097 this.$element.append( this.$icon, this.$group, this.$movers );
3098 this.setAbilities( config.abilities || {} );
3099 };
3100
3101 /* Setup */
3102
3103 OO.inheritClass( OO.ui.OutlineControlsWidget, OO.ui.Widget );
3104 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.GroupElement );
3105 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.mixin.IconElement );
3106
3107 /* Events */
3108
3109 /**
3110 * @event move
3111 * @param {number} places Number of places to move
3112 */
3113
3114 /**
3115 * @event remove
3116 */
3117
3118 /* Methods */
3119
3120 /**
3121 * Set abilities.
3122 *
3123 * @param {Object} abilities List of abilties
3124 * @param {boolean} [abilities.move] Allow moving movable items
3125 * @param {boolean} [abilities.remove] Allow removing removable items
3126 */
3127 OO.ui.OutlineControlsWidget.prototype.setAbilities = function ( abilities ) {
3128 var ability;
3129
3130 for ( ability in this.abilities ) {
3131 if ( abilities[ ability ] !== undefined ) {
3132 this.abilities[ ability ] = !!abilities[ ability ];
3133 }
3134 }
3135
3136 this.onOutlineChange();
3137 };
3138
3139 /**
3140 * Handle outline change events.
3141 *
3142 * @private
3143 */
3144 OO.ui.OutlineControlsWidget.prototype.onOutlineChange = function () {
3145 var i, len, firstMovable, lastMovable,
3146 items = this.outline.getItems(),
3147 selectedItem = this.outline.findSelectedItem(),
3148 movable = this.abilities.move && selectedItem && selectedItem.isMovable(),
3149 removable = this.abilities.remove && selectedItem && selectedItem.isRemovable();
3150
3151 if ( movable ) {
3152 i = -1;
3153 len = items.length;
3154 while ( ++i < len ) {
3155 if ( items[ i ].isMovable() ) {
3156 firstMovable = items[ i ];
3157 break;
3158 }
3159 }
3160 i = len;
3161 while ( i-- ) {
3162 if ( items[ i ].isMovable() ) {
3163 lastMovable = items[ i ];
3164 break;
3165 }
3166 }
3167 }
3168 this.upButton.setDisabled( !movable || selectedItem === firstMovable );
3169 this.downButton.setDisabled( !movable || selectedItem === lastMovable );
3170 this.removeButton.setDisabled( !removable );
3171 };
3172
3173 /**
3174 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
3175 *
3176 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
3177 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
3178 * for an example.
3179 *
3180 * @class
3181 * @extends OO.ui.DecoratedOptionWidget
3182 *
3183 * @constructor
3184 * @param {Object} [config] Configuration options
3185 * @cfg {number} [level] Indentation level
3186 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
3187 */
3188 OO.ui.OutlineOptionWidget = function OoUiOutlineOptionWidget( config ) {
3189 // Configuration initialization
3190 config = config || {};
3191
3192 // Parent constructor
3193 OO.ui.OutlineOptionWidget.parent.call( this, config );
3194
3195 // Properties
3196 this.level = 0;
3197 this.movable = !!config.movable;
3198 this.removable = !!config.removable;
3199
3200 // Initialization
3201 this.$element.addClass( 'oo-ui-outlineOptionWidget' );
3202 this.setLevel( config.level );
3203 };
3204
3205 /* Setup */
3206
3207 OO.inheritClass( OO.ui.OutlineOptionWidget, OO.ui.DecoratedOptionWidget );
3208
3209 /* Static Properties */
3210
3211 /**
3212 * @static
3213 * @inheritdoc
3214 */
3215 OO.ui.OutlineOptionWidget.static.highlightable = true;
3216
3217 /**
3218 * @static
3219 * @inheritdoc
3220 */
3221 OO.ui.OutlineOptionWidget.static.scrollIntoViewOnSelect = true;
3222
3223 /**
3224 * @static
3225 * @inheritable
3226 * @property {string}
3227 */
3228 OO.ui.OutlineOptionWidget.static.levelClass = 'oo-ui-outlineOptionWidget-level-';
3229
3230 /**
3231 * @static
3232 * @inheritable
3233 * @property {number}
3234 */
3235 OO.ui.OutlineOptionWidget.static.levels = 3;
3236
3237 /* Methods */
3238
3239 /**
3240 * Check if item is movable.
3241 *
3242 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
3243 *
3244 * @return {boolean} Item is movable
3245 */
3246 OO.ui.OutlineOptionWidget.prototype.isMovable = function () {
3247 return this.movable;
3248 };
3249
3250 /**
3251 * Check if item is removable.
3252 *
3253 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
3254 *
3255 * @return {boolean} Item is removable
3256 */
3257 OO.ui.OutlineOptionWidget.prototype.isRemovable = function () {
3258 return this.removable;
3259 };
3260
3261 /**
3262 * Get indentation level.
3263 *
3264 * @return {number} Indentation level
3265 */
3266 OO.ui.OutlineOptionWidget.prototype.getLevel = function () {
3267 return this.level;
3268 };
3269
3270 /**
3271 * @inheritdoc
3272 */
3273 OO.ui.OutlineOptionWidget.prototype.setPressed = function ( state ) {
3274 OO.ui.OutlineOptionWidget.parent.prototype.setPressed.call( this, state );
3275 return this;
3276 };
3277
3278 /**
3279 * Set movability.
3280 *
3281 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
3282 *
3283 * @param {boolean} movable Item is movable
3284 * @chainable
3285 */
3286 OO.ui.OutlineOptionWidget.prototype.setMovable = function ( movable ) {
3287 this.movable = !!movable;
3288 this.updateThemeClasses();
3289 return this;
3290 };
3291
3292 /**
3293 * Set removability.
3294 *
3295 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
3296 *
3297 * @param {boolean} removable Item is removable
3298 * @chainable
3299 */
3300 OO.ui.OutlineOptionWidget.prototype.setRemovable = function ( removable ) {
3301 this.removable = !!removable;
3302 this.updateThemeClasses();
3303 return this;
3304 };
3305
3306 /**
3307 * @inheritdoc
3308 */
3309 OO.ui.OutlineOptionWidget.prototype.setSelected = function ( state ) {
3310 OO.ui.OutlineOptionWidget.parent.prototype.setSelected.call( this, state );
3311 return this;
3312 };
3313
3314 /**
3315 * Set indentation level.
3316 *
3317 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
3318 * @chainable
3319 */
3320 OO.ui.OutlineOptionWidget.prototype.setLevel = function ( level ) {
3321 var levels = this.constructor.static.levels,
3322 levelClass = this.constructor.static.levelClass,
3323 i = levels;
3324
3325 this.level = level ? Math.max( 0, Math.min( levels - 1, level ) ) : 0;
3326 while ( i-- ) {
3327 if ( this.level === i ) {
3328 this.$element.addClass( levelClass + i );
3329 } else {
3330 this.$element.removeClass( levelClass + i );
3331 }
3332 }
3333 this.updateThemeClasses();
3334
3335 return this;
3336 };
3337
3338 /**
3339 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
3340 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
3341 *
3342 * **Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}.**
3343 *
3344 * @class
3345 * @extends OO.ui.SelectWidget
3346 * @mixins OO.ui.mixin.TabIndexedElement
3347 *
3348 * @constructor
3349 * @param {Object} [config] Configuration options
3350 */
3351 OO.ui.OutlineSelectWidget = function OoUiOutlineSelectWidget( config ) {
3352 // Parent constructor
3353 OO.ui.OutlineSelectWidget.parent.call( this, config );
3354
3355 // Mixin constructors
3356 OO.ui.mixin.TabIndexedElement.call( this, config );
3357
3358 // Events
3359 this.$element.on( {
3360 focus: this.bindKeyDownListener.bind( this ),
3361 blur: this.unbindKeyDownListener.bind( this )
3362 } );
3363
3364 // Initialization
3365 this.$element.addClass( 'oo-ui-outlineSelectWidget' );
3366 };
3367
3368 /* Setup */
3369
3370 OO.inheritClass( OO.ui.OutlineSelectWidget, OO.ui.SelectWidget );
3371 OO.mixinClass( OO.ui.OutlineSelectWidget, OO.ui.mixin.TabIndexedElement );
3372
3373 /**
3374 * ButtonOptionWidget is a special type of {@link OO.ui.mixin.ButtonElement button element} that
3375 * can be selected and configured with data. The class is
3376 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
3377 * [OOUI documentation on MediaWiki] [1] for more information.
3378 *
3379 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Button_selects_and_options
3380 *
3381 * @class
3382 * @extends OO.ui.OptionWidget
3383 * @mixins OO.ui.mixin.ButtonElement
3384 * @mixins OO.ui.mixin.IconElement
3385 * @mixins OO.ui.mixin.IndicatorElement
3386 * @mixins OO.ui.mixin.TitledElement
3387 *
3388 * @constructor
3389 * @param {Object} [config] Configuration options
3390 */
3391 OO.ui.ButtonOptionWidget = function OoUiButtonOptionWidget( config ) {
3392 // Configuration initialization
3393 config = config || {};
3394
3395 // Parent constructor
3396 OO.ui.ButtonOptionWidget.parent.call( this, config );
3397
3398 // Mixin constructors
3399 OO.ui.mixin.ButtonElement.call( this, config );
3400 OO.ui.mixin.IconElement.call( this, config );
3401 OO.ui.mixin.IndicatorElement.call( this, config );
3402 OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
3403
3404 // Initialization
3405 this.$element.addClass( 'oo-ui-buttonOptionWidget' );
3406 this.$button.append( this.$icon, this.$label, this.$indicator );
3407 this.$element.append( this.$button );
3408 };
3409
3410 /* Setup */
3411
3412 OO.inheritClass( OO.ui.ButtonOptionWidget, OO.ui.OptionWidget );
3413 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.ButtonElement );
3414 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.IconElement );
3415 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.IndicatorElement );
3416 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.TitledElement );
3417
3418 /* Static Properties */
3419
3420 /**
3421 * Allow button mouse down events to pass through so they can be handled by the parent select widget
3422 *
3423 * @static
3424 * @inheritdoc
3425 */
3426 OO.ui.ButtonOptionWidget.static.cancelButtonMouseDownEvents = false;
3427
3428 /**
3429 * @static
3430 * @inheritdoc
3431 */
3432 OO.ui.ButtonOptionWidget.static.highlightable = false;
3433
3434 /* Methods */
3435
3436 /**
3437 * @inheritdoc
3438 */
3439 OO.ui.ButtonOptionWidget.prototype.setSelected = function ( state ) {
3440 OO.ui.ButtonOptionWidget.parent.prototype.setSelected.call( this, state );
3441
3442 if ( this.constructor.static.selectable ) {
3443 this.setActive( state );
3444 }
3445
3446 return this;
3447 };
3448
3449 /**
3450 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
3451 * button options and is used together with
3452 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
3453 * highlighting, choosing, and selecting mutually exclusive options. Please see
3454 * the [OOUI documentation on MediaWiki] [1] for more information.
3455 *
3456 * @example
3457 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
3458 * var option1 = new OO.ui.ButtonOptionWidget( {
3459 * data: 1,
3460 * label: 'Option 1',
3461 * title: 'Button option 1'
3462 * } );
3463 *
3464 * var option2 = new OO.ui.ButtonOptionWidget( {
3465 * data: 2,
3466 * label: 'Option 2',
3467 * title: 'Button option 2'
3468 * } );
3469 *
3470 * var option3 = new OO.ui.ButtonOptionWidget( {
3471 * data: 3,
3472 * label: 'Option 3',
3473 * title: 'Button option 3'
3474 * } );
3475 *
3476 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
3477 * items: [ option1, option2, option3 ]
3478 * } );
3479 * $( 'body' ).append( buttonSelect.$element );
3480 *
3481 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options
3482 *
3483 * @class
3484 * @extends OO.ui.SelectWidget
3485 * @mixins OO.ui.mixin.TabIndexedElement
3486 *
3487 * @constructor
3488 * @param {Object} [config] Configuration options
3489 */
3490 OO.ui.ButtonSelectWidget = function OoUiButtonSelectWidget( config ) {
3491 // Parent constructor
3492 OO.ui.ButtonSelectWidget.parent.call( this, config );
3493
3494 // Mixin constructors
3495 OO.ui.mixin.TabIndexedElement.call( this, config );
3496
3497 // Events
3498 this.$element.on( {
3499 focus: this.bindKeyDownListener.bind( this ),
3500 blur: this.unbindKeyDownListener.bind( this )
3501 } );
3502
3503 // Initialization
3504 this.$element.addClass( 'oo-ui-buttonSelectWidget' );
3505 };
3506
3507 /* Setup */
3508
3509 OO.inheritClass( OO.ui.ButtonSelectWidget, OO.ui.SelectWidget );
3510 OO.mixinClass( OO.ui.ButtonSelectWidget, OO.ui.mixin.TabIndexedElement );
3511
3512 /**
3513 * TabOptionWidget is an item in a {@link OO.ui.TabSelectWidget TabSelectWidget}.
3514 *
3515 * Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}, which contain
3516 * {@link OO.ui.TabPanelLayout tab panel layouts}. See {@link OO.ui.IndexLayout IndexLayout}
3517 * for an example.
3518 *
3519 * @class
3520 * @extends OO.ui.OptionWidget
3521 *
3522 * @constructor
3523 * @param {Object} [config] Configuration options
3524 */
3525 OO.ui.TabOptionWidget = function OoUiTabOptionWidget( config ) {
3526 // Configuration initialization
3527 config = config || {};
3528
3529 // Parent constructor
3530 OO.ui.TabOptionWidget.parent.call( this, config );
3531
3532 // Initialization
3533 this.$element.addClass( 'oo-ui-tabOptionWidget' );
3534 };
3535
3536 /* Setup */
3537
3538 OO.inheritClass( OO.ui.TabOptionWidget, OO.ui.OptionWidget );
3539
3540 /* Static Properties */
3541
3542 /**
3543 * @static
3544 * @inheritdoc
3545 */
3546 OO.ui.TabOptionWidget.static.highlightable = false;
3547
3548 /**
3549 * TabSelectWidget is a list that contains {@link OO.ui.TabOptionWidget tab options}
3550 *
3551 * **Currently, this class is only used by {@link OO.ui.IndexLayout index layouts}.**
3552 *
3553 * @class
3554 * @extends OO.ui.SelectWidget
3555 * @mixins OO.ui.mixin.TabIndexedElement
3556 *
3557 * @constructor
3558 * @param {Object} [config] Configuration options
3559 */
3560 OO.ui.TabSelectWidget = function OoUiTabSelectWidget( config ) {
3561 // Parent constructor
3562 OO.ui.TabSelectWidget.parent.call( this, config );
3563
3564 // Mixin constructors
3565 OO.ui.mixin.TabIndexedElement.call( this, config );
3566
3567 // Events
3568 this.$element.on( {
3569 focus: this.bindKeyDownListener.bind( this ),
3570 blur: this.unbindKeyDownListener.bind( this )
3571 } );
3572
3573 // Initialization
3574 this.$element.addClass( 'oo-ui-tabSelectWidget' );
3575 };
3576
3577 /* Setup */
3578
3579 OO.inheritClass( OO.ui.TabSelectWidget, OO.ui.SelectWidget );
3580 OO.mixinClass( OO.ui.TabSelectWidget, OO.ui.mixin.TabIndexedElement );
3581
3582 /**
3583 * CapsuleItemWidgets are used within a {@link OO.ui.CapsuleMultiselectWidget
3584 * CapsuleMultiselectWidget} to display the selected items.
3585 *
3586 * @class
3587 * @extends OO.ui.Widget
3588 * @mixins OO.ui.mixin.ItemWidget
3589 * @mixins OO.ui.mixin.LabelElement
3590 * @mixins OO.ui.mixin.FlaggedElement
3591 * @mixins OO.ui.mixin.TabIndexedElement
3592 *
3593 * @constructor
3594 * @param {Object} [config] Configuration options
3595 */
3596 OO.ui.CapsuleItemWidget = function OoUiCapsuleItemWidget( config ) {
3597 // Configuration initialization
3598 config = config || {};
3599
3600 // Parent constructor
3601 OO.ui.CapsuleItemWidget.parent.call( this, config );
3602
3603 // Mixin constructors
3604 OO.ui.mixin.ItemWidget.call( this );
3605 OO.ui.mixin.LabelElement.call( this, config );
3606 OO.ui.mixin.FlaggedElement.call( this, config );
3607 OO.ui.mixin.TabIndexedElement.call( this, config );
3608
3609 // Events
3610 this.closeButton = new OO.ui.ButtonWidget( {
3611 framed: false,
3612 icon: 'close',
3613 tabIndex: -1,
3614 title: OO.ui.msg( 'ooui-item-remove' )
3615 } ).on( 'click', this.onCloseClick.bind( this ) );
3616
3617 this.on( 'disable', function ( disabled ) {
3618 this.closeButton.setDisabled( disabled );
3619 }.bind( this ) );
3620
3621 // Initialization
3622 this.$element
3623 .on( {
3624 click: this.onClick.bind( this ),
3625 keydown: this.onKeyDown.bind( this )
3626 } )
3627 .addClass( 'oo-ui-capsuleItemWidget' )
3628 .append( this.$label, this.closeButton.$element );
3629 };
3630
3631 /* Setup */
3632
3633 OO.inheritClass( OO.ui.CapsuleItemWidget, OO.ui.Widget );
3634 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.ItemWidget );
3635 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.LabelElement );
3636 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.FlaggedElement );
3637 OO.mixinClass( OO.ui.CapsuleItemWidget, OO.ui.mixin.TabIndexedElement );
3638
3639 /* Methods */
3640
3641 /**
3642 * Handle close icon clicks
3643 */
3644 OO.ui.CapsuleItemWidget.prototype.onCloseClick = function () {
3645 var element = this.getElementGroup();
3646
3647 if ( element && $.isFunction( element.removeItems ) ) {
3648 element.removeItems( [ this ] );
3649 element.focus();
3650 }
3651 };
3652
3653 /**
3654 * Handle click event for the entire capsule
3655 */
3656 OO.ui.CapsuleItemWidget.prototype.onClick = function () {
3657 var element = this.getElementGroup();
3658
3659 if ( !this.isDisabled() && element && $.isFunction( element.editItem ) ) {
3660 element.editItem( this );
3661 }
3662 };
3663
3664 /**
3665 * Handle keyDown event for the entire capsule
3666 *
3667 * @param {jQuery.Event} e Key down event
3668 */
3669 OO.ui.CapsuleItemWidget.prototype.onKeyDown = function ( e ) {
3670 var element = this.getElementGroup();
3671
3672 if ( e.keyCode === OO.ui.Keys.BACKSPACE || e.keyCode === OO.ui.Keys.DELETE ) {
3673 element.removeItems( [ this ] );
3674 element.focus();
3675 return false;
3676 } else if ( e.keyCode === OO.ui.Keys.ENTER ) {
3677 element.editItem( this );
3678 return false;
3679 } else if ( e.keyCode === OO.ui.Keys.LEFT ) {
3680 element.getPreviousItem( this ).focus();
3681 } else if ( e.keyCode === OO.ui.Keys.RIGHT ) {
3682 element.getNextItem( this ).focus();
3683 }
3684 };
3685
3686 /**
3687 * CapsuleMultiselectWidgets are something like a {@link OO.ui.ComboBoxInputWidget combo box widget}
3688 * that allows for selecting multiple values.
3689 *
3690 * For more information about menus and options, please see the [OOUI documentation on MediaWiki][1].
3691 *
3692 * @example
3693 * // Example: A CapsuleMultiselectWidget.
3694 * var capsule = new OO.ui.CapsuleMultiselectWidget( {
3695 * label: 'CapsuleMultiselectWidget',
3696 * selected: [ 'Option 1', 'Option 3' ],
3697 * menu: {
3698 * items: [
3699 * new OO.ui.MenuOptionWidget( {
3700 * data: 'Option 1',
3701 * label: 'Option One'
3702 * } ),
3703 * new OO.ui.MenuOptionWidget( {
3704 * data: 'Option 2',
3705 * label: 'Option Two'
3706 * } ),
3707 * new OO.ui.MenuOptionWidget( {
3708 * data: 'Option 3',
3709 * label: 'Option Three'
3710 * } ),
3711 * new OO.ui.MenuOptionWidget( {
3712 * data: 'Option 4',
3713 * label: 'Option Four'
3714 * } ),
3715 * new OO.ui.MenuOptionWidget( {
3716 * data: 'Option 5',
3717 * label: 'Option Five'
3718 * } )
3719 * ]
3720 * }
3721 * } );
3722 * $( 'body' ).append( capsule.$element );
3723 *
3724 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Menu_selects_and_options
3725 *
3726 * @class
3727 * @extends OO.ui.Widget
3728 * @mixins OO.ui.mixin.GroupElement
3729 * @mixins OO.ui.mixin.PopupElement
3730 * @mixins OO.ui.mixin.TabIndexedElement
3731 * @mixins OO.ui.mixin.IndicatorElement
3732 * @mixins OO.ui.mixin.IconElement
3733 * @uses OO.ui.CapsuleItemWidget
3734 * @uses OO.ui.MenuSelectWidget
3735 *
3736 * @constructor
3737 * @param {Object} [config] Configuration options
3738 * @cfg {string} [placeholder] Placeholder text
3739 * @cfg {boolean} [allowArbitrary=false] Allow data items to be added even if not present in the menu.
3740 * @cfg {boolean} [allowDuplicates=false] Allow duplicate items to be added.
3741 * @cfg {Object} [menu] (required) Configuration options to pass to the
3742 * {@link OO.ui.MenuSelectWidget menu select widget}.
3743 * @cfg {Object} [popup] Configuration options to pass to the {@link OO.ui.PopupWidget popup widget}.
3744 * If specified, this popup will be shown instead of the menu (but the menu
3745 * will still be used for item labels and allowArbitrary=false). The widgets
3746 * in the popup should use {@link #addItemsFromData} or {@link #addItems} as necessary.
3747 * @cfg {jQuery} [$overlay=this.$element] Render the menu or popup into a separate layer.
3748 * This configuration is useful in cases where the expanded menu is larger than
3749 * its containing `<div>`. The specified overlay layer is usually on top of
3750 * the containing `<div>` and has a larger area. By default, the menu uses
3751 * relative positioning.
3752 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
3753 */
3754 OO.ui.CapsuleMultiselectWidget = function OoUiCapsuleMultiselectWidget( config ) {
3755 var $tabFocus;
3756
3757 // Parent constructor
3758 OO.ui.CapsuleMultiselectWidget.parent.call( this, config );
3759
3760 // Configuration initialization
3761 config = $.extend( {
3762 allowArbitrary: false,
3763 allowDuplicates: false
3764 }, config );
3765
3766 // Properties (must be set before mixin constructor calls)
3767 this.$handle = $( '<div>' );
3768 this.$input = config.popup ? null : $( '<input>' );
3769 if ( config.placeholder !== undefined && config.placeholder !== '' ) {
3770 this.$input.attr( 'placeholder', config.placeholder );
3771 }
3772
3773 // Mixin constructors
3774 OO.ui.mixin.GroupElement.call( this, config );
3775 if ( config.popup ) {
3776 config.popup = $.extend( {}, config.popup, {
3777 align: 'forwards',
3778 anchor: false
3779 } );
3780 OO.ui.mixin.PopupElement.call( this, config );
3781 $tabFocus = $( '<span>' );
3782 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: $tabFocus } ) );
3783 } else {
3784 this.popup = null;
3785 $tabFocus = null;
3786 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
3787 }
3788 OO.ui.mixin.IndicatorElement.call( this, config );
3789 OO.ui.mixin.IconElement.call( this, config );
3790
3791 // Properties
3792 this.$content = $( '<div>' );
3793 this.allowArbitrary = config.allowArbitrary;
3794 this.allowDuplicates = config.allowDuplicates;
3795 this.$overlay = ( config.$overlay === true ? OO.ui.getDefaultOverlay() : config.$overlay ) || this.$element;
3796 this.menu = new OO.ui.MenuSelectWidget( $.extend(
3797 {
3798 widget: this,
3799 $input: this.$input,
3800 $floatableContainer: this.$element,
3801 filterFromInput: true,
3802 disabled: this.isDisabled()
3803 },
3804 config.menu
3805 ) );
3806
3807 // Events
3808 if ( this.popup ) {
3809 $tabFocus.on( {
3810 focus: this.focus.bind( this )
3811 } );
3812 this.popup.$element.on( 'focusout', this.onPopupFocusOut.bind( this ) );
3813 if ( this.popup.$autoCloseIgnore ) {
3814 this.popup.$autoCloseIgnore.on( 'focusout', this.onPopupFocusOut.bind( this ) );
3815 }
3816 this.popup.connect( this, {
3817 toggle: function ( visible ) {
3818 $tabFocus.toggle( !visible );
3819 }
3820 } );
3821 } else {
3822 this.$input.on( {
3823 focus: this.onInputFocus.bind( this ),
3824 blur: this.onInputBlur.bind( this ),
3825 'propertychange change click mouseup keydown keyup input cut paste select focus':
3826 OO.ui.debounce( this.updateInputSize.bind( this ) ),
3827 keydown: this.onKeyDown.bind( this ),
3828 keypress: this.onKeyPress.bind( this )
3829 } );
3830 }
3831 this.menu.connect( this, {
3832 choose: 'onMenuChoose',
3833 toggle: 'onMenuToggle',
3834 add: 'onMenuItemsChange',
3835 remove: 'onMenuItemsChange'
3836 } );
3837 this.$handle.on( {
3838 mousedown: this.onMouseDown.bind( this )
3839 } );
3840
3841 // Initialization
3842 if ( this.$input ) {
3843 this.$input.prop( 'disabled', this.isDisabled() );
3844 this.$input.attr( {
3845 role: 'combobox',
3846 'aria-owns': this.menu.getElementId(),
3847 'aria-autocomplete': 'list'
3848 } );
3849 }
3850 if ( config.data ) {
3851 this.setItemsFromData( config.data );
3852 }
3853 this.$content.addClass( 'oo-ui-capsuleMultiselectWidget-content' )
3854 .append( this.$group );
3855 this.$group.addClass( 'oo-ui-capsuleMultiselectWidget-group' );
3856 this.$handle.addClass( 'oo-ui-capsuleMultiselectWidget-handle' )
3857 .append( this.$indicator, this.$icon, this.$content );
3858 this.$element.addClass( 'oo-ui-capsuleMultiselectWidget' )
3859 .append( this.$handle );
3860 if ( this.popup ) {
3861 this.popup.$element.addClass( 'oo-ui-capsuleMultiselectWidget-popup' );
3862 this.$content.append( $tabFocus );
3863 this.$overlay.append( this.popup.$element );
3864 } else {
3865 this.$content.append( this.$input );
3866 this.$overlay.append( this.menu.$element );
3867 }
3868 if ( $tabFocus ) {
3869 $tabFocus.addClass( 'oo-ui-capsuleMultiselectWidget-focusTrap' );
3870 }
3871
3872 // Input size needs to be calculated after everything else is rendered
3873 setTimeout( function () {
3874 if ( this.$input ) {
3875 this.updateInputSize();
3876 }
3877 }.bind( this ) );
3878
3879 this.onMenuItemsChange();
3880 };
3881
3882 /* Setup */
3883
3884 OO.inheritClass( OO.ui.CapsuleMultiselectWidget, OO.ui.Widget );
3885 OO.mixinClass( OO.ui.CapsuleMultiselectWidget, OO.ui.mixin.GroupElement );
3886 OO.mixinClass( OO.ui.CapsuleMultiselectWidget, OO.ui.mixin.PopupElement );
3887 OO.mixinClass( OO.ui.CapsuleMultiselectWidget, OO.ui.mixin.TabIndexedElement );
3888 OO.mixinClass( OO.ui.CapsuleMultiselectWidget, OO.ui.mixin.IndicatorElement );
3889 OO.mixinClass( OO.ui.CapsuleMultiselectWidget, OO.ui.mixin.IconElement );
3890
3891 /* Events */
3892
3893 /**
3894 * @event change
3895 *
3896 * A change event is emitted when the set of selected items changes.
3897 *
3898 * @param {Mixed[]} datas Data of the now-selected items
3899 */
3900
3901 /**
3902 * @event resize
3903 *
3904 * A resize event is emitted when the widget's dimensions change to accomodate newly added items or
3905 * current user input.
3906 */
3907
3908 /* Methods */
3909
3910 /**
3911 * Construct a OO.ui.CapsuleItemWidget (or a subclass thereof) from given label and data.
3912 * May return `null` if the given label and data are not valid.
3913 *
3914 * @protected
3915 * @param {Mixed} data Custom data of any type.
3916 * @param {string} label The label text.
3917 * @return {OO.ui.CapsuleItemWidget|null}
3918 */
3919 OO.ui.CapsuleMultiselectWidget.prototype.createItemWidget = function ( data, label ) {
3920 if ( label === '' ) {
3921 return null;
3922 }
3923 return new OO.ui.CapsuleItemWidget( { data: data, label: label } );
3924 };
3925
3926 /**
3927 * @inheritdoc
3928 */
3929 OO.ui.CapsuleMultiselectWidget.prototype.getInputId = function () {
3930 if ( !this.$input ) {
3931 return null;
3932 }
3933 return OO.ui.mixin.TabIndexedElement.prototype.getInputId.call( this );
3934 };
3935
3936 /**
3937 * Get the data of the items in the capsule
3938 *
3939 * @return {Mixed[]}
3940 */
3941 OO.ui.CapsuleMultiselectWidget.prototype.getItemsData = function () {
3942 return this.getItems().map( function ( item ) {
3943 return item.data;
3944 } );
3945 };
3946
3947 /**
3948 * Set the items in the capsule by providing data
3949 *
3950 * @chainable
3951 * @param {Mixed[]} datas
3952 * @return {OO.ui.CapsuleMultiselectWidget}
3953 */
3954 OO.ui.CapsuleMultiselectWidget.prototype.setItemsFromData = function ( datas ) {
3955 var widget = this,
3956 menu = this.menu,
3957 items = this.getItems();
3958
3959 $.each( datas, function ( i, data ) {
3960 var j, label,
3961 item = menu.findItemFromData( data );
3962
3963 if ( item ) {
3964 label = item.label;
3965 } else if ( widget.allowArbitrary ) {
3966 label = String( data );
3967 } else {
3968 return;
3969 }
3970
3971 item = null;
3972 for ( j = 0; j < items.length; j++ ) {
3973 if ( items[ j ].data === data && items[ j ].label === label ) {
3974 item = items[ j ];
3975 items.splice( j, 1 );
3976 break;
3977 }
3978 }
3979 if ( !item ) {
3980 item = widget.createItemWidget( data, label );
3981 }
3982 if ( item ) {
3983 widget.addItems( [ item ], i );
3984 }
3985 } );
3986
3987 if ( items.length ) {
3988 widget.removeItems( items );
3989 }
3990
3991 return this;
3992 };
3993
3994 /**
3995 * Add items to the capsule by providing their data
3996 *
3997 * @chainable
3998 * @param {Mixed[]} datas
3999 * @return {OO.ui.CapsuleMultiselectWidget}
4000 */
4001 OO.ui.CapsuleMultiselectWidget.prototype.addItemsFromData = function ( datas ) {
4002 var widget = this,
4003 menu = this.menu,
4004 items = [];
4005
4006 $.each( datas, function ( i, data ) {
4007 var item;
4008
4009 if ( !widget.findItemFromData( data ) || widget.allowDuplicates ) {
4010 item = menu.findItemFromData( data );
4011 if ( item ) {
4012 item = widget.createItemWidget( data, item.label );
4013 } else if ( widget.allowArbitrary ) {
4014 item = widget.createItemWidget( data, String( data ) );
4015 }
4016 if ( item ) {
4017 items.push( item );
4018 }
4019 }
4020 } );
4021
4022 if ( items.length ) {
4023 this.addItems( items );
4024 }
4025
4026 return this;
4027 };
4028
4029 /**
4030 * Add items to the capsule by providing a label
4031 *
4032 * @param {string} label
4033 * @return {boolean} Whether the item was added or not
4034 */
4035 OO.ui.CapsuleMultiselectWidget.prototype.addItemFromLabel = function ( label ) {
4036 var item, items;
4037 item = this.menu.getItemFromLabel( label, true );
4038 if ( item ) {
4039 this.addItemsFromData( [ item.data ] );
4040 return true;
4041 } else if ( this.allowArbitrary ) {
4042 items = this.getItems();
4043 this.addItemsFromData( [ label ] );
4044 return !OO.compare( this.getItems(), items );
4045 }
4046 return false;
4047 };
4048
4049 /**
4050 * Remove items by data
4051 *
4052 * @chainable
4053 * @param {Mixed[]} datas
4054 * @return {OO.ui.CapsuleMultiselectWidget}
4055 */
4056 OO.ui.CapsuleMultiselectWidget.prototype.removeItemsFromData = function ( datas ) {
4057 var widget = this,
4058 items = [];
4059
4060 $.each( datas, function ( i, data ) {
4061 var item = widget.findItemFromData( data );
4062 if ( item ) {
4063 items.push( item );
4064 }
4065 } );
4066
4067 if ( items.length ) {
4068 this.removeItems( items );
4069 }
4070
4071 return this;
4072 };
4073
4074 /**
4075 * @inheritdoc
4076 */
4077 OO.ui.CapsuleMultiselectWidget.prototype.addItems = function ( items ) {
4078 var same, i, l,
4079 oldItems = this.items.slice();
4080
4081 OO.ui.mixin.GroupElement.prototype.addItems.call( this, items );
4082
4083 if ( this.items.length !== oldItems.length ) {
4084 same = false;
4085 } else {
4086 same = true;
4087 for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
4088 same = same && this.items[ i ] === oldItems[ i ];
4089 }
4090 }
4091 if ( !same ) {
4092 this.emit( 'change', this.getItemsData() );
4093 this.updateInputSize();
4094 }
4095
4096 return this;
4097 };
4098
4099 /**
4100 * Removes the item from the list and copies its label to `this.$input`.
4101 *
4102 * @param {Object} item
4103 */
4104 OO.ui.CapsuleMultiselectWidget.prototype.editItem = function ( item ) {
4105 this.addItemFromLabel( this.$input.val() );
4106 this.clearInput();
4107 this.$input.val( item.label );
4108 this.updateInputSize();
4109 this.focus();
4110 this.menu.updateItemVisibility(); // Hack, we shouldn't be calling this method directly
4111 this.removeItems( [ item ] );
4112 };
4113
4114 /**
4115 * @inheritdoc
4116 */
4117 OO.ui.CapsuleMultiselectWidget.prototype.removeItems = function ( items ) {
4118 var same, i, l,
4119 oldItems = this.items.slice();
4120
4121 OO.ui.mixin.GroupElement.prototype.removeItems.call( this, items );
4122
4123 if ( this.items.length !== oldItems.length ) {
4124 same = false;
4125 } else {
4126 same = true;
4127 for ( i = 0, l = oldItems.length; same && i < l; i++ ) {
4128 same = same && this.items[ i ] === oldItems[ i ];
4129 }
4130 }
4131 if ( !same ) {
4132 this.emit( 'change', this.getItemsData() );
4133 this.updateInputSize();
4134 }
4135
4136 return this;
4137 };
4138
4139 /**
4140 * @inheritdoc
4141 */
4142 OO.ui.CapsuleMultiselectWidget.prototype.clearItems = function () {
4143 if ( this.items.length ) {
4144 OO.ui.mixin.GroupElement.prototype.clearItems.call( this );
4145 this.emit( 'change', this.getItemsData() );
4146 this.updateInputSize();
4147 }
4148 return this;
4149 };
4150
4151 /**
4152 * Given an item, returns the item after it. If its the last item,
4153 * returns `this.$input`. If no item is passed, returns the very first
4154 * item.
4155 *
4156 * @param {OO.ui.CapsuleItemWidget} [item]
4157 * @return {OO.ui.CapsuleItemWidget|jQuery|boolean}
4158 */
4159 OO.ui.CapsuleMultiselectWidget.prototype.getNextItem = function ( item ) {
4160 var itemIndex;
4161
4162 if ( item === undefined ) {
4163 return this.items[ 0 ];
4164 }
4165
4166 itemIndex = this.items.indexOf( item );
4167 if ( itemIndex < 0 ) { // Item not in list
4168 return false;
4169 } else if ( itemIndex === this.items.length - 1 ) { // Last item
4170 return this.$input;
4171 } else {
4172 return this.items[ itemIndex + 1 ];
4173 }
4174 };
4175
4176 /**
4177 * Given an item, returns the item before it. If its the first item,
4178 * returns `this.$input`. If no item is passed, returns the very last
4179 * item.
4180 *
4181 * @param {OO.ui.CapsuleItemWidget} [item]
4182 * @return {OO.ui.CapsuleItemWidget|jQuery|boolean}
4183 */
4184 OO.ui.CapsuleMultiselectWidget.prototype.getPreviousItem = function ( item ) {
4185 var itemIndex;
4186
4187 if ( item === undefined ) {
4188 return this.items[ this.items.length - 1 ];
4189 }
4190
4191 itemIndex = this.items.indexOf( item );
4192 if ( itemIndex < 0 ) { // Item not in list
4193 return false;
4194 } else if ( itemIndex === 0 ) { // First item
4195 return this.$input;
4196 } else {
4197 return this.items[ itemIndex - 1 ];
4198 }
4199 };
4200
4201 /**
4202 * Get the capsule widget's menu.
4203 *
4204 * @return {OO.ui.MenuSelectWidget} Menu widget
4205 */
4206 OO.ui.CapsuleMultiselectWidget.prototype.getMenu = function () {
4207 return this.menu;
4208 };
4209
4210 /**
4211 * Handle focus events
4212 *
4213 * @private
4214 * @param {jQuery.Event} event
4215 */
4216 OO.ui.CapsuleMultiselectWidget.prototype.onInputFocus = function () {
4217 if ( !this.isDisabled() ) {
4218 this.updateInputSize();
4219 this.menu.toggle( true );
4220 }
4221 };
4222
4223 /**
4224 * Handle blur events
4225 *
4226 * @private
4227 * @param {jQuery.Event} event
4228 */
4229 OO.ui.CapsuleMultiselectWidget.prototype.onInputBlur = function () {
4230 this.addItemFromLabel( this.$input.val() );
4231 this.clearInput();
4232 };
4233
4234 /**
4235 * Handles popup focus out events.
4236 *
4237 * @private
4238 * @param {jQuery.Event} e Focus out event
4239 */
4240 OO.ui.CapsuleMultiselectWidget.prototype.onPopupFocusOut = function () {
4241 var widget = this.popup;
4242
4243 setTimeout( function () {
4244 if (
4245 widget.isVisible() &&
4246 !OO.ui.contains( widget.$element.add( widget.$autoCloseIgnore ).get(), document.activeElement, true )
4247 ) {
4248 widget.toggle( false );
4249 }
4250 } );
4251 };
4252
4253 /**
4254 * Handle mouse down events.
4255 *
4256 * @private
4257 * @param {jQuery.Event} e Mouse down event
4258 */
4259 OO.ui.CapsuleMultiselectWidget.prototype.onMouseDown = function ( e ) {
4260 if ( e.which === OO.ui.MouseButtons.LEFT ) {
4261 this.focus();
4262 return false;
4263 } else {
4264 this.updateInputSize();
4265 }
4266 };
4267
4268 /**
4269 * Handle key press events.
4270 *
4271 * @private
4272 * @param {jQuery.Event} e Key press event
4273 */
4274 OO.ui.CapsuleMultiselectWidget.prototype.onKeyPress = function ( e ) {
4275 if ( !this.isDisabled() ) {
4276 if ( e.which === OO.ui.Keys.ESCAPE ) {
4277 this.clearInput();
4278 return false;
4279 }
4280
4281 if ( !this.popup ) {
4282 this.menu.toggle( true );
4283 if ( e.which === OO.ui.Keys.ENTER ) {
4284 if ( this.addItemFromLabel( this.$input.val() ) ) {
4285 this.clearInput();
4286 }
4287 return false;
4288 }
4289
4290 // Make sure the input gets resized.
4291 setTimeout( this.updateInputSize.bind( this ), 0 );
4292 }
4293 }
4294 };
4295
4296 /**
4297 * Handle key down events.
4298 *
4299 * @private
4300 * @param {jQuery.Event} e Key down event
4301 */
4302 OO.ui.CapsuleMultiselectWidget.prototype.onKeyDown = function ( e ) {
4303 if (
4304 !this.isDisabled() &&
4305 this.$input.val() === '' &&
4306 this.items.length
4307 ) {
4308 // 'keypress' event is not triggered for Backspace
4309 if ( e.keyCode === OO.ui.Keys.BACKSPACE ) {
4310 if ( e.metaKey || e.ctrlKey ) {
4311 this.removeItems( this.items.slice( -1 ) );
4312 } else {
4313 this.editItem( this.items[ this.items.length - 1 ] );
4314 }
4315 return false;
4316 } else if ( e.keyCode === OO.ui.Keys.LEFT ) {
4317 this.getPreviousItem().focus();
4318 } else if ( e.keyCode === OO.ui.Keys.RIGHT ) {
4319 this.getNextItem().focus();
4320 }
4321 }
4322 };
4323
4324 /**
4325 * Update the dimensions of the text input field to encompass all available area.
4326 *
4327 * @private
4328 * @param {jQuery.Event} e Event of some sort
4329 */
4330 OO.ui.CapsuleMultiselectWidget.prototype.updateInputSize = function () {
4331 var $lastItem, direction, contentWidth, currentWidth, bestWidth;
4332 if ( this.$input && !this.isDisabled() ) {
4333 this.$input.css( 'width', '1em' );
4334 $lastItem = this.$group.children().last();
4335 direction = OO.ui.Element.static.getDir( this.$handle );
4336
4337 // Get the width of the input with the placeholder text as
4338 // the value and save it so that we don't keep recalculating
4339 if (
4340 this.contentWidthWithPlaceholder === undefined &&
4341 this.$input.val() === '' &&
4342 this.$input.attr( 'placeholder' ) !== undefined
4343 ) {
4344 this.$input.val( this.$input.attr( 'placeholder' ) );
4345 this.contentWidthWithPlaceholder = this.$input[ 0 ].scrollWidth;
4346 this.$input.val( '' );
4347
4348 }
4349
4350 // Always keep the input wide enough for the placeholder text
4351 contentWidth = Math.max(
4352 this.$input[ 0 ].scrollWidth,
4353 // undefined arguments in Math.max lead to NaN
4354 ( this.contentWidthWithPlaceholder === undefined ) ?
4355 0 : this.contentWidthWithPlaceholder
4356 );
4357 currentWidth = this.$input.width();
4358
4359 if ( contentWidth < currentWidth ) {
4360 this.updateIfHeightChanged();
4361 // All is fine, don't perform expensive calculations
4362 return;
4363 }
4364
4365 if ( $lastItem.length === 0 ) {
4366 bestWidth = this.$content.innerWidth();
4367 } else {
4368 bestWidth = direction === 'ltr' ?
4369 this.$content.innerWidth() - $lastItem.position().left - $lastItem.outerWidth() :
4370 $lastItem.position().left;
4371 }
4372
4373 // Some safety margin for sanity, because I *really* don't feel like finding out where the few
4374 // pixels this is off by are coming from.
4375 bestWidth -= 10;
4376 if ( contentWidth > bestWidth ) {
4377 // This will result in the input getting shifted to the next line
4378 bestWidth = this.$content.innerWidth() - 10;
4379 }
4380 this.$input.width( Math.floor( bestWidth ) );
4381 this.updateIfHeightChanged();
4382 } else {
4383 this.updateIfHeightChanged();
4384 }
4385 };
4386
4387 /**
4388 * Determine if widget height changed, and if so, update menu position and emit 'resize' event.
4389 *
4390 * @private
4391 */
4392 OO.ui.CapsuleMultiselectWidget.prototype.updateIfHeightChanged = function () {
4393 var height = this.$element.height();
4394 if ( height !== this.height ) {
4395 this.height = height;
4396 this.menu.position();
4397 if ( this.popup ) {
4398 this.popup.updateDimensions();
4399 }
4400 this.emit( 'resize' );
4401 }
4402 };
4403
4404 /**
4405 * Handle menu choose events.
4406 *
4407 * @private
4408 * @param {OO.ui.OptionWidget} item Chosen item
4409 */
4410 OO.ui.CapsuleMultiselectWidget.prototype.onMenuChoose = function ( item ) {
4411 if ( item && item.isVisible() ) {
4412 this.addItemsFromData( [ item.getData() ] );
4413 this.clearInput();
4414 }
4415 };
4416
4417 /**
4418 * Handle menu toggle events.
4419 *
4420 * @private
4421 * @param {boolean} isVisible Open state of the menu
4422 */
4423 OO.ui.CapsuleMultiselectWidget.prototype.onMenuToggle = function ( isVisible ) {
4424 this.$element.toggleClass( 'oo-ui-capsuleMultiselectWidget-open', isVisible );
4425 };
4426
4427 /**
4428 * Handle menu item change events.
4429 *
4430 * @private
4431 */
4432 OO.ui.CapsuleMultiselectWidget.prototype.onMenuItemsChange = function () {
4433 this.setItemsFromData( this.getItemsData() );
4434 this.$element.toggleClass( 'oo-ui-capsuleMultiselectWidget-empty', this.menu.isEmpty() );
4435 };
4436
4437 /**
4438 * Clear the input field
4439 *
4440 * @private
4441 */
4442 OO.ui.CapsuleMultiselectWidget.prototype.clearInput = function () {
4443 if ( this.$input ) {
4444 this.$input.val( '' );
4445 this.updateInputSize();
4446 }
4447 if ( this.popup ) {
4448 this.popup.toggle( false );
4449 }
4450 this.menu.toggle( false );
4451 this.menu.selectItem();
4452 this.menu.highlightItem();
4453 };
4454
4455 /**
4456 * @inheritdoc
4457 */
4458 OO.ui.CapsuleMultiselectWidget.prototype.setDisabled = function ( disabled ) {
4459 var i, len;
4460
4461 // Parent method
4462 OO.ui.CapsuleMultiselectWidget.parent.prototype.setDisabled.call( this, disabled );
4463
4464 if ( this.$input ) {
4465 this.$input.prop( 'disabled', this.isDisabled() );
4466 }
4467 if ( this.menu ) {
4468 this.menu.setDisabled( this.isDisabled() );
4469 }
4470 if ( this.popup ) {
4471 this.popup.setDisabled( this.isDisabled() );
4472 }
4473
4474 if ( this.items ) {
4475 for ( i = 0, len = this.items.length; i < len; i++ ) {
4476 this.items[ i ].updateDisabled();
4477 }
4478 }
4479
4480 return this;
4481 };
4482
4483 /**
4484 * Focus the widget
4485 *
4486 * @chainable
4487 */
4488 OO.ui.CapsuleMultiselectWidget.prototype.focus = function () {
4489 if ( !this.isDisabled() ) {
4490 if ( this.popup ) {
4491 this.popup.setSize( this.$handle.outerWidth() );
4492 this.popup.toggle( true );
4493 OO.ui.findFocusable( this.popup.$element ).focus();
4494 } else {
4495 OO.ui.mixin.TabIndexedElement.prototype.focus.call( this );
4496 }
4497 }
4498 return this;
4499 };
4500
4501 /**
4502 * TagItemWidgets are used within a {@link OO.ui.TagMultiselectWidget
4503 * TagMultiselectWidget} to display the selected items.
4504 *
4505 * @class
4506 * @extends OO.ui.Widget
4507 * @mixins OO.ui.mixin.ItemWidget
4508 * @mixins OO.ui.mixin.LabelElement
4509 * @mixins OO.ui.mixin.FlaggedElement
4510 * @mixins OO.ui.mixin.TabIndexedElement
4511 * @mixins OO.ui.mixin.DraggableElement
4512 *
4513 * @constructor
4514 * @param {Object} [config] Configuration object
4515 * @cfg {boolean} [valid=true] Item is valid
4516 * @cfg {boolean} [fixed] Item is fixed. This means the item is
4517 * always included in the values and cannot be removed.
4518 */
4519 OO.ui.TagItemWidget = function OoUiTagItemWidget( config ) {
4520 config = config || {};
4521
4522 // Parent constructor
4523 OO.ui.TagItemWidget.parent.call( this, config );
4524
4525 // Mixin constructors
4526 OO.ui.mixin.ItemWidget.call( this );
4527 OO.ui.mixin.LabelElement.call( this, config );
4528 OO.ui.mixin.FlaggedElement.call( this, config );
4529 OO.ui.mixin.TabIndexedElement.call( this, config );
4530 OO.ui.mixin.DraggableElement.call( this, config );
4531
4532 this.valid = config.valid === undefined ? true : !!config.valid;
4533 this.fixed = !!config.fixed;
4534
4535 this.closeButton = new OO.ui.ButtonWidget( {
4536 framed: false,
4537 icon: 'close',
4538 tabIndex: -1,
4539 title: OO.ui.msg( 'ooui-item-remove' )
4540 } );
4541 this.closeButton.setDisabled( this.isDisabled() );
4542
4543 // Events
4544 this.closeButton
4545 .connect( this, { click: 'remove' } );
4546 this.$element
4547 .on( 'click', this.select.bind( this ) )
4548 .on( 'keydown', this.onKeyDown.bind( this ) )
4549 // Prevent propagation of mousedown; the tag item "lives" in the
4550 // clickable area of the TagMultiselectWidget, which listens to
4551 // mousedown to open the menu or popup. We want to prevent that
4552 // for clicks specifically on the tag itself, so the actions taken
4553 // are more deliberate. When the tag is clicked, it will emit the
4554 // selection event (similar to how #OO.ui.MultioptionWidget emits 'change')
4555 // and can be handled separately.
4556 .on( 'mousedown', function ( e ) { e.stopPropagation(); } );
4557
4558 // Initialization
4559 this.$element
4560 .addClass( 'oo-ui-tagItemWidget' )
4561 .append( this.$label, this.closeButton.$element );
4562 };
4563
4564 /* Initialization */
4565
4566 OO.inheritClass( OO.ui.TagItemWidget, OO.ui.Widget );
4567 OO.mixinClass( OO.ui.TagItemWidget, OO.ui.mixin.ItemWidget );
4568 OO.mixinClass( OO.ui.TagItemWidget, OO.ui.mixin.LabelElement );
4569 OO.mixinClass( OO.ui.TagItemWidget, OO.ui.mixin.FlaggedElement );
4570 OO.mixinClass( OO.ui.TagItemWidget, OO.ui.mixin.TabIndexedElement );
4571 OO.mixinClass( OO.ui.TagItemWidget, OO.ui.mixin.DraggableElement );
4572
4573 /* Events */
4574
4575 /**
4576 * @event remove
4577 *
4578 * A remove action was performed on the item
4579 */
4580
4581 /**
4582 * @event navigate
4583 * @param {string} direction Direction of the movement, forward or backwards
4584 *
4585 * A navigate action was performed on the item
4586 */
4587
4588 /**
4589 * @event select
4590 *
4591 * The tag widget was selected. This can occur when the widget
4592 * is either clicked or enter was pressed on it.
4593 */
4594
4595 /**
4596 * @event valid
4597 * @param {boolean} isValid Item is valid
4598 *
4599 * Item validity has changed
4600 */
4601
4602 /**
4603 * @event fixed
4604 * @param {boolean} isFixed Item is fixed
4605 *
4606 * Item fixed state has changed
4607 */
4608
4609 /* Methods */
4610
4611 /**
4612 * Set this item as fixed, meaning it cannot be removed
4613 *
4614 * @param {string} [state] Item is fixed
4615 * @fires fixed
4616 */
4617 OO.ui.TagItemWidget.prototype.setFixed = function ( state ) {
4618 state = state === undefined ? !this.fixed : !!state;
4619
4620 if ( this.fixed !== state ) {
4621 this.fixed = state;
4622 if ( this.closeButton ) {
4623 this.closeButton.toggle( !this.fixed );
4624 }
4625
4626 if ( !this.fixed && this.elementGroup && !this.elementGroup.isDraggable() ) {
4627 // Only enable the state of the item if the
4628 // entire group is draggable
4629 this.toggleDraggable( !this.fixed );
4630 }
4631 this.$element.toggleClass( 'oo-ui-tagItemWidget-fixed', this.fixed );
4632
4633 this.emit( 'fixed', this.isFixed() );
4634 }
4635 return this;
4636 };
4637
4638 /**
4639 * Check whether the item is fixed
4640 */
4641 OO.ui.TagItemWidget.prototype.isFixed = function () {
4642 return this.fixed;
4643 };
4644
4645 /**
4646 * @inheritdoc
4647 */
4648 OO.ui.TagItemWidget.prototype.setDisabled = function ( state ) {
4649 if ( state && this.elementGroup && !this.elementGroup.isDisabled() ) {
4650 OO.ui.warnDeprecation( 'TagItemWidget#setDisabled: Disabling individual items is deprecated and will result in inconsistent behavior. Use #setFixed instead. See T193571.' );
4651 }
4652 // Parent method
4653 OO.ui.TagItemWidget.parent.prototype.setDisabled.call( this, state );
4654 if (
4655 !state &&
4656 // Verify we have a group, and that the widget is ready
4657 this.toggleDraggable && this.elementGroup &&
4658 !this.isFixed() &&
4659 !this.elementGroup.isDraggable()
4660 ) {
4661 // Only enable the draggable state of the item if the
4662 // entire group is draggable to begin with, and if the
4663 // item is not fixed
4664 this.toggleDraggable( !state );
4665 }
4666
4667 if ( this.closeButton ) {
4668 this.closeButton.setDisabled( state );
4669 }
4670
4671 return this;
4672 };
4673
4674 /**
4675 * Handle removal of the item
4676 *
4677 * This is mainly for extensibility concerns, so other children
4678 * of this class can change the behavior if they need to. This
4679 * is called by both clicking the 'remove' button but also
4680 * on keypress, which is harder to override if needed.
4681 *
4682 * @fires remove
4683 */
4684 OO.ui.TagItemWidget.prototype.remove = function () {
4685 if ( !this.isDisabled() ) {
4686 this.emit( 'remove' );
4687 }
4688 };
4689
4690 /**
4691 * Handle a keydown event on the widget
4692 *
4693 * @fires navigate
4694 * @fires remove
4695 * @param {jQuery.Event} e Key down event
4696 * @return {boolean|undefined} false to stop the operation
4697 */
4698 OO.ui.TagItemWidget.prototype.onKeyDown = function ( e ) {
4699 var movement;
4700
4701 if ( !this.isDisabled() && !this.isFixed() && e.keyCode === OO.ui.Keys.BACKSPACE || e.keyCode === OO.ui.Keys.DELETE ) {
4702 this.remove();
4703 return false;
4704 } else if ( e.keyCode === OO.ui.Keys.ENTER ) {
4705 this.select();
4706 return false;
4707 } else if (
4708 e.keyCode === OO.ui.Keys.LEFT ||
4709 e.keyCode === OO.ui.Keys.RIGHT
4710 ) {
4711 if ( OO.ui.Element.static.getDir( this.$element ) === 'rtl' ) {
4712 movement = {
4713 left: 'forwards',
4714 right: 'backwards'
4715 };
4716 } else {
4717 movement = {
4718 left: 'backwards',
4719 right: 'forwards'
4720 };
4721 }
4722
4723 this.emit(
4724 'navigate',
4725 e.keyCode === OO.ui.Keys.LEFT ?
4726 movement.left : movement.right
4727 );
4728 return false;
4729 }
4730 };
4731
4732 /**
4733 * Select this item
4734 *
4735 * @fires select
4736 */
4737 OO.ui.TagItemWidget.prototype.select = function () {
4738 if ( !this.isDisabled() ) {
4739 this.emit( 'select' );
4740 }
4741 };
4742
4743 /**
4744 * Set the valid state of this item
4745 *
4746 * @param {boolean} [valid] Item is valid
4747 * @fires valid
4748 */
4749 OO.ui.TagItemWidget.prototype.toggleValid = function ( valid ) {
4750 valid = valid === undefined ? !this.valid : !!valid;
4751
4752 if ( this.valid !== valid ) {
4753 this.valid = valid;
4754
4755 this.setFlags( { invalid: !this.valid } );
4756
4757 this.emit( 'valid', this.valid );
4758 }
4759 };
4760
4761 /**
4762 * Check whether the item is valid
4763 *
4764 * @return {boolean} Item is valid
4765 */
4766 OO.ui.TagItemWidget.prototype.isValid = function () {
4767 return this.valid;
4768 };
4769
4770 /**
4771 * A basic tag multiselect widget, similar in concept to {@link OO.ui.ComboBoxInputWidget combo box widget}
4772 * that allows the user to add multiple values that are displayed in a tag area.
4773 *
4774 * This widget is a base widget; see {@link OO.ui.MenuTagMultiselectWidget MenuTagMultiselectWidget} and
4775 * {@link OO.ui.PopupTagMultiselectWidget PopupTagMultiselectWidget} for the implementations that use
4776 * a menu and a popup respectively.
4777 *
4778 * @example
4779 * // Example: A basic TagMultiselectWidget.
4780 * var widget = new OO.ui.TagMultiselectWidget( {
4781 * inputPosition: 'outline',
4782 * allowedValues: [ 'Option 1', 'Option 2', 'Option 3' ],
4783 * selected: [ 'Option 1' ]
4784 * } );
4785 * $( 'body' ).append( widget.$element );
4786 *
4787 * @class
4788 * @extends OO.ui.Widget
4789 * @mixins OO.ui.mixin.GroupWidget
4790 * @mixins OO.ui.mixin.DraggableGroupElement
4791 * @mixins OO.ui.mixin.IndicatorElement
4792 * @mixins OO.ui.mixin.IconElement
4793 * @mixins OO.ui.mixin.TabIndexedElement
4794 * @mixins OO.ui.mixin.FlaggedElement
4795 *
4796 * @constructor
4797 * @param {Object} config Configuration object
4798 * @cfg {Object} [input] Configuration options for the input widget
4799 * @cfg {OO.ui.InputWidget} [inputWidget] An optional input widget. If given, it will
4800 * replace the input widget used in the TagMultiselectWidget. If not given,
4801 * TagMultiselectWidget creates its own.
4802 * @cfg {boolean} [inputPosition='inline'] Position of the input. Options are:
4803 * - inline: The input is invisible, but exists inside the tag list, so
4804 * the user types into the tag groups to add tags.
4805 * - outline: The input is underneath the tag area.
4806 * - none: No input supplied
4807 * @cfg {boolean} [allowEditTags=true] Allow editing of the tags by clicking them
4808 * @cfg {boolean} [allowArbitrary=false] Allow data items to be added even if
4809 * not present in the menu.
4810 * @cfg {Object[]} [allowedValues] An array representing the allowed items
4811 * by their datas.
4812 * @cfg {boolean} [allowDuplicates=false] Allow duplicate items to be added
4813 * @cfg {boolean} [allowDisplayInvalidTags=false] Allow the display of
4814 * invalid tags. These tags will display with an invalid state, and
4815 * the widget as a whole will have an invalid state if any invalid tags
4816 * are present.
4817 * @cfg {boolean} [allowReordering=true] Allow reordering of the items
4818 * @cfg {Object[]|String[]} [selected] A set of selected tags. If given,
4819 * these will appear in the tag list on initialization, as long as they
4820 * pass the validity tests.
4821 */
4822 OO.ui.TagMultiselectWidget = function OoUiTagMultiselectWidget( config ) {
4823 var inputEvents,
4824 rAF = window.requestAnimationFrame || setTimeout,
4825 widget = this,
4826 $tabFocus = $( '<span>' )
4827 .addClass( 'oo-ui-tagMultiselectWidget-focusTrap' );
4828
4829 config = config || {};
4830
4831 // Parent constructor
4832 OO.ui.TagMultiselectWidget.parent.call( this, config );
4833
4834 // Mixin constructors
4835 OO.ui.mixin.GroupWidget.call( this, config );
4836 OO.ui.mixin.IndicatorElement.call( this, config );
4837 OO.ui.mixin.IconElement.call( this, config );
4838 OO.ui.mixin.TabIndexedElement.call( this, config );
4839 OO.ui.mixin.FlaggedElement.call( this, config );
4840 OO.ui.mixin.DraggableGroupElement.call( this, config );
4841
4842 this.toggleDraggable(
4843 config.allowReordering === undefined ?
4844 true : !!config.allowReordering
4845 );
4846
4847 this.inputPosition =
4848 this.constructor.static.allowedInputPositions.indexOf( config.inputPosition ) > -1 ?
4849 config.inputPosition : 'inline';
4850 this.allowEditTags = config.allowEditTags === undefined ? true : !!config.allowEditTags;
4851 this.allowArbitrary = !!config.allowArbitrary;
4852 this.allowDuplicates = !!config.allowDuplicates;
4853 this.allowedValues = config.allowedValues || [];
4854 this.allowDisplayInvalidTags = config.allowDisplayInvalidTags;
4855 this.hasInput = this.inputPosition !== 'none';
4856 this.height = null;
4857 this.valid = true;
4858
4859 this.$content = $( '<div>' )
4860 .addClass( 'oo-ui-tagMultiselectWidget-content' );
4861 this.$handle = $( '<div>' )
4862 .addClass( 'oo-ui-tagMultiselectWidget-handle' )
4863 .append(
4864 this.$indicator,
4865 this.$icon,
4866 this.$content
4867 .append(
4868 this.$group
4869 .addClass( 'oo-ui-tagMultiselectWidget-group' )
4870 )
4871 );
4872
4873 // Events
4874 this.aggregate( {
4875 remove: 'itemRemove',
4876 navigate: 'itemNavigate',
4877 select: 'itemSelect',
4878 fixed: 'itemFixed'
4879 } );
4880 this.connect( this, {
4881 itemRemove: 'onTagRemove',
4882 itemSelect: 'onTagSelect',
4883 itemFixed: 'onTagFixed',
4884 itemNavigate: 'onTagNavigate',
4885 change: 'onChangeTags'
4886 } );
4887 this.$handle.on( {
4888 mousedown: this.onMouseDown.bind( this )
4889 } );
4890
4891 // Initialize
4892 this.$element
4893 .addClass( 'oo-ui-tagMultiselectWidget' )
4894 .append( this.$handle );
4895
4896 if ( this.hasInput ) {
4897 if ( config.inputWidget ) {
4898 this.input = config.inputWidget;
4899 } else {
4900 this.input = new OO.ui.TextInputWidget( $.extend( {
4901 placeholder: config.placeholder,
4902 classes: [ 'oo-ui-tagMultiselectWidget-input' ]
4903 }, config.input ) );
4904 }
4905 this.input.setDisabled( this.isDisabled() );
4906
4907 inputEvents = {
4908 focus: this.onInputFocus.bind( this ),
4909 blur: this.onInputBlur.bind( this ),
4910 'propertychange change click mouseup keydown keyup input cut paste select focus':
4911 OO.ui.debounce( this.updateInputSize.bind( this ) ),
4912 keydown: this.onInputKeyDown.bind( this ),
4913 keypress: this.onInputKeyPress.bind( this )
4914 };
4915
4916 this.input.$input.on( inputEvents );
4917
4918 if ( this.inputPosition === 'outline' ) {
4919 // Override max-height for the input widget
4920 // in the case the widget is outline so it can
4921 // stretch all the way if the widet is wide
4922 this.input.$element.css( 'max-width', 'inherit' );
4923 this.$element
4924 .addClass( 'oo-ui-tagMultiselectWidget-outlined' )
4925 .append( this.input.$element );
4926 } else {
4927 this.$element.addClass( 'oo-ui-tagMultiselectWidget-inlined' );
4928 // HACK: When the widget is using 'inline' input, the
4929 // behavior needs to only use the $input itself
4930 // so we style and size it accordingly (otherwise
4931 // the styling and sizing can get very convoluted
4932 // when the wrapping divs and other elements)
4933 // We are taking advantage of still being able to
4934 // call the widget itself for operations like
4935 // .getValue() and setDisabled() and .focus() but
4936 // having only the $input attached to the DOM
4937 this.$content.append( this.input.$input );
4938 }
4939 } else {
4940 this.$content.append( $tabFocus );
4941 }
4942
4943 this.setTabIndexedElement(
4944 this.hasInput ?
4945 this.input.$input :
4946 $tabFocus
4947 );
4948
4949 if ( config.selected ) {
4950 this.setValue( config.selected );
4951 }
4952
4953 // HACK: Input size needs to be calculated after everything
4954 // else is rendered
4955 rAF( function () {
4956 if ( widget.hasInput ) {
4957 widget.updateInputSize();
4958 }
4959 } );
4960 };
4961
4962 /* Initialization */
4963
4964 OO.inheritClass( OO.ui.TagMultiselectWidget, OO.ui.Widget );
4965 OO.mixinClass( OO.ui.TagMultiselectWidget, OO.ui.mixin.GroupWidget );
4966 OO.mixinClass( OO.ui.TagMultiselectWidget, OO.ui.mixin.DraggableGroupElement );
4967 OO.mixinClass( OO.ui.TagMultiselectWidget, OO.ui.mixin.IndicatorElement );
4968 OO.mixinClass( OO.ui.TagMultiselectWidget, OO.ui.mixin.IconElement );
4969 OO.mixinClass( OO.ui.TagMultiselectWidget, OO.ui.mixin.TabIndexedElement );
4970 OO.mixinClass( OO.ui.TagMultiselectWidget, OO.ui.mixin.FlaggedElement );
4971
4972 /* Static properties */
4973
4974 /**
4975 * Allowed input positions.
4976 * - inline: The input is inside the tag list
4977 * - outline: The input is under the tag list
4978 * - none: There is no input
4979 *
4980 * @property {Array}
4981 */
4982 OO.ui.TagMultiselectWidget.static.allowedInputPositions = [ 'inline', 'outline', 'none' ];
4983
4984 /* Methods */
4985
4986 /**
4987 * Handle mouse down events.
4988 *
4989 * @private
4990 * @param {jQuery.Event} e Mouse down event
4991 * @return {boolean} False to prevent defaults
4992 */
4993 OO.ui.TagMultiselectWidget.prototype.onMouseDown = function ( e ) {
4994 if (
4995 !this.isDisabled() &&
4996 ( !this.hasInput || e.target !== this.input.$input[ 0 ] ) &&
4997 e.which === OO.ui.MouseButtons.LEFT
4998 ) {
4999 this.focus();
5000 return false;
5001 }
5002 };
5003
5004 /**
5005 * Handle key press events.
5006 *
5007 * @private
5008 * @param {jQuery.Event} e Key press event
5009 * @return {boolean} Whether to prevent defaults
5010 */
5011 OO.ui.TagMultiselectWidget.prototype.onInputKeyPress = function ( e ) {
5012 var stopOrContinue,
5013 withMetaKey = e.metaKey || e.ctrlKey;
5014
5015 if ( !this.isDisabled() ) {
5016 if ( e.which === OO.ui.Keys.ENTER ) {
5017 stopOrContinue = this.doInputEnter( e, withMetaKey );
5018 }
5019
5020 // Make sure the input gets resized.
5021 setTimeout( this.updateInputSize.bind( this ), 0 );
5022 return stopOrContinue;
5023 }
5024 };
5025
5026 /**
5027 * Handle key down events.
5028 *
5029 * @private
5030 * @param {jQuery.Event} e Key down event
5031 * @return {boolean}
5032 */
5033 OO.ui.TagMultiselectWidget.prototype.onInputKeyDown = function ( e ) {
5034 var movement, direction,
5035 widget = this,
5036 withMetaKey = e.metaKey || e.ctrlKey,
5037 isMovementInsideInput = function ( direction ) {
5038 var inputRange = widget.input.getRange(),
5039 inputValue = widget.hasInput && widget.input.getValue();
5040
5041 if ( direction === 'forwards' && inputRange.to > inputValue.length - 1 ) {
5042 return false;
5043 }
5044
5045 if ( direction === 'backwards' && inputRange.from <= 0 ) {
5046 return false;
5047 }
5048
5049 return true;
5050 };
5051
5052 if ( !this.isDisabled() ) {
5053 // 'keypress' event is not triggered for Backspace
5054 if ( e.keyCode === OO.ui.Keys.BACKSPACE ) {
5055 return this.doInputBackspace( e, withMetaKey );
5056 } else if ( e.keyCode === OO.ui.Keys.ESCAPE ) {
5057 return this.doInputEscape( e );
5058 } else if (
5059 e.keyCode === OO.ui.Keys.LEFT ||
5060 e.keyCode === OO.ui.Keys.RIGHT
5061 ) {
5062 if ( OO.ui.Element.static.getDir( this.$element ) === 'rtl' ) {
5063 movement = {
5064 left: 'forwards',
5065 right: 'backwards'
5066 };
5067 } else {
5068 movement = {
5069 left: 'backwards',
5070 right: 'forwards'
5071 };
5072 }
5073 direction = e.keyCode === OO.ui.Keys.LEFT ?
5074 movement.left : movement.right;
5075
5076 if ( !this.hasInput || !isMovementInsideInput( direction ) ) {
5077 return this.doInputArrow( e, direction, withMetaKey );
5078 }
5079 }
5080 }
5081 };
5082
5083 /**
5084 * Respond to input focus event
5085 */
5086 OO.ui.TagMultiselectWidget.prototype.onInputFocus = function () {
5087 this.$element.addClass( 'oo-ui-tagMultiselectWidget-focus' );
5088 };
5089
5090 /**
5091 * Respond to input blur event
5092 */
5093 OO.ui.TagMultiselectWidget.prototype.onInputBlur = function () {
5094 this.$element.removeClass( 'oo-ui-tagMultiselectWidget-focus' );
5095 };
5096
5097 /**
5098 * Perform an action after the enter key on the input
5099 *
5100 * @param {jQuery.Event} e Event data
5101 * @param {boolean} [withMetaKey] Whether this key was pressed with
5102 * a meta key like 'ctrl'
5103 * @return {boolean} Whether to prevent defaults
5104 */
5105 OO.ui.TagMultiselectWidget.prototype.doInputEnter = function () {
5106 this.addTagFromInput();
5107 return false;
5108 };
5109
5110 /**
5111 * Perform an action responding to the enter key on the input
5112 *
5113 * @param {jQuery.Event} e Event data
5114 * @param {boolean} [withMetaKey] Whether this key was pressed with
5115 * a meta key like 'ctrl'
5116 * @return {boolean} Whether to prevent defaults
5117 */
5118 OO.ui.TagMultiselectWidget.prototype.doInputBackspace = function ( e, withMetaKey ) {
5119 var items, item;
5120
5121 if (
5122 this.inputPosition === 'inline' &&
5123 this.input.getValue() === '' &&
5124 !this.isEmpty()
5125 ) {
5126 // Delete the last item
5127 items = this.getItems();
5128 item = items[ items.length - 1 ];
5129
5130 if ( !item.isDisabled() ) {
5131 this.removeItems( [ item ] );
5132 // If Ctrl/Cmd was pressed, delete item entirely.
5133 // Otherwise put it into the text field for editing.
5134 if ( !withMetaKey ) {
5135 this.input.setValue( item.getData() );
5136 }
5137 }
5138
5139 return false;
5140 }
5141 };
5142
5143 /**
5144 * Perform an action after the escape key on the input
5145 *
5146 * @param {jQuery.Event} e Event data
5147 */
5148 OO.ui.TagMultiselectWidget.prototype.doInputEscape = function () {
5149 this.clearInput();
5150 };
5151
5152 /**
5153 * Perform an action after the arrow key on the input, select the previous
5154 * item from the input.
5155 * See #getPreviousItem
5156 *
5157 * @param {jQuery.Event} e Event data
5158 * @param {string} direction Direction of the movement; forwards or backwards
5159 * @param {boolean} [withMetaKey] Whether this key was pressed with
5160 * a meta key like 'ctrl'
5161 */
5162 OO.ui.TagMultiselectWidget.prototype.doInputArrow = function ( e, direction ) {
5163 if (
5164 this.inputPosition === 'inline' &&
5165 !this.isEmpty() &&
5166 direction === 'backwards'
5167 ) {
5168 // Get previous item
5169 this.getPreviousItem().focus();
5170 }
5171 };
5172
5173 /**
5174 * Respond to item select event
5175 *
5176 * @param {OO.ui.TagItemWidget} item Selected item
5177 */
5178 OO.ui.TagMultiselectWidget.prototype.onTagSelect = function ( item ) {
5179 if ( this.hasInput && this.allowEditTags && !item.isFixed() ) {
5180 if ( this.input.getValue() ) {
5181 this.addTagFromInput();
5182 }
5183 // 1. Get the label of the tag into the input
5184 this.input.setValue( item.getData() );
5185 // 2. Remove the tag
5186 this.removeItems( [ item ] );
5187 // 3. Focus the input
5188 this.focus();
5189 }
5190 };
5191
5192 /**
5193 * Respond to item fixed state change
5194 *
5195 * @param {OO.ui.TagItemWidget} item Selected item
5196 */
5197 OO.ui.TagMultiselectWidget.prototype.onTagFixed = function ( item ) {
5198 var i,
5199 items = this.getItems();
5200
5201 // Move item to the end of the static items
5202 for ( i = 0; i < items.length; i++ ) {
5203 if ( items[ i ] !== item && !items[ i ].isFixed() ) {
5204 break;
5205 }
5206 }
5207 this.addItems( item, i );
5208 };
5209 /**
5210 * Respond to change event, where items were added, removed, or cleared.
5211 */
5212 OO.ui.TagMultiselectWidget.prototype.onChangeTags = function () {
5213 this.toggleValid( this.checkValidity() );
5214 if ( this.hasInput ) {
5215 this.updateInputSize();
5216 }
5217 this.updateIfHeightChanged();
5218 };
5219
5220 /**
5221 * @inheritdoc
5222 */
5223 OO.ui.TagMultiselectWidget.prototype.setDisabled = function ( isDisabled ) {
5224 // Parent method
5225 OO.ui.TagMultiselectWidget.parent.prototype.setDisabled.call( this, isDisabled );
5226
5227 if ( this.hasInput && this.input ) {
5228 this.input.setDisabled( !!isDisabled );
5229 }
5230
5231 if ( this.items ) {
5232 this.getItems().forEach( function ( item ) {
5233 item.setDisabled( !!isDisabled );
5234 } );
5235 }
5236 };
5237
5238 /**
5239 * Respond to tag remove event
5240 * @param {OO.ui.TagItemWidget} item Removed tag
5241 */
5242 OO.ui.TagMultiselectWidget.prototype.onTagRemove = function ( item ) {
5243 this.removeTagByData( item.getData() );
5244 };
5245
5246 /**
5247 * Respond to navigate event on the tag
5248 *
5249 * @param {OO.ui.TagItemWidget} item Removed tag
5250 * @param {string} direction Direction of movement; 'forwards' or 'backwards'
5251 */
5252 OO.ui.TagMultiselectWidget.prototype.onTagNavigate = function ( item, direction ) {
5253 var firstItem = this.getItems()[ 0 ];
5254
5255 if ( direction === 'forwards' ) {
5256 this.getNextItem( item ).focus();
5257 } else if ( !this.inputPosition === 'inline' || item !== firstItem ) {
5258 // If the widget has an inline input, we want to stop at the starting edge
5259 // of the tags
5260 this.getPreviousItem( item ).focus();
5261 }
5262 };
5263
5264 /**
5265 * Add tag from input value
5266 */
5267 OO.ui.TagMultiselectWidget.prototype.addTagFromInput = function () {
5268 var val = this.input.getValue(),
5269 isValid = this.isAllowedData( val );
5270
5271 if ( !val ) {
5272 return;
5273 }
5274
5275 if ( isValid || this.allowDisplayInvalidTags ) {
5276 this.addTag( val );
5277 this.clearInput();
5278 this.focus();
5279 }
5280 };
5281
5282 /**
5283 * Clear the input
5284 */
5285 OO.ui.TagMultiselectWidget.prototype.clearInput = function () {
5286 this.input.setValue( '' );
5287 };
5288
5289 /**
5290 * Check whether the given value is a duplicate of an existing
5291 * tag already in the list.
5292 *
5293 * @param {string|Object} data Requested value
5294 * @return {boolean} Value is duplicate
5295 */
5296 OO.ui.TagMultiselectWidget.prototype.isDuplicateData = function ( data ) {
5297 return !!this.findItemFromData( data );
5298 };
5299
5300 /**
5301 * Check whether a given value is allowed to be added
5302 *
5303 * @param {string|Object} data Requested value
5304 * @return {boolean} Value is allowed
5305 */
5306 OO.ui.TagMultiselectWidget.prototype.isAllowedData = function ( data ) {
5307 if (
5308 !this.allowDuplicates &&
5309 this.isDuplicateData( data )
5310 ) {
5311 return false;
5312 }
5313
5314 if ( this.allowArbitrary ) {
5315 return true;
5316 }
5317
5318 // Check with allowed values
5319 if (
5320 this.getAllowedValues().some( function ( value ) {
5321 return data === value;
5322 } )
5323 ) {
5324 return true;
5325 }
5326
5327 return false;
5328 };
5329
5330 /**
5331 * Get the allowed values list
5332 *
5333 * @return {string[]} Allowed data values
5334 */
5335 OO.ui.TagMultiselectWidget.prototype.getAllowedValues = function () {
5336 return this.allowedValues;
5337 };
5338
5339 /**
5340 * Add a value to the allowed values list
5341 *
5342 * @param {string} value Allowed data value
5343 */
5344 OO.ui.TagMultiselectWidget.prototype.addAllowedValue = function ( value ) {
5345 if ( this.allowedValues.indexOf( value ) === -1 ) {
5346 this.allowedValues.push( value );
5347 }
5348 };
5349
5350 /**
5351 * Get the datas of the currently selected items
5352 *
5353 * @return {string[]|Object[]} Datas of currently selected items
5354 */
5355 OO.ui.TagMultiselectWidget.prototype.getValue = function () {
5356 return this.getItems()
5357 .filter( function ( item ) {
5358 return item.isValid();
5359 } )
5360 .map( function ( item ) {
5361 return item.getData();
5362 } );
5363 };
5364
5365 /**
5366 * Set the value of this widget by datas.
5367 *
5368 * @param {string|string[]|Object|Object[]} valueObject An object representing the data
5369 * and label of the value. If the widget allows arbitrary values,
5370 * the items will be added as-is. Otherwise, the data value will
5371 * be checked against allowedValues.
5372 * This object must contain at least a data key. Example:
5373 * { data: 'foo', label: 'Foo item' }
5374 * For multiple items, use an array of objects. For example:
5375 * [
5376 * { data: 'foo', label: 'Foo item' },
5377 * { data: 'bar', label: 'Bar item' }
5378 * ]
5379 * Value can also be added with plaintext array, for example:
5380 * [ 'foo', 'bar', 'bla' ] or a single string, like 'foo'
5381 */
5382 OO.ui.TagMultiselectWidget.prototype.setValue = function ( valueObject ) {
5383 valueObject = Array.isArray( valueObject ) ? valueObject : [ valueObject ];
5384
5385 this.clearItems();
5386 valueObject.forEach( function ( obj ) {
5387 if ( typeof obj === 'string' ) {
5388 this.addTag( obj );
5389 } else {
5390 this.addTag( obj.data, obj.label );
5391 }
5392 }.bind( this ) );
5393 };
5394
5395 /**
5396 * Add tag to the display area
5397 *
5398 * @param {string|Object} data Tag data
5399 * @param {string} [label] Tag label. If no label is provided, the
5400 * stringified version of the data will be used instead.
5401 * @return {boolean} Item was added successfully
5402 */
5403 OO.ui.TagMultiselectWidget.prototype.addTag = function ( data, label ) {
5404 var newItemWidget,
5405 isValid = this.isAllowedData( data );
5406
5407 if ( isValid || this.allowDisplayInvalidTags ) {
5408 newItemWidget = this.createTagItemWidget( data, label );
5409 newItemWidget.toggleValid( isValid );
5410 this.addItems( [ newItemWidget ] );
5411 return true;
5412 }
5413 return false;
5414 };
5415
5416 /**
5417 * Remove tag by its data property.
5418 *
5419 * @param {string|Object} data Tag data
5420 */
5421 OO.ui.TagMultiselectWidget.prototype.removeTagByData = function ( data ) {
5422 var item = this.findItemFromData( data );
5423
5424 this.removeItems( [ item ] );
5425 };
5426
5427 /**
5428 * Construct a OO.ui.TagItemWidget (or a subclass thereof) from given label and data.
5429 *
5430 * @protected
5431 * @param {string} data Item data
5432 * @param {string} label The label text.
5433 * @return {OO.ui.TagItemWidget}
5434 */
5435 OO.ui.TagMultiselectWidget.prototype.createTagItemWidget = function ( data, label ) {
5436 label = label || data;
5437
5438 return new OO.ui.TagItemWidget( { data: data, label: label } );
5439 };
5440
5441 /**
5442 * Given an item, returns the item after it. If the item is already the
5443 * last item, return `this.input`. If no item is passed, returns the
5444 * very first item.
5445 *
5446 * @protected
5447 * @param {OO.ui.TagItemWidget} [item] Tag item
5448 * @return {OO.ui.Widget} The next widget available.
5449 */
5450 OO.ui.TagMultiselectWidget.prototype.getNextItem = function ( item ) {
5451 var itemIndex = this.items.indexOf( item );
5452
5453 if ( item === undefined || itemIndex === -1 ) {
5454 return this.items[ 0 ];
5455 }
5456
5457 if ( itemIndex === this.items.length - 1 ) { // Last item
5458 if ( this.hasInput ) {
5459 return this.input;
5460 } else {
5461 // Return first item
5462 return this.items[ 0 ];
5463 }
5464 } else {
5465 return this.items[ itemIndex + 1 ];
5466 }
5467 };
5468
5469 /**
5470 * Given an item, returns the item before it. If the item is already the
5471 * first item, return `this.input`. If no item is passed, returns the
5472 * very last item.
5473 *
5474 * @protected
5475 * @param {OO.ui.TagItemWidget} [item] Tag item
5476 * @return {OO.ui.Widget} The previous widget available.
5477 */
5478 OO.ui.TagMultiselectWidget.prototype.getPreviousItem = function ( item ) {
5479 var itemIndex = this.items.indexOf( item );
5480
5481 if ( item === undefined || itemIndex === -1 ) {
5482 return this.items[ this.items.length - 1 ];
5483 }
5484
5485 if ( itemIndex === 0 ) {
5486 if ( this.hasInput ) {
5487 return this.input;
5488 } else {
5489 // Return the last item
5490 return this.items[ this.items.length - 1 ];
5491 }
5492 } else {
5493 return this.items[ itemIndex - 1 ];
5494 }
5495 };
5496
5497 /**
5498 * Update the dimensions of the text input field to encompass all available area.
5499 * This is especially relevant for when the input is at the edge of a line
5500 * and should get smaller. The usual operation (as an inline-block with min-width)
5501 * does not work in that case, pushing the input downwards to the next line.
5502 *
5503 * @private
5504 */
5505 OO.ui.TagMultiselectWidget.prototype.updateInputSize = function () {
5506 var $lastItem, direction, contentWidth, currentWidth, bestWidth;
5507 if ( this.inputPosition === 'inline' && !this.isDisabled() ) {
5508 if ( this.input.$input[ 0 ].scrollWidth === 0 ) {
5509 // Input appears to be attached but not visible.
5510 // Don't attempt to adjust its size, because our measurements
5511 // are going to fail anyway.
5512 return;
5513 }
5514 this.input.$input.css( 'width', '1em' );
5515 $lastItem = this.$group.children().last();
5516 direction = OO.ui.Element.static.getDir( this.$handle );
5517
5518 // Get the width of the input with the placeholder text as
5519 // the value and save it so that we don't keep recalculating
5520 if (
5521 this.contentWidthWithPlaceholder === undefined &&
5522 this.input.getValue() === '' &&
5523 this.input.$input.attr( 'placeholder' ) !== undefined
5524 ) {
5525 this.input.setValue( this.input.$input.attr( 'placeholder' ) );
5526 this.contentWidthWithPlaceholder = this.input.$input[ 0 ].scrollWidth;
5527 this.input.setValue( '' );
5528
5529 }
5530
5531 // Always keep the input wide enough for the placeholder text
5532 contentWidth = Math.max(
5533 this.input.$input[ 0 ].scrollWidth,
5534 // undefined arguments in Math.max lead to NaN
5535 ( this.contentWidthWithPlaceholder === undefined ) ?
5536 0 : this.contentWidthWithPlaceholder
5537 );
5538 currentWidth = this.input.$input.width();
5539
5540 if ( contentWidth < currentWidth ) {
5541 this.updateIfHeightChanged();
5542 // All is fine, don't perform expensive calculations
5543 return;
5544 }
5545
5546 if ( $lastItem.length === 0 ) {
5547 bestWidth = this.$content.innerWidth();
5548 } else {
5549 bestWidth = direction === 'ltr' ?
5550 this.$content.innerWidth() - $lastItem.position().left - $lastItem.outerWidth() :
5551 $lastItem.position().left;
5552 }
5553
5554 // Some safety margin for sanity, because I *really* don't feel like finding out where the few
5555 // pixels this is off by are coming from.
5556 bestWidth -= 10;
5557 if ( contentWidth > bestWidth ) {
5558 // This will result in the input getting shifted to the next line
5559 bestWidth = this.$content.innerWidth() - 10;
5560 }
5561 this.input.$input.width( Math.floor( bestWidth ) );
5562 this.updateIfHeightChanged();
5563 } else {
5564 this.updateIfHeightChanged();
5565 }
5566 };
5567
5568 /**
5569 * Determine if widget height changed, and if so,
5570 * emit the resize event. This is useful for when there are either
5571 * menus or popups attached to the bottom of the widget, to allow
5572 * them to change their positioning in case the widget moved down
5573 * or up.
5574 *
5575 * @private
5576 */
5577 OO.ui.TagMultiselectWidget.prototype.updateIfHeightChanged = function () {
5578 var height = this.$element.height();
5579 if ( height !== this.height ) {
5580 this.height = height;
5581 this.emit( 'resize' );
5582 }
5583 };
5584
5585 /**
5586 * Check whether all items in the widget are valid
5587 *
5588 * @return {boolean} Widget is valid
5589 */
5590 OO.ui.TagMultiselectWidget.prototype.checkValidity = function () {
5591 return this.getItems().every( function ( item ) {
5592 return item.isValid();
5593 } );
5594 };
5595
5596 /**
5597 * Set the valid state of this item
5598 *
5599 * @param {boolean} [valid] Item is valid
5600 * @fires valid
5601 */
5602 OO.ui.TagMultiselectWidget.prototype.toggleValid = function ( valid ) {
5603 valid = valid === undefined ? !this.valid : !!valid;
5604
5605 if ( this.valid !== valid ) {
5606 this.valid = valid;
5607
5608 this.setFlags( { invalid: !this.valid } );
5609
5610 this.emit( 'valid', this.valid );
5611 }
5612 };
5613
5614 /**
5615 * Get the current valid state of the widget
5616 *
5617 * @return {boolean} Widget is valid
5618 */
5619 OO.ui.TagMultiselectWidget.prototype.isValid = function () {
5620 return this.valid;
5621 };
5622
5623 /**
5624 * PopupTagMultiselectWidget is a {@link OO.ui.TagMultiselectWidget OO.ui.TagMultiselectWidget} intended
5625 * to use a popup. The popup can be configured to have a default input to insert values into the widget.
5626 *
5627 * @example
5628 * // Example: A basic PopupTagMultiselectWidget.
5629 * var widget = new OO.ui.PopupTagMultiselectWidget();
5630 * $( 'body' ).append( widget.$element );
5631 *
5632 * // Example: A PopupTagMultiselectWidget with an external popup.
5633 * var popupInput = new OO.ui.TextInputWidget(),
5634 * widget = new OO.ui.PopupTagMultiselectWidget( {
5635 * popupInput: popupInput,
5636 * popup: {
5637 * $content: popupInput.$element
5638 * }
5639 * } );
5640 * $( 'body' ).append( widget.$element );
5641 *
5642 * @class
5643 * @extends OO.ui.TagMultiselectWidget
5644 * @mixins OO.ui.mixin.PopupElement
5645 *
5646 * @param {Object} config Configuration object
5647 * @cfg {jQuery} [$overlay] An overlay for the popup.
5648 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
5649 * @cfg {Object} [popup] Configuration options for the popup
5650 * @cfg {OO.ui.InputWidget} [popupInput] An input widget inside the popup that will be
5651 * focused when the popup is opened and will be used as replacement for the
5652 * general input in the widget.
5653 */
5654 OO.ui.PopupTagMultiselectWidget = function OoUiPopupTagMultiselectWidget( config ) {
5655 var defaultInput,
5656 defaultConfig = { popup: {} };
5657
5658 config = config || {};
5659
5660 // Parent constructor
5661 OO.ui.PopupTagMultiselectWidget.parent.call( this, $.extend( { inputPosition: 'none' }, config ) );
5662
5663 this.$overlay = ( config.$overlay === true ? OO.ui.getDefaultOverlay() : config.$overlay ) || this.$element;
5664
5665 if ( !config.popup ) {
5666 // For the default base implementation, we give a popup
5667 // with an input widget inside it. For any other use cases
5668 // the popup needs to be populated externally and the
5669 // event handled to add tags separately and manually
5670 defaultInput = new OO.ui.TextInputWidget();
5671
5672 defaultConfig.popupInput = defaultInput;
5673 defaultConfig.popup.$content = defaultInput.$element;
5674 defaultConfig.popup.padded = true;
5675
5676 this.$element.addClass( 'oo-ui-popupTagMultiselectWidget-defaultPopup' );
5677 }
5678
5679 // Add overlay, and add that to the autoCloseIgnore
5680 defaultConfig.popup.$overlay = this.$overlay;
5681 defaultConfig.popup.$autoCloseIgnore = this.hasInput ?
5682 this.input.$element.add( this.$overlay ) : this.$overlay;
5683
5684 // Allow extending any of the above
5685 config = $.extend( defaultConfig, config );
5686
5687 // Mixin constructors
5688 OO.ui.mixin.PopupElement.call( this, config );
5689
5690 if ( this.hasInput ) {
5691 this.input.$input.on( 'focus', this.popup.toggle.bind( this.popup, true ) );
5692 }
5693
5694 // Configuration options
5695 this.popupInput = config.popupInput;
5696 if ( this.popupInput ) {
5697 this.popupInput.connect( this, {
5698 enter: 'onPopupInputEnter'
5699 } );
5700 }
5701
5702 // Events
5703 this.on( 'resize', this.popup.updateDimensions.bind( this.popup ) );
5704 this.popup.connect( this, { toggle: 'onPopupToggle' } );
5705 this.$tabIndexed
5706 .on( 'focus', this.onFocus.bind( this ) );
5707
5708 // Initialize
5709 this.$element
5710 .append( this.popup.$element )
5711 .addClass( 'oo-ui-popupTagMultiselectWidget' );
5712 };
5713
5714 /* Initialization */
5715
5716 OO.inheritClass( OO.ui.PopupTagMultiselectWidget, OO.ui.TagMultiselectWidget );
5717 OO.mixinClass( OO.ui.PopupTagMultiselectWidget, OO.ui.mixin.PopupElement );
5718
5719 /* Methods */
5720
5721 /**
5722 * Focus event handler.
5723 *
5724 * @private
5725 */
5726 OO.ui.PopupTagMultiselectWidget.prototype.onFocus = function () {
5727 this.popup.toggle( true );
5728 };
5729
5730 /**
5731 * Respond to popup toggle event
5732 *
5733 * @param {boolean} isVisible Popup is visible
5734 */
5735 OO.ui.PopupTagMultiselectWidget.prototype.onPopupToggle = function ( isVisible ) {
5736 if ( isVisible && this.popupInput ) {
5737 this.popupInput.focus();
5738 }
5739 };
5740
5741 /**
5742 * Respond to popup input enter event
5743 */
5744 OO.ui.PopupTagMultiselectWidget.prototype.onPopupInputEnter = function () {
5745 if ( this.popupInput ) {
5746 this.addTagByPopupValue( this.popupInput.getValue() );
5747 this.popupInput.setValue( '' );
5748 }
5749 };
5750
5751 /**
5752 * @inheritdoc
5753 */
5754 OO.ui.PopupTagMultiselectWidget.prototype.onTagSelect = function ( item ) {
5755 if ( this.popupInput && this.allowEditTags ) {
5756 this.popupInput.setValue( item.getData() );
5757 this.removeItems( [ item ] );
5758
5759 this.popup.toggle( true );
5760 this.popupInput.focus();
5761 } else {
5762 // Parent
5763 OO.ui.PopupTagMultiselectWidget.parent.prototype.onTagSelect.call( this, item );
5764 }
5765 };
5766
5767 /**
5768 * Add a tag by the popup value.
5769 * Whatever is responsible for setting the value in the popup should call
5770 * this method to add a tag, or use the regular methods like #addTag or
5771 * #setValue directly.
5772 *
5773 * @param {string} data The value of item
5774 * @param {string} [label] The label of the tag. If not given, the data is used.
5775 */
5776 OO.ui.PopupTagMultiselectWidget.prototype.addTagByPopupValue = function ( data, label ) {
5777 this.addTag( data, label );
5778 };
5779
5780 /**
5781 * MenuTagMultiselectWidget is a {@link OO.ui.TagMultiselectWidget OO.ui.TagMultiselectWidget} intended
5782 * to use a menu of selectable options.
5783 *
5784 * @example
5785 * // Example: A basic MenuTagMultiselectWidget.
5786 * var widget = new OO.ui.MenuTagMultiselectWidget( {
5787 * inputPosition: 'outline',
5788 * options: [
5789 * { data: 'option1', label: 'Option 1' },
5790 * { data: 'option2', label: 'Option 2' },
5791 * { data: 'option3', label: 'Option 3' },
5792 * ],
5793 * selected: [ 'option1', 'option2' ]
5794 * } );
5795 * $( 'body' ).append( widget.$element );
5796 *
5797 * @class
5798 * @extends OO.ui.TagMultiselectWidget
5799 *
5800 * @constructor
5801 * @param {Object} [config] Configuration object
5802 * @cfg {boolean} [clearInputOnChoose=true] Clear the text input value when a menu option is chosen
5803 * @cfg {Object} [menu] Configuration object for the menu widget
5804 * @cfg {jQuery} [$overlay] An overlay for the menu.
5805 * See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
5806 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
5807 */
5808 OO.ui.MenuTagMultiselectWidget = function OoUiMenuTagMultiselectWidget( config ) {
5809 config = config || {};
5810
5811 // Parent constructor
5812 OO.ui.MenuTagMultiselectWidget.parent.call( this, config );
5813
5814 this.$overlay = ( config.$overlay === true ? OO.ui.getDefaultOverlay() : config.$overlay ) || this.$element;
5815 this.clearInputOnChoose = config.clearInputOnChoose === undefined || !!config.clearInputOnChoose;
5816 this.menu = this.createMenuWidget( $.extend( {
5817 widget: this,
5818 input: this.hasInput ? this.input : null,
5819 $input: this.hasInput ? this.input.$input : null,
5820 filterFromInput: !!this.hasInput,
5821 $autoCloseIgnore: this.hasInput ?
5822 this.input.$element : $( [] ),
5823 $floatableContainer: this.hasInput && this.inputPosition === 'outline' ?
5824 this.input.$element : this.$element,
5825 $overlay: this.$overlay,
5826 disabled: this.isDisabled()
5827 }, config.menu ) );
5828 this.addOptions( config.options || [] );
5829
5830 // Events
5831 this.menu.connect( this, {
5832 choose: 'onMenuChoose',
5833 toggle: 'onMenuToggle'
5834 } );
5835 if ( this.hasInput ) {
5836 this.input.connect( this, { change: 'onInputChange' } );
5837 }
5838 this.connect( this, { resize: 'onResize' } );
5839
5840 // Initialization
5841 this.$overlay
5842 .append( this.menu.$element );
5843 this.$element
5844 .addClass( 'oo-ui-menuTagMultiselectWidget' );
5845 // TagMultiselectWidget already does this, but it doesn't work right because this.menu is not yet
5846 // set up while the parent constructor runs, and #getAllowedValues rejects everything.
5847 if ( config.selected ) {
5848 this.setValue( config.selected );
5849 }
5850 };
5851
5852 /* Initialization */
5853
5854 OO.inheritClass( OO.ui.MenuTagMultiselectWidget, OO.ui.TagMultiselectWidget );
5855
5856 /* Methods */
5857
5858 /**
5859 * Respond to resize event
5860 */
5861 OO.ui.MenuTagMultiselectWidget.prototype.onResize = function () {
5862 // Reposition the menu
5863 this.menu.position();
5864 };
5865
5866 /**
5867 * @inheritdoc
5868 */
5869 OO.ui.MenuTagMultiselectWidget.prototype.onInputFocus = function () {
5870 // Parent method
5871 OO.ui.MenuTagMultiselectWidget.parent.prototype.onInputFocus.call( this );
5872
5873 this.menu.toggle( true );
5874 };
5875
5876 /**
5877 * Respond to input change event
5878 */
5879 OO.ui.MenuTagMultiselectWidget.prototype.onInputChange = function () {
5880 this.menu.toggle( true );
5881 this.initializeMenuSelection();
5882 };
5883
5884 /**
5885 * Respond to menu choose event
5886 *
5887 * @param {OO.ui.OptionWidget} menuItem Chosen menu item
5888 */
5889 OO.ui.MenuTagMultiselectWidget.prototype.onMenuChoose = function ( menuItem ) {
5890 // Add tag
5891 this.addTag( menuItem.getData(), menuItem.getLabel() );
5892 if ( this.hasInput && this.clearInputOnChoose ) {
5893 this.input.setValue( '' );
5894 }
5895 };
5896
5897 /**
5898 * Respond to menu toggle event. Reset item highlights on hide.
5899 *
5900 * @param {boolean} isVisible The menu is visible
5901 */
5902 OO.ui.MenuTagMultiselectWidget.prototype.onMenuToggle = function ( isVisible ) {
5903 if ( !isVisible ) {
5904 this.menu.selectItem( null );
5905 this.menu.highlightItem( null );
5906 } else {
5907 this.initializeMenuSelection();
5908 }
5909 };
5910
5911 /**
5912 * @inheritdoc
5913 */
5914 OO.ui.MenuTagMultiselectWidget.prototype.onTagSelect = function ( tagItem ) {
5915 var menuItem = this.menu.findItemFromData( tagItem.getData() );
5916 if ( !this.allowArbitrary ) {
5917 // Override the base behavior from TagMultiselectWidget; the base behavior
5918 // in TagMultiselectWidget is to remove the tag to edit it in the input,
5919 // but in our case, we want to utilize the menu selection behavior, and
5920 // definitely not remove the item.
5921
5922 // If there is an input that is used for filtering, erase the value so we don't filter
5923 if ( this.hasInput && this.menu.filterFromInput ) {
5924 this.input.setValue( '' );
5925 }
5926
5927 // Select the menu item
5928 this.menu.selectItem( menuItem );
5929
5930 this.focus();
5931 } else {
5932 // Use the default
5933 OO.ui.MenuTagMultiselectWidget.parent.prototype.onTagSelect.call( this, tagItem );
5934 }
5935 };
5936
5937 /**
5938 * Highlight the first selectable item in the menu, if configured.
5939 *
5940 * @private
5941 * @chainable
5942 */
5943 OO.ui.MenuTagMultiselectWidget.prototype.initializeMenuSelection = function () {
5944 if ( !this.menu.findSelectedItem() ) {
5945 this.menu.highlightItem( this.menu.findFirstSelectableItem() );
5946 }
5947 };
5948
5949 /**
5950 * @inheritdoc
5951 */
5952 OO.ui.MenuTagMultiselectWidget.prototype.addTagFromInput = function () {
5953 var inputValue = this.input.getValue(),
5954 validated = false,
5955 highlightedItem = this.menu.findHighlightedItem(),
5956 item = this.menu.findItemFromData( inputValue );
5957
5958 if ( !inputValue ) {
5959 return;
5960 }
5961
5962 // Override the parent method so we add from the menu
5963 // rather than directly from the input
5964
5965 // Look for a highlighted item first
5966 if ( highlightedItem ) {
5967 validated = this.addTag( highlightedItem.getData(), highlightedItem.getLabel() );
5968 } else if ( item ) {
5969 // Look for the element that fits the data
5970 validated = this.addTag( item.getData(), item.getLabel() );
5971 } else {
5972 // Otherwise, add the tag - the method will only add if the
5973 // tag is valid or if invalid tags are allowed
5974 validated = this.addTag( inputValue );
5975 }
5976
5977 if ( validated ) {
5978 this.clearInput();
5979 this.focus();
5980 }
5981 };
5982
5983 /**
5984 * Return the visible items in the menu. This is mainly used for when
5985 * the menu is filtering results.
5986 *
5987 * @return {OO.ui.MenuOptionWidget[]} Visible results
5988 */
5989 OO.ui.MenuTagMultiselectWidget.prototype.getMenuVisibleItems = function () {
5990 return this.menu.getItems().filter( function ( menuItem ) {
5991 return menuItem.isVisible();
5992 } );
5993 };
5994
5995 /**
5996 * Create the menu for this widget. This is in a separate method so that
5997 * child classes can override this without polluting the constructor with
5998 * unnecessary extra objects that will be overidden.
5999 *
6000 * @param {Object} menuConfig Configuration options
6001 * @return {OO.ui.MenuSelectWidget} Menu widget
6002 */
6003 OO.ui.MenuTagMultiselectWidget.prototype.createMenuWidget = function ( menuConfig ) {
6004 return new OO.ui.MenuSelectWidget( menuConfig );
6005 };
6006
6007 /**
6008 * Add options to the menu
6009 *
6010 * @param {Object[]} menuOptions Object defining options
6011 */
6012 OO.ui.MenuTagMultiselectWidget.prototype.addOptions = function ( menuOptions ) {
6013 var widget = this,
6014 items = menuOptions.map( function ( obj ) {
6015 return widget.createMenuOptionWidget( obj.data, obj.label );
6016 } );
6017
6018 this.menu.addItems( items );
6019 };
6020
6021 /**
6022 * Create a menu option widget.
6023 *
6024 * @param {string} data Item data
6025 * @param {string} [label] Item label
6026 * @return {OO.ui.OptionWidget} Option widget
6027 */
6028 OO.ui.MenuTagMultiselectWidget.prototype.createMenuOptionWidget = function ( data, label ) {
6029 return new OO.ui.MenuOptionWidget( {
6030 data: data,
6031 label: label || data
6032 } );
6033 };
6034
6035 /**
6036 * Get the menu
6037 *
6038 * @return {OO.ui.MenuSelectWidget} Menu
6039 */
6040 OO.ui.MenuTagMultiselectWidget.prototype.getMenu = function () {
6041 return this.menu;
6042 };
6043
6044 /**
6045 * Get the allowed values list
6046 *
6047 * @return {string[]} Allowed data values
6048 */
6049 OO.ui.MenuTagMultiselectWidget.prototype.getAllowedValues = function () {
6050 var menuDatas = [];
6051 if ( this.menu ) {
6052 // If the parent constructor is calling us, we're not ready yet, this.menu is not set up.
6053 menuDatas = this.menu.getItems().map( function ( menuItem ) {
6054 return menuItem.getData();
6055 } );
6056 }
6057 return this.allowedValues.concat( menuDatas );
6058 };
6059
6060 /**
6061 * SelectFileWidgets allow for selecting files, using the HTML5 File API. These
6062 * widgets can be configured with {@link OO.ui.mixin.IconElement icons} and {@link
6063 * OO.ui.mixin.IndicatorElement indicators}.
6064 * Please see the [OOUI documentation on MediaWiki] [1] for more information and examples.
6065 *
6066 * @example
6067 * // Example of a file select widget
6068 * var selectFile = new OO.ui.SelectFileWidget();
6069 * $( 'body' ).append( selectFile.$element );
6070 *
6071 * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets
6072 *
6073 * @class
6074 * @extends OO.ui.Widget
6075 * @mixins OO.ui.mixin.IconElement
6076 * @mixins OO.ui.mixin.IndicatorElement
6077 * @mixins OO.ui.mixin.PendingElement
6078 * @mixins OO.ui.mixin.LabelElement
6079 *
6080 * @constructor
6081 * @param {Object} [config] Configuration options
6082 * @cfg {string[]|null} [accept=null] MIME types to accept. null accepts all types.
6083 * @cfg {string} [placeholder] Text to display when no file is selected.
6084 * @cfg {string} [notsupported] Text to display when file support is missing in the browser.
6085 * @cfg {boolean} [droppable=true] Whether to accept files by drag and drop.
6086 * @cfg {boolean} [showDropTarget=false] Whether to show a drop target. Requires droppable to be true.
6087 * @cfg {number} [thumbnailSizeLimit=20] File size limit in MiB above which to not try and show a
6088 * preview (for performance)
6089 */
6090 OO.ui.SelectFileWidget = function OoUiSelectFileWidget( config ) {
6091 var dragHandler;
6092
6093 // Configuration initialization
6094 config = $.extend( {
6095 accept: null,
6096 placeholder: OO.ui.msg( 'ooui-selectfile-placeholder' ),
6097 notsupported: OO.ui.msg( 'ooui-selectfile-not-supported' ),
6098 droppable: true,
6099 showDropTarget: false,
6100 thumbnailSizeLimit: 20
6101 }, config );
6102
6103 // Parent constructor
6104 OO.ui.SelectFileWidget.parent.call( this, config );
6105
6106 // Mixin constructors
6107 OO.ui.mixin.IconElement.call( this, config );
6108 OO.ui.mixin.IndicatorElement.call( this, config );
6109 OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$info } ) );
6110 OO.ui.mixin.LabelElement.call( this, config );
6111
6112 // Properties
6113 this.$info = $( '<span>' );
6114 this.showDropTarget = config.showDropTarget;
6115 this.thumbnailSizeLimit = config.thumbnailSizeLimit;
6116 this.isSupported = this.constructor.static.isSupported();
6117 this.currentFile = null;
6118 if ( Array.isArray( config.accept ) ) {
6119 this.accept = config.accept;
6120 } else {
6121 this.accept = null;
6122 }
6123 this.placeholder = config.placeholder;
6124 this.notsupported = config.notsupported;
6125 this.onFileSelectedHandler = this.onFileSelected.bind( this );
6126
6127 this.selectButton = new OO.ui.ButtonWidget( {
6128 $element: $( '<label>' ),
6129 classes: [ 'oo-ui-selectFileWidget-selectButton' ],
6130 label: OO.ui.msg( 'ooui-selectfile-button-select' ),
6131 disabled: this.disabled || !this.isSupported
6132 } );
6133
6134 this.clearButton = new OO.ui.ButtonWidget( {
6135 classes: [ 'oo-ui-selectFileWidget-clearButton' ],
6136 framed: false,
6137 icon: 'close',
6138 disabled: this.disabled
6139 } );
6140
6141 // Events
6142 this.selectButton.$button.on( {
6143 keypress: this.onKeyPress.bind( this )
6144 } );
6145 this.clearButton.connect( this, {
6146 click: 'onClearClick'
6147 } );
6148 if ( config.droppable ) {
6149 dragHandler = this.onDragEnterOrOver.bind( this );
6150 this.$element.on( {
6151 dragenter: dragHandler,
6152 dragover: dragHandler,
6153 dragleave: this.onDragLeave.bind( this ),
6154 drop: this.onDrop.bind( this )
6155 } );
6156 }
6157
6158 // Initialization
6159 this.addInput();
6160 this.$label.addClass( 'oo-ui-selectFileWidget-label' );
6161 this.$info
6162 .addClass( 'oo-ui-selectFileWidget-info' )
6163 .append( this.$icon, this.$label, this.clearButton.$element, this.$indicator );
6164
6165 if ( config.droppable && config.showDropTarget ) {
6166 this.selectButton.setIcon( 'upload' );
6167 this.$thumbnail = $( '<div>' ).addClass( 'oo-ui-selectFileWidget-thumbnail' );
6168 this.setPendingElement( this.$thumbnail );
6169 this.$element
6170 .addClass( 'oo-ui-selectFileWidget-dropTarget oo-ui-selectFileWidget' )
6171 .on( {
6172 click: this.onDropTargetClick.bind( this )
6173 } )
6174 .append(
6175 this.$thumbnail,
6176 this.$info,
6177 this.selectButton.$element,
6178 $( '<span>' )
6179 .addClass( 'oo-ui-selectFileWidget-dropLabel' )
6180 .text( OO.ui.msg( 'ooui-selectfile-dragdrop-placeholder' ) )
6181 );
6182 } else {
6183 this.$element
6184 .addClass( 'oo-ui-selectFileWidget' )
6185 .append( this.$info, this.selectButton.$element );
6186 }
6187 this.updateUI();
6188 };
6189
6190 /* Setup */
6191
6192 OO.inheritClass( OO.ui.SelectFileWidget, OO.ui.Widget );
6193 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IconElement );
6194 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.IndicatorElement );
6195 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.PendingElement );
6196 OO.mixinClass( OO.ui.SelectFileWidget, OO.ui.mixin.LabelElement );
6197
6198 /* Static Properties */
6199
6200 /**
6201 * Check if this widget is supported
6202 *
6203 * @static
6204 * @return {boolean}
6205 */
6206 OO.ui.SelectFileWidget.static.isSupported = function () {
6207 var $input;
6208 if ( OO.ui.SelectFileWidget.static.isSupportedCache === null ) {
6209 $input = $( '<input>' ).attr( 'type', 'file' );
6210 OO.ui.SelectFileWidget.static.isSupportedCache = $input[ 0 ].files !== undefined;
6211 }
6212 return OO.ui.SelectFileWidget.static.isSupportedCache;
6213 };
6214
6215 OO.ui.SelectFileWidget.static.isSupportedCache = null;
6216
6217 /* Events */
6218
6219 /**
6220 * @event change
6221 *
6222 * A change event is emitted when the on/off state of the toggle changes.
6223 *
6224 * @param {File|null} value New value
6225 */
6226
6227 /* Methods */
6228
6229 /**
6230 * Get the current value of the field
6231 *
6232 * @return {File|null}
6233 */
6234 OO.ui.SelectFileWidget.prototype.getValue = function () {
6235 return this.currentFile;
6236 };
6237
6238 /**
6239 * Set the current value of the field
6240 *
6241 * @param {File|null} file File to select
6242 */
6243 OO.ui.SelectFileWidget.prototype.setValue = function ( file ) {
6244 if ( this.currentFile !== file ) {
6245 this.currentFile = file;
6246 this.updateUI();
6247 this.emit( 'change', this.currentFile );
6248 }
6249 };
6250
6251 /**
6252 * Focus the widget.
6253 *
6254 * Focusses the select file button.
6255 *
6256 * @chainable
6257 */
6258 OO.ui.SelectFileWidget.prototype.focus = function () {
6259 this.selectButton.focus();
6260 return this;
6261 };
6262
6263 /**
6264 * Blur the widget.
6265 *
6266 * @chainable
6267 */
6268 OO.ui.SelectFileWidget.prototype.blur = function () {
6269 this.selectButton.blur();
6270 return this;
6271 };
6272
6273 /**
6274 * @inheritdoc
6275 */
6276 OO.ui.SelectFileWidget.prototype.simulateLabelClick = function () {
6277 this.focus();
6278 };
6279
6280 /**
6281 * Update the user interface when a file is selected or unselected
6282 *
6283 * @protected
6284 */
6285 OO.ui.SelectFileWidget.prototype.updateUI = function () {
6286 var $label;
6287 if ( !this.isSupported ) {
6288 this.$element.addClass( 'oo-ui-selectFileWidget-notsupported' );
6289 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
6290 this.setLabel( this.notsupported );
6291 } else {
6292 this.$element.addClass( 'oo-ui-selectFileWidget-supported' );
6293 if ( this.currentFile ) {
6294 this.$element.removeClass( 'oo-ui-selectFileWidget-empty' );
6295 $label = $( [] );
6296 $label = $label.add(
6297 $( '<span>' )
6298 .addClass( 'oo-ui-selectFileWidget-fileName' )
6299 .text( this.currentFile.name )
6300 );
6301 this.setLabel( $label );
6302
6303 if ( this.showDropTarget ) {
6304 this.pushPending();
6305 this.loadAndGetImageUrl().done( function ( url ) {
6306 this.$thumbnail.css( 'background-image', 'url( ' + url + ' )' );
6307 }.bind( this ) ).fail( function () {
6308 this.$thumbnail.append(
6309 new OO.ui.IconWidget( {
6310 icon: 'attachment',
6311 classes: [ 'oo-ui-selectFileWidget-noThumbnail-icon' ]
6312 } ).$element
6313 );
6314 }.bind( this ) ).always( function () {
6315 this.popPending();
6316 }.bind( this ) );
6317 this.$element.off( 'click' );
6318 }
6319 } else {
6320 if ( this.showDropTarget ) {
6321 this.$element.off( 'click' );
6322 this.$element.on( {
6323 click: this.onDropTargetClick.bind( this )
6324 } );
6325 this.$thumbnail
6326 .empty()
6327 .css( 'background-image', '' );
6328 }
6329 this.$element.addClass( 'oo-ui-selectFileWidget-empty' );
6330 this.setLabel( this.placeholder );
6331 }
6332 }
6333 };
6334
6335 /**
6336 * If the selected file is an image, get its URL and load it.
6337 *
6338 * @return {jQuery.Promise} Promise resolves with the image URL after it has loaded
6339 */
6340 OO.ui.SelectFileWidget.prototype.loadAndGetImageUrl = function () {
6341 var deferred = $.Deferred(),
6342 file = this.currentFile,
6343 reader = new FileReader();
6344
6345 if (
6346 file &&
6347 ( OO.getProp( file, 'type' ) || '' ).indexOf( 'image/' ) === 0 &&
6348 file.size < this.thumbnailSizeLimit * 1024 * 1024
6349 ) {
6350 reader.onload = function ( event ) {
6351 var img = document.createElement( 'img' );
6352 img.addEventListener( 'load', function () {
6353 if (
6354 img.naturalWidth === 0 ||
6355 img.naturalHeight === 0 ||
6356 img.complete === false
6357 ) {
6358 deferred.reject();
6359 } else {
6360 deferred.resolve( event.target.result );
6361 }
6362 } );
6363 img.src = event.target.result;
6364 };
6365 reader.readAsDataURL( file );
6366 } else {
6367 deferred.reject();
6368 }
6369
6370 return deferred.promise();
6371 };
6372
6373 /**
6374 * Add the input to the widget
6375 *
6376 * @private
6377 */
6378 OO.ui.SelectFileWidget.prototype.addInput = function () {
6379 if ( this.$input ) {
6380 this.$input.remove();
6381 }
6382
6383 if ( !this.isSupported ) {
6384 this.$input = null;
6385 return;
6386 }
6387
6388 this.$input = $( '<input>' ).attr( 'type', 'file' );
6389 this.$input.on( 'change', this.onFileSelectedHandler );
6390 this.$input.on( 'click', function ( e ) {
6391 // Prevents dropTarget to get clicked which calls
6392 // a click on this input
6393 e.stopPropagation();
6394 } );
6395 this.$input.attr( {
6396 tabindex: -1
6397 } );
6398 if ( this.accept ) {
6399 this.$input.attr( 'accept', this.accept.join( ', ' ) );
6400 }
6401 this.selectButton.$button.append( this.$input );
6402 };
6403
6404 /**
6405 * Determine if we should accept this file
6406 *
6407 * @private
6408 * @param {string} mimeType File MIME type
6409 * @return {boolean}
6410 */
6411 OO.ui.SelectFileWidget.prototype.isAllowedType = function ( mimeType ) {
6412 var i, mimeTest;
6413
6414 if ( !this.accept || !mimeType ) {
6415 return true;
6416 }
6417
6418 for ( i = 0; i < this.accept.length; i++ ) {
6419 mimeTest = this.accept[ i ];
6420 if ( mimeTest === mimeType ) {
6421 return true;
6422 } else if ( mimeTest.substr( -2 ) === '/*' ) {
6423 mimeTest = mimeTest.substr( 0, mimeTest.length - 1 );
6424 if ( mimeType.substr( 0, mimeTest.length ) === mimeTest ) {
6425 return true;
6426 }
6427 }
6428 }
6429
6430 return false;
6431 };
6432
6433 /**
6434 * Handle file selection from the input
6435 *
6436 * @private
6437 * @param {jQuery.Event} e
6438 */
6439 OO.ui.SelectFileWidget.prototype.onFileSelected = function ( e ) {
6440 var file = OO.getProp( e.target, 'files', 0 ) || null;
6441
6442 if ( file && !this.isAllowedType( file.type ) ) {
6443 file = null;
6444 }
6445
6446 this.setValue( file );
6447 this.addInput();
6448 };
6449
6450 /**
6451 * Handle clear button click events.
6452 *
6453 * @private
6454 */
6455 OO.ui.SelectFileWidget.prototype.onClearClick = function () {
6456 this.setValue( null );
6457 return false;
6458 };
6459
6460 /**
6461 * Handle key press events.
6462 *
6463 * @private
6464 * @param {jQuery.Event} e Key press event
6465 */
6466 OO.ui.SelectFileWidget.prototype.onKeyPress = function ( e ) {
6467 if ( this.isSupported && !this.isDisabled() && this.$input &&
6468 ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
6469 ) {
6470 this.$input.click();
6471 return false;
6472 }
6473 };
6474
6475 /**
6476 * Handle drop target click events.
6477 *
6478 * @private
6479 * @param {jQuery.Event} e Key press event
6480 */
6481 OO.ui.SelectFileWidget.prototype.onDropTargetClick = function () {
6482 if ( this.isSupported && !this.isDisabled() && this.$input ) {
6483 this.$input.click();
6484 return false;
6485 }
6486 };
6487
6488 /**
6489 * Handle drag enter and over events
6490 *
6491 * @private
6492 * @param {jQuery.Event} e Drag event
6493 */
6494 OO.ui.SelectFileWidget.prototype.onDragEnterOrOver = function ( e ) {
6495 var itemOrFile,
6496 droppableFile = false,
6497 dt = e.originalEvent.dataTransfer;
6498
6499 e.preventDefault();
6500 e.stopPropagation();
6501
6502 if ( this.isDisabled() || !this.isSupported ) {
6503 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
6504 dt.dropEffect = 'none';
6505 return false;
6506 }
6507
6508 // DataTransferItem and File both have a type property, but in Chrome files
6509 // have no information at this point.
6510 itemOrFile = OO.getProp( dt, 'items', 0 ) || OO.getProp( dt, 'files', 0 );
6511 if ( itemOrFile ) {
6512 if ( this.isAllowedType( itemOrFile.type ) ) {
6513 droppableFile = true;
6514 }
6515 // dt.types is Array-like, but not an Array
6516 } else if ( Array.prototype.indexOf.call( OO.getProp( dt, 'types' ) || [], 'Files' ) !== -1 ) {
6517 // File information is not available at this point for security so just assume
6518 // it is acceptable for now.
6519 // https://bugzilla.mozilla.org/show_bug.cgi?id=640534
6520 droppableFile = true;
6521 }
6522
6523 this.$element.toggleClass( 'oo-ui-selectFileWidget-canDrop', droppableFile );
6524 if ( !droppableFile ) {
6525 dt.dropEffect = 'none';
6526 }
6527
6528 return false;
6529 };
6530
6531 /**
6532 * Handle drag leave events
6533 *
6534 * @private
6535 * @param {jQuery.Event} e Drag event
6536 */
6537 OO.ui.SelectFileWidget.prototype.onDragLeave = function () {
6538 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
6539 };
6540
6541 /**
6542 * Handle drop events
6543 *
6544 * @private
6545 * @param {jQuery.Event} e Drop event
6546 */
6547 OO.ui.SelectFileWidget.prototype.onDrop = function ( e ) {
6548 var file = null,
6549 dt = e.originalEvent.dataTransfer;
6550
6551 e.preventDefault();
6552 e.stopPropagation();
6553 this.$element.removeClass( 'oo-ui-selectFileWidget-canDrop' );
6554
6555 if ( this.isDisabled() || !this.isSupported ) {
6556 return false;
6557 }
6558
6559 file = OO.getProp( dt, 'files', 0 );
6560 if ( file && !this.isAllowedType( file.type ) ) {
6561 file = null;
6562 }
6563 if ( file ) {
6564 this.setValue( file );
6565 }
6566
6567 return false;
6568 };
6569
6570 /**
6571 * @inheritdoc
6572 */
6573 OO.ui.SelectFileWidget.prototype.setDisabled = function ( disabled ) {
6574 OO.ui.SelectFileWidget.parent.prototype.setDisabled.call( this, disabled );
6575 if ( this.selectButton ) {
6576 this.selectButton.setDisabled( disabled );
6577 }
6578 if ( this.clearButton ) {
6579 this.clearButton.setDisabled( disabled );
6580 }
6581 return this;
6582 };
6583
6584 /**
6585 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
6586 * and a menu of search results, which is displayed beneath the query
6587 * field. Unlike {@link OO.ui.mixin.LookupElement lookup menus}, search result menus are always visible to the user.
6588 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
6589 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
6590 *
6591 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
6592 * the [OOUI demos][1] for an example.
6593 *
6594 * [1]: https://doc.wikimedia.org/oojs-ui/master/demos/#SearchInputWidget-type-search
6595 *
6596 * @class
6597 * @extends OO.ui.Widget
6598 *
6599 * @constructor
6600 * @param {Object} [config] Configuration options
6601 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
6602 * @cfg {string} [value] Initial query value
6603 */
6604 OO.ui.SearchWidget = function OoUiSearchWidget( config ) {
6605 // Configuration initialization
6606 config = config || {};
6607
6608 // Parent constructor
6609 OO.ui.SearchWidget.parent.call( this, config );
6610
6611 // Properties
6612 this.query = new OO.ui.TextInputWidget( {
6613 icon: 'search',
6614 placeholder: config.placeholder,
6615 value: config.value
6616 } );
6617 this.results = new OO.ui.SelectWidget();
6618 this.$query = $( '<div>' );
6619 this.$results = $( '<div>' );
6620
6621 // Events
6622 this.query.connect( this, {
6623 change: 'onQueryChange',
6624 enter: 'onQueryEnter'
6625 } );
6626 this.query.$input.on( 'keydown', this.onQueryKeydown.bind( this ) );
6627
6628 // Initialization
6629 this.$query
6630 .addClass( 'oo-ui-searchWidget-query' )
6631 .append( this.query.$element );
6632 this.$results
6633 .addClass( 'oo-ui-searchWidget-results' )
6634 .append( this.results.$element );
6635 this.$element
6636 .addClass( 'oo-ui-searchWidget' )
6637 .append( this.$results, this.$query );
6638 };
6639
6640 /* Setup */
6641
6642 OO.inheritClass( OO.ui.SearchWidget, OO.ui.Widget );
6643
6644 /* Methods */
6645
6646 /**
6647 * Handle query key down events.
6648 *
6649 * @private
6650 * @param {jQuery.Event} e Key down event
6651 */
6652 OO.ui.SearchWidget.prototype.onQueryKeydown = function ( e ) {
6653 var highlightedItem, nextItem,
6654 dir = e.which === OO.ui.Keys.DOWN ? 1 : ( e.which === OO.ui.Keys.UP ? -1 : 0 );
6655
6656 if ( dir ) {
6657 highlightedItem = this.results.findHighlightedItem();
6658 if ( !highlightedItem ) {
6659 highlightedItem = this.results.findSelectedItem();
6660 }
6661 nextItem = this.results.findRelativeSelectableItem( highlightedItem, dir );
6662 this.results.highlightItem( nextItem );
6663 nextItem.scrollElementIntoView();
6664 }
6665 };
6666
6667 /**
6668 * Handle select widget select events.
6669 *
6670 * Clears existing results. Subclasses should repopulate items according to new query.
6671 *
6672 * @private
6673 * @param {string} value New value
6674 */
6675 OO.ui.SearchWidget.prototype.onQueryChange = function () {
6676 // Reset
6677 this.results.clearItems();
6678 };
6679
6680 /**
6681 * Handle select widget enter key events.
6682 *
6683 * Chooses highlighted item.
6684 *
6685 * @private
6686 * @param {string} value New value
6687 */
6688 OO.ui.SearchWidget.prototype.onQueryEnter = function () {
6689 var highlightedItem = this.results.findHighlightedItem();
6690 if ( highlightedItem ) {
6691 this.results.chooseItem( highlightedItem );
6692 }
6693 };
6694
6695 /**
6696 * Get the query input.
6697 *
6698 * @return {OO.ui.TextInputWidget} Query input
6699 */
6700 OO.ui.SearchWidget.prototype.getQuery = function () {
6701 return this.query;
6702 };
6703
6704 /**
6705 * Get the search results menu.
6706 *
6707 * @return {OO.ui.SelectWidget} Menu of search results
6708 */
6709 OO.ui.SearchWidget.prototype.getResults = function () {
6710 return this.results;
6711 };
6712
6713 }( OO ) );
6714
6715 //# sourceMappingURL=oojs-ui-widgets.js.map