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