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