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