Debian Codegraph @

resources/lib/ooui/oojs-ui-widgets.js

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