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