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