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