1011949cea8558677be515058861e6e1d33a8cda
[lhc/web/wiklou.git] / resources / lib / oojs-ui / oojs-ui.js
1 /*!
2 * OOjs UI v0.10.0
3 * https://www.mediawiki.org/wiki/OOjs_UI
4 *
5 * Copyright 2011–2015 OOjs Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
8 *
9 * Date: 2015-04-23T00:54:26Z
10 */
11 ( function ( OO ) {
12
13 'use strict';
14
15 /**
16 * Namespace for all classes, static methods and static properties.
17 *
18 * @class
19 * @singleton
20 */
21 OO.ui = {};
22
23 OO.ui.bind = $.proxy;
24
25 /**
26 * @property {Object}
27 */
28 OO.ui.Keys = {
29 UNDEFINED: 0,
30 BACKSPACE: 8,
31 DELETE: 46,
32 LEFT: 37,
33 RIGHT: 39,
34 UP: 38,
35 DOWN: 40,
36 ENTER: 13,
37 END: 35,
38 HOME: 36,
39 TAB: 9,
40 PAGEUP: 33,
41 PAGEDOWN: 34,
42 ESCAPE: 27,
43 SHIFT: 16,
44 SPACE: 32
45 };
46
47 /**
48 * Check if an element is focusable.
49 * Inspired from :focusable in jQueryUI v1.11.4 - 2015-04-14
50 *
51 * @param {jQuery} element Element to test
52 * @return {Boolean} [description]
53 */
54 OO.ui.isFocusableElement = function ( $element ) {
55 var node = $element[0],
56 nodeName = node.nodeName.toLowerCase(),
57 // Check if the element have tabindex set
58 isInElementGroup = /^(input|select|textarea|button|object)$/.test( nodeName ),
59 // Check if the element is a link with href or if it has tabindex
60 isOtherElement = (
61 ( nodeName === 'a' && node.href ) ||
62 !isNaN( $element.attr( 'tabindex' ) )
63 ),
64 // Check if the element is visible
65 isVisible = (
66 // This is quicker than calling $element.is( ':visible' )
67 $.expr.filters.visible( node ) &&
68 // Check that all parents are visible
69 !$element.parents().addBack().filter( function () {
70 return $.css( this, 'visibility' ) === 'hidden';
71 } ).length
72 );
73
74 return (
75 ( isInElementGroup ? !node.disabled : isOtherElement ) &&
76 isVisible
77 );
78 };
79
80 /**
81 * Get the user's language and any fallback languages.
82 *
83 * These language codes are used to localize user interface elements in the user's language.
84 *
85 * In environments that provide a localization system, this function should be overridden to
86 * return the user's language(s). The default implementation returns English (en) only.
87 *
88 * @return {string[]} Language codes, in descending order of priority
89 */
90 OO.ui.getUserLanguages = function () {
91 return [ 'en' ];
92 };
93
94 /**
95 * Get a value in an object keyed by language code.
96 *
97 * @param {Object.<string,Mixed>} obj Object keyed by language code
98 * @param {string|null} [lang] Language code, if omitted or null defaults to any user language
99 * @param {string} [fallback] Fallback code, used if no matching language can be found
100 * @return {Mixed} Local value
101 */
102 OO.ui.getLocalValue = function ( obj, lang, fallback ) {
103 var i, len, langs;
104
105 // Requested language
106 if ( obj[ lang ] ) {
107 return obj[ lang ];
108 }
109 // Known user language
110 langs = OO.ui.getUserLanguages();
111 for ( i = 0, len = langs.length; i < len; i++ ) {
112 lang = langs[ i ];
113 if ( obj[ lang ] ) {
114 return obj[ lang ];
115 }
116 }
117 // Fallback language
118 if ( obj[ fallback ] ) {
119 return obj[ fallback ];
120 }
121 // First existing language
122 for ( lang in obj ) {
123 return obj[ lang ];
124 }
125
126 return undefined;
127 };
128
129 /**
130 * Check if a node is contained within another node
131 *
132 * Similar to jQuery#contains except a list of containers can be supplied
133 * and a boolean argument allows you to include the container in the match list
134 *
135 * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in
136 * @param {HTMLElement} contained Node to find
137 * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants
138 * @return {boolean} The node is in the list of target nodes
139 */
140 OO.ui.contains = function ( containers, contained, matchContainers ) {
141 var i;
142 if ( !Array.isArray( containers ) ) {
143 containers = [ containers ];
144 }
145 for ( i = containers.length - 1; i >= 0; i-- ) {
146 if ( ( matchContainers && contained === containers[ i ] ) || $.contains( containers[ i ], contained ) ) {
147 return true;
148 }
149 }
150 return false;
151 };
152
153 /**
154 * Reconstitute a JavaScript object corresponding to a widget created by
155 * the PHP implementation.
156 *
157 * This is an alias for `OO.ui.Element.static.infuse()`.
158 *
159 * @param {string|HTMLElement|jQuery} idOrNode
160 * A DOM id (if a string) or node for the widget to infuse.
161 * @return {OO.ui.Element}
162 * The `OO.ui.Element` corresponding to this (infusable) document node.
163 */
164 OO.ui.infuse = function ( idOrNode ) {
165 return OO.ui.Element.static.infuse( idOrNode );
166 };
167
168 ( function () {
169 /**
170 * Message store for the default implementation of OO.ui.msg
171 *
172 * Environments that provide a localization system should not use this, but should override
173 * OO.ui.msg altogether.
174 *
175 * @private
176 */
177 var messages = {
178 // Tool tip for a button that moves items in a list down one place
179 'ooui-outline-control-move-down': 'Move item down',
180 // Tool tip for a button that moves items in a list up one place
181 'ooui-outline-control-move-up': 'Move item up',
182 // Tool tip for a button that removes items from a list
183 'ooui-outline-control-remove': 'Remove item',
184 // Label for the toolbar group that contains a list of all other available tools
185 'ooui-toolbar-more': 'More',
186 // Label for the fake tool that expands the full list of tools in a toolbar group
187 'ooui-toolgroup-expand': 'More',
188 // Label for the fake tool that collapses the full list of tools in a toolbar group
189 'ooui-toolgroup-collapse': 'Fewer',
190 // Default label for the accept button of a confirmation dialog
191 'ooui-dialog-message-accept': 'OK',
192 // Default label for the reject button of a confirmation dialog
193 'ooui-dialog-message-reject': 'Cancel',
194 // Title for process dialog error description
195 'ooui-dialog-process-error': 'Something went wrong',
196 // Label for process dialog dismiss error button, visible when describing errors
197 'ooui-dialog-process-dismiss': 'Dismiss',
198 // Label for process dialog retry action button, visible when describing only recoverable errors
199 'ooui-dialog-process-retry': 'Try again',
200 // Label for process dialog retry action button, visible when describing only warnings
201 'ooui-dialog-process-continue': 'Continue'
202 };
203
204 /**
205 * Get a localized message.
206 *
207 * In environments that provide a localization system, this function should be overridden to
208 * return the message translated in the user's language. The default implementation always returns
209 * English messages.
210 *
211 * After the message key, message parameters may optionally be passed. In the default implementation,
212 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
213 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
214 * they support unnamed, ordered message parameters.
215 *
216 * @abstract
217 * @param {string} key Message key
218 * @param {Mixed...} [params] Message parameters
219 * @return {string} Translated message with parameters substituted
220 */
221 OO.ui.msg = function ( key ) {
222 var message = messages[ key ],
223 params = Array.prototype.slice.call( arguments, 1 );
224 if ( typeof message === 'string' ) {
225 // Perform $1 substitution
226 message = message.replace( /\$(\d+)/g, function ( unused, n ) {
227 var i = parseInt( n, 10 );
228 return params[ i - 1 ] !== undefined ? params[ i - 1 ] : '$' + n;
229 } );
230 } else {
231 // Return placeholder if message not found
232 message = '[' + key + ']';
233 }
234 return message;
235 };
236
237 /**
238 * Package a message and arguments for deferred resolution.
239 *
240 * Use this when you are statically specifying a message and the message may not yet be present.
241 *
242 * @param {string} key Message key
243 * @param {Mixed...} [params] Message parameters
244 * @return {Function} Function that returns the resolved message when executed
245 */
246 OO.ui.deferMsg = function () {
247 var args = arguments;
248 return function () {
249 return OO.ui.msg.apply( OO.ui, args );
250 };
251 };
252
253 /**
254 * Resolve a message.
255 *
256 * If the message is a function it will be executed, otherwise it will pass through directly.
257 *
258 * @param {Function|string} msg Deferred message, or message text
259 * @return {string} Resolved message
260 */
261 OO.ui.resolveMsg = function ( msg ) {
262 if ( $.isFunction( msg ) ) {
263 return msg();
264 }
265 return msg;
266 };
267
268 } )();
269
270 /**
271 * Element that can be marked as pending.
272 *
273 * @abstract
274 * @class
275 *
276 * @constructor
277 * @param {Object} [config] Configuration options
278 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
279 */
280 OO.ui.PendingElement = function OoUiPendingElement( config ) {
281 // Configuration initialization
282 config = config || {};
283
284 // Properties
285 this.pending = 0;
286 this.$pending = null;
287
288 // Initialisation
289 this.setPendingElement( config.$pending || this.$element );
290 };
291
292 /* Setup */
293
294 OO.initClass( OO.ui.PendingElement );
295
296 /* Methods */
297
298 /**
299 * Set the pending element (and clean up any existing one).
300 *
301 * @param {jQuery} $pending The element to set to pending.
302 */
303 OO.ui.PendingElement.prototype.setPendingElement = function ( $pending ) {
304 if ( this.$pending ) {
305 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
306 }
307
308 this.$pending = $pending;
309 if ( this.pending > 0 ) {
310 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
311 }
312 };
313
314 /**
315 * Check if input is pending.
316 *
317 * @return {boolean}
318 */
319 OO.ui.PendingElement.prototype.isPending = function () {
320 return !!this.pending;
321 };
322
323 /**
324 * Increase the pending stack.
325 *
326 * @chainable
327 */
328 OO.ui.PendingElement.prototype.pushPending = function () {
329 if ( this.pending === 0 ) {
330 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
331 this.updateThemeClasses();
332 }
333 this.pending++;
334
335 return this;
336 };
337
338 /**
339 * Reduce the pending stack.
340 *
341 * Clamped at zero.
342 *
343 * @chainable
344 */
345 OO.ui.PendingElement.prototype.popPending = function () {
346 if ( this.pending === 1 ) {
347 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
348 this.updateThemeClasses();
349 }
350 this.pending = Math.max( 0, this.pending - 1 );
351
352 return this;
353 };
354
355 /**
356 * ActionSets manage the behavior of the {@link OO.ui.ActionWidget action widgets} that comprise them.
357 * Actions can be made available for specific contexts (modes) and circumstances
358 * (abilities). Action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
359 *
360 * ActionSets contain two types of actions:
361 *
362 * - Special: Special actions are the first visible actions with special flags, such as 'safe' and 'primary', the default special flags. Additional special flags can be configured in subclasses with the static #specialFlags property.
363 * - Other: Other actions include all non-special visible actions.
364 *
365 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
366 *
367 * @example
368 * // Example: An action set used in a process dialog
369 * function MyProcessDialog( config ) {
370 * MyProcessDialog.super.call( this, config );
371 * }
372 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
373 * MyProcessDialog.static.title = 'An action set in a process dialog';
374 * // An action set that uses modes ('edit' and 'help' mode, in this example).
375 * MyProcessDialog.static.actions = [
376 * { action: 'continue', modes: 'edit', label: 'Continue', flags: [ 'primary', 'constructive' ] },
377 * { action: 'help', modes: 'edit', label: 'Help' },
378 * { modes: 'edit', label: 'Cancel', flags: 'safe' },
379 * { action: 'back', modes: 'help', label: 'Back', flags: 'safe' }
380 * ];
381 *
382 * MyProcessDialog.prototype.initialize = function () {
383 * MyProcessDialog.super.prototype.initialize.apply( this, arguments );
384 * this.panel1 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
385 * this.panel1.$element.append( '<p>This dialog uses an action set (continue, help, cancel, back) configured with modes. This is edit mode. Click \'help\' to see help mode.</p>' );
386 * this.panel2 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
387 * this.panel2.$element.append( '<p>This is help mode. Only the \'back\' action widget is configured to be visible here. Click \'back\' to return to \'edit\' mode.</p>' );
388 * this.stackLayout = new OO.ui.StackLayout( {
389 * items: [ this.panel1, this.panel2 ]
390 * } );
391 * this.$body.append( this.stackLayout.$element );
392 * };
393 * MyProcessDialog.prototype.getSetupProcess = function ( data ) {
394 * return MyProcessDialog.super.prototype.getSetupProcess.call( this, data )
395 * .next( function () {
396 * this.actions.setMode( 'edit' );
397 * }, this );
398 * };
399 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
400 * if ( action === 'help' ) {
401 * this.actions.setMode( 'help' );
402 * this.stackLayout.setItem( this.panel2 );
403 * } else if ( action === 'back' ) {
404 * this.actions.setMode( 'edit' );
405 * this.stackLayout.setItem( this.panel1 );
406 * } else if ( action === 'continue' ) {
407 * var dialog = this;
408 * return new OO.ui.Process( function () {
409 * dialog.close();
410 * } );
411 * }
412 * return MyProcessDialog.super.prototype.getActionProcess.call( this, action );
413 * };
414 * MyProcessDialog.prototype.getBodyHeight = function () {
415 * return this.panel1.$element.outerHeight( true );
416 * };
417 * var windowManager = new OO.ui.WindowManager();
418 * $( 'body' ).append( windowManager.$element );
419 * var dialog = new MyProcessDialog( {
420 * size: 'medium'
421 * } );
422 * windowManager.addWindows( [ dialog ] );
423 * windowManager.openWindow( dialog );
424 *
425 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
426 *
427 * @abstract
428 * @class
429 * @mixins OO.EventEmitter
430 *
431 * @constructor
432 * @param {Object} [config] Configuration options
433 */
434 OO.ui.ActionSet = function OoUiActionSet( config ) {
435 // Configuration initialization
436 config = config || {};
437
438 // Mixin constructors
439 OO.EventEmitter.call( this );
440
441 // Properties
442 this.list = [];
443 this.categories = {
444 actions: 'getAction',
445 flags: 'getFlags',
446 modes: 'getModes'
447 };
448 this.categorized = {};
449 this.special = {};
450 this.others = [];
451 this.organized = false;
452 this.changing = false;
453 this.changed = false;
454 };
455
456 /* Setup */
457
458 OO.mixinClass( OO.ui.ActionSet, OO.EventEmitter );
459
460 /* Static Properties */
461
462 /**
463 * Symbolic name of the flags used to identify special actions. Special actions are displayed in the
464 * header of a {@link OO.ui.ProcessDialog process dialog}.
465 * See the [OOjs UI documentation on MediaWiki][2] for more information and examples.
466 *
467 * [2]:https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
468 *
469 * @abstract
470 * @static
471 * @inheritable
472 * @property {string}
473 */
474 OO.ui.ActionSet.static.specialFlags = [ 'safe', 'primary' ];
475
476 /* Events */
477
478 /**
479 * @event click
480 *
481 * A 'click' event is emitted when an action is clicked.
482 *
483 * @param {OO.ui.ActionWidget} action Action that was clicked
484 */
485
486 /**
487 * @event resize
488 *
489 * A 'resize' event is emitted when an action widget is resized.
490 *
491 * @param {OO.ui.ActionWidget} action Action that was resized
492 */
493
494 /**
495 * @event add
496 *
497 * An 'add' event is emitted when actions are {@link #method-add added} to the action set.
498 *
499 * @param {OO.ui.ActionWidget[]} added Actions added
500 */
501
502 /**
503 * @event remove
504 *
505 * A 'remove' event is emitted when actions are {@link #method-remove removed}
506 * or {@link #clear cleared}.
507 *
508 * @param {OO.ui.ActionWidget[]} added Actions removed
509 */
510
511 /**
512 * @event change
513 *
514 * A 'change' event is emitted when actions are {@link #method-add added}, {@link #clear cleared},
515 * or {@link #method-remove removed} from the action set or when the {@link #setMode mode} is changed.
516 *
517 */
518
519 /* Methods */
520
521 /**
522 * Handle action change events.
523 *
524 * @private
525 * @fires change
526 */
527 OO.ui.ActionSet.prototype.onActionChange = function () {
528 this.organized = false;
529 if ( this.changing ) {
530 this.changed = true;
531 } else {
532 this.emit( 'change' );
533 }
534 };
535
536 /**
537 * Check if an action is one of the special actions.
538 *
539 * @param {OO.ui.ActionWidget} action Action to check
540 * @return {boolean} Action is special
541 */
542 OO.ui.ActionSet.prototype.isSpecial = function ( action ) {
543 var flag;
544
545 for ( flag in this.special ) {
546 if ( action === this.special[ flag ] ) {
547 return true;
548 }
549 }
550
551 return false;
552 };
553
554 /**
555 * Get action widgets based on the specified filter: ‘actions’, ‘flags’, ‘modes’, ‘visible’,
556 * or ‘disabled’.
557 *
558 * @param {Object} [filters] Filters to use, omit to get all actions
559 * @param {string|string[]} [filters.actions] Actions that action widgets must have
560 * @param {string|string[]} [filters.flags] Flags that action widgets must have (e.g., 'safe')
561 * @param {string|string[]} [filters.modes] Modes that action widgets must have
562 * @param {boolean} [filters.visible] Action widgets must be visible
563 * @param {boolean} [filters.disabled] Action widgets must be disabled
564 * @return {OO.ui.ActionWidget[]} Action widgets matching all criteria
565 */
566 OO.ui.ActionSet.prototype.get = function ( filters ) {
567 var i, len, list, category, actions, index, match, matches;
568
569 if ( filters ) {
570 this.organize();
571
572 // Collect category candidates
573 matches = [];
574 for ( category in this.categorized ) {
575 list = filters[ category ];
576 if ( list ) {
577 if ( !Array.isArray( list ) ) {
578 list = [ list ];
579 }
580 for ( i = 0, len = list.length; i < len; i++ ) {
581 actions = this.categorized[ category ][ list[ i ] ];
582 if ( Array.isArray( actions ) ) {
583 matches.push.apply( matches, actions );
584 }
585 }
586 }
587 }
588 // Remove by boolean filters
589 for ( i = 0, len = matches.length; i < len; i++ ) {
590 match = matches[ i ];
591 if (
592 ( filters.visible !== undefined && match.isVisible() !== filters.visible ) ||
593 ( filters.disabled !== undefined && match.isDisabled() !== filters.disabled )
594 ) {
595 matches.splice( i, 1 );
596 len--;
597 i--;
598 }
599 }
600 // Remove duplicates
601 for ( i = 0, len = matches.length; i < len; i++ ) {
602 match = matches[ i ];
603 index = matches.lastIndexOf( match );
604 while ( index !== i ) {
605 matches.splice( index, 1 );
606 len--;
607 index = matches.lastIndexOf( match );
608 }
609 }
610 return matches;
611 }
612 return this.list.slice();
613 };
614
615 /**
616 * Get 'special' actions.
617 *
618 * Special actions are the first visible action widgets with special flags, such as 'safe' and 'primary'.
619 * Special flags can be configured in subclasses by changing the static #specialFlags property.
620 *
621 * @return {OO.ui.ActionWidget[]|null} 'Special' action widgets.
622 */
623 OO.ui.ActionSet.prototype.getSpecial = function () {
624 this.organize();
625 return $.extend( {}, this.special );
626 };
627
628 /**
629 * Get 'other' actions.
630 *
631 * Other actions include all non-special visible action widgets.
632 *
633 * @return {OO.ui.ActionWidget[]} 'Other' action widgets
634 */
635 OO.ui.ActionSet.prototype.getOthers = function () {
636 this.organize();
637 return this.others.slice();
638 };
639
640 /**
641 * Set the mode (e.g., ‘edit’ or ‘view’). Only {@link OO.ui.ActionWidget#modes actions} configured
642 * to be available in the specified mode will be made visible. All other actions will be hidden.
643 *
644 * @param {string} mode The mode. Only actions configured to be available in the specified
645 * mode will be made visible.
646 * @chainable
647 * @fires toggle
648 * @fires change
649 */
650 OO.ui.ActionSet.prototype.setMode = function ( mode ) {
651 var i, len, action;
652
653 this.changing = true;
654 for ( i = 0, len = this.list.length; i < len; i++ ) {
655 action = this.list[ i ];
656 action.toggle( action.hasMode( mode ) );
657 }
658
659 this.organized = false;
660 this.changing = false;
661 this.emit( 'change' );
662
663 return this;
664 };
665
666 /**
667 * Set the abilities of the specified actions.
668 *
669 * Action widgets that are configured with the specified actions will be enabled
670 * or disabled based on the boolean values specified in the `actions`
671 * parameter.
672 *
673 * @param {Object.<string,boolean>} actions A list keyed by action name with boolean
674 * values that indicate whether or not the action should be enabled.
675 * @chainable
676 */
677 OO.ui.ActionSet.prototype.setAbilities = function ( actions ) {
678 var i, len, action, item;
679
680 for ( i = 0, len = this.list.length; i < len; i++ ) {
681 item = this.list[ i ];
682 action = item.getAction();
683 if ( actions[ action ] !== undefined ) {
684 item.setDisabled( !actions[ action ] );
685 }
686 }
687
688 return this;
689 };
690
691 /**
692 * Executes a function once per action.
693 *
694 * When making changes to multiple actions, use this method instead of iterating over the actions
695 * manually to defer emitting a #change event until after all actions have been changed.
696 *
697 * @param {Object|null} actions Filters to use to determine which actions to iterate over; see #get
698 * @param {Function} callback Callback to run for each action; callback is invoked with three
699 * arguments: the action, the action's index, the list of actions being iterated over
700 * @chainable
701 */
702 OO.ui.ActionSet.prototype.forEach = function ( filter, callback ) {
703 this.changed = false;
704 this.changing = true;
705 this.get( filter ).forEach( callback );
706 this.changing = false;
707 if ( this.changed ) {
708 this.emit( 'change' );
709 }
710
711 return this;
712 };
713
714 /**
715 * Add action widgets to the action set.
716 *
717 * @param {OO.ui.ActionWidget[]} actions Action widgets to add
718 * @chainable
719 * @fires add
720 * @fires change
721 */
722 OO.ui.ActionSet.prototype.add = function ( actions ) {
723 var i, len, action;
724
725 this.changing = true;
726 for ( i = 0, len = actions.length; i < len; i++ ) {
727 action = actions[ i ];
728 action.connect( this, {
729 click: [ 'emit', 'click', action ],
730 resize: [ 'emit', 'resize', action ],
731 toggle: [ 'onActionChange' ]
732 } );
733 this.list.push( action );
734 }
735 this.organized = false;
736 this.emit( 'add', actions );
737 this.changing = false;
738 this.emit( 'change' );
739
740 return this;
741 };
742
743 /**
744 * Remove action widgets from the set.
745 *
746 * To remove all actions, you may wish to use the #clear method instead.
747 *
748 * @param {OO.ui.ActionWidget[]} actions Action widgets to remove
749 * @chainable
750 * @fires remove
751 * @fires change
752 */
753 OO.ui.ActionSet.prototype.remove = function ( actions ) {
754 var i, len, index, action;
755
756 this.changing = true;
757 for ( i = 0, len = actions.length; i < len; i++ ) {
758 action = actions[ i ];
759 index = this.list.indexOf( action );
760 if ( index !== -1 ) {
761 action.disconnect( this );
762 this.list.splice( index, 1 );
763 }
764 }
765 this.organized = false;
766 this.emit( 'remove', actions );
767 this.changing = false;
768 this.emit( 'change' );
769
770 return this;
771 };
772
773 /**
774 * Remove all action widets from the set.
775 *
776 * To remove only specified actions, use the {@link #method-remove remove} method instead.
777 *
778 * @chainable
779 * @fires remove
780 * @fires change
781 */
782 OO.ui.ActionSet.prototype.clear = function () {
783 var i, len, action,
784 removed = this.list.slice();
785
786 this.changing = true;
787 for ( i = 0, len = this.list.length; i < len; i++ ) {
788 action = this.list[ i ];
789 action.disconnect( this );
790 }
791
792 this.list = [];
793
794 this.organized = false;
795 this.emit( 'remove', removed );
796 this.changing = false;
797 this.emit( 'change' );
798
799 return this;
800 };
801
802 /**
803 * Organize actions.
804 *
805 * This is called whenever organized information is requested. It will only reorganize the actions
806 * if something has changed since the last time it ran.
807 *
808 * @private
809 * @chainable
810 */
811 OO.ui.ActionSet.prototype.organize = function () {
812 var i, iLen, j, jLen, flag, action, category, list, item, special,
813 specialFlags = this.constructor.static.specialFlags;
814
815 if ( !this.organized ) {
816 this.categorized = {};
817 this.special = {};
818 this.others = [];
819 for ( i = 0, iLen = this.list.length; i < iLen; i++ ) {
820 action = this.list[ i ];
821 if ( action.isVisible() ) {
822 // Populate categories
823 for ( category in this.categories ) {
824 if ( !this.categorized[ category ] ) {
825 this.categorized[ category ] = {};
826 }
827 list = action[ this.categories[ category ] ]();
828 if ( !Array.isArray( list ) ) {
829 list = [ list ];
830 }
831 for ( j = 0, jLen = list.length; j < jLen; j++ ) {
832 item = list[ j ];
833 if ( !this.categorized[ category ][ item ] ) {
834 this.categorized[ category ][ item ] = [];
835 }
836 this.categorized[ category ][ item ].push( action );
837 }
838 }
839 // Populate special/others
840 special = false;
841 for ( j = 0, jLen = specialFlags.length; j < jLen; j++ ) {
842 flag = specialFlags[ j ];
843 if ( !this.special[ flag ] && action.hasFlag( flag ) ) {
844 this.special[ flag ] = action;
845 special = true;
846 break;
847 }
848 }
849 if ( !special ) {
850 this.others.push( action );
851 }
852 }
853 }
854 this.organized = true;
855 }
856
857 return this;
858 };
859
860 /**
861 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
862 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
863 * connected to them and can't be interacted with.
864 *
865 * @abstract
866 * @class
867 *
868 * @constructor
869 * @param {Object} [config] Configuration options
870 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
871 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
872 * for an example.
873 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
874 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
875 * @cfg {string} [text] Text to insert
876 * @cfg {Array} [content] An array of content elements to append (after #text).
877 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
878 * Instances of OO.ui.Element will have their $element appended.
879 * @cfg {jQuery} [$content] Content elements to append (after #text)
880 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
881 * Data can also be specified with the #setData method.
882 */
883 OO.ui.Element = function OoUiElement( config ) {
884 // Configuration initialization
885 config = config || {};
886
887 // Properties
888 this.$ = $;
889 this.visible = true;
890 this.data = config.data;
891 this.$element = config.$element ||
892 $( document.createElement( this.getTagName() ) );
893 this.elementGroup = null;
894 this.debouncedUpdateThemeClassesHandler = this.debouncedUpdateThemeClasses.bind( this );
895 this.updateThemeClassesPending = false;
896
897 // Initialization
898 if ( Array.isArray( config.classes ) ) {
899 this.$element.addClass( config.classes.join( ' ' ) );
900 }
901 if ( config.id ) {
902 this.$element.attr( 'id', config.id );
903 }
904 if ( config.text ) {
905 this.$element.text( config.text );
906 }
907 if ( config.content ) {
908 // The `content` property treats plain strings as text; use an
909 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
910 // appropriate $element appended.
911 this.$element.append( config.content.map( function ( v ) {
912 if ( typeof v === 'string' ) {
913 // Escape string so it is properly represented in HTML.
914 return document.createTextNode( v );
915 } else if ( v instanceof OO.ui.HtmlSnippet ) {
916 // Bypass escaping.
917 return v.toString();
918 } else if ( v instanceof OO.ui.Element ) {
919 return v.$element;
920 }
921 return v;
922 } ) );
923 }
924 if ( config.$content ) {
925 // The `$content` property treats plain strings as HTML.
926 this.$element.append( config.$content );
927 }
928 };
929
930 /* Setup */
931
932 OO.initClass( OO.ui.Element );
933
934 /* Static Properties */
935
936 /**
937 * The name of the HTML tag used by the element.
938 *
939 * The static value may be ignored if the #getTagName method is overridden.
940 *
941 * @static
942 * @inheritable
943 * @property {string}
944 */
945 OO.ui.Element.static.tagName = 'div';
946
947 /* Static Methods */
948
949 /**
950 * Reconstitute a JavaScript object corresponding to a widget created
951 * by the PHP implementation.
952 *
953 * @param {string|HTMLElement|jQuery} idOrNode
954 * A DOM id (if a string) or node for the widget to infuse.
955 * @return {OO.ui.Element}
956 * The `OO.ui.Element` corresponding to this (infusable) document node.
957 * For `Tag` objects emitted on the HTML side (used occasionally for content)
958 * the value returned is a newly-created Element wrapping around the existing
959 * DOM node.
960 */
961 OO.ui.Element.static.infuse = function ( idOrNode ) {
962 var obj = OO.ui.Element.static.unsafeInfuse( idOrNode, true );
963 // Verify that the type matches up.
964 // FIXME: uncomment after T89721 is fixed (see T90929)
965 /*
966 if ( !( obj instanceof this['class'] ) ) {
967 throw new Error( 'Infusion type mismatch!' );
968 }
969 */
970 return obj;
971 };
972
973 /**
974 * Implementation helper for `infuse`; skips the type check and has an
975 * extra property so that only the top-level invocation touches the DOM.
976 * @private
977 * @param {string|HTMLElement|jQuery} idOrNode
978 * @param {boolean} top True only for top-level invocation.
979 * @return {OO.ui.Element}
980 */
981 OO.ui.Element.static.unsafeInfuse = function ( idOrNode, top ) {
982 // look for a cached result of a previous infusion.
983 var id, $elem, data, cls, obj;
984 if ( typeof idOrNode === 'string' ) {
985 id = idOrNode;
986 $elem = $( document.getElementById( id ) );
987 } else {
988 $elem = $( idOrNode );
989 id = $elem.attr( 'id' );
990 }
991 data = $elem.data( 'ooui-infused' );
992 if ( data ) {
993 // cached!
994 if ( data === true ) {
995 throw new Error( 'Circular dependency! ' + id );
996 }
997 return data;
998 }
999 if ( !$elem.length ) {
1000 throw new Error( 'Widget not found: ' + id );
1001 }
1002 data = $elem.attr( 'data-ooui' );
1003 if ( !data ) {
1004 throw new Error( 'No infusion data found: ' + id );
1005 }
1006 try {
1007 data = $.parseJSON( data );
1008 } catch ( _ ) {
1009 data = null;
1010 }
1011 if ( !( data && data._ ) ) {
1012 throw new Error( 'No valid infusion data found: ' + id );
1013 }
1014 if ( data._ === 'Tag' ) {
1015 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
1016 return new OO.ui.Element( { $element: $elem } );
1017 }
1018 cls = OO.ui[data._];
1019 if ( !cls ) {
1020 throw new Error( 'Unknown widget type: ' + id );
1021 }
1022 $elem.data( 'ooui-infused', true ); // prevent loops
1023 data.id = id; // implicit
1024 data = OO.copy( data, null, function deserialize( value ) {
1025 if ( OO.isPlainObject( value ) ) {
1026 if ( value.tag ) {
1027 return OO.ui.Element.static.unsafeInfuse( value.tag, false );
1028 }
1029 if ( value.html ) {
1030 return new OO.ui.HtmlSnippet( value.html );
1031 }
1032 }
1033 } );
1034 // jscs:disable requireCapitalizedConstructors
1035 obj = new cls( data ); // rebuild widget
1036 // now replace old DOM with this new DOM.
1037 if ( top ) {
1038 $elem.replaceWith( obj.$element );
1039 }
1040 obj.$element.data( 'ooui-infused', obj );
1041 // set the 'data-ooui' attribute so we can identify infused widgets
1042 obj.$element.attr( 'data-ooui', '' );
1043 return obj;
1044 };
1045
1046 /**
1047 * Get a jQuery function within a specific document.
1048 *
1049 * @static
1050 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
1051 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
1052 * not in an iframe
1053 * @return {Function} Bound jQuery function
1054 */
1055 OO.ui.Element.static.getJQuery = function ( context, $iframe ) {
1056 function wrapper( selector ) {
1057 return $( selector, wrapper.context );
1058 }
1059
1060 wrapper.context = this.getDocument( context );
1061
1062 if ( $iframe ) {
1063 wrapper.$iframe = $iframe;
1064 }
1065
1066 return wrapper;
1067 };
1068
1069 /**
1070 * Get the document of an element.
1071 *
1072 * @static
1073 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
1074 * @return {HTMLDocument|null} Document object
1075 */
1076 OO.ui.Element.static.getDocument = function ( obj ) {
1077 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
1078 return ( obj[ 0 ] && obj[ 0 ].ownerDocument ) ||
1079 // Empty jQuery selections might have a context
1080 obj.context ||
1081 // HTMLElement
1082 obj.ownerDocument ||
1083 // Window
1084 obj.document ||
1085 // HTMLDocument
1086 ( obj.nodeType === 9 && obj ) ||
1087 null;
1088 };
1089
1090 /**
1091 * Get the window of an element or document.
1092 *
1093 * @static
1094 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
1095 * @return {Window} Window object
1096 */
1097 OO.ui.Element.static.getWindow = function ( obj ) {
1098 var doc = this.getDocument( obj );
1099 return doc.parentWindow || doc.defaultView;
1100 };
1101
1102 /**
1103 * Get the direction of an element or document.
1104 *
1105 * @static
1106 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
1107 * @return {string} Text direction, either 'ltr' or 'rtl'
1108 */
1109 OO.ui.Element.static.getDir = function ( obj ) {
1110 var isDoc, isWin;
1111
1112 if ( obj instanceof jQuery ) {
1113 obj = obj[ 0 ];
1114 }
1115 isDoc = obj.nodeType === 9;
1116 isWin = obj.document !== undefined;
1117 if ( isDoc || isWin ) {
1118 if ( isWin ) {
1119 obj = obj.document;
1120 }
1121 obj = obj.body;
1122 }
1123 return $( obj ).css( 'direction' );
1124 };
1125
1126 /**
1127 * Get the offset between two frames.
1128 *
1129 * TODO: Make this function not use recursion.
1130 *
1131 * @static
1132 * @param {Window} from Window of the child frame
1133 * @param {Window} [to=window] Window of the parent frame
1134 * @param {Object} [offset] Offset to start with, used internally
1135 * @return {Object} Offset object, containing left and top properties
1136 */
1137 OO.ui.Element.static.getFrameOffset = function ( from, to, offset ) {
1138 var i, len, frames, frame, rect;
1139
1140 if ( !to ) {
1141 to = window;
1142 }
1143 if ( !offset ) {
1144 offset = { top: 0, left: 0 };
1145 }
1146 if ( from.parent === from ) {
1147 return offset;
1148 }
1149
1150 // Get iframe element
1151 frames = from.parent.document.getElementsByTagName( 'iframe' );
1152 for ( i = 0, len = frames.length; i < len; i++ ) {
1153 if ( frames[ i ].contentWindow === from ) {
1154 frame = frames[ i ];
1155 break;
1156 }
1157 }
1158
1159 // Recursively accumulate offset values
1160 if ( frame ) {
1161 rect = frame.getBoundingClientRect();
1162 offset.left += rect.left;
1163 offset.top += rect.top;
1164 if ( from !== to ) {
1165 this.getFrameOffset( from.parent, offset );
1166 }
1167 }
1168 return offset;
1169 };
1170
1171 /**
1172 * Get the offset between two elements.
1173 *
1174 * The two elements may be in a different frame, but in that case the frame $element is in must
1175 * be contained in the frame $anchor is in.
1176 *
1177 * @static
1178 * @param {jQuery} $element Element whose position to get
1179 * @param {jQuery} $anchor Element to get $element's position relative to
1180 * @return {Object} Translated position coordinates, containing top and left properties
1181 */
1182 OO.ui.Element.static.getRelativePosition = function ( $element, $anchor ) {
1183 var iframe, iframePos,
1184 pos = $element.offset(),
1185 anchorPos = $anchor.offset(),
1186 elementDocument = this.getDocument( $element ),
1187 anchorDocument = this.getDocument( $anchor );
1188
1189 // If $element isn't in the same document as $anchor, traverse up
1190 while ( elementDocument !== anchorDocument ) {
1191 iframe = elementDocument.defaultView.frameElement;
1192 if ( !iframe ) {
1193 throw new Error( '$element frame is not contained in $anchor frame' );
1194 }
1195 iframePos = $( iframe ).offset();
1196 pos.left += iframePos.left;
1197 pos.top += iframePos.top;
1198 elementDocument = iframe.ownerDocument;
1199 }
1200 pos.left -= anchorPos.left;
1201 pos.top -= anchorPos.top;
1202 return pos;
1203 };
1204
1205 /**
1206 * Get element border sizes.
1207 *
1208 * @static
1209 * @param {HTMLElement} el Element to measure
1210 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1211 */
1212 OO.ui.Element.static.getBorders = function ( el ) {
1213 var doc = el.ownerDocument,
1214 win = doc.parentWindow || doc.defaultView,
1215 style = win && win.getComputedStyle ?
1216 win.getComputedStyle( el, null ) :
1217 el.currentStyle,
1218 $el = $( el ),
1219 top = parseFloat( style ? style.borderTopWidth : $el.css( 'borderTopWidth' ) ) || 0,
1220 left = parseFloat( style ? style.borderLeftWidth : $el.css( 'borderLeftWidth' ) ) || 0,
1221 bottom = parseFloat( style ? style.borderBottomWidth : $el.css( 'borderBottomWidth' ) ) || 0,
1222 right = parseFloat( style ? style.borderRightWidth : $el.css( 'borderRightWidth' ) ) || 0;
1223
1224 return {
1225 top: top,
1226 left: left,
1227 bottom: bottom,
1228 right: right
1229 };
1230 };
1231
1232 /**
1233 * Get dimensions of an element or window.
1234 *
1235 * @static
1236 * @param {HTMLElement|Window} el Element to measure
1237 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1238 */
1239 OO.ui.Element.static.getDimensions = function ( el ) {
1240 var $el, $win,
1241 doc = el.ownerDocument || el.document,
1242 win = doc.parentWindow || doc.defaultView;
1243
1244 if ( win === el || el === doc.documentElement ) {
1245 $win = $( win );
1246 return {
1247 borders: { top: 0, left: 0, bottom: 0, right: 0 },
1248 scroll: {
1249 top: $win.scrollTop(),
1250 left: $win.scrollLeft()
1251 },
1252 scrollbar: { right: 0, bottom: 0 },
1253 rect: {
1254 top: 0,
1255 left: 0,
1256 bottom: $win.innerHeight(),
1257 right: $win.innerWidth()
1258 }
1259 };
1260 } else {
1261 $el = $( el );
1262 return {
1263 borders: this.getBorders( el ),
1264 scroll: {
1265 top: $el.scrollTop(),
1266 left: $el.scrollLeft()
1267 },
1268 scrollbar: {
1269 right: $el.innerWidth() - el.clientWidth,
1270 bottom: $el.innerHeight() - el.clientHeight
1271 },
1272 rect: el.getBoundingClientRect()
1273 };
1274 }
1275 };
1276
1277 /**
1278 * Get scrollable object parent
1279 *
1280 * documentElement can't be used to get or set the scrollTop
1281 * property on Blink. Changing and testing its value lets us
1282 * use 'body' or 'documentElement' based on what is working.
1283 *
1284 * https://code.google.com/p/chromium/issues/detail?id=303131
1285 *
1286 * @static
1287 * @param {HTMLElement} el Element to find scrollable parent for
1288 * @return {HTMLElement} Scrollable parent
1289 */
1290 OO.ui.Element.static.getRootScrollableElement = function ( el ) {
1291 var scrollTop, body;
1292
1293 if ( OO.ui.scrollableElement === undefined ) {
1294 body = el.ownerDocument.body;
1295 scrollTop = body.scrollTop;
1296 body.scrollTop = 1;
1297
1298 if ( body.scrollTop === 1 ) {
1299 body.scrollTop = scrollTop;
1300 OO.ui.scrollableElement = 'body';
1301 } else {
1302 OO.ui.scrollableElement = 'documentElement';
1303 }
1304 }
1305
1306 return el.ownerDocument[ OO.ui.scrollableElement ];
1307 };
1308
1309 /**
1310 * Get closest scrollable container.
1311 *
1312 * Traverses up until either a scrollable element or the root is reached, in which case the window
1313 * will be returned.
1314 *
1315 * @static
1316 * @param {HTMLElement} el Element to find scrollable container for
1317 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1318 * @return {HTMLElement} Closest scrollable container
1319 */
1320 OO.ui.Element.static.getClosestScrollableContainer = function ( el, dimension ) {
1321 var i, val,
1322 props = [ 'overflow' ],
1323 $parent = $( el ).parent();
1324
1325 if ( dimension === 'x' || dimension === 'y' ) {
1326 props.push( 'overflow-' + dimension );
1327 }
1328
1329 while ( $parent.length ) {
1330 if ( $parent[ 0 ] === this.getRootScrollableElement( el ) ) {
1331 return $parent[ 0 ];
1332 }
1333 i = props.length;
1334 while ( i-- ) {
1335 val = $parent.css( props[ i ] );
1336 if ( val === 'auto' || val === 'scroll' ) {
1337 return $parent[ 0 ];
1338 }
1339 }
1340 $parent = $parent.parent();
1341 }
1342 return this.getDocument( el ).body;
1343 };
1344
1345 /**
1346 * Scroll element into view.
1347 *
1348 * @static
1349 * @param {HTMLElement} el Element to scroll into view
1350 * @param {Object} [config] Configuration options
1351 * @param {string} [config.duration] jQuery animation duration value
1352 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1353 * to scroll in both directions
1354 * @param {Function} [config.complete] Function to call when scrolling completes
1355 */
1356 OO.ui.Element.static.scrollIntoView = function ( el, config ) {
1357 // Configuration initialization
1358 config = config || {};
1359
1360 var rel, anim = {},
1361 callback = typeof config.complete === 'function' && config.complete,
1362 sc = this.getClosestScrollableContainer( el, config.direction ),
1363 $sc = $( sc ),
1364 eld = this.getDimensions( el ),
1365 scd = this.getDimensions( sc ),
1366 $win = $( this.getWindow( el ) );
1367
1368 // Compute the distances between the edges of el and the edges of the scroll viewport
1369 if ( $sc.is( 'html, body' ) ) {
1370 // If the scrollable container is the root, this is easy
1371 rel = {
1372 top: eld.rect.top,
1373 bottom: $win.innerHeight() - eld.rect.bottom,
1374 left: eld.rect.left,
1375 right: $win.innerWidth() - eld.rect.right
1376 };
1377 } else {
1378 // Otherwise, we have to subtract el's coordinates from sc's coordinates
1379 rel = {
1380 top: eld.rect.top - ( scd.rect.top + scd.borders.top ),
1381 bottom: scd.rect.bottom - scd.borders.bottom - scd.scrollbar.bottom - eld.rect.bottom,
1382 left: eld.rect.left - ( scd.rect.left + scd.borders.left ),
1383 right: scd.rect.right - scd.borders.right - scd.scrollbar.right - eld.rect.right
1384 };
1385 }
1386
1387 if ( !config.direction || config.direction === 'y' ) {
1388 if ( rel.top < 0 ) {
1389 anim.scrollTop = scd.scroll.top + rel.top;
1390 } else if ( rel.top > 0 && rel.bottom < 0 ) {
1391 anim.scrollTop = scd.scroll.top + Math.min( rel.top, -rel.bottom );
1392 }
1393 }
1394 if ( !config.direction || config.direction === 'x' ) {
1395 if ( rel.left < 0 ) {
1396 anim.scrollLeft = scd.scroll.left + rel.left;
1397 } else if ( rel.left > 0 && rel.right < 0 ) {
1398 anim.scrollLeft = scd.scroll.left + Math.min( rel.left, -rel.right );
1399 }
1400 }
1401 if ( !$.isEmptyObject( anim ) ) {
1402 $sc.stop( true ).animate( anim, config.duration || 'fast' );
1403 if ( callback ) {
1404 $sc.queue( function ( next ) {
1405 callback();
1406 next();
1407 } );
1408 }
1409 } else {
1410 if ( callback ) {
1411 callback();
1412 }
1413 }
1414 };
1415
1416 /**
1417 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1418 * and reserve space for them, because it probably doesn't.
1419 *
1420 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1421 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1422 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1423 * and then reattach (or show) them back.
1424 *
1425 * @static
1426 * @param {HTMLElement} el Element to reconsider the scrollbars on
1427 */
1428 OO.ui.Element.static.reconsiderScrollbars = function ( el ) {
1429 var i, len, nodes = [];
1430 // Detach all children
1431 while ( el.firstChild ) {
1432 nodes.push( el.firstChild );
1433 el.removeChild( el.firstChild );
1434 }
1435 // Force reflow
1436 void el.offsetHeight;
1437 // Reattach all children
1438 for ( i = 0, len = nodes.length; i < len; i++ ) {
1439 el.appendChild( nodes[ i ] );
1440 }
1441 };
1442
1443 /* Methods */
1444
1445 /**
1446 * Toggle visibility of an element.
1447 *
1448 * @param {boolean} [show] Make element visible, omit to toggle visibility
1449 * @fires visible
1450 * @chainable
1451 */
1452 OO.ui.Element.prototype.toggle = function ( show ) {
1453 show = show === undefined ? !this.visible : !!show;
1454
1455 if ( show !== this.isVisible() ) {
1456 this.visible = show;
1457 this.$element.toggleClass( 'oo-ui-element-hidden', !this.visible );
1458 this.emit( 'toggle', show );
1459 }
1460
1461 return this;
1462 };
1463
1464 /**
1465 * Check if element is visible.
1466 *
1467 * @return {boolean} element is visible
1468 */
1469 OO.ui.Element.prototype.isVisible = function () {
1470 return this.visible;
1471 };
1472
1473 /**
1474 * Get element data.
1475 *
1476 * @return {Mixed} Element data
1477 */
1478 OO.ui.Element.prototype.getData = function () {
1479 return this.data;
1480 };
1481
1482 /**
1483 * Set element data.
1484 *
1485 * @param {Mixed} Element data
1486 * @chainable
1487 */
1488 OO.ui.Element.prototype.setData = function ( data ) {
1489 this.data = data;
1490 return this;
1491 };
1492
1493 /**
1494 * Check if element supports one or more methods.
1495 *
1496 * @param {string|string[]} methods Method or list of methods to check
1497 * @return {boolean} All methods are supported
1498 */
1499 OO.ui.Element.prototype.supports = function ( methods ) {
1500 var i, len,
1501 support = 0;
1502
1503 methods = Array.isArray( methods ) ? methods : [ methods ];
1504 for ( i = 0, len = methods.length; i < len; i++ ) {
1505 if ( $.isFunction( this[ methods[ i ] ] ) ) {
1506 support++;
1507 }
1508 }
1509
1510 return methods.length === support;
1511 };
1512
1513 /**
1514 * Update the theme-provided classes.
1515 *
1516 * @localdoc This is called in element mixins and widget classes any time state changes.
1517 * Updating is debounced, minimizing overhead of changing multiple attributes and
1518 * guaranteeing that theme updates do not occur within an element's constructor
1519 */
1520 OO.ui.Element.prototype.updateThemeClasses = function () {
1521 if ( !this.updateThemeClassesPending ) {
1522 this.updateThemeClassesPending = true;
1523 setTimeout( this.debouncedUpdateThemeClassesHandler );
1524 }
1525 };
1526
1527 /**
1528 * @private
1529 */
1530 OO.ui.Element.prototype.debouncedUpdateThemeClasses = function () {
1531 OO.ui.theme.updateElementClasses( this );
1532 this.updateThemeClassesPending = false;
1533 };
1534
1535 /**
1536 * Get the HTML tag name.
1537 *
1538 * Override this method to base the result on instance information.
1539 *
1540 * @return {string} HTML tag name
1541 */
1542 OO.ui.Element.prototype.getTagName = function () {
1543 return this.constructor.static.tagName;
1544 };
1545
1546 /**
1547 * Check if the element is attached to the DOM
1548 * @return {boolean} The element is attached to the DOM
1549 */
1550 OO.ui.Element.prototype.isElementAttached = function () {
1551 return $.contains( this.getElementDocument(), this.$element[ 0 ] );
1552 };
1553
1554 /**
1555 * Get the DOM document.
1556 *
1557 * @return {HTMLDocument} Document object
1558 */
1559 OO.ui.Element.prototype.getElementDocument = function () {
1560 // Don't cache this in other ways either because subclasses could can change this.$element
1561 return OO.ui.Element.static.getDocument( this.$element );
1562 };
1563
1564 /**
1565 * Get the DOM window.
1566 *
1567 * @return {Window} Window object
1568 */
1569 OO.ui.Element.prototype.getElementWindow = function () {
1570 return OO.ui.Element.static.getWindow( this.$element );
1571 };
1572
1573 /**
1574 * Get closest scrollable container.
1575 */
1576 OO.ui.Element.prototype.getClosestScrollableElementContainer = function () {
1577 return OO.ui.Element.static.getClosestScrollableContainer( this.$element[ 0 ] );
1578 };
1579
1580 /**
1581 * Get group element is in.
1582 *
1583 * @return {OO.ui.GroupElement|null} Group element, null if none
1584 */
1585 OO.ui.Element.prototype.getElementGroup = function () {
1586 return this.elementGroup;
1587 };
1588
1589 /**
1590 * Set group element is in.
1591 *
1592 * @param {OO.ui.GroupElement|null} group Group element, null if none
1593 * @chainable
1594 */
1595 OO.ui.Element.prototype.setElementGroup = function ( group ) {
1596 this.elementGroup = group;
1597 return this;
1598 };
1599
1600 /**
1601 * Scroll element into view.
1602 *
1603 * @param {Object} [config] Configuration options
1604 */
1605 OO.ui.Element.prototype.scrollElementIntoView = function ( config ) {
1606 return OO.ui.Element.static.scrollIntoView( this.$element[ 0 ], config );
1607 };
1608
1609 /**
1610 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1611 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1612 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1613 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1614 * and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1615 *
1616 * @abstract
1617 * @class
1618 * @extends OO.ui.Element
1619 * @mixins OO.EventEmitter
1620 *
1621 * @constructor
1622 * @param {Object} [config] Configuration options
1623 */
1624 OO.ui.Layout = function OoUiLayout( config ) {
1625 // Configuration initialization
1626 config = config || {};
1627
1628 // Parent constructor
1629 OO.ui.Layout.super.call( this, config );
1630
1631 // Mixin constructors
1632 OO.EventEmitter.call( this );
1633
1634 // Initialization
1635 this.$element.addClass( 'oo-ui-layout' );
1636 };
1637
1638 /* Setup */
1639
1640 OO.inheritClass( OO.ui.Layout, OO.ui.Element );
1641 OO.mixinClass( OO.ui.Layout, OO.EventEmitter );
1642
1643 /**
1644 * Widgets are compositions of one or more OOjs UI elements that users can both view
1645 * and interact with. All widgets can be configured and modified via a standard API,
1646 * and their state can change dynamically according to a model.
1647 *
1648 * @abstract
1649 * @class
1650 * @extends OO.ui.Element
1651 * @mixins OO.EventEmitter
1652 *
1653 * @constructor
1654 * @param {Object} [config] Configuration options
1655 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1656 * appearance reflects this state.
1657 */
1658 OO.ui.Widget = function OoUiWidget( config ) {
1659 // Initialize config
1660 config = $.extend( { disabled: false }, config );
1661
1662 // Parent constructor
1663 OO.ui.Widget.super.call( this, config );
1664
1665 // Mixin constructors
1666 OO.EventEmitter.call( this );
1667
1668 // Properties
1669 this.disabled = null;
1670 this.wasDisabled = null;
1671
1672 // Initialization
1673 this.$element.addClass( 'oo-ui-widget' );
1674 this.setDisabled( !!config.disabled );
1675 };
1676
1677 /* Setup */
1678
1679 OO.inheritClass( OO.ui.Widget, OO.ui.Element );
1680 OO.mixinClass( OO.ui.Widget, OO.EventEmitter );
1681
1682 /* Events */
1683
1684 /**
1685 * @event disable
1686 *
1687 * A 'disable' event is emitted when a widget is disabled.
1688 *
1689 * @param {boolean} disabled Widget is disabled
1690 */
1691
1692 /**
1693 * @event toggle
1694 *
1695 * A 'toggle' event is emitted when the visibility of the widget changes.
1696 *
1697 * @param {boolean} visible Widget is visible
1698 */
1699
1700 /* Methods */
1701
1702 /**
1703 * Check if the widget is disabled.
1704 *
1705 * @return {boolean} Widget is disabled
1706 */
1707 OO.ui.Widget.prototype.isDisabled = function () {
1708 return this.disabled;
1709 };
1710
1711 /**
1712 * Set the 'disabled' state of the widget.
1713 *
1714 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1715 *
1716 * @param {boolean} disabled Disable widget
1717 * @chainable
1718 */
1719 OO.ui.Widget.prototype.setDisabled = function ( disabled ) {
1720 var isDisabled;
1721
1722 this.disabled = !!disabled;
1723 isDisabled = this.isDisabled();
1724 if ( isDisabled !== this.wasDisabled ) {
1725 this.$element.toggleClass( 'oo-ui-widget-disabled', isDisabled );
1726 this.$element.toggleClass( 'oo-ui-widget-enabled', !isDisabled );
1727 this.$element.attr( 'aria-disabled', isDisabled.toString() );
1728 this.emit( 'disable', isDisabled );
1729 this.updateThemeClasses();
1730 }
1731 this.wasDisabled = isDisabled;
1732
1733 return this;
1734 };
1735
1736 /**
1737 * Update the disabled state, in case of changes in parent widget.
1738 *
1739 * @chainable
1740 */
1741 OO.ui.Widget.prototype.updateDisabled = function () {
1742 this.setDisabled( this.disabled );
1743 return this;
1744 };
1745
1746 /**
1747 * A window is a container for elements that are in a child frame. They are used with
1748 * a window manager (OO.ui.WindowManager), which is used to open and close the window and control
1749 * its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’, ‘medium’,
1750 * ‘large’), which is interpreted by the window manager. If the requested size is not recognized,
1751 * the window manager will choose a sensible fallback.
1752 *
1753 * The lifecycle of a window has three primary stages (opening, opened, and closing) in which
1754 * different processes are executed:
1755 *
1756 * **opening**: The opening stage begins when the window manager's {@link OO.ui.WindowManager#openWindow
1757 * openWindow} or the window's {@link #open open} methods are used, and the window manager begins to open
1758 * the window.
1759 *
1760 * - {@link #getSetupProcess} method is called and its result executed
1761 * - {@link #getReadyProcess} method is called and its result executed
1762 *
1763 * **opened**: The window is now open
1764 *
1765 * **closing**: The closing stage begins when the window manager's
1766 * {@link OO.ui.WindowManager#closeWindow closeWindow}
1767 * or the window's {@link #close} methods are used, and the window manager begins to close the window.
1768 *
1769 * - {@link #getHoldProcess} method is called and its result executed
1770 * - {@link #getTeardownProcess} method is called and its result executed. The window is now closed
1771 *
1772 * Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses
1773 * by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and #getTeardownProcess
1774 * methods. Note that each {@link OO.ui.Process process} is executed in series, so asynchronous
1775 * processing can complete. Always assume window processes are executed asynchronously.
1776 *
1777 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
1778 *
1779 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows
1780 *
1781 * @abstract
1782 * @class
1783 * @extends OO.ui.Element
1784 * @mixins OO.EventEmitter
1785 *
1786 * @constructor
1787 * @param {Object} [config] Configuration options
1788 * @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or
1789 * `full`. If omitted, the value of the {@link #static-size static size} property will be used.
1790 */
1791 OO.ui.Window = function OoUiWindow( config ) {
1792 // Configuration initialization
1793 config = config || {};
1794
1795 // Parent constructor
1796 OO.ui.Window.super.call( this, config );
1797
1798 // Mixin constructors
1799 OO.EventEmitter.call( this );
1800
1801 // Properties
1802 this.manager = null;
1803 this.size = config.size || this.constructor.static.size;
1804 this.$frame = $( '<div>' );
1805 this.$overlay = $( '<div>' );
1806 this.$content = $( '<div>' );
1807
1808 // Initialization
1809 this.$overlay.addClass( 'oo-ui-window-overlay' );
1810 this.$content
1811 .addClass( 'oo-ui-window-content' )
1812 .attr( 'tabIndex', 0 );
1813 this.$frame
1814 .addClass( 'oo-ui-window-frame' )
1815 .append( this.$content );
1816
1817 this.$element
1818 .addClass( 'oo-ui-window' )
1819 .append( this.$frame, this.$overlay );
1820
1821 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
1822 // that reference properties not initialized at that time of parent class construction
1823 // TODO: Find a better way to handle post-constructor setup
1824 this.visible = false;
1825 this.$element.addClass( 'oo-ui-element-hidden' );
1826 };
1827
1828 /* Setup */
1829
1830 OO.inheritClass( OO.ui.Window, OO.ui.Element );
1831 OO.mixinClass( OO.ui.Window, OO.EventEmitter );
1832
1833 /* Static Properties */
1834
1835 /**
1836 * Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`.
1837 *
1838 * The static size is used if no #size is configured during construction.
1839 *
1840 * @static
1841 * @inheritable
1842 * @property {string}
1843 */
1844 OO.ui.Window.static.size = 'medium';
1845
1846 /* Methods */
1847
1848 /**
1849 * Handle mouse down events.
1850 *
1851 * @private
1852 * @param {jQuery.Event} e Mouse down event
1853 */
1854 OO.ui.Window.prototype.onMouseDown = function ( e ) {
1855 // Prevent clicking on the click-block from stealing focus
1856 if ( e.target === this.$element[ 0 ] ) {
1857 return false;
1858 }
1859 };
1860
1861 /**
1862 * Check if the window has been initialized.
1863 *
1864 * Initialization occurs when a window is added to a manager.
1865 *
1866 * @return {boolean} Window has been initialized
1867 */
1868 OO.ui.Window.prototype.isInitialized = function () {
1869 return !!this.manager;
1870 };
1871
1872 /**
1873 * Check if the window is visible.
1874 *
1875 * @return {boolean} Window is visible
1876 */
1877 OO.ui.Window.prototype.isVisible = function () {
1878 return this.visible;
1879 };
1880
1881 /**
1882 * Check if the window is opening.
1883 *
1884 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpening isOpening}
1885 * method.
1886 *
1887 * @return {boolean} Window is opening
1888 */
1889 OO.ui.Window.prototype.isOpening = function () {
1890 return this.manager.isOpening( this );
1891 };
1892
1893 /**
1894 * Check if the window is closing.
1895 *
1896 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isClosing isClosing} method.
1897 *
1898 * @return {boolean} Window is closing
1899 */
1900 OO.ui.Window.prototype.isClosing = function () {
1901 return this.manager.isClosing( this );
1902 };
1903
1904 /**
1905 * Check if the window is opened.
1906 *
1907 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpened isOpened} method.
1908 *
1909 * @return {boolean} Window is opened
1910 */
1911 OO.ui.Window.prototype.isOpened = function () {
1912 return this.manager.isOpened( this );
1913 };
1914
1915 /**
1916 * Get the window manager.
1917 *
1918 * All windows must be attached to a window manager, which is used to open
1919 * and close the window and control its presentation.
1920 *
1921 * @return {OO.ui.WindowManager} Manager of window
1922 */
1923 OO.ui.Window.prototype.getManager = function () {
1924 return this.manager;
1925 };
1926
1927 /**
1928 * Get the symbolic name of the window size (e.g., `small` or `medium`).
1929 *
1930 * @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full`
1931 */
1932 OO.ui.Window.prototype.getSize = function () {
1933 return this.size;
1934 };
1935
1936 /**
1937 * Disable transitions on window's frame for the duration of the callback function, then enable them
1938 * back.
1939 *
1940 * @private
1941 * @param {Function} callback Function to call while transitions are disabled
1942 */
1943 OO.ui.Window.prototype.withoutSizeTransitions = function ( callback ) {
1944 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
1945 // Disable transitions first, otherwise we'll get values from when the window was animating.
1946 var oldTransition,
1947 styleObj = this.$frame[ 0 ].style;
1948 oldTransition = styleObj.transition || styleObj.OTransition || styleObj.MsTransition ||
1949 styleObj.MozTransition || styleObj.WebkitTransition;
1950 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
1951 styleObj.MozTransition = styleObj.WebkitTransition = 'none';
1952 callback();
1953 // Force reflow to make sure the style changes done inside callback really are not transitioned
1954 this.$frame.height();
1955 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
1956 styleObj.MozTransition = styleObj.WebkitTransition = oldTransition;
1957 };
1958
1959 /**
1960 * Get the height of the full window contents (i.e., the window head, body and foot together).
1961 *
1962 * What consistitutes the head, body, and foot varies depending on the window type.
1963 * A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body,
1964 * and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title
1965 * and special actions in the head, and dialog content in the body.
1966 *
1967 * To get just the height of the dialog body, use the #getBodyHeight method.
1968 *
1969 * @return {number} The height of the window contents (the dialog head, body and foot) in pixels
1970 */
1971 OO.ui.Window.prototype.getContentHeight = function () {
1972 var bodyHeight,
1973 win = this,
1974 bodyStyleObj = this.$body[ 0 ].style,
1975 frameStyleObj = this.$frame[ 0 ].style;
1976
1977 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
1978 // Disable transitions first, otherwise we'll get values from when the window was animating.
1979 this.withoutSizeTransitions( function () {
1980 var oldHeight = frameStyleObj.height,
1981 oldPosition = bodyStyleObj.position;
1982 frameStyleObj.height = '1px';
1983 // Force body to resize to new width
1984 bodyStyleObj.position = 'relative';
1985 bodyHeight = win.getBodyHeight();
1986 frameStyleObj.height = oldHeight;
1987 bodyStyleObj.position = oldPosition;
1988 } );
1989
1990 return (
1991 // Add buffer for border
1992 ( this.$frame.outerHeight() - this.$frame.innerHeight() ) +
1993 // Use combined heights of children
1994 ( this.$head.outerHeight( true ) + bodyHeight + this.$foot.outerHeight( true ) )
1995 );
1996 };
1997
1998 /**
1999 * Get the height of the window body.
2000 *
2001 * To get the height of the full window contents (the window body, head, and foot together),
2002 * use #getContentHeight.
2003 *
2004 * When this function is called, the window will temporarily have been resized
2005 * to height=1px, so .scrollHeight measurements can be taken accurately.
2006 *
2007 * @return {number} Height of the window body in pixels
2008 */
2009 OO.ui.Window.prototype.getBodyHeight = function () {
2010 return this.$body[ 0 ].scrollHeight;
2011 };
2012
2013 /**
2014 * Get the directionality of the frame (right-to-left or left-to-right).
2015 *
2016 * @return {string} Directionality: `'ltr'` or `'rtl'`
2017 */
2018 OO.ui.Window.prototype.getDir = function () {
2019 return this.dir;
2020 };
2021
2022 /**
2023 * Get the 'setup' process.
2024 *
2025 * The setup process is used to set up a window for use in a particular context,
2026 * based on the `data` argument. This method is called during the opening phase of the window’s
2027 * lifecycle.
2028 *
2029 * Override this method to add additional steps to the ‘setup’ process the parent method provides
2030 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2031 * of OO.ui.Process.
2032 *
2033 * To add window content that persists between openings, you may wish to use the #initialize method
2034 * instead.
2035 *
2036 * @abstract
2037 * @param {Object} [data] Window opening data
2038 * @return {OO.ui.Process} Setup process
2039 */
2040 OO.ui.Window.prototype.getSetupProcess = function () {
2041 return new OO.ui.Process();
2042 };
2043
2044 /**
2045 * Get the ‘ready’ process.
2046 *
2047 * The ready process is used to ready a window for use in a particular
2048 * context, based on the `data` argument. This method is called during the opening phase of
2049 * the window’s lifecycle, after the window has been {@link #getSetupProcess setup}.
2050 *
2051 * Override this method to add additional steps to the ‘ready’ process the parent method
2052 * provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next}
2053 * methods of OO.ui.Process.
2054 *
2055 * @abstract
2056 * @param {Object} [data] Window opening data
2057 * @return {OO.ui.Process} Ready process
2058 */
2059 OO.ui.Window.prototype.getReadyProcess = function () {
2060 return new OO.ui.Process();
2061 };
2062
2063 /**
2064 * Get the 'hold' process.
2065 *
2066 * The hold proccess is used to keep a window from being used in a particular context,
2067 * based on the `data` argument. This method is called during the closing phase of the window’s
2068 * lifecycle.
2069 *
2070 * Override this method to add additional steps to the 'hold' process the parent method provides
2071 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2072 * of OO.ui.Process.
2073 *
2074 * @abstract
2075 * @param {Object} [data] Window closing data
2076 * @return {OO.ui.Process} Hold process
2077 */
2078 OO.ui.Window.prototype.getHoldProcess = function () {
2079 return new OO.ui.Process();
2080 };
2081
2082 /**
2083 * Get the ‘teardown’ process.
2084 *
2085 * The teardown process is used to teardown a window after use. During teardown,
2086 * user interactions within the window are conveyed and the window is closed, based on the `data`
2087 * argument. This method is called during the closing phase of the window’s lifecycle.
2088 *
2089 * Override this method to add additional steps to the ‘teardown’ process the parent method provides
2090 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2091 * of OO.ui.Process.
2092 *
2093 * @abstract
2094 * @param {Object} [data] Window closing data
2095 * @return {OO.ui.Process} Teardown process
2096 */
2097 OO.ui.Window.prototype.getTeardownProcess = function () {
2098 return new OO.ui.Process();
2099 };
2100
2101 /**
2102 * Set the window manager.
2103 *
2104 * This will cause the window to initialize. Calling it more than once will cause an error.
2105 *
2106 * @param {OO.ui.WindowManager} manager Manager for this window
2107 * @throws {Error} An error is thrown if the method is called more than once
2108 * @chainable
2109 */
2110 OO.ui.Window.prototype.setManager = function ( manager ) {
2111 if ( this.manager ) {
2112 throw new Error( 'Cannot set window manager, window already has a manager' );
2113 }
2114
2115 this.manager = manager;
2116 this.initialize();
2117
2118 return this;
2119 };
2120
2121 /**
2122 * Set the window size by symbolic name (e.g., 'small' or 'medium')
2123 *
2124 * @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or
2125 * `full`
2126 * @chainable
2127 */
2128 OO.ui.Window.prototype.setSize = function ( size ) {
2129 this.size = size;
2130 this.updateSize();
2131 return this;
2132 };
2133
2134 /**
2135 * Update the window size.
2136 *
2137 * @throws {Error} An error is thrown if the window is not attached to a window manager
2138 * @chainable
2139 */
2140 OO.ui.Window.prototype.updateSize = function () {
2141 if ( !this.manager ) {
2142 throw new Error( 'Cannot update window size, must be attached to a manager' );
2143 }
2144
2145 this.manager.updateWindowSize( this );
2146
2147 return this;
2148 };
2149
2150 /**
2151 * Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager}
2152 * when the window is opening. In general, setDimensions should not be called directly.
2153 *
2154 * To set the size of the window, use the #setSize method.
2155 *
2156 * @param {Object} dim CSS dimension properties
2157 * @param {string|number} [dim.width] Width
2158 * @param {string|number} [dim.minWidth] Minimum width
2159 * @param {string|number} [dim.maxWidth] Maximum width
2160 * @param {string|number} [dim.width] Height, omit to set based on height of contents
2161 * @param {string|number} [dim.minWidth] Minimum height
2162 * @param {string|number} [dim.maxWidth] Maximum height
2163 * @chainable
2164 */
2165 OO.ui.Window.prototype.setDimensions = function ( dim ) {
2166 var height,
2167 win = this,
2168 styleObj = this.$frame[ 0 ].style;
2169
2170 // Calculate the height we need to set using the correct width
2171 if ( dim.height === undefined ) {
2172 this.withoutSizeTransitions( function () {
2173 var oldWidth = styleObj.width;
2174 win.$frame.css( 'width', dim.width || '' );
2175 height = win.getContentHeight();
2176 styleObj.width = oldWidth;
2177 } );
2178 } else {
2179 height = dim.height;
2180 }
2181
2182 this.$frame.css( {
2183 width: dim.width || '',
2184 minWidth: dim.minWidth || '',
2185 maxWidth: dim.maxWidth || '',
2186 height: height || '',
2187 minHeight: dim.minHeight || '',
2188 maxHeight: dim.maxHeight || ''
2189 } );
2190
2191 return this;
2192 };
2193
2194 /**
2195 * Initialize window contents.
2196 *
2197 * Before the window is opened for the first time, #initialize is called so that content that
2198 * persists between openings can be added to the window.
2199 *
2200 * To set up a window with new content each time the window opens, use #getSetupProcess.
2201 *
2202 * @throws {Error} An error is thrown if the window is not attached to a window manager
2203 * @chainable
2204 */
2205 OO.ui.Window.prototype.initialize = function () {
2206 if ( !this.manager ) {
2207 throw new Error( 'Cannot initialize window, must be attached to a manager' );
2208 }
2209
2210 // Properties
2211 this.$head = $( '<div>' );
2212 this.$body = $( '<div>' );
2213 this.$foot = $( '<div>' );
2214 this.dir = OO.ui.Element.static.getDir( this.$content ) || 'ltr';
2215 this.$document = $( this.getElementDocument() );
2216
2217 // Events
2218 this.$element.on( 'mousedown', this.onMouseDown.bind( this ) );
2219
2220 // Initialization
2221 this.$head.addClass( 'oo-ui-window-head' );
2222 this.$body.addClass( 'oo-ui-window-body' );
2223 this.$foot.addClass( 'oo-ui-window-foot' );
2224 this.$content.append( this.$head, this.$body, this.$foot );
2225
2226 return this;
2227 };
2228
2229 /**
2230 * Open the window.
2231 *
2232 * This method is a wrapper around a call to the window manager’s {@link OO.ui.WindowManager#openWindow openWindow}
2233 * method, which returns a promise resolved when the window is done opening.
2234 *
2235 * To customize the window each time it opens, use #getSetupProcess or #getReadyProcess.
2236 *
2237 * @param {Object} [data] Window opening data
2238 * @return {jQuery.Promise} Promise resolved with a value when the window is opened, or rejected
2239 * if the window fails to open. When the promise is resolved successfully, the first argument of the
2240 * value is a new promise, which is resolved when the window begins closing.
2241 * @throws {Error} An error is thrown if the window is not attached to a window manager
2242 */
2243 OO.ui.Window.prototype.open = function ( data ) {
2244 if ( !this.manager ) {
2245 throw new Error( 'Cannot open window, must be attached to a manager' );
2246 }
2247
2248 return this.manager.openWindow( this, data );
2249 };
2250
2251 /**
2252 * Close the window.
2253 *
2254 * This method is a wrapper around a call to the window
2255 * manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method,
2256 * which returns a closing promise resolved when the window is done closing.
2257 *
2258 * The window's #getHoldProcess and #getTeardownProcess methods are called during the closing
2259 * phase of the window’s lifecycle and can be used to specify closing behavior each time
2260 * the window closes.
2261 *
2262 * @param {Object} [data] Window closing data
2263 * @return {jQuery.Promise} Promise resolved when window is closed
2264 * @throws {Error} An error is thrown if the window is not attached to a window manager
2265 */
2266 OO.ui.Window.prototype.close = function ( data ) {
2267 if ( !this.manager ) {
2268 throw new Error( 'Cannot close window, must be attached to a manager' );
2269 }
2270
2271 return this.manager.closeWindow( this, data );
2272 };
2273
2274 /**
2275 * Setup window.
2276 *
2277 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2278 * by other systems.
2279 *
2280 * @param {Object} [data] Window opening data
2281 * @return {jQuery.Promise} Promise resolved when window is setup
2282 */
2283 OO.ui.Window.prototype.setup = function ( data ) {
2284 var win = this,
2285 deferred = $.Deferred();
2286
2287 this.toggle( true );
2288
2289 this.getSetupProcess( data ).execute().done( function () {
2290 // Force redraw by asking the browser to measure the elements' widths
2291 win.$element.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2292 win.$content.addClass( 'oo-ui-window-content-setup' ).width();
2293 deferred.resolve();
2294 } );
2295
2296 return deferred.promise();
2297 };
2298
2299 /**
2300 * Ready window.
2301 *
2302 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2303 * by other systems.
2304 *
2305 * @param {Object} [data] Window opening data
2306 * @return {jQuery.Promise} Promise resolved when window is ready
2307 */
2308 OO.ui.Window.prototype.ready = function ( data ) {
2309 var win = this,
2310 deferred = $.Deferred();
2311
2312 this.$content.focus();
2313 this.getReadyProcess( data ).execute().done( function () {
2314 // Force redraw by asking the browser to measure the elements' widths
2315 win.$element.addClass( 'oo-ui-window-ready' ).width();
2316 win.$content.addClass( 'oo-ui-window-content-ready' ).width();
2317 deferred.resolve();
2318 } );
2319
2320 return deferred.promise();
2321 };
2322
2323 /**
2324 * Hold window.
2325 *
2326 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2327 * by other systems.
2328 *
2329 * @param {Object} [data] Window closing data
2330 * @return {jQuery.Promise} Promise resolved when window is held
2331 */
2332 OO.ui.Window.prototype.hold = function ( data ) {
2333 var win = this,
2334 deferred = $.Deferred();
2335
2336 this.getHoldProcess( data ).execute().done( function () {
2337 // Get the focused element within the window's content
2338 var $focus = win.$content.find( OO.ui.Element.static.getDocument( win.$content ).activeElement );
2339
2340 // Blur the focused element
2341 if ( $focus.length ) {
2342 $focus[ 0 ].blur();
2343 }
2344
2345 // Force redraw by asking the browser to measure the elements' widths
2346 win.$element.removeClass( 'oo-ui-window-ready' ).width();
2347 win.$content.removeClass( 'oo-ui-window-content-ready' ).width();
2348 deferred.resolve();
2349 } );
2350
2351 return deferred.promise();
2352 };
2353
2354 /**
2355 * Teardown window.
2356 *
2357 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2358 * by other systems.
2359 *
2360 * @param {Object} [data] Window closing data
2361 * @return {jQuery.Promise} Promise resolved when window is torn down
2362 */
2363 OO.ui.Window.prototype.teardown = function ( data ) {
2364 var win = this;
2365
2366 return this.getTeardownProcess( data ).execute()
2367 .done( function () {
2368 // Force redraw by asking the browser to measure the elements' widths
2369 win.$element.removeClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2370 win.$content.removeClass( 'oo-ui-window-content-setup' ).width();
2371 win.toggle( false );
2372 } );
2373 };
2374
2375 /**
2376 * The Dialog class serves as the base class for the other types of dialogs.
2377 * Unless extended to include controls, the rendered dialog box is a simple window
2378 * that users can close by hitting the ‘Esc’ key. Dialog windows are used with OO.ui.WindowManager,
2379 * which opens, closes, and controls the presentation of the window. See the
2380 * [OOjs UI documentation on MediaWiki] [1] for more information.
2381 *
2382 * @example
2383 * // A simple dialog window.
2384 * function MyDialog( config ) {
2385 * MyDialog.super.call( this, config );
2386 * }
2387 * OO.inheritClass( MyDialog, OO.ui.Dialog );
2388 * MyDialog.prototype.initialize = function () {
2389 * MyDialog.super.prototype.initialize.call( this );
2390 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
2391 * this.content.$element.append( '<p>A simple dialog window. Press \'Esc\' to close.</p>' );
2392 * this.$body.append( this.content.$element );
2393 * };
2394 * MyDialog.prototype.getBodyHeight = function () {
2395 * return this.content.$element.outerHeight( true );
2396 * };
2397 * var myDialog = new MyDialog( {
2398 * size: 'medium'
2399 * } );
2400 * // Create and append a window manager, which opens and closes the window.
2401 * var windowManager = new OO.ui.WindowManager();
2402 * $( 'body' ).append( windowManager.$element );
2403 * windowManager.addWindows( [ myDialog ] );
2404 * // Open the window!
2405 * windowManager.openWindow( myDialog );
2406 *
2407 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Dialogs
2408 *
2409 * @abstract
2410 * @class
2411 * @extends OO.ui.Window
2412 * @mixins OO.ui.PendingElement
2413 *
2414 * @constructor
2415 * @param {Object} [config] Configuration options
2416 */
2417 OO.ui.Dialog = function OoUiDialog( config ) {
2418 // Parent constructor
2419 OO.ui.Dialog.super.call( this, config );
2420
2421 // Mixin constructors
2422 OO.ui.PendingElement.call( this );
2423
2424 // Properties
2425 this.actions = new OO.ui.ActionSet();
2426 this.attachedActions = [];
2427 this.currentAction = null;
2428 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
2429
2430 // Events
2431 this.actions.connect( this, {
2432 click: 'onActionClick',
2433 resize: 'onActionResize',
2434 change: 'onActionsChange'
2435 } );
2436
2437 // Initialization
2438 this.$element
2439 .addClass( 'oo-ui-dialog' )
2440 .attr( 'role', 'dialog' );
2441 };
2442
2443 /* Setup */
2444
2445 OO.inheritClass( OO.ui.Dialog, OO.ui.Window );
2446 OO.mixinClass( OO.ui.Dialog, OO.ui.PendingElement );
2447
2448 /* Static Properties */
2449
2450 /**
2451 * Symbolic name of dialog.
2452 *
2453 * The dialog class must have a symbolic name in order to be registered with OO.Factory.
2454 * Please see the [OOjs UI documentation on MediaWiki] [3] for more information.
2455 *
2456 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2457 *
2458 * @abstract
2459 * @static
2460 * @inheritable
2461 * @property {string}
2462 */
2463 OO.ui.Dialog.static.name = '';
2464
2465 /**
2466 * The dialog title.
2467 *
2468 * The title can be specified as a plaintext string, a {@link OO.ui.LabelElement Label} node, or a function
2469 * that will produce a Label node or string. The title can also be specified with data passed to the
2470 * constructor (see #getSetupProcess). In this case, the static value will be overriden.
2471 *
2472 * @abstract
2473 * @static
2474 * @inheritable
2475 * @property {jQuery|string|Function}
2476 */
2477 OO.ui.Dialog.static.title = '';
2478
2479 /**
2480 * An array of configured {@link OO.ui.ActionWidget action widgets}.
2481 *
2482 * Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this case, the static
2483 * value will be overriden.
2484 *
2485 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
2486 *
2487 * @static
2488 * @inheritable
2489 * @property {Object[]}
2490 */
2491 OO.ui.Dialog.static.actions = [];
2492
2493 /**
2494 * Close the dialog when the 'Esc' key is pressed.
2495 *
2496 * @static
2497 * @abstract
2498 * @inheritable
2499 * @property {boolean}
2500 */
2501 OO.ui.Dialog.static.escapable = true;
2502
2503 /* Methods */
2504
2505 /**
2506 * Handle frame document key down events.
2507 *
2508 * @private
2509 * @param {jQuery.Event} e Key down event
2510 */
2511 OO.ui.Dialog.prototype.onDocumentKeyDown = function ( e ) {
2512 if ( e.which === OO.ui.Keys.ESCAPE ) {
2513 this.close();
2514 e.preventDefault();
2515 e.stopPropagation();
2516 }
2517 };
2518
2519 /**
2520 * Handle action resized events.
2521 *
2522 * @private
2523 * @param {OO.ui.ActionWidget} action Action that was resized
2524 */
2525 OO.ui.Dialog.prototype.onActionResize = function () {
2526 // Override in subclass
2527 };
2528
2529 /**
2530 * Handle action click events.
2531 *
2532 * @private
2533 * @param {OO.ui.ActionWidget} action Action that was clicked
2534 */
2535 OO.ui.Dialog.prototype.onActionClick = function ( action ) {
2536 if ( !this.isPending() ) {
2537 this.executeAction( action.getAction() );
2538 }
2539 };
2540
2541 /**
2542 * Handle actions change event.
2543 *
2544 * @private
2545 */
2546 OO.ui.Dialog.prototype.onActionsChange = function () {
2547 this.detachActions();
2548 if ( !this.isClosing() ) {
2549 this.attachActions();
2550 }
2551 };
2552
2553 /**
2554 * Get the set of actions used by the dialog.
2555 *
2556 * @return {OO.ui.ActionSet}
2557 */
2558 OO.ui.Dialog.prototype.getActions = function () {
2559 return this.actions;
2560 };
2561
2562 /**
2563 * Get a process for taking action.
2564 *
2565 * When you override this method, you can create a new OO.ui.Process and return it, or add additional
2566 * accept steps to the process the parent method provides using the {@link OO.ui.Process#first 'first'}
2567 * and {@link OO.ui.Process#next 'next'} methods of OO.ui.Process.
2568 *
2569 * @abstract
2570 * @param {string} [action] Symbolic name of action
2571 * @return {OO.ui.Process} Action process
2572 */
2573 OO.ui.Dialog.prototype.getActionProcess = function ( action ) {
2574 return new OO.ui.Process()
2575 .next( function () {
2576 if ( !action ) {
2577 // An empty action always closes the dialog without data, which should always be
2578 // safe and make no changes
2579 this.close();
2580 }
2581 }, this );
2582 };
2583
2584 /**
2585 * @inheritdoc
2586 *
2587 * @param {Object} [data] Dialog opening data
2588 * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use
2589 * the {@link #static-title static title}
2590 * @param {Object[]} [data.actions] List of configuration options for each
2591 * {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}.
2592 */
2593 OO.ui.Dialog.prototype.getSetupProcess = function ( data ) {
2594 data = data || {};
2595
2596 // Parent method
2597 return OO.ui.Dialog.super.prototype.getSetupProcess.call( this, data )
2598 .next( function () {
2599 var config = this.constructor.static,
2600 actions = data.actions !== undefined ? data.actions : config.actions;
2601
2602 this.title.setLabel(
2603 data.title !== undefined ? data.title : this.constructor.static.title
2604 );
2605 this.actions.add( this.getActionWidgets( actions ) );
2606
2607 if ( this.constructor.static.escapable ) {
2608 this.$document.on( 'keydown', this.onDocumentKeyDownHandler );
2609 }
2610 }, this );
2611 };
2612
2613 /**
2614 * @inheritdoc
2615 */
2616 OO.ui.Dialog.prototype.getTeardownProcess = function ( data ) {
2617 // Parent method
2618 return OO.ui.Dialog.super.prototype.getTeardownProcess.call( this, data )
2619 .first( function () {
2620 if ( this.constructor.static.escapable ) {
2621 this.$document.off( 'keydown', this.onDocumentKeyDownHandler );
2622 }
2623
2624 this.actions.clear();
2625 this.currentAction = null;
2626 }, this );
2627 };
2628
2629 /**
2630 * @inheritdoc
2631 */
2632 OO.ui.Dialog.prototype.initialize = function () {
2633 // Parent method
2634 OO.ui.Dialog.super.prototype.initialize.call( this );
2635
2636 // Properties
2637 this.title = new OO.ui.LabelWidget();
2638
2639 // Initialization
2640 this.$content.addClass( 'oo-ui-dialog-content' );
2641 this.setPendingElement( this.$head );
2642 };
2643
2644 /**
2645 * Get action widgets from a list of configs
2646 *
2647 * @param {Object[]} actions Action widget configs
2648 * @return {OO.ui.ActionWidget[]} Action widgets
2649 */
2650 OO.ui.Dialog.prototype.getActionWidgets = function ( actions ) {
2651 var i, len, widgets = [];
2652 for ( i = 0, len = actions.length; i < len; i++ ) {
2653 widgets.push(
2654 new OO.ui.ActionWidget( actions[ i ] )
2655 );
2656 }
2657 return widgets;
2658 };
2659
2660 /**
2661 * Attach action actions.
2662 *
2663 * @protected
2664 */
2665 OO.ui.Dialog.prototype.attachActions = function () {
2666 // Remember the list of potentially attached actions
2667 this.attachedActions = this.actions.get();
2668 };
2669
2670 /**
2671 * Detach action actions.
2672 *
2673 * @protected
2674 * @chainable
2675 */
2676 OO.ui.Dialog.prototype.detachActions = function () {
2677 var i, len;
2678
2679 // Detach all actions that may have been previously attached
2680 for ( i = 0, len = this.attachedActions.length; i < len; i++ ) {
2681 this.attachedActions[ i ].$element.detach();
2682 }
2683 this.attachedActions = [];
2684 };
2685
2686 /**
2687 * Execute an action.
2688 *
2689 * @param {string} action Symbolic name of action to execute
2690 * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
2691 */
2692 OO.ui.Dialog.prototype.executeAction = function ( action ) {
2693 this.pushPending();
2694 this.currentAction = action;
2695 return this.getActionProcess( action ).execute()
2696 .always( this.popPending.bind( this ) );
2697 };
2698
2699 /**
2700 * Window managers are used to open and close {@link OO.ui.Window windows} and control their presentation.
2701 * Managed windows are mutually exclusive. If a new window is opened while a current window is opening
2702 * or is opened, the current window will be closed and any ongoing {@link OO.ui.Process process} will be cancelled. Windows
2703 * themselves are persistent and—rather than being torn down when closed—can be repopulated with the
2704 * pertinent data and reused.
2705 *
2706 * Over the lifecycle of a window, the window manager makes available three promises: `opening`,
2707 * `opened`, and `closing`, which represent the primary stages of the cycle:
2708 *
2709 * **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s
2710 * {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window.
2711 *
2712 * - an `opening` event is emitted with an `opening` promise
2713 * - the #getSetupDelay method is called and the returned value is used to time a pause in execution before
2714 * the window’s {@link OO.ui.Window#getSetupProcess getSetupProcess} method is called on the
2715 * window and its result executed
2716 * - a `setup` progress notification is emitted from the `opening` promise
2717 * - the #getReadyDelay method is called the returned value is used to time a pause in execution before
2718 * the window’s {@link OO.ui.Window#getReadyProcess getReadyProcess} method is called on the
2719 * window and its result executed
2720 * - a `ready` progress notification is emitted from the `opening` promise
2721 * - the `opening` promise is resolved with an `opened` promise
2722 *
2723 * **Opened**: the window is now open.
2724 *
2725 * **Closing**: the closing stage begins when the window manager's #closeWindow or the
2726 * window's {@link OO.ui.Window#close close} methods is used, and the window manager begins
2727 * to close the window.
2728 *
2729 * - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted
2730 * - the #getHoldDelay method is called and the returned value is used to time a pause in execution before
2731 * the window's {@link OO.ui.Window#getHoldProcess getHoldProces} method is called on the
2732 * window and its result executed
2733 * - a `hold` progress notification is emitted from the `closing` promise
2734 * - the #getTeardownDelay() method is called and the returned value is used to time a pause in execution before
2735 * the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method is called on the
2736 * window and its result executed
2737 * - a `teardown` progress notification is emitted from the `closing` promise
2738 * - the `closing` promise is resolved. The window is now closed
2739 *
2740 * See the [OOjs UI documentation on MediaWiki][1] for more information.
2741 *
2742 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2743 *
2744 * @class
2745 * @extends OO.ui.Element
2746 * @mixins OO.EventEmitter
2747 *
2748 * @constructor
2749 * @param {Object} [config] Configuration options
2750 * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
2751 * Note that window classes that are instantiated with a factory must have
2752 * a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name.
2753 * @cfg {boolean} [modal=true] Prevent interaction outside the dialog
2754 */
2755 OO.ui.WindowManager = function OoUiWindowManager( config ) {
2756 // Configuration initialization
2757 config = config || {};
2758
2759 // Parent constructor
2760 OO.ui.WindowManager.super.call( this, config );
2761
2762 // Mixin constructors
2763 OO.EventEmitter.call( this );
2764
2765 // Properties
2766 this.factory = config.factory;
2767 this.modal = config.modal === undefined || !!config.modal;
2768 this.windows = {};
2769 this.opening = null;
2770 this.opened = null;
2771 this.closing = null;
2772 this.preparingToOpen = null;
2773 this.preparingToClose = null;
2774 this.currentWindow = null;
2775 this.globalEvents = false;
2776 this.$ariaHidden = null;
2777 this.onWindowResizeTimeout = null;
2778 this.onWindowResizeHandler = this.onWindowResize.bind( this );
2779 this.afterWindowResizeHandler = this.afterWindowResize.bind( this );
2780
2781 // Initialization
2782 this.$element
2783 .addClass( 'oo-ui-windowManager' )
2784 .toggleClass( 'oo-ui-windowManager-modal', this.modal );
2785 };
2786
2787 /* Setup */
2788
2789 OO.inheritClass( OO.ui.WindowManager, OO.ui.Element );
2790 OO.mixinClass( OO.ui.WindowManager, OO.EventEmitter );
2791
2792 /* Events */
2793
2794 /**
2795 * An 'opening' event is emitted when the window begins to be opened.
2796 *
2797 * @event opening
2798 * @param {OO.ui.Window} win Window that's being opened
2799 * @param {jQuery.Promise} opening An `opening` promise resolved with a value when the window is opened successfully.
2800 * When the `opening` promise is resolved, the first argument of the value is an 'opened' promise, the second argument
2801 * is the opening data. The `opening` promise emits `setup` and `ready` notifications when those processes are complete.
2802 * @param {Object} data Window opening data
2803 */
2804
2805 /**
2806 * A 'closing' event is emitted when the window begins to be closed.
2807 *
2808 * @event closing
2809 * @param {OO.ui.Window} win Window that's being closed
2810 * @param {jQuery.Promise} closing A `closing` promise is resolved with a value when the window
2811 * is closed successfully. The promise emits `hold` and `teardown` notifications when those
2812 * processes are complete. When the `closing` promise is resolved, the first argument of its value
2813 * is the closing data.
2814 * @param {Object} data Window closing data
2815 */
2816
2817 /**
2818 * A 'resize' event is emitted when a window is resized.
2819 *
2820 * @event resize
2821 * @param {OO.ui.Window} win Window that was resized
2822 */
2823
2824 /* Static Properties */
2825
2826 /**
2827 * Map of the symbolic name of each window size and its CSS properties.
2828 *
2829 * @static
2830 * @inheritable
2831 * @property {Object}
2832 */
2833 OO.ui.WindowManager.static.sizes = {
2834 small: {
2835 width: 300
2836 },
2837 medium: {
2838 width: 500
2839 },
2840 large: {
2841 width: 700
2842 },
2843 larger: {
2844 width: 900
2845 },
2846 full: {
2847 // These can be non-numeric because they are never used in calculations
2848 width: '100%',
2849 height: '100%'
2850 }
2851 };
2852
2853 /**
2854 * Symbolic name of the default window size.
2855 *
2856 * The default size is used if the window's requested size is not recognized.
2857 *
2858 * @static
2859 * @inheritable
2860 * @property {string}
2861 */
2862 OO.ui.WindowManager.static.defaultSize = 'medium';
2863
2864 /* Methods */
2865
2866 /**
2867 * Handle window resize events.
2868 *
2869 * @private
2870 * @param {jQuery.Event} e Window resize event
2871 */
2872 OO.ui.WindowManager.prototype.onWindowResize = function () {
2873 clearTimeout( this.onWindowResizeTimeout );
2874 this.onWindowResizeTimeout = setTimeout( this.afterWindowResizeHandler, 200 );
2875 };
2876
2877 /**
2878 * Handle window resize events.
2879 *
2880 * @private
2881 * @param {jQuery.Event} e Window resize event
2882 */
2883 OO.ui.WindowManager.prototype.afterWindowResize = function () {
2884 if ( this.currentWindow ) {
2885 this.updateWindowSize( this.currentWindow );
2886 }
2887 };
2888
2889 /**
2890 * Check if window is opening.
2891 *
2892 * @return {boolean} Window is opening
2893 */
2894 OO.ui.WindowManager.prototype.isOpening = function ( win ) {
2895 return win === this.currentWindow && !!this.opening && this.opening.state() === 'pending';
2896 };
2897
2898 /**
2899 * Check if window is closing.
2900 *
2901 * @return {boolean} Window is closing
2902 */
2903 OO.ui.WindowManager.prototype.isClosing = function ( win ) {
2904 return win === this.currentWindow && !!this.closing && this.closing.state() === 'pending';
2905 };
2906
2907 /**
2908 * Check if window is opened.
2909 *
2910 * @return {boolean} Window is opened
2911 */
2912 OO.ui.WindowManager.prototype.isOpened = function ( win ) {
2913 return win === this.currentWindow && !!this.opened && this.opened.state() === 'pending';
2914 };
2915
2916 /**
2917 * Check if a window is being managed.
2918 *
2919 * @param {OO.ui.Window} win Window to check
2920 * @return {boolean} Window is being managed
2921 */
2922 OO.ui.WindowManager.prototype.hasWindow = function ( win ) {
2923 var name;
2924
2925 for ( name in this.windows ) {
2926 if ( this.windows[ name ] === win ) {
2927 return true;
2928 }
2929 }
2930
2931 return false;
2932 };
2933
2934 /**
2935 * Get the number of milliseconds to wait after opening begins before executing the ‘setup’ process.
2936 *
2937 * @param {OO.ui.Window} win Window being opened
2938 * @param {Object} [data] Window opening data
2939 * @return {number} Milliseconds to wait
2940 */
2941 OO.ui.WindowManager.prototype.getSetupDelay = function () {
2942 return 0;
2943 };
2944
2945 /**
2946 * Get the number of milliseconds to wait after setup has finished before executing the ‘ready’ process.
2947 *
2948 * @param {OO.ui.Window} win Window being opened
2949 * @param {Object} [data] Window opening data
2950 * @return {number} Milliseconds to wait
2951 */
2952 OO.ui.WindowManager.prototype.getReadyDelay = function () {
2953 return 0;
2954 };
2955
2956 /**
2957 * Get the number of milliseconds to wait after closing has begun before executing the 'hold' process.
2958 *
2959 * @param {OO.ui.Window} win Window being closed
2960 * @param {Object} [data] Window closing data
2961 * @return {number} Milliseconds to wait
2962 */
2963 OO.ui.WindowManager.prototype.getHoldDelay = function () {
2964 return 0;
2965 };
2966
2967 /**
2968 * Get the number of milliseconds to wait after the ‘hold’ process has finished before
2969 * executing the ‘teardown’ process.
2970 *
2971 * @param {OO.ui.Window} win Window being closed
2972 * @param {Object} [data] Window closing data
2973 * @return {number} Milliseconds to wait
2974 */
2975 OO.ui.WindowManager.prototype.getTeardownDelay = function () {
2976 return this.modal ? 250 : 0;
2977 };
2978
2979 /**
2980 * Get a window by its symbolic name.
2981 *
2982 * If the window is not yet instantiated and its symbolic name is recognized by a factory, it will be
2983 * instantiated and added to the window manager automatically. Please see the [OOjs UI documentation on MediaWiki][3]
2984 * for more information about using factories.
2985 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2986 *
2987 * @param {string} name Symbolic name of the window
2988 * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
2989 * @throws {Error} An error is thrown if the symbolic name is not recognized by the factory.
2990 * @throws {Error} An error is thrown if the named window is not recognized as a managed window.
2991 */
2992 OO.ui.WindowManager.prototype.getWindow = function ( name ) {
2993 var deferred = $.Deferred(),
2994 win = this.windows[ name ];
2995
2996 if ( !( win instanceof OO.ui.Window ) ) {
2997 if ( this.factory ) {
2998 if ( !this.factory.lookup( name ) ) {
2999 deferred.reject( new OO.ui.Error(
3000 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
3001 ) );
3002 } else {
3003 win = this.factory.create( name );
3004 this.addWindows( [ win ] );
3005 deferred.resolve( win );
3006 }
3007 } else {
3008 deferred.reject( new OO.ui.Error(
3009 'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
3010 ) );
3011 }
3012 } else {
3013 deferred.resolve( win );
3014 }
3015
3016 return deferred.promise();
3017 };
3018
3019 /**
3020 * Get current window.
3021 *
3022 * @return {OO.ui.Window|null} Currently opening/opened/closing window
3023 */
3024 OO.ui.WindowManager.prototype.getCurrentWindow = function () {
3025 return this.currentWindow;
3026 };
3027
3028 /**
3029 * Open a window.
3030 *
3031 * @param {OO.ui.Window|string} win Window object or symbolic name of window to open
3032 * @param {Object} [data] Window opening data
3033 * @return {jQuery.Promise} An `opening` promise resolved when the window is done opening.
3034 * See {@link #event-opening 'opening' event} for more information about `opening` promises.
3035 * @fires opening
3036 */
3037 OO.ui.WindowManager.prototype.openWindow = function ( win, data ) {
3038 var manager = this,
3039 opening = $.Deferred();
3040
3041 // Argument handling
3042 if ( typeof win === 'string' ) {
3043 return this.getWindow( win ).then( function ( win ) {
3044 return manager.openWindow( win, data );
3045 } );
3046 }
3047
3048 // Error handling
3049 if ( !this.hasWindow( win ) ) {
3050 opening.reject( new OO.ui.Error(
3051 'Cannot open window: window is not attached to manager'
3052 ) );
3053 } else if ( this.preparingToOpen || this.opening || this.opened ) {
3054 opening.reject( new OO.ui.Error(
3055 'Cannot open window: another window is opening or open'
3056 ) );
3057 }
3058
3059 // Window opening
3060 if ( opening.state() !== 'rejected' ) {
3061 // If a window is currently closing, wait for it to complete
3062 this.preparingToOpen = $.when( this.closing );
3063 // Ensure handlers get called after preparingToOpen is set
3064 this.preparingToOpen.done( function () {
3065 if ( manager.modal ) {
3066 manager.toggleGlobalEvents( true );
3067 manager.toggleAriaIsolation( true );
3068 }
3069 manager.currentWindow = win;
3070 manager.opening = opening;
3071 manager.preparingToOpen = null;
3072 manager.emit( 'opening', win, opening, data );
3073 setTimeout( function () {
3074 win.setup( data ).then( function () {
3075 manager.updateWindowSize( win );
3076 manager.opening.notify( { state: 'setup' } );
3077 setTimeout( function () {
3078 win.ready( data ).then( function () {
3079 manager.opening.notify( { state: 'ready' } );
3080 manager.opening = null;
3081 manager.opened = $.Deferred();
3082 opening.resolve( manager.opened.promise(), data );
3083 } );
3084 }, manager.getReadyDelay() );
3085 } );
3086 }, manager.getSetupDelay() );
3087 } );
3088 }
3089
3090 return opening.promise();
3091 };
3092
3093 /**
3094 * Close a window.
3095 *
3096 * @param {OO.ui.Window|string} win Window object or symbolic name of window to close
3097 * @param {Object} [data] Window closing data
3098 * @return {jQuery.Promise} A `closing` promise resolved when the window is done closing.
3099 * See {@link #event-closing 'closing' event} for more information about closing promises.
3100 * @throws {Error} An error is thrown if the window is not managed by the window manager.
3101 * @fires closing
3102 */
3103 OO.ui.WindowManager.prototype.closeWindow = function ( win, data ) {
3104 var manager = this,
3105 closing = $.Deferred(),
3106 opened;
3107
3108 // Argument handling
3109 if ( typeof win === 'string' ) {
3110 win = this.windows[ win ];
3111 } else if ( !this.hasWindow( win ) ) {
3112 win = null;
3113 }
3114
3115 // Error handling
3116 if ( !win ) {
3117 closing.reject( new OO.ui.Error(
3118 'Cannot close window: window is not attached to manager'
3119 ) );
3120 } else if ( win !== this.currentWindow ) {
3121 closing.reject( new OO.ui.Error(
3122 'Cannot close window: window already closed with different data'
3123 ) );
3124 } else if ( this.preparingToClose || this.closing ) {
3125 closing.reject( new OO.ui.Error(
3126 'Cannot close window: window already closing with different data'
3127 ) );
3128 }
3129
3130 // Window closing
3131 if ( closing.state() !== 'rejected' ) {
3132 // If the window is currently opening, close it when it's done
3133 this.preparingToClose = $.when( this.opening );
3134 // Ensure handlers get called after preparingToClose is set
3135 this.preparingToClose.done( function () {
3136 manager.closing = closing;
3137 manager.preparingToClose = null;
3138 manager.emit( 'closing', win, closing, data );
3139 opened = manager.opened;
3140 manager.opened = null;
3141 opened.resolve( closing.promise(), data );
3142 setTimeout( function () {
3143 win.hold( data ).then( function () {
3144 closing.notify( { state: 'hold' } );
3145 setTimeout( function () {
3146 win.teardown( data ).then( function () {
3147 closing.notify( { state: 'teardown' } );
3148 if ( manager.modal ) {
3149 manager.toggleGlobalEvents( false );
3150 manager.toggleAriaIsolation( false );
3151 }
3152 manager.closing = null;
3153 manager.currentWindow = null;
3154 closing.resolve( data );
3155 } );
3156 }, manager.getTeardownDelay() );
3157 } );
3158 }, manager.getHoldDelay() );
3159 } );
3160 }
3161
3162 return closing.promise();
3163 };
3164
3165 /**
3166 * Add windows to the window manager.
3167 *
3168 * Windows can be added by reference, symbolic name, or explicitly defined symbolic names.
3169 * See the [OOjs ui documentation on MediaWiki] [2] for examples.
3170 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3171 *
3172 * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified
3173 * by reference, symbolic name, or explicitly defined symbolic names.
3174 * @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an
3175 * explicit nor a statically configured symbolic name.
3176 */
3177 OO.ui.WindowManager.prototype.addWindows = function ( windows ) {
3178 var i, len, win, name, list;
3179
3180 if ( Array.isArray( windows ) ) {
3181 // Convert to map of windows by looking up symbolic names from static configuration
3182 list = {};
3183 for ( i = 0, len = windows.length; i < len; i++ ) {
3184 name = windows[ i ].constructor.static.name;
3185 if ( typeof name !== 'string' ) {
3186 throw new Error( 'Cannot add window' );
3187 }
3188 list[ name ] = windows[ i ];
3189 }
3190 } else if ( OO.isPlainObject( windows ) ) {
3191 list = windows;
3192 }
3193
3194 // Add windows
3195 for ( name in list ) {
3196 win = list[ name ];
3197 this.windows[ name ] = win.toggle( false );
3198 this.$element.append( win.$element );
3199 win.setManager( this );
3200 }
3201 };
3202
3203 /**
3204 * Remove the specified windows from the windows manager.
3205 *
3206 * Windows will be closed before they are removed. If you wish to remove all windows, you may wish to use
3207 * the #clearWindows method instead. If you no longer need the window manager and want to ensure that it no
3208 * longer listens to events, use the #destroy method.
3209 *
3210 * @param {string[]} names Symbolic names of windows to remove
3211 * @return {jQuery.Promise} Promise resolved when window is closed and removed
3212 * @throws {Error} An error is thrown if the named windows are not managed by the window manager.
3213 */
3214 OO.ui.WindowManager.prototype.removeWindows = function ( names ) {
3215 var i, len, win, name, cleanupWindow,
3216 manager = this,
3217 promises = [],
3218 cleanup = function ( name, win ) {
3219 delete manager.windows[ name ];
3220 win.$element.detach();
3221 };
3222
3223 for ( i = 0, len = names.length; i < len; i++ ) {
3224 name = names[ i ];
3225 win = this.windows[ name ];
3226 if ( !win ) {
3227 throw new Error( 'Cannot remove window' );
3228 }
3229 cleanupWindow = cleanup.bind( null, name, win );
3230 promises.push( this.closeWindow( name ).then( cleanupWindow, cleanupWindow ) );
3231 }
3232
3233 return $.when.apply( $, promises );
3234 };
3235
3236 /**
3237 * Remove all windows from the window manager.
3238 *
3239 * Windows will be closed before they are removed. Note that the window manager, though not in use, will still
3240 * listen to events. If the window manager will not be used again, you may wish to use the #destroy method instead.
3241 * To remove just a subset of windows, use the #removeWindows method.
3242 *
3243 * @return {jQuery.Promise} Promise resolved when all windows are closed and removed
3244 */
3245 OO.ui.WindowManager.prototype.clearWindows = function () {
3246 return this.removeWindows( Object.keys( this.windows ) );
3247 };
3248
3249 /**
3250 * Set dialog size. In general, this method should not be called directly.
3251 *
3252 * Fullscreen mode will be used if the dialog is too wide to fit in the screen.
3253 *
3254 * @chainable
3255 */
3256 OO.ui.WindowManager.prototype.updateWindowSize = function ( win ) {
3257 // Bypass for non-current, and thus invisible, windows
3258 if ( win !== this.currentWindow ) {
3259 return;
3260 }
3261
3262 var viewport = OO.ui.Element.static.getDimensions( win.getElementWindow() ),
3263 sizes = this.constructor.static.sizes,
3264 size = win.getSize();
3265
3266 if ( !sizes[ size ] ) {
3267 size = this.constructor.static.defaultSize;
3268 }
3269 if ( size !== 'full' && viewport.rect.right - viewport.rect.left < sizes[ size ].width ) {
3270 size = 'full';
3271 }
3272
3273 this.$element.toggleClass( 'oo-ui-windowManager-fullscreen', size === 'full' );
3274 this.$element.toggleClass( 'oo-ui-windowManager-floating', size !== 'full' );
3275 win.setDimensions( sizes[ size ] );
3276
3277 this.emit( 'resize', win );
3278
3279 return this;
3280 };
3281
3282 /**
3283 * Bind or unbind global events for scrolling.
3284 *
3285 * @private
3286 * @param {boolean} [on] Bind global events
3287 * @chainable
3288 */
3289 OO.ui.WindowManager.prototype.toggleGlobalEvents = function ( on ) {
3290 on = on === undefined ? !!this.globalEvents : !!on;
3291
3292 var scrollWidth, bodyMargin,
3293 $body = $( this.getElementDocument().body ),
3294 // We could have multiple window managers open so only modify
3295 // the body css at the bottom of the stack
3296 stackDepth = $body.data( 'windowManagerGlobalEvents' ) || 0 ;
3297
3298 if ( on ) {
3299 if ( !this.globalEvents ) {
3300 $( this.getElementWindow() ).on( {
3301 // Start listening for top-level window dimension changes
3302 'orientationchange resize': this.onWindowResizeHandler
3303 } );
3304 if ( stackDepth === 0 ) {
3305 scrollWidth = window.innerWidth - document.documentElement.clientWidth;
3306 bodyMargin = parseFloat( $body.css( 'margin-right' ) ) || 0;
3307 $body.css( {
3308 overflow: 'hidden',
3309 'margin-right': bodyMargin + scrollWidth
3310 } );
3311 }
3312 stackDepth++;
3313 this.globalEvents = true;
3314 }
3315 } else if ( this.globalEvents ) {
3316 $( this.getElementWindow() ).off( {
3317 // Stop listening for top-level window dimension changes
3318 'orientationchange resize': this.onWindowResizeHandler
3319 } );
3320 stackDepth--;
3321 if ( stackDepth === 0 ) {
3322 $body.css( {
3323 overflow: '',
3324 'margin-right': ''
3325 } );
3326 }
3327 this.globalEvents = false;
3328 }
3329 $body.data( 'windowManagerGlobalEvents', stackDepth );
3330
3331 return this;
3332 };
3333
3334 /**
3335 * Toggle screen reader visibility of content other than the window manager.
3336 *
3337 * @private
3338 * @param {boolean} [isolate] Make only the window manager visible to screen readers
3339 * @chainable
3340 */
3341 OO.ui.WindowManager.prototype.toggleAriaIsolation = function ( isolate ) {
3342 isolate = isolate === undefined ? !this.$ariaHidden : !!isolate;
3343
3344 if ( isolate ) {
3345 if ( !this.$ariaHidden ) {
3346 // Hide everything other than the window manager from screen readers
3347 this.$ariaHidden = $( 'body' )
3348 .children()
3349 .not( this.$element.parentsUntil( 'body' ).last() )
3350 .attr( 'aria-hidden', '' );
3351 }
3352 } else if ( this.$ariaHidden ) {
3353 // Restore screen reader visibility
3354 this.$ariaHidden.removeAttr( 'aria-hidden' );
3355 this.$ariaHidden = null;
3356 }
3357
3358 return this;
3359 };
3360
3361 /**
3362 * Destroy the window manager.
3363 *
3364 * Destroying the window manager ensures that it will no longer listen to events. If you would like to
3365 * continue using the window manager, but wish to remove all windows from it, use the #clearWindows method
3366 * instead.
3367 */
3368 OO.ui.WindowManager.prototype.destroy = function () {
3369 this.toggleGlobalEvents( false );
3370 this.toggleAriaIsolation( false );
3371 this.clearWindows();
3372 this.$element.remove();
3373 };
3374
3375 /**
3376 * Errors contain a required message (either a string or jQuery selection) that is used to describe what went wrong
3377 * in a {@link OO.ui.Process process}. The error's #recoverable and #warning configurations are used to customize the
3378 * appearance and functionality of the error interface.
3379 *
3380 * The basic error interface contains a formatted error message as well as two buttons: 'Dismiss' and 'Try again' (i.e., the error
3381 * is 'recoverable' by default). If the error is not recoverable, the 'Try again' button will not be rendered and the widget
3382 * that initiated the failed process will be disabled.
3383 *
3384 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button, which will try the
3385 * process again.
3386 *
3387 * For an example of error interfaces, please see the [OOjs UI documentation on MediaWiki][1].
3388 *
3389 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Processes_and_errors
3390 *
3391 * @class
3392 *
3393 * @constructor
3394 * @param {string|jQuery} message Description of error
3395 * @param {Object} [config] Configuration options
3396 * @cfg {boolean} [recoverable=true] Error is recoverable.
3397 * By default, errors are recoverable, and users can try the process again.
3398 * @cfg {boolean} [warning=false] Error is a warning.
3399 * If the error is a warning, the error interface will include a
3400 * 'Dismiss' and a 'Continue' button. It is the responsibility of the developer to ensure that the warning
3401 * is not triggered a second time if the user chooses to continue.
3402 */
3403 OO.ui.Error = function OoUiError( message, config ) {
3404 // Allow passing positional parameters inside the config object
3405 if ( OO.isPlainObject( message ) && config === undefined ) {
3406 config = message;
3407 message = config.message;
3408 }
3409
3410 // Configuration initialization
3411 config = config || {};
3412
3413 // Properties
3414 this.message = message instanceof jQuery ? message : String( message );
3415 this.recoverable = config.recoverable === undefined || !!config.recoverable;
3416 this.warning = !!config.warning;
3417 };
3418
3419 /* Setup */
3420
3421 OO.initClass( OO.ui.Error );
3422
3423 /* Methods */
3424
3425 /**
3426 * Check if the error is recoverable.
3427 *
3428 * If the error is recoverable, users are able to try the process again.
3429 *
3430 * @return {boolean} Error is recoverable
3431 */
3432 OO.ui.Error.prototype.isRecoverable = function () {
3433 return this.recoverable;
3434 };
3435
3436 /**
3437 * Check if the error is a warning.
3438 *
3439 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button.
3440 *
3441 * @return {boolean} Error is warning
3442 */
3443 OO.ui.Error.prototype.isWarning = function () {
3444 return this.warning;
3445 };
3446
3447 /**
3448 * Get error message as DOM nodes.
3449 *
3450 * @return {jQuery} Error message in DOM nodes
3451 */
3452 OO.ui.Error.prototype.getMessage = function () {
3453 return this.message instanceof jQuery ?
3454 this.message.clone() :
3455 $( '<div>' ).text( this.message ).contents();
3456 };
3457
3458 /**
3459 * Get the error message text.
3460 *
3461 * @return {string} Error message
3462 */
3463 OO.ui.Error.prototype.getMessageText = function () {
3464 return this.message instanceof jQuery ? this.message.text() : this.message;
3465 };
3466
3467 /**
3468 * Wraps an HTML snippet for use with configuration values which default
3469 * to strings. This bypasses the default html-escaping done to string
3470 * values.
3471 *
3472 * @class
3473 *
3474 * @constructor
3475 * @param {string} [content] HTML content
3476 */
3477 OO.ui.HtmlSnippet = function OoUiHtmlSnippet( content ) {
3478 // Properties
3479 this.content = content;
3480 };
3481
3482 /* Setup */
3483
3484 OO.initClass( OO.ui.HtmlSnippet );
3485
3486 /* Methods */
3487
3488 /**
3489 * Render into HTML.
3490 *
3491 * @return {string} Unchanged HTML snippet.
3492 */
3493 OO.ui.HtmlSnippet.prototype.toString = function () {
3494 return this.content;
3495 };
3496
3497 /**
3498 * A Process is a list of steps that are called in sequence. The step can be a number, a jQuery promise,
3499 * or a function:
3500 *
3501 * - **number**: the process will wait for the specified number of milliseconds before proceeding.
3502 * - **promise**: the process will continue to the next step when the promise is successfully resolved
3503 * or stop if the promise is rejected.
3504 * - **function**: the process will execute the function. The process will stop if the function returns
3505 * either a boolean `false` or a promise that is rejected; if the function returns a number, the process
3506 * will wait for that number of milliseconds before proceeding.
3507 *
3508 * If the process fails, an {@link OO.ui.Error error} is generated. Depending on how the error is
3509 * configured, users can dismiss the error and try the process again, or not. If a process is stopped,
3510 * its remaining steps will not be performed.
3511 *
3512 * @class
3513 *
3514 * @constructor
3515 * @param {number|jQuery.Promise|Function} step Number of miliseconds to wait before proceeding, promise
3516 * that must be resolved before proceeding, or a function to execute. See #createStep for more information. see #createStep for more information
3517 * @param {Object} [context=null] Execution context of the function. The context is ignored if the step is
3518 * a number or promise.
3519 * @return {Object} Step object, with `callback` and `context` properties
3520 */
3521 OO.ui.Process = function ( step, context ) {
3522 // Properties
3523 this.steps = [];
3524
3525 // Initialization
3526 if ( step !== undefined ) {
3527 this.next( step, context );
3528 }
3529 };
3530
3531 /* Setup */
3532
3533 OO.initClass( OO.ui.Process );
3534
3535 /* Methods */
3536
3537 /**
3538 * Start the process.
3539 *
3540 * @return {jQuery.Promise} Promise that is resolved when all steps have successfully completed.
3541 * If any of the steps return a promise that is rejected or a boolean false, this promise is rejected
3542 * and any remaining steps are not performed.
3543 */
3544 OO.ui.Process.prototype.execute = function () {
3545 var i, len, promise;
3546
3547 /**
3548 * Continue execution.
3549 *
3550 * @ignore
3551 * @param {Array} step A function and the context it should be called in
3552 * @return {Function} Function that continues the process
3553 */
3554 function proceed( step ) {
3555 return function () {
3556 // Execute step in the correct context
3557 var deferred,
3558 result = step.callback.call( step.context );
3559
3560 if ( result === false ) {
3561 // Use rejected promise for boolean false results
3562 return $.Deferred().reject( [] ).promise();
3563 }
3564 if ( typeof result === 'number' ) {
3565 if ( result < 0 ) {
3566 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
3567 }
3568 // Use a delayed promise for numbers, expecting them to be in milliseconds
3569 deferred = $.Deferred();
3570 setTimeout( deferred.resolve, result );
3571 return deferred.promise();
3572 }
3573 if ( result instanceof OO.ui.Error ) {
3574 // Use rejected promise for error
3575 return $.Deferred().reject( [ result ] ).promise();
3576 }
3577 if ( Array.isArray( result ) && result.length && result[ 0 ] instanceof OO.ui.Error ) {
3578 // Use rejected promise for list of errors
3579 return $.Deferred().reject( result ).promise();
3580 }
3581 // Duck-type the object to see if it can produce a promise
3582 if ( result && $.isFunction( result.promise ) ) {
3583 // Use a promise generated from the result
3584 return result.promise();
3585 }
3586 // Use resolved promise for other results
3587 return $.Deferred().resolve().promise();
3588 };
3589 }
3590
3591 if ( this.steps.length ) {
3592 // Generate a chain reaction of promises
3593 promise = proceed( this.steps[ 0 ] )();
3594 for ( i = 1, len = this.steps.length; i < len; i++ ) {
3595 promise = promise.then( proceed( this.steps[ i ] ) );
3596 }
3597 } else {
3598 promise = $.Deferred().resolve().promise();
3599 }
3600
3601 return promise;
3602 };
3603
3604 /**
3605 * Create a process step.
3606 *
3607 * @private
3608 * @param {number|jQuery.Promise|Function} step
3609 *
3610 * - Number of milliseconds to wait before proceeding
3611 * - Promise that must be resolved before proceeding
3612 * - Function to execute
3613 * - If the function returns a boolean false the process will stop
3614 * - If the function returns a promise, the process will continue to the next
3615 * step when the promise is resolved or stop if the promise is rejected
3616 * - If the function returns a number, the process will wait for that number of
3617 * milliseconds before proceeding
3618 * @param {Object} [context=null] Execution context of the function. The context is
3619 * ignored if the step is a number or promise.
3620 * @return {Object} Step object, with `callback` and `context` properties
3621 */
3622 OO.ui.Process.prototype.createStep = function ( step, context ) {
3623 if ( typeof step === 'number' || $.isFunction( step.promise ) ) {
3624 return {
3625 callback: function () {
3626 return step;
3627 },
3628 context: null
3629 };
3630 }
3631 if ( $.isFunction( step ) ) {
3632 return {
3633 callback: step,
3634 context: context
3635 };
3636 }
3637 throw new Error( 'Cannot create process step: number, promise or function expected' );
3638 };
3639
3640 /**
3641 * Add step to the beginning of the process.
3642 *
3643 * @inheritdoc #createStep
3644 * @return {OO.ui.Process} this
3645 * @chainable
3646 */
3647 OO.ui.Process.prototype.first = function ( step, context ) {
3648 this.steps.unshift( this.createStep( step, context ) );
3649 return this;
3650 };
3651
3652 /**
3653 * Add step to the end of the process.
3654 *
3655 * @inheritdoc #createStep
3656 * @return {OO.ui.Process} this
3657 * @chainable
3658 */
3659 OO.ui.Process.prototype.next = function ( step, context ) {
3660 this.steps.push( this.createStep( step, context ) );
3661 return this;
3662 };
3663
3664 /**
3665 * Factory for tools.
3666 *
3667 * @class
3668 * @extends OO.Factory
3669 * @constructor
3670 */
3671 OO.ui.ToolFactory = function OoUiToolFactory() {
3672 // Parent constructor
3673 OO.ui.ToolFactory.super.call( this );
3674 };
3675
3676 /* Setup */
3677
3678 OO.inheritClass( OO.ui.ToolFactory, OO.Factory );
3679
3680 /* Methods */
3681
3682 /**
3683 * Get tools from the factory
3684 *
3685 * @param {Array} include Included tools
3686 * @param {Array} exclude Excluded tools
3687 * @param {Array} promote Promoted tools
3688 * @param {Array} demote Demoted tools
3689 * @return {string[]} List of tools
3690 */
3691 OO.ui.ToolFactory.prototype.getTools = function ( include, exclude, promote, demote ) {
3692 var i, len, included, promoted, demoted,
3693 auto = [],
3694 used = {};
3695
3696 // Collect included and not excluded tools
3697 included = OO.simpleArrayDifference( this.extract( include ), this.extract( exclude ) );
3698
3699 // Promotion
3700 promoted = this.extract( promote, used );
3701 demoted = this.extract( demote, used );
3702
3703 // Auto
3704 for ( i = 0, len = included.length; i < len; i++ ) {
3705 if ( !used[ included[ i ] ] ) {
3706 auto.push( included[ i ] );
3707 }
3708 }
3709
3710 return promoted.concat( auto ).concat( demoted );
3711 };
3712
3713 /**
3714 * Get a flat list of names from a list of names or groups.
3715 *
3716 * Tools can be specified in the following ways:
3717 *
3718 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
3719 * - All tools in a group: `{ group: 'group-name' }`
3720 * - All tools: `'*'`
3721 *
3722 * @private
3723 * @param {Array|string} collection List of tools
3724 * @param {Object} [used] Object with names that should be skipped as properties; extracted
3725 * names will be added as properties
3726 * @return {string[]} List of extracted names
3727 */
3728 OO.ui.ToolFactory.prototype.extract = function ( collection, used ) {
3729 var i, len, item, name, tool,
3730 names = [];
3731
3732 if ( collection === '*' ) {
3733 for ( name in this.registry ) {
3734 tool = this.registry[ name ];
3735 if (
3736 // Only add tools by group name when auto-add is enabled
3737 tool.static.autoAddToCatchall &&
3738 // Exclude already used tools
3739 ( !used || !used[ name ] )
3740 ) {
3741 names.push( name );
3742 if ( used ) {
3743 used[ name ] = true;
3744 }
3745 }
3746 }
3747 } else if ( Array.isArray( collection ) ) {
3748 for ( i = 0, len = collection.length; i < len; i++ ) {
3749 item = collection[ i ];
3750 // Allow plain strings as shorthand for named tools
3751 if ( typeof item === 'string' ) {
3752 item = { name: item };
3753 }
3754 if ( OO.isPlainObject( item ) ) {
3755 if ( item.group ) {
3756 for ( name in this.registry ) {
3757 tool = this.registry[ name ];
3758 if (
3759 // Include tools with matching group
3760 tool.static.group === item.group &&
3761 // Only add tools by group name when auto-add is enabled
3762 tool.static.autoAddToGroup &&
3763 // Exclude already used tools
3764 ( !used || !used[ name ] )
3765 ) {
3766 names.push( name );
3767 if ( used ) {
3768 used[ name ] = true;
3769 }
3770 }
3771 }
3772 // Include tools with matching name and exclude already used tools
3773 } else if ( item.name && ( !used || !used[ item.name ] ) ) {
3774 names.push( item.name );
3775 if ( used ) {
3776 used[ item.name ] = true;
3777 }
3778 }
3779 }
3780 }
3781 }
3782 return names;
3783 };
3784
3785 /**
3786 * Factory for tool groups.
3787 *
3788 * @class
3789 * @extends OO.Factory
3790 * @constructor
3791 */
3792 OO.ui.ToolGroupFactory = function OoUiToolGroupFactory() {
3793 // Parent constructor
3794 OO.Factory.call( this );
3795
3796 var i, l,
3797 defaultClasses = this.constructor.static.getDefaultClasses();
3798
3799 // Register default toolgroups
3800 for ( i = 0, l = defaultClasses.length; i < l; i++ ) {
3801 this.register( defaultClasses[ i ] );
3802 }
3803 };
3804
3805 /* Setup */
3806
3807 OO.inheritClass( OO.ui.ToolGroupFactory, OO.Factory );
3808
3809 /* Static Methods */
3810
3811 /**
3812 * Get a default set of classes to be registered on construction
3813 *
3814 * @return {Function[]} Default classes
3815 */
3816 OO.ui.ToolGroupFactory.static.getDefaultClasses = function () {
3817 return [
3818 OO.ui.BarToolGroup,
3819 OO.ui.ListToolGroup,
3820 OO.ui.MenuToolGroup
3821 ];
3822 };
3823
3824 /**
3825 * Theme logic.
3826 *
3827 * @abstract
3828 * @class
3829 *
3830 * @constructor
3831 * @param {Object} [config] Configuration options
3832 */
3833 OO.ui.Theme = function OoUiTheme( config ) {
3834 // Configuration initialization
3835 config = config || {};
3836 };
3837
3838 /* Setup */
3839
3840 OO.initClass( OO.ui.Theme );
3841
3842 /* Methods */
3843
3844 /**
3845 * Get a list of classes to be applied to a widget.
3846 *
3847 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
3848 * otherwise state transitions will not work properly.
3849 *
3850 * @param {OO.ui.Element} element Element for which to get classes
3851 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
3852 */
3853 OO.ui.Theme.prototype.getElementClasses = function ( /* element */ ) {
3854 return { on: [], off: [] };
3855 };
3856
3857 /**
3858 * Update CSS classes provided by the theme.
3859 *
3860 * For elements with theme logic hooks, this should be called any time there's a state change.
3861 *
3862 * @param {OO.ui.Element} element Element for which to update classes
3863 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
3864 */
3865 OO.ui.Theme.prototype.updateElementClasses = function ( element ) {
3866 var classes = this.getElementClasses( element );
3867
3868 element.$element
3869 .removeClass( classes.off.join( ' ' ) )
3870 .addClass( classes.on.join( ' ' ) );
3871 };
3872
3873 /**
3874 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
3875 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
3876 * order in which users will navigate through the focusable elements via the "tab" key.
3877 *
3878 * @example
3879 * // TabIndexedElement is mixed into the ButtonWidget class
3880 * // to provide a tabIndex property.
3881 * var button1 = new OO.ui.ButtonWidget( {
3882 * label: 'fourth',
3883 * tabIndex: 4
3884 * } );
3885 * var button2 = new OO.ui.ButtonWidget( {
3886 * label: 'second',
3887 * tabIndex: 2
3888 * } );
3889 * var button3 = new OO.ui.ButtonWidget( {
3890 * label: 'third',
3891 * tabIndex: 3
3892 * } );
3893 * var button4 = new OO.ui.ButtonWidget( {
3894 * label: 'first',
3895 * tabIndex: 1
3896 * } );
3897 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
3898 *
3899 * @abstract
3900 * @class
3901 *
3902 * @constructor
3903 * @param {Object} [config] Configuration options
3904 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
3905 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
3906 * functionality will be applied to it instead.
3907 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
3908 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
3909 * to remove the element from the tab-navigation flow.
3910 */
3911 OO.ui.TabIndexedElement = function OoUiTabIndexedElement( config ) {
3912 // Configuration initialization
3913 config = $.extend( { tabIndex: 0 }, config );
3914
3915 // Properties
3916 this.$tabIndexed = null;
3917 this.tabIndex = null;
3918
3919 // Events
3920 this.connect( this, { disable: 'onDisable' } );
3921
3922 // Initialization
3923 this.setTabIndex( config.tabIndex );
3924 this.setTabIndexedElement( config.$tabIndexed || this.$element );
3925 };
3926
3927 /* Setup */
3928
3929 OO.initClass( OO.ui.TabIndexedElement );
3930
3931 /* Methods */
3932
3933 /**
3934 * Set the element that should use the tabindex functionality.
3935 *
3936 * This method is used to retarget a tabindex mixin so that its functionality applies
3937 * to the specified element. If an element is currently using the functionality, the mixin’s
3938 * effect on that element is removed before the new element is set up.
3939 *
3940 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
3941 * @chainable
3942 */
3943 OO.ui.TabIndexedElement.prototype.setTabIndexedElement = function ( $tabIndexed ) {
3944 var tabIndex = this.tabIndex;
3945 // Remove attributes from old $tabIndexed
3946 this.setTabIndex( null );
3947 // Force update of new $tabIndexed
3948 this.$tabIndexed = $tabIndexed;
3949 this.tabIndex = tabIndex;
3950 return this.updateTabIndex();
3951 };
3952
3953 /**
3954 * Set the value of the tabindex.
3955 *
3956 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
3957 * @chainable
3958 */
3959 OO.ui.TabIndexedElement.prototype.setTabIndex = function ( tabIndex ) {
3960 tabIndex = typeof tabIndex === 'number' ? tabIndex : null;
3961
3962 if ( this.tabIndex !== tabIndex ) {
3963 this.tabIndex = tabIndex;
3964 this.updateTabIndex();
3965 }
3966
3967 return this;
3968 };
3969
3970 /**
3971 * Update the `tabindex` attribute, in case of changes to tab index or
3972 * disabled state.
3973 *
3974 * @private
3975 * @chainable
3976 */
3977 OO.ui.TabIndexedElement.prototype.updateTabIndex = function () {
3978 if ( this.$tabIndexed ) {
3979 if ( this.tabIndex !== null ) {
3980 // Do not index over disabled elements
3981 this.$tabIndexed.attr( {
3982 tabindex: this.isDisabled() ? -1 : this.tabIndex,
3983 // ChromeVox and NVDA do not seem to inherit this from parent elements
3984 'aria-disabled': this.isDisabled().toString()
3985 } );
3986 } else {
3987 this.$tabIndexed.removeAttr( 'tabindex aria-disabled' );
3988 }
3989 }
3990 return this;
3991 };
3992
3993 /**
3994 * Handle disable events.
3995 *
3996 * @private
3997 * @param {boolean} disabled Element is disabled
3998 */
3999 OO.ui.TabIndexedElement.prototype.onDisable = function () {
4000 this.updateTabIndex();
4001 };
4002
4003 /**
4004 * Get the value of the tabindex.
4005 *
4006 * @return {number|null} Tabindex value
4007 */
4008 OO.ui.TabIndexedElement.prototype.getTabIndex = function () {
4009 return this.tabIndex;
4010 };
4011
4012 /**
4013 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
4014 * interface element that can be configured with access keys for accessibility.
4015 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
4016 *
4017 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
4018 * @abstract
4019 * @class
4020 *
4021 * @constructor
4022 * @param {Object} [config] Configuration options
4023 * @cfg {jQuery} [$button] The button element created by the class.
4024 * If this configuration is omitted, the button element will use a generated `<a>`.
4025 * @cfg {boolean} [framed=true] Render the button with a frame
4026 * @cfg {string} [accessKey] Button's access key
4027 */
4028 OO.ui.ButtonElement = function OoUiButtonElement( config ) {
4029 // Configuration initialization
4030 config = config || {};
4031
4032 // Properties
4033 this.$button = null;
4034 this.framed = null;
4035 this.accessKey = null;
4036 this.active = false;
4037 this.onMouseUpHandler = this.onMouseUp.bind( this );
4038 this.onMouseDownHandler = this.onMouseDown.bind( this );
4039 this.onKeyDownHandler = this.onKeyDown.bind( this );
4040 this.onKeyUpHandler = this.onKeyUp.bind( this );
4041 this.onClickHandler = this.onClick.bind( this );
4042 this.onKeyPressHandler = this.onKeyPress.bind( this );
4043
4044 // Initialization
4045 this.$element.addClass( 'oo-ui-buttonElement' );
4046 this.toggleFramed( config.framed === undefined || config.framed );
4047 this.setAccessKey( config.accessKey );
4048 this.setButtonElement( config.$button || $( '<a>' ) );
4049 };
4050
4051 /* Setup */
4052
4053 OO.initClass( OO.ui.ButtonElement );
4054
4055 /* Static Properties */
4056
4057 /**
4058 * Cancel mouse down events.
4059 *
4060 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
4061 * Classes such as {@link OO.ui.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
4062 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
4063 * parent widget.
4064 *
4065 * @static
4066 * @inheritable
4067 * @property {boolean}
4068 */
4069 OO.ui.ButtonElement.static.cancelButtonMouseDownEvents = true;
4070
4071 /* Events */
4072
4073 /**
4074 * A 'click' event is emitted when the button element is clicked.
4075 *
4076 * @event click
4077 */
4078
4079 /* Methods */
4080
4081 /**
4082 * Set the button element.
4083 *
4084 * This method is used to retarget a button mixin so that its functionality applies to
4085 * the specified button element instead of the one created by the class. If a button element
4086 * is already set, the method will remove the mixin’s effect on that element.
4087 *
4088 * @param {jQuery} $button Element to use as button
4089 */
4090 OO.ui.ButtonElement.prototype.setButtonElement = function ( $button ) {
4091 if ( this.$button ) {
4092 this.$button
4093 .removeClass( 'oo-ui-buttonElement-button' )
4094 .removeAttr( 'role accesskey' )
4095 .off( {
4096 mousedown: this.onMouseDownHandler,
4097 keydown: this.onKeyDownHandler,
4098 click: this.onClickHandler,
4099 keypress: this.onKeyPressHandler
4100 } );
4101 }
4102
4103 this.$button = $button
4104 .addClass( 'oo-ui-buttonElement-button' )
4105 .attr( { role: 'button', accesskey: this.accessKey } )
4106 .on( {
4107 mousedown: this.onMouseDownHandler,
4108 keydown: this.onKeyDownHandler,
4109 click: this.onClickHandler,
4110 keypress: this.onKeyPressHandler
4111 } );
4112 };
4113
4114 /**
4115 * Handles mouse down events.
4116 *
4117 * @protected
4118 * @param {jQuery.Event} e Mouse down event
4119 */
4120 OO.ui.ButtonElement.prototype.onMouseDown = function ( e ) {
4121 if ( this.isDisabled() || e.which !== 1 ) {
4122 return;
4123 }
4124 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
4125 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
4126 // reliably remove the pressed class
4127 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler, true );
4128 // Prevent change of focus unless specifically configured otherwise
4129 if ( this.constructor.static.cancelButtonMouseDownEvents ) {
4130 return false;
4131 }
4132 };
4133
4134 /**
4135 * Handles mouse up events.
4136 *
4137 * @protected
4138 * @param {jQuery.Event} e Mouse up event
4139 */
4140 OO.ui.ButtonElement.prototype.onMouseUp = function ( e ) {
4141 if ( this.isDisabled() || e.which !== 1 ) {
4142 return;
4143 }
4144 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
4145 // Stop listening for mouseup, since we only needed this once
4146 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler, true );
4147 };
4148
4149 /**
4150 * Handles mouse click events.
4151 *
4152 * @protected
4153 * @param {jQuery.Event} e Mouse click event
4154 * @fires click
4155 */
4156 OO.ui.ButtonElement.prototype.onClick = function ( e ) {
4157 if ( !this.isDisabled() && e.which === 1 ) {
4158 this.emit( 'click' );
4159 }
4160 return false;
4161 };
4162
4163 /**
4164 * Handles key down events.
4165 *
4166 * @protected
4167 * @param {jQuery.Event} e Key down event
4168 */
4169 OO.ui.ButtonElement.prototype.onKeyDown = function ( e ) {
4170 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
4171 return;
4172 }
4173 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
4174 // Run the keyup handler no matter where the key is when the button is let go, so we can
4175 // reliably remove the pressed class
4176 this.getElementDocument().addEventListener( 'keyup', this.onKeyUpHandler, true );
4177 };
4178
4179 /**
4180 * Handles key up events.
4181 *
4182 * @protected
4183 * @param {jQuery.Event} e Key up event
4184 */
4185 OO.ui.ButtonElement.prototype.onKeyUp = function ( e ) {
4186 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
4187 return;
4188 }
4189 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
4190 // Stop listening for keyup, since we only needed this once
4191 this.getElementDocument().removeEventListener( 'keyup', this.onKeyUpHandler, true );
4192 };
4193
4194 /**
4195 * Handles key press events.
4196 *
4197 * @protected
4198 * @param {jQuery.Event} e Key press event
4199 * @fires click
4200 */
4201 OO.ui.ButtonElement.prototype.onKeyPress = function ( e ) {
4202 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
4203 this.emit( 'click' );
4204 return false;
4205 }
4206 };
4207
4208 /**
4209 * Check if button has a frame.
4210 *
4211 * @return {boolean} Button is framed
4212 */
4213 OO.ui.ButtonElement.prototype.isFramed = function () {
4214 return this.framed;
4215 };
4216
4217 /**
4218 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
4219 *
4220 * @param {boolean} [framed] Make button framed, omit to toggle
4221 * @chainable
4222 */
4223 OO.ui.ButtonElement.prototype.toggleFramed = function ( framed ) {
4224 framed = framed === undefined ? !this.framed : !!framed;
4225 if ( framed !== this.framed ) {
4226 this.framed = framed;
4227 this.$element
4228 .toggleClass( 'oo-ui-buttonElement-frameless', !framed )
4229 .toggleClass( 'oo-ui-buttonElement-framed', framed );
4230 this.updateThemeClasses();
4231 }
4232
4233 return this;
4234 };
4235
4236 /**
4237 * Set the button's access key.
4238 *
4239 * @param {string} accessKey Button's access key, use empty string to remove
4240 * @chainable
4241 */
4242 OO.ui.ButtonElement.prototype.setAccessKey = function ( accessKey ) {
4243 accessKey = typeof accessKey === 'string' && accessKey.length ? accessKey : null;
4244
4245 if ( this.accessKey !== accessKey ) {
4246 if ( this.$button ) {
4247 if ( accessKey !== null ) {
4248 this.$button.attr( 'accesskey', accessKey );
4249 } else {
4250 this.$button.removeAttr( 'accesskey' );
4251 }
4252 }
4253 this.accessKey = accessKey;
4254 }
4255
4256 return this;
4257 };
4258
4259 /**
4260 * Set the button to its 'active' state.
4261 *
4262 * The active state occurs when a {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} or
4263 * a {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} is pressed. This method does nothing
4264 * for other button types.
4265 *
4266 * @param {boolean} [value] Make button active
4267 * @chainable
4268 */
4269 OO.ui.ButtonElement.prototype.setActive = function ( value ) {
4270 this.$element.toggleClass( 'oo-ui-buttonElement-active', !!value );
4271 return this;
4272 };
4273
4274 /**
4275 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
4276 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
4277 * items from the group is done through the interface the class provides.
4278 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
4279 *
4280 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
4281 *
4282 * @abstract
4283 * @class
4284 *
4285 * @constructor
4286 * @param {Object} [config] Configuration options
4287 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
4288 * is omitted, the group element will use a generated `<div>`.
4289 */
4290 OO.ui.GroupElement = function OoUiGroupElement( config ) {
4291 // Configuration initialization
4292 config = config || {};
4293
4294 // Properties
4295 this.$group = null;
4296 this.items = [];
4297 this.aggregateItemEvents = {};
4298
4299 // Initialization
4300 this.setGroupElement( config.$group || $( '<div>' ) );
4301 };
4302
4303 /* Methods */
4304
4305 /**
4306 * Set the group element.
4307 *
4308 * If an element is already set, items will be moved to the new element.
4309 *
4310 * @param {jQuery} $group Element to use as group
4311 */
4312 OO.ui.GroupElement.prototype.setGroupElement = function ( $group ) {
4313 var i, len;
4314
4315 this.$group = $group;
4316 for ( i = 0, len = this.items.length; i < len; i++ ) {
4317 this.$group.append( this.items[ i ].$element );
4318 }
4319 };
4320
4321 /**
4322 * Check if a group contains no items.
4323 *
4324 * @return {boolean} Group is empty
4325 */
4326 OO.ui.GroupElement.prototype.isEmpty = function () {
4327 return !this.items.length;
4328 };
4329
4330 /**
4331 * Get all items in the group.
4332 *
4333 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
4334 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
4335 * from a group).
4336 *
4337 * @return {OO.ui.Element[]} An array of items.
4338 */
4339 OO.ui.GroupElement.prototype.getItems = function () {
4340 return this.items.slice( 0 );
4341 };
4342
4343 /**
4344 * Get an item by its data.
4345 *
4346 * Only the first item with matching data will be returned. To return all matching items,
4347 * use the #getItemsFromData method.
4348 *
4349 * @param {Object} data Item data to search for
4350 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
4351 */
4352 OO.ui.GroupElement.prototype.getItemFromData = function ( data ) {
4353 var i, len, item,
4354 hash = OO.getHash( data );
4355
4356 for ( i = 0, len = this.items.length; i < len; i++ ) {
4357 item = this.items[ i ];
4358 if ( hash === OO.getHash( item.getData() ) ) {
4359 return item;
4360 }
4361 }
4362
4363 return null;
4364 };
4365
4366 /**
4367 * Get items by their data.
4368 *
4369 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
4370 *
4371 * @param {Object} data Item data to search for
4372 * @return {OO.ui.Element[]} Items with equivalent data
4373 */
4374 OO.ui.GroupElement.prototype.getItemsFromData = function ( data ) {
4375 var i, len, item,
4376 hash = OO.getHash( data ),
4377 items = [];
4378
4379 for ( i = 0, len = this.items.length; i < len; i++ ) {
4380 item = this.items[ i ];
4381 if ( hash === OO.getHash( item.getData() ) ) {
4382 items.push( item );
4383 }
4384 }
4385
4386 return items;
4387 };
4388
4389 /**
4390 * Aggregate the events emitted by the group.
4391 *
4392 * When events are aggregated, the group will listen to all contained items for the event,
4393 * and then emit the event under a new name. The new event will contain an additional leading
4394 * parameter containing the item that emitted the original event. Other arguments emitted from
4395 * the original event are passed through.
4396 *
4397 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
4398 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
4399 * A `null` value will remove aggregated events.
4400
4401 * @throws {Error} An error is thrown if aggregation already exists.
4402 */
4403 OO.ui.GroupElement.prototype.aggregate = function ( events ) {
4404 var i, len, item, add, remove, itemEvent, groupEvent;
4405
4406 for ( itemEvent in events ) {
4407 groupEvent = events[ itemEvent ];
4408
4409 // Remove existing aggregated event
4410 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4411 // Don't allow duplicate aggregations
4412 if ( groupEvent ) {
4413 throw new Error( 'Duplicate item event aggregation for ' + itemEvent );
4414 }
4415 // Remove event aggregation from existing items
4416 for ( i = 0, len = this.items.length; i < len; i++ ) {
4417 item = this.items[ i ];
4418 if ( item.connect && item.disconnect ) {
4419 remove = {};
4420 remove[ itemEvent ] = [ 'emit', groupEvent, item ];
4421 item.disconnect( this, remove );
4422 }
4423 }
4424 // Prevent future items from aggregating event
4425 delete this.aggregateItemEvents[ itemEvent ];
4426 }
4427
4428 // Add new aggregate event
4429 if ( groupEvent ) {
4430 // Make future items aggregate event
4431 this.aggregateItemEvents[ itemEvent ] = groupEvent;
4432 // Add event aggregation to existing items
4433 for ( i = 0, len = this.items.length; i < len; i++ ) {
4434 item = this.items[ i ];
4435 if ( item.connect && item.disconnect ) {
4436 add = {};
4437 add[ itemEvent ] = [ 'emit', groupEvent, item ];
4438 item.connect( this, add );
4439 }
4440 }
4441 }
4442 }
4443 };
4444
4445 /**
4446 * Add items to the group.
4447 *
4448 * Items will be added to the end of the group array unless the optional `index` parameter specifies
4449 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
4450 *
4451 * @param {OO.ui.Element[]} items An array of items to add to the group
4452 * @param {number} [index] Index of the insertion point
4453 * @chainable
4454 */
4455 OO.ui.GroupElement.prototype.addItems = function ( items, index ) {
4456 var i, len, item, event, events, currentIndex,
4457 itemElements = [];
4458
4459 for ( i = 0, len = items.length; i < len; i++ ) {
4460 item = items[ i ];
4461
4462 // Check if item exists then remove it first, effectively "moving" it
4463 currentIndex = $.inArray( item, this.items );
4464 if ( currentIndex >= 0 ) {
4465 this.removeItems( [ item ] );
4466 // Adjust index to compensate for removal
4467 if ( currentIndex < index ) {
4468 index--;
4469 }
4470 }
4471 // Add the item
4472 if ( item.connect && item.disconnect && !$.isEmptyObject( this.aggregateItemEvents ) ) {
4473 events = {};
4474 for ( event in this.aggregateItemEvents ) {
4475 events[ event ] = [ 'emit', this.aggregateItemEvents[ event ], item ];
4476 }
4477 item.connect( this, events );
4478 }
4479 item.setElementGroup( this );
4480 itemElements.push( item.$element.get( 0 ) );
4481 }
4482
4483 if ( index === undefined || index < 0 || index >= this.items.length ) {
4484 this.$group.append( itemElements );
4485 this.items.push.apply( this.items, items );
4486 } else if ( index === 0 ) {
4487 this.$group.prepend( itemElements );
4488 this.items.unshift.apply( this.items, items );
4489 } else {
4490 this.items[ index ].$element.before( itemElements );
4491 this.items.splice.apply( this.items, [ index, 0 ].concat( items ) );
4492 }
4493
4494 return this;
4495 };
4496
4497 /**
4498 * Remove the specified items from a group.
4499 *
4500 * Removed items are detached (not removed) from the DOM so that they may be reused.
4501 * To remove all items from a group, you may wish to use the #clearItems method instead.
4502 *
4503 * @param {OO.ui.Element[]} items An array of items to remove
4504 * @chainable
4505 */
4506 OO.ui.GroupElement.prototype.removeItems = function ( items ) {
4507 var i, len, item, index, remove, itemEvent;
4508
4509 // Remove specific items
4510 for ( i = 0, len = items.length; i < len; i++ ) {
4511 item = items[ i ];
4512 index = $.inArray( item, this.items );
4513 if ( index !== -1 ) {
4514 if (
4515 item.connect && item.disconnect &&
4516 !$.isEmptyObject( this.aggregateItemEvents )
4517 ) {
4518 remove = {};
4519 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4520 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4521 }
4522 item.disconnect( this, remove );
4523 }
4524 item.setElementGroup( null );
4525 this.items.splice( index, 1 );
4526 item.$element.detach();
4527 }
4528 }
4529
4530 return this;
4531 };
4532
4533 /**
4534 * Clear all items from the group.
4535 *
4536 * Cleared items are detached from the DOM, not removed, so that they may be reused.
4537 * To remove only a subset of items from a group, use the #removeItems method.
4538 *
4539 * @chainable
4540 */
4541 OO.ui.GroupElement.prototype.clearItems = function () {
4542 var i, len, item, remove, itemEvent;
4543
4544 // Remove all items
4545 for ( i = 0, len = this.items.length; i < len; i++ ) {
4546 item = this.items[ i ];
4547 if (
4548 item.connect && item.disconnect &&
4549 !$.isEmptyObject( this.aggregateItemEvents )
4550 ) {
4551 remove = {};
4552 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4553 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4554 }
4555 item.disconnect( this, remove );
4556 }
4557 item.setElementGroup( null );
4558 item.$element.detach();
4559 }
4560
4561 this.items = [];
4562 return this;
4563 };
4564
4565 /**
4566 * DraggableElement is a mixin class used to create elements that can be clicked
4567 * and dragged by a mouse to a new position within a group. This class must be used
4568 * in conjunction with OO.ui.DraggableGroupElement, which provides a container for
4569 * the draggable elements.
4570 *
4571 * @abstract
4572 * @class
4573 *
4574 * @constructor
4575 */
4576 OO.ui.DraggableElement = function OoUiDraggableElement() {
4577 // Properties
4578 this.index = null;
4579
4580 // Initialize and events
4581 this.$element
4582 .attr( 'draggable', true )
4583 .addClass( 'oo-ui-draggableElement' )
4584 .on( {
4585 dragstart: this.onDragStart.bind( this ),
4586 dragover: this.onDragOver.bind( this ),
4587 dragend: this.onDragEnd.bind( this ),
4588 drop: this.onDrop.bind( this )
4589 } );
4590 };
4591
4592 OO.initClass( OO.ui.DraggableElement );
4593
4594 /* Events */
4595
4596 /**
4597 * @event dragstart
4598 *
4599 * A dragstart event is emitted when the user clicks and begins dragging an item.
4600 * @param {OO.ui.DraggableElement} item The item the user has clicked and is dragging with the mouse.
4601 */
4602
4603 /**
4604 * @event dragend
4605 * A dragend event is emitted when the user drags an item and releases the mouse,
4606 * thus terminating the drag operation.
4607 */
4608
4609 /**
4610 * @event drop
4611 * A drop event is emitted when the user drags an item and then releases the mouse button
4612 * over a valid target.
4613 */
4614
4615 /* Static Properties */
4616
4617 /**
4618 * @inheritdoc OO.ui.ButtonElement
4619 */
4620 OO.ui.DraggableElement.static.cancelButtonMouseDownEvents = false;
4621
4622 /* Methods */
4623
4624 /**
4625 * Respond to dragstart event.
4626 *
4627 * @private
4628 * @param {jQuery.Event} event jQuery event
4629 * @fires dragstart
4630 */
4631 OO.ui.DraggableElement.prototype.onDragStart = function ( e ) {
4632 var dataTransfer = e.originalEvent.dataTransfer;
4633 // Define drop effect
4634 dataTransfer.dropEffect = 'none';
4635 dataTransfer.effectAllowed = 'move';
4636 // We must set up a dataTransfer data property or Firefox seems to
4637 // ignore the fact the element is draggable.
4638 try {
4639 dataTransfer.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
4640 } catch ( err ) {
4641 // The above is only for firefox. No need to set a catch clause
4642 // if it fails, move on.
4643 }
4644 // Add dragging class
4645 this.$element.addClass( 'oo-ui-draggableElement-dragging' );
4646 // Emit event
4647 this.emit( 'dragstart', this );
4648 return true;
4649 };
4650
4651 /**
4652 * Respond to dragend event.
4653 *
4654 * @private
4655 * @fires dragend
4656 */
4657 OO.ui.DraggableElement.prototype.onDragEnd = function () {
4658 this.$element.removeClass( 'oo-ui-draggableElement-dragging' );
4659 this.emit( 'dragend' );
4660 };
4661
4662 /**
4663 * Handle drop event.
4664 *
4665 * @private
4666 * @param {jQuery.Event} event jQuery event
4667 * @fires drop
4668 */
4669 OO.ui.DraggableElement.prototype.onDrop = function ( e ) {
4670 e.preventDefault();
4671 this.emit( 'drop', e );
4672 };
4673
4674 /**
4675 * In order for drag/drop to work, the dragover event must
4676 * return false and stop propogation.
4677 *
4678 * @private
4679 */
4680 OO.ui.DraggableElement.prototype.onDragOver = function ( e ) {
4681 e.preventDefault();
4682 };
4683
4684 /**
4685 * Set item index.
4686 * Store it in the DOM so we can access from the widget drag event
4687 *
4688 * @private
4689 * @param {number} Item index
4690 */
4691 OO.ui.DraggableElement.prototype.setIndex = function ( index ) {
4692 if ( this.index !== index ) {
4693 this.index = index;
4694 this.$element.data( 'index', index );
4695 }
4696 };
4697
4698 /**
4699 * Get item index
4700 *
4701 * @private
4702 * @return {number} Item index
4703 */
4704 OO.ui.DraggableElement.prototype.getIndex = function () {
4705 return this.index;
4706 };
4707
4708 /**
4709 * DraggableGroupElement is a mixin class used to create a group element to
4710 * contain draggable elements, which are items that can be clicked and dragged by a mouse.
4711 * The class is used with OO.ui.DraggableElement.
4712 *
4713 * @abstract
4714 * @class
4715 * @mixins OO.ui.GroupElement
4716 *
4717 * @constructor
4718 * @param {Object} [config] Configuration options
4719 * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation
4720 * should match the layout of the items. Items displayed in a single row
4721 * or in several rows should use horizontal orientation. The vertical orientation should only be
4722 * used when the items are displayed in a single column. Defaults to 'vertical'
4723 */
4724 OO.ui.DraggableGroupElement = function OoUiDraggableGroupElement( config ) {
4725 // Configuration initialization
4726 config = config || {};
4727
4728 // Parent constructor
4729 OO.ui.GroupElement.call( this, config );
4730
4731 // Properties
4732 this.orientation = config.orientation || 'vertical';
4733 this.dragItem = null;
4734 this.itemDragOver = null;
4735 this.itemKeys = {};
4736 this.sideInsertion = '';
4737
4738 // Events
4739 this.aggregate( {
4740 dragstart: 'itemDragStart',
4741 dragend: 'itemDragEnd',
4742 drop: 'itemDrop'
4743 } );
4744 this.connect( this, {
4745 itemDragStart: 'onItemDragStart',
4746 itemDrop: 'onItemDrop',
4747 itemDragEnd: 'onItemDragEnd'
4748 } );
4749 this.$element.on( {
4750 dragover: $.proxy( this.onDragOver, this ),
4751 dragleave: $.proxy( this.onDragLeave, this )
4752 } );
4753
4754 // Initialize
4755 if ( Array.isArray( config.items ) ) {
4756 this.addItems( config.items );
4757 }
4758 this.$placeholder = $( '<div>' )
4759 .addClass( 'oo-ui-draggableGroupElement-placeholder' );
4760 this.$element
4761 .addClass( 'oo-ui-draggableGroupElement' )
4762 .append( this.$status )
4763 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation === 'horizontal' )
4764 .prepend( this.$placeholder );
4765 };
4766
4767 /* Setup */
4768 OO.mixinClass( OO.ui.DraggableGroupElement, OO.ui.GroupElement );
4769
4770 /* Events */
4771
4772 /**
4773 * A 'reorder' event is emitted when the order of items in the group changes.
4774 *
4775 * @event reorder
4776 * @param {OO.ui.DraggableElement} item Reordered item
4777 * @param {number} [newIndex] New index for the item
4778 */
4779
4780 /* Methods */
4781
4782 /**
4783 * Respond to item drag start event
4784 *
4785 * @private
4786 * @param {OO.ui.DraggableElement} item Dragged item
4787 */
4788 OO.ui.DraggableGroupElement.prototype.onItemDragStart = function ( item ) {
4789 var i, len;
4790
4791 // Map the index of each object
4792 for ( i = 0, len = this.items.length; i < len; i++ ) {
4793 this.items[ i ].setIndex( i );
4794 }
4795
4796 if ( this.orientation === 'horizontal' ) {
4797 // Set the height of the indicator
4798 this.$placeholder.css( {
4799 height: item.$element.outerHeight(),
4800 width: 2
4801 } );
4802 } else {
4803 // Set the width of the indicator
4804 this.$placeholder.css( {
4805 height: 2,
4806 width: item.$element.outerWidth()
4807 } );
4808 }
4809 this.setDragItem( item );
4810 };
4811
4812 /**
4813 * Respond to item drag end event
4814 *
4815 * @private
4816 */
4817 OO.ui.DraggableGroupElement.prototype.onItemDragEnd = function () {
4818 this.unsetDragItem();
4819 return false;
4820 };
4821
4822 /**
4823 * Handle drop event and switch the order of the items accordingly
4824 *
4825 * @private
4826 * @param {OO.ui.DraggableElement} item Dropped item
4827 * @fires reorder
4828 */
4829 OO.ui.DraggableGroupElement.prototype.onItemDrop = function ( item ) {
4830 var toIndex = item.getIndex();
4831 // Check if the dropped item is from the current group
4832 // TODO: Figure out a way to configure a list of legally droppable
4833 // elements even if they are not yet in the list
4834 if ( this.getDragItem() ) {
4835 // If the insertion point is 'after', the insertion index
4836 // is shifted to the right (or to the left in RTL, hence 'after')
4837 if ( this.sideInsertion === 'after' ) {
4838 toIndex++;
4839 }
4840 // Emit change event
4841 this.emit( 'reorder', this.getDragItem(), toIndex );
4842 }
4843 this.unsetDragItem();
4844 // Return false to prevent propogation
4845 return false;
4846 };
4847
4848 /**
4849 * Handle dragleave event.
4850 *
4851 * @private
4852 */
4853 OO.ui.DraggableGroupElement.prototype.onDragLeave = function () {
4854 // This means the item was dragged outside the widget
4855 this.$placeholder
4856 .css( 'left', 0 )
4857 .addClass( 'oo-ui-element-hidden' );
4858 };
4859
4860 /**
4861 * Respond to dragover event
4862 *
4863 * @private
4864 * @param {jQuery.Event} event Event details
4865 */
4866 OO.ui.DraggableGroupElement.prototype.onDragOver = function ( e ) {
4867 var dragOverObj, $optionWidget, itemOffset, itemMidpoint, itemBoundingRect,
4868 itemSize, cssOutput, dragPosition, itemIndex, itemPosition,
4869 clientX = e.originalEvent.clientX,
4870 clientY = e.originalEvent.clientY;
4871
4872 // Get the OptionWidget item we are dragging over
4873 dragOverObj = this.getElementDocument().elementFromPoint( clientX, clientY );
4874 $optionWidget = $( dragOverObj ).closest( '.oo-ui-draggableElement' );
4875 if ( $optionWidget[ 0 ] ) {
4876 itemOffset = $optionWidget.offset();
4877 itemBoundingRect = $optionWidget[ 0 ].getBoundingClientRect();
4878 itemPosition = $optionWidget.position();
4879 itemIndex = $optionWidget.data( 'index' );
4880 }
4881
4882 if (
4883 itemOffset &&
4884 this.isDragging() &&
4885 itemIndex !== this.getDragItem().getIndex()
4886 ) {
4887 if ( this.orientation === 'horizontal' ) {
4888 // Calculate where the mouse is relative to the item width
4889 itemSize = itemBoundingRect.width;
4890 itemMidpoint = itemBoundingRect.left + itemSize / 2;
4891 dragPosition = clientX;
4892 // Which side of the item we hover over will dictate
4893 // where the placeholder will appear, on the left or
4894 // on the right
4895 cssOutput = {
4896 left: dragPosition < itemMidpoint ? itemPosition.left : itemPosition.left + itemSize,
4897 top: itemPosition.top
4898 };
4899 } else {
4900 // Calculate where the mouse is relative to the item height
4901 itemSize = itemBoundingRect.height;
4902 itemMidpoint = itemBoundingRect.top + itemSize / 2;
4903 dragPosition = clientY;
4904 // Which side of the item we hover over will dictate
4905 // where the placeholder will appear, on the top or
4906 // on the bottom
4907 cssOutput = {
4908 top: dragPosition < itemMidpoint ? itemPosition.top : itemPosition.top + itemSize,
4909 left: itemPosition.left
4910 };
4911 }
4912 // Store whether we are before or after an item to rearrange
4913 // For horizontal layout, we need to account for RTL, as this is flipped
4914 if ( this.orientation === 'horizontal' && this.$element.css( 'direction' ) === 'rtl' ) {
4915 this.sideInsertion = dragPosition < itemMidpoint ? 'after' : 'before';
4916 } else {
4917 this.sideInsertion = dragPosition < itemMidpoint ? 'before' : 'after';
4918 }
4919 // Add drop indicator between objects
4920 this.$placeholder
4921 .css( cssOutput )
4922 .removeClass( 'oo-ui-element-hidden' );
4923 } else {
4924 // This means the item was dragged outside the widget
4925 this.$placeholder
4926 .css( 'left', 0 )
4927 .addClass( 'oo-ui-element-hidden' );
4928 }
4929 // Prevent default
4930 e.preventDefault();
4931 };
4932
4933 /**
4934 * Set a dragged item
4935 *
4936 * @param {OO.ui.DraggableElement} item Dragged item
4937 */
4938 OO.ui.DraggableGroupElement.prototype.setDragItem = function ( item ) {
4939 this.dragItem = item;
4940 };
4941
4942 /**
4943 * Unset the current dragged item
4944 */
4945 OO.ui.DraggableGroupElement.prototype.unsetDragItem = function () {
4946 this.dragItem = null;
4947 this.itemDragOver = null;
4948 this.$placeholder.addClass( 'oo-ui-element-hidden' );
4949 this.sideInsertion = '';
4950 };
4951
4952 /**
4953 * Get the item that is currently being dragged.
4954 *
4955 * @return {OO.ui.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged
4956 */
4957 OO.ui.DraggableGroupElement.prototype.getDragItem = function () {
4958 return this.dragItem;
4959 };
4960
4961 /**
4962 * Check if an item in the group is currently being dragged.
4963 *
4964 * @return {Boolean} Item is being dragged
4965 */
4966 OO.ui.DraggableGroupElement.prototype.isDragging = function () {
4967 return this.getDragItem() !== null;
4968 };
4969
4970 /**
4971 * IconElement is often mixed into other classes to generate an icon.
4972 * Icons are graphics, about the size of normal text. They are used to aid the user
4973 * in locating a control or to convey information in a space-efficient way. See the
4974 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
4975 * included in the library.
4976 *
4977 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
4978 *
4979 * @abstract
4980 * @class
4981 *
4982 * @constructor
4983 * @param {Object} [config] Configuration options
4984 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
4985 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
4986 * the icon element be set to an existing icon instead of the one generated by this class, set a
4987 * value using a jQuery selection. For example:
4988 *
4989 * // Use a <div> tag instead of a <span>
4990 * $icon: $("<div>")
4991 * // Use an existing icon element instead of the one generated by the class
4992 * $icon: this.$element
4993 * // Use an icon element from a child widget
4994 * $icon: this.childwidget.$element
4995 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
4996 * symbolic names. A map is used for i18n purposes and contains a `default` icon
4997 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
4998 * by the user's language.
4999 *
5000 * Example of an i18n map:
5001 *
5002 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5003 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
5004 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
5005 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
5006 * text. The icon title is displayed when users move the mouse over the icon.
5007 */
5008 OO.ui.IconElement = function OoUiIconElement( config ) {
5009 // Configuration initialization
5010 config = config || {};
5011
5012 // Properties
5013 this.$icon = null;
5014 this.icon = null;
5015 this.iconTitle = null;
5016
5017 // Initialization
5018 this.setIcon( config.icon || this.constructor.static.icon );
5019 this.setIconTitle( config.iconTitle || this.constructor.static.iconTitle );
5020 this.setIconElement( config.$icon || $( '<span>' ) );
5021 };
5022
5023 /* Setup */
5024
5025 OO.initClass( OO.ui.IconElement );
5026
5027 /* Static Properties */
5028
5029 /**
5030 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
5031 * for i18n purposes and contains a `default` icon name and additional names keyed by
5032 * language code. The `default` name is used when no icon is keyed by the user's language.
5033 *
5034 * Example of an i18n map:
5035 *
5036 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5037 *
5038 * Note: the static property will be overridden if the #icon configuration is used.
5039 *
5040 * @static
5041 * @inheritable
5042 * @property {Object|string}
5043 */
5044 OO.ui.IconElement.static.icon = null;
5045
5046 /**
5047 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
5048 * function that returns title text, or `null` for no title.
5049 *
5050 * The static property will be overridden if the #iconTitle configuration is used.
5051 *
5052 * @static
5053 * @inheritable
5054 * @property {string|Function|null}
5055 */
5056 OO.ui.IconElement.static.iconTitle = null;
5057
5058 /* Methods */
5059
5060 /**
5061 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
5062 * applies to the specified icon element instead of the one created by the class. If an icon
5063 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
5064 * and mixin methods will no longer affect the element.
5065 *
5066 * @param {jQuery} $icon Element to use as icon
5067 */
5068 OO.ui.IconElement.prototype.setIconElement = function ( $icon ) {
5069 if ( this.$icon ) {
5070 this.$icon
5071 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon )
5072 .removeAttr( 'title' );
5073 }
5074
5075 this.$icon = $icon
5076 .addClass( 'oo-ui-iconElement-icon' )
5077 .toggleClass( 'oo-ui-icon-' + this.icon, !!this.icon );
5078 if ( this.iconTitle !== null ) {
5079 this.$icon.attr( 'title', this.iconTitle );
5080 }
5081 };
5082
5083 /**
5084 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
5085 * The icon parameter can also be set to a map of icon names. See the #icon config setting
5086 * for an example.
5087 *
5088 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
5089 * by language code, or `null` to remove the icon.
5090 * @chainable
5091 */
5092 OO.ui.IconElement.prototype.setIcon = function ( icon ) {
5093 icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon;
5094 icon = typeof icon === 'string' && icon.trim().length ? icon.trim() : null;
5095
5096 if ( this.icon !== icon ) {
5097 if ( this.$icon ) {
5098 if ( this.icon !== null ) {
5099 this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
5100 }
5101 if ( icon !== null ) {
5102 this.$icon.addClass( 'oo-ui-icon-' + icon );
5103 }
5104 }
5105 this.icon = icon;
5106 }
5107
5108 this.$element.toggleClass( 'oo-ui-iconElement', !!this.icon );
5109 this.updateThemeClasses();
5110
5111 return this;
5112 };
5113
5114 /**
5115 * Set the icon title. Use `null` to remove the title.
5116 *
5117 * @param {string|Function|null} iconTitle A text string used as the icon title,
5118 * a function that returns title text, or `null` for no title.
5119 * @chainable
5120 */
5121 OO.ui.IconElement.prototype.setIconTitle = function ( iconTitle ) {
5122 iconTitle = typeof iconTitle === 'function' ||
5123 ( typeof iconTitle === 'string' && iconTitle.length ) ?
5124 OO.ui.resolveMsg( iconTitle ) : null;
5125
5126 if ( this.iconTitle !== iconTitle ) {
5127 this.iconTitle = iconTitle;
5128 if ( this.$icon ) {
5129 if ( this.iconTitle !== null ) {
5130 this.$icon.attr( 'title', iconTitle );
5131 } else {
5132 this.$icon.removeAttr( 'title' );
5133 }
5134 }
5135 }
5136
5137 return this;
5138 };
5139
5140 /**
5141 * Get the symbolic name of the icon.
5142 *
5143 * @return {string} Icon name
5144 */
5145 OO.ui.IconElement.prototype.getIcon = function () {
5146 return this.icon;
5147 };
5148
5149 /**
5150 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
5151 *
5152 * @return {string} Icon title text
5153 */
5154 OO.ui.IconElement.prototype.getIconTitle = function () {
5155 return this.iconTitle;
5156 };
5157
5158 /**
5159 * IndicatorElement is often mixed into other classes to generate an indicator.
5160 * Indicators are small graphics that are generally used in two ways:
5161 *
5162 * - To draw attention to the status of an item. For example, an indicator might be
5163 * used to show that an item in a list has errors that need to be resolved.
5164 * - To clarify the function of a control that acts in an exceptional way (a button
5165 * that opens a menu instead of performing an action directly, for example).
5166 *
5167 * For a list of indicators included in the library, please see the
5168 * [OOjs UI documentation on MediaWiki] [1].
5169 *
5170 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5171 *
5172 * @abstract
5173 * @class
5174 *
5175 * @constructor
5176 * @param {Object} [config] Configuration options
5177 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
5178 * configuration is omitted, the indicator element will use a generated `<span>`.
5179 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5180 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
5181 * in the library.
5182 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5183 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
5184 * or a function that returns title text. The indicator title is displayed when users move
5185 * the mouse over the indicator.
5186 */
5187 OO.ui.IndicatorElement = function OoUiIndicatorElement( config ) {
5188 // Configuration initialization
5189 config = config || {};
5190
5191 // Properties
5192 this.$indicator = null;
5193 this.indicator = null;
5194 this.indicatorTitle = null;
5195
5196 // Initialization
5197 this.setIndicator( config.indicator || this.constructor.static.indicator );
5198 this.setIndicatorTitle( config.indicatorTitle || this.constructor.static.indicatorTitle );
5199 this.setIndicatorElement( config.$indicator || $( '<span>' ) );
5200 };
5201
5202 /* Setup */
5203
5204 OO.initClass( OO.ui.IndicatorElement );
5205
5206 /* Static Properties */
5207
5208 /**
5209 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5210 * The static property will be overridden if the #indicator configuration is used.
5211 *
5212 * @static
5213 * @inheritable
5214 * @property {string|null}
5215 */
5216 OO.ui.IndicatorElement.static.indicator = null;
5217
5218 /**
5219 * A text string used as the indicator title, a function that returns title text, or `null`
5220 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
5221 *
5222 * @static
5223 * @inheritable
5224 * @property {string|Function|null}
5225 */
5226 OO.ui.IndicatorElement.static.indicatorTitle = null;
5227
5228 /* Methods */
5229
5230 /**
5231 * Set the indicator element.
5232 *
5233 * If an element is already set, it will be cleaned up before setting up the new element.
5234 *
5235 * @param {jQuery} $indicator Element to use as indicator
5236 */
5237 OO.ui.IndicatorElement.prototype.setIndicatorElement = function ( $indicator ) {
5238 if ( this.$indicator ) {
5239 this.$indicator
5240 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator )
5241 .removeAttr( 'title' );
5242 }
5243
5244 this.$indicator = $indicator
5245 .addClass( 'oo-ui-indicatorElement-indicator' )
5246 .toggleClass( 'oo-ui-indicator-' + this.indicator, !!this.indicator );
5247 if ( this.indicatorTitle !== null ) {
5248 this.$indicator.attr( 'title', this.indicatorTitle );
5249 }
5250 };
5251
5252 /**
5253 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
5254 *
5255 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
5256 * @chainable
5257 */
5258 OO.ui.IndicatorElement.prototype.setIndicator = function ( indicator ) {
5259 indicator = typeof indicator === 'string' && indicator.length ? indicator.trim() : null;
5260
5261 if ( this.indicator !== indicator ) {
5262 if ( this.$indicator ) {
5263 if ( this.indicator !== null ) {
5264 this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator );
5265 }
5266 if ( indicator !== null ) {
5267 this.$indicator.addClass( 'oo-ui-indicator-' + indicator );
5268 }
5269 }
5270 this.indicator = indicator;
5271 }
5272
5273 this.$element.toggleClass( 'oo-ui-indicatorElement', !!this.indicator );
5274 this.updateThemeClasses();
5275
5276 return this;
5277 };
5278
5279 /**
5280 * Set the indicator title.
5281 *
5282 * The title is displayed when a user moves the mouse over the indicator.
5283 *
5284 * @param {string|Function|null} indicator Indicator title text, a function that returns text, or
5285 * `null` for no indicator title
5286 * @chainable
5287 */
5288 OO.ui.IndicatorElement.prototype.setIndicatorTitle = function ( indicatorTitle ) {
5289 indicatorTitle = typeof indicatorTitle === 'function' ||
5290 ( typeof indicatorTitle === 'string' && indicatorTitle.length ) ?
5291 OO.ui.resolveMsg( indicatorTitle ) : null;
5292
5293 if ( this.indicatorTitle !== indicatorTitle ) {
5294 this.indicatorTitle = indicatorTitle;
5295 if ( this.$indicator ) {
5296 if ( this.indicatorTitle !== null ) {
5297 this.$indicator.attr( 'title', indicatorTitle );
5298 } else {
5299 this.$indicator.removeAttr( 'title' );
5300 }
5301 }
5302 }
5303
5304 return this;
5305 };
5306
5307 /**
5308 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5309 *
5310 * @return {string} Symbolic name of indicator
5311 */
5312 OO.ui.IndicatorElement.prototype.getIndicator = function () {
5313 return this.indicator;
5314 };
5315
5316 /**
5317 * Get the indicator title.
5318 *
5319 * The title is displayed when a user moves the mouse over the indicator.
5320 *
5321 * @return {string} Indicator title text
5322 */
5323 OO.ui.IndicatorElement.prototype.getIndicatorTitle = function () {
5324 return this.indicatorTitle;
5325 };
5326
5327 /**
5328 * LabelElement is often mixed into other classes to generate a label, which
5329 * helps identify the function of an interface element.
5330 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
5331 *
5332 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5333 *
5334 * @abstract
5335 * @class
5336 *
5337 * @constructor
5338 * @param {Object} [config] Configuration options
5339 * @cfg {jQuery} [$label] The label element created by the class. If this
5340 * configuration is omitted, the label element will use a generated `<span>`.
5341 * @cfg {jQuery|string|Function} [label] The label text. The label can be specified as a plaintext string,
5342 * a jQuery selection of elements, or a function that will produce a string in the future. See the
5343 * [OOjs UI documentation on MediaWiki] [2] for examples.
5344 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5345 * @cfg {boolean} [autoFitLabel=true] Fit the label to the width of the parent element.
5346 * The label will be truncated to fit if necessary.
5347 */
5348 OO.ui.LabelElement = function OoUiLabelElement( config ) {
5349 // Configuration initialization
5350 config = config || {};
5351
5352 // Properties
5353 this.$label = null;
5354 this.label = null;
5355 this.autoFitLabel = config.autoFitLabel === undefined || !!config.autoFitLabel;
5356
5357 // Initialization
5358 this.setLabel( config.label || this.constructor.static.label );
5359 this.setLabelElement( config.$label || $( '<span>' ) );
5360 };
5361
5362 /* Setup */
5363
5364 OO.initClass( OO.ui.LabelElement );
5365
5366 /* Events */
5367
5368 /**
5369 * @event labelChange
5370 * @param {string} value
5371 */
5372
5373 /* Static Properties */
5374
5375 /**
5376 * The label text. The label can be specified as a plaintext string, a function that will
5377 * produce a string in the future, or `null` for no label. The static value will
5378 * be overridden if a label is specified with the #label config option.
5379 *
5380 * @static
5381 * @inheritable
5382 * @property {string|Function|null}
5383 */
5384 OO.ui.LabelElement.static.label = null;
5385
5386 /* Methods */
5387
5388 /**
5389 * Set the label element.
5390 *
5391 * If an element is already set, it will be cleaned up before setting up the new element.
5392 *
5393 * @param {jQuery} $label Element to use as label
5394 */
5395 OO.ui.LabelElement.prototype.setLabelElement = function ( $label ) {
5396 if ( this.$label ) {
5397 this.$label.removeClass( 'oo-ui-labelElement-label' ).empty();
5398 }
5399
5400 this.$label = $label.addClass( 'oo-ui-labelElement-label' );
5401 this.setLabelContent( this.label );
5402 };
5403
5404 /**
5405 * Set the label.
5406 *
5407 * An empty string will result in the label being hidden. A string containing only whitespace will
5408 * be converted to a single `&nbsp;`.
5409 *
5410 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
5411 * text; or null for no label
5412 * @chainable
5413 */
5414 OO.ui.LabelElement.prototype.setLabel = function ( label ) {
5415 label = typeof label === 'function' ? OO.ui.resolveMsg( label ) : label;
5416 label = ( ( typeof label === 'string' && label.length ) || label instanceof jQuery || label instanceof OO.ui.HtmlSnippet ) ? label : null;
5417
5418 this.$element.toggleClass( 'oo-ui-labelElement', !!label );
5419
5420 if ( this.label !== label ) {
5421 if ( this.$label ) {
5422 this.setLabelContent( label );
5423 }
5424 this.label = label;
5425 this.emit( 'labelChange' );
5426 }
5427
5428 return this;
5429 };
5430
5431 /**
5432 * Get the label.
5433 *
5434 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
5435 * text; or null for no label
5436 */
5437 OO.ui.LabelElement.prototype.getLabel = function () {
5438 return this.label;
5439 };
5440
5441 /**
5442 * Fit the label.
5443 *
5444 * @chainable
5445 */
5446 OO.ui.LabelElement.prototype.fitLabel = function () {
5447 if ( this.$label && this.$label.autoEllipsis && this.autoFitLabel ) {
5448 this.$label.autoEllipsis( { hasSpan: false, tooltip: true } );
5449 }
5450
5451 return this;
5452 };
5453
5454 /**
5455 * Set the content of the label.
5456 *
5457 * Do not call this method until after the label element has been set by #setLabelElement.
5458 *
5459 * @private
5460 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
5461 * text; or null for no label
5462 */
5463 OO.ui.LabelElement.prototype.setLabelContent = function ( label ) {
5464 if ( typeof label === 'string' ) {
5465 if ( label.match( /^\s*$/ ) ) {
5466 // Convert whitespace only string to a single non-breaking space
5467 this.$label.html( '&nbsp;' );
5468 } else {
5469 this.$label.text( label );
5470 }
5471 } else if ( label instanceof OO.ui.HtmlSnippet ) {
5472 this.$label.html( label.toString() );
5473 } else if ( label instanceof jQuery ) {
5474 this.$label.empty().append( label );
5475 } else {
5476 this.$label.empty();
5477 }
5478 };
5479
5480 /**
5481 * LookupElement is a mixin that creates a {@link OO.ui.TextInputMenuSelectWidget menu} of suggested values for
5482 * a {@link OO.ui.TextInputWidget text input widget}. Suggested values are based on the characters the user types
5483 * into the text input field and, in general, the menu is only displayed when the user types. If a suggested value is chosen
5484 * from the lookup menu, that value becomes the value of the input field.
5485 *
5486 * Note that a new menu of suggested items is displayed when a value is chosen from the lookup menu. If this is
5487 * not the desired behavior, disable lookup menus with the #setLookupsDisabled method, then set the value, then
5488 * re-enable lookups.
5489 *
5490 * See the [OOjs UI demos][1] for an example.
5491 *
5492 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/index.html#widgets-apex-vector-ltr
5493 *
5494 * @class
5495 * @abstract
5496 *
5497 * @constructor
5498 * @param {Object} [config] Configuration options
5499 * @cfg {jQuery} [$overlay] Overlay for the lookup menu; defaults to relative positioning
5500 * @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element.
5501 * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty.
5502 * By default, the lookup menu is not generated and displayed until the user begins to type.
5503 */
5504 OO.ui.LookupElement = function OoUiLookupElement( config ) {
5505 // Configuration initialization
5506 config = config || {};
5507
5508 // Properties
5509 this.$overlay = config.$overlay || this.$element;
5510 this.lookupMenu = new OO.ui.TextInputMenuSelectWidget( this, {
5511 widget: this,
5512 input: this,
5513 $container: config.$container
5514 } );
5515
5516 this.allowSuggestionsWhenEmpty = config.allowSuggestionsWhenEmpty || false;
5517
5518 this.lookupCache = {};
5519 this.lookupQuery = null;
5520 this.lookupRequest = null;
5521 this.lookupsDisabled = false;
5522 this.lookupInputFocused = false;
5523
5524 // Events
5525 this.$input.on( {
5526 focus: this.onLookupInputFocus.bind( this ),
5527 blur: this.onLookupInputBlur.bind( this ),
5528 mousedown: this.onLookupInputMouseDown.bind( this )
5529 } );
5530 this.connect( this, { change: 'onLookupInputChange' } );
5531 this.lookupMenu.connect( this, {
5532 toggle: 'onLookupMenuToggle',
5533 choose: 'onLookupMenuItemChoose'
5534 } );
5535
5536 // Initialization
5537 this.$element.addClass( 'oo-ui-lookupElement' );
5538 this.lookupMenu.$element.addClass( 'oo-ui-lookupElement-menu' );
5539 this.$overlay.append( this.lookupMenu.$element );
5540 };
5541
5542 /* Methods */
5543
5544 /**
5545 * Handle input focus event.
5546 *
5547 * @protected
5548 * @param {jQuery.Event} e Input focus event
5549 */
5550 OO.ui.LookupElement.prototype.onLookupInputFocus = function () {
5551 this.lookupInputFocused = true;
5552 this.populateLookupMenu();
5553 };
5554
5555 /**
5556 * Handle input blur event.
5557 *
5558 * @protected
5559 * @param {jQuery.Event} e Input blur event
5560 */
5561 OO.ui.LookupElement.prototype.onLookupInputBlur = function () {
5562 this.closeLookupMenu();
5563 this.lookupInputFocused = false;
5564 };
5565
5566 /**
5567 * Handle input mouse down event.
5568 *
5569 * @protected
5570 * @param {jQuery.Event} e Input mouse down event
5571 */
5572 OO.ui.LookupElement.prototype.onLookupInputMouseDown = function () {
5573 // Only open the menu if the input was already focused.
5574 // This way we allow the user to open the menu again after closing it with Esc
5575 // by clicking in the input. Opening (and populating) the menu when initially
5576 // clicking into the input is handled by the focus handler.
5577 if ( this.lookupInputFocused && !this.lookupMenu.isVisible() ) {
5578 this.populateLookupMenu();
5579 }
5580 };
5581
5582 /**
5583 * Handle input change event.
5584 *
5585 * @protected
5586 * @param {string} value New input value
5587 */
5588 OO.ui.LookupElement.prototype.onLookupInputChange = function () {
5589 if ( this.lookupInputFocused ) {
5590 this.populateLookupMenu();
5591 }
5592 };
5593
5594 /**
5595 * Handle the lookup menu being shown/hidden.
5596 *
5597 * @protected
5598 * @param {boolean} visible Whether the lookup menu is now visible.
5599 */
5600 OO.ui.LookupElement.prototype.onLookupMenuToggle = function ( visible ) {
5601 if ( !visible ) {
5602 // When the menu is hidden, abort any active request and clear the menu.
5603 // This has to be done here in addition to closeLookupMenu(), because
5604 // MenuSelectWidget will close itself when the user presses Esc.
5605 this.abortLookupRequest();
5606 this.lookupMenu.clearItems();
5607 }
5608 };
5609
5610 /**
5611 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
5612 *
5613 * @protected
5614 * @param {OO.ui.MenuOptionWidget} item Selected item
5615 */
5616 OO.ui.LookupElement.prototype.onLookupMenuItemChoose = function ( item ) {
5617 this.setValue( item.getData() );
5618 };
5619
5620 /**
5621 * Get lookup menu.
5622 *
5623 * @private
5624 * @return {OO.ui.TextInputMenuSelectWidget}
5625 */
5626 OO.ui.LookupElement.prototype.getLookupMenu = function () {
5627 return this.lookupMenu;
5628 };
5629
5630 /**
5631 * Disable or re-enable lookups.
5632 *
5633 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
5634 *
5635 * @param {boolean} disabled Disable lookups
5636 */
5637 OO.ui.LookupElement.prototype.setLookupsDisabled = function ( disabled ) {
5638 this.lookupsDisabled = !!disabled;
5639 };
5640
5641 /**
5642 * Open the menu. If there are no entries in the menu, this does nothing.
5643 *
5644 * @private
5645 * @chainable
5646 */
5647 OO.ui.LookupElement.prototype.openLookupMenu = function () {
5648 if ( !this.lookupMenu.isEmpty() ) {
5649 this.lookupMenu.toggle( true );
5650 }
5651 return this;
5652 };
5653
5654 /**
5655 * Close the menu, empty it, and abort any pending request.
5656 *
5657 * @private
5658 * @chainable
5659 */
5660 OO.ui.LookupElement.prototype.closeLookupMenu = function () {
5661 this.lookupMenu.toggle( false );
5662 this.abortLookupRequest();
5663 this.lookupMenu.clearItems();
5664 return this;
5665 };
5666
5667 /**
5668 * Request menu items based on the input's current value, and when they arrive,
5669 * populate the menu with these items and show the menu.
5670 *
5671 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
5672 *
5673 * @private
5674 * @chainable
5675 */
5676 OO.ui.LookupElement.prototype.populateLookupMenu = function () {
5677 var widget = this,
5678 value = this.getValue();
5679
5680 if ( this.lookupsDisabled ) {
5681 return;
5682 }
5683
5684 // If the input is empty, clear the menu, unless suggestions when empty are allowed.
5685 if ( !this.allowSuggestionsWhenEmpty && value === '' ) {
5686 this.closeLookupMenu();
5687 // Skip population if there is already a request pending for the current value
5688 } else if ( value !== this.lookupQuery ) {
5689 this.getLookupMenuItems()
5690 .done( function ( items ) {
5691 widget.lookupMenu.clearItems();
5692 if ( items.length ) {
5693 widget.lookupMenu
5694 .addItems( items )
5695 .toggle( true );
5696 widget.initializeLookupMenuSelection();
5697 } else {
5698 widget.lookupMenu.toggle( false );
5699 }
5700 } )
5701 .fail( function () {
5702 widget.lookupMenu.clearItems();
5703 } );
5704 }
5705
5706 return this;
5707 };
5708
5709 /**
5710 * Select and highlight the first selectable item in the menu.
5711 *
5712 * @private
5713 * @chainable
5714 */
5715 OO.ui.LookupElement.prototype.initializeLookupMenuSelection = function () {
5716 if ( !this.lookupMenu.getSelectedItem() ) {
5717 this.lookupMenu.selectItem( this.lookupMenu.getFirstSelectableItem() );
5718 }
5719 this.lookupMenu.highlightItem( this.lookupMenu.getSelectedItem() );
5720 };
5721
5722 /**
5723 * Get lookup menu items for the current query.
5724 *
5725 * @private
5726 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
5727 * the done event. If the request was aborted to make way for a subsequent request, this promise
5728 * will not be rejected: it will remain pending forever.
5729 */
5730 OO.ui.LookupElement.prototype.getLookupMenuItems = function () {
5731 var widget = this,
5732 value = this.getValue(),
5733 deferred = $.Deferred(),
5734 ourRequest;
5735
5736 this.abortLookupRequest();
5737 if ( Object.prototype.hasOwnProperty.call( this.lookupCache, value ) ) {
5738 deferred.resolve( this.getLookupMenuOptionsFromData( this.lookupCache[ value ] ) );
5739 } else {
5740 this.pushPending();
5741 this.lookupQuery = value;
5742 ourRequest = this.lookupRequest = this.getLookupRequest();
5743 ourRequest
5744 .always( function () {
5745 // We need to pop pending even if this is an old request, otherwise
5746 // the widget will remain pending forever.
5747 // TODO: this assumes that an aborted request will fail or succeed soon after
5748 // being aborted, or at least eventually. It would be nice if we could popPending()
5749 // at abort time, but only if we knew that we hadn't already called popPending()
5750 // for that request.
5751 widget.popPending();
5752 } )
5753 .done( function ( response ) {
5754 // If this is an old request (and aborting it somehow caused it to still succeed),
5755 // ignore its success completely
5756 if ( ourRequest === widget.lookupRequest ) {
5757 widget.lookupQuery = null;
5758 widget.lookupRequest = null;
5759 widget.lookupCache[ value ] = widget.getLookupCacheDataFromResponse( response );
5760 deferred.resolve( widget.getLookupMenuOptionsFromData( widget.lookupCache[ value ] ) );
5761 }
5762 } )
5763 .fail( function () {
5764 // If this is an old request (or a request failing because it's being aborted),
5765 // ignore its failure completely
5766 if ( ourRequest === widget.lookupRequest ) {
5767 widget.lookupQuery = null;
5768 widget.lookupRequest = null;
5769 deferred.reject();
5770 }
5771 } );
5772 }
5773 return deferred.promise();
5774 };
5775
5776 /**
5777 * Abort the currently pending lookup request, if any.
5778 *
5779 * @private
5780 */
5781 OO.ui.LookupElement.prototype.abortLookupRequest = function () {
5782 var oldRequest = this.lookupRequest;
5783 if ( oldRequest ) {
5784 // First unset this.lookupRequest to the fail handler will notice
5785 // that the request is no longer current
5786 this.lookupRequest = null;
5787 this.lookupQuery = null;
5788 oldRequest.abort();
5789 }
5790 };
5791
5792 /**
5793 * Get a new request object of the current lookup query value.
5794 *
5795 * @protected
5796 * @abstract
5797 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
5798 */
5799 OO.ui.LookupElement.prototype.getLookupRequest = function () {
5800 // Stub, implemented in subclass
5801 return null;
5802 };
5803
5804 /**
5805 * Pre-process data returned by the request from #getLookupRequest.
5806 *
5807 * The return value of this function will be cached, and any further queries for the given value
5808 * will use the cache rather than doing API requests.
5809 *
5810 * @protected
5811 * @abstract
5812 * @param {Mixed} response Response from server
5813 * @return {Mixed} Cached result data
5814 */
5815 OO.ui.LookupElement.prototype.getLookupCacheDataFromResponse = function () {
5816 // Stub, implemented in subclass
5817 return [];
5818 };
5819
5820 /**
5821 * Get a list of menu option widgets from the (possibly cached) data returned by
5822 * #getLookupCacheDataFromResponse.
5823 *
5824 * @protected
5825 * @abstract
5826 * @param {Mixed} data Cached result data, usually an array
5827 * @return {OO.ui.MenuOptionWidget[]} Menu items
5828 */
5829 OO.ui.LookupElement.prototype.getLookupMenuOptionsFromData = function () {
5830 // Stub, implemented in subclass
5831 return [];
5832 };
5833
5834 /**
5835 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
5836 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
5837 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
5838 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
5839 *
5840 * @abstract
5841 * @class
5842 *
5843 * @constructor
5844 * @param {Object} [config] Configuration options
5845 * @cfg {Object} [popup] Configuration to pass to popup
5846 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
5847 */
5848 OO.ui.PopupElement = function OoUiPopupElement( config ) {
5849 // Configuration initialization
5850 config = config || {};
5851
5852 // Properties
5853 this.popup = new OO.ui.PopupWidget( $.extend(
5854 { autoClose: true },
5855 config.popup,
5856 { $autoCloseIgnore: this.$element }
5857 ) );
5858 };
5859
5860 /* Methods */
5861
5862 /**
5863 * Get popup.
5864 *
5865 * @return {OO.ui.PopupWidget} Popup widget
5866 */
5867 OO.ui.PopupElement.prototype.getPopup = function () {
5868 return this.popup;
5869 };
5870
5871 /**
5872 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
5873 * additional functionality to an element created by another class. The class provides
5874 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
5875 * which are used to customize the look and feel of a widget to better describe its
5876 * importance and functionality.
5877 *
5878 * The library currently contains the following styling flags for general use:
5879 *
5880 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
5881 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
5882 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
5883 *
5884 * The flags affect the appearance of the buttons:
5885 *
5886 * @example
5887 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
5888 * var button1 = new OO.ui.ButtonWidget( {
5889 * label: 'Constructive',
5890 * flags: 'constructive'
5891 * } );
5892 * var button2 = new OO.ui.ButtonWidget( {
5893 * label: 'Destructive',
5894 * flags: 'destructive'
5895 * } );
5896 * var button3 = new OO.ui.ButtonWidget( {
5897 * label: 'Progressive',
5898 * flags: 'progressive'
5899 * } );
5900 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
5901 *
5902 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
5903 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
5904 *
5905 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
5906 *
5907 * @abstract
5908 * @class
5909 *
5910 * @constructor
5911 * @param {Object} [config] Configuration options
5912 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
5913 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
5914 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
5915 * @cfg {jQuery} [$flagged] The flagged element. By default,
5916 * the flagged functionality is applied to the element created by the class ($element).
5917 * If a different element is specified, the flagged functionality will be applied to it instead.
5918 */
5919 OO.ui.FlaggedElement = function OoUiFlaggedElement( config ) {
5920 // Configuration initialization
5921 config = config || {};
5922
5923 // Properties
5924 this.flags = {};
5925 this.$flagged = null;
5926
5927 // Initialization
5928 this.setFlags( config.flags );
5929 this.setFlaggedElement( config.$flagged || this.$element );
5930 };
5931
5932 /* Events */
5933
5934 /**
5935 * @event flag
5936 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
5937 * parameter contains the name of each modified flag and indicates whether it was
5938 * added or removed.
5939 *
5940 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
5941 * that the flag was added, `false` that the flag was removed.
5942 */
5943
5944 /* Methods */
5945
5946 /**
5947 * Set the flagged element.
5948 *
5949 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
5950 * If an element is already set, the method will remove the mixin’s effect on that element.
5951 *
5952 * @param {jQuery} $flagged Element that should be flagged
5953 */
5954 OO.ui.FlaggedElement.prototype.setFlaggedElement = function ( $flagged ) {
5955 var classNames = Object.keys( this.flags ).map( function ( flag ) {
5956 return 'oo-ui-flaggedElement-' + flag;
5957 } ).join( ' ' );
5958
5959 if ( this.$flagged ) {
5960 this.$flagged.removeClass( classNames );
5961 }
5962
5963 this.$flagged = $flagged.addClass( classNames );
5964 };
5965
5966 /**
5967 * Check if the specified flag is set.
5968 *
5969 * @param {string} flag Name of flag
5970 * @return {boolean} The flag is set
5971 */
5972 OO.ui.FlaggedElement.prototype.hasFlag = function ( flag ) {
5973 return flag in this.flags;
5974 };
5975
5976 /**
5977 * Get the names of all flags set.
5978 *
5979 * @return {string[]} Flag names
5980 */
5981 OO.ui.FlaggedElement.prototype.getFlags = function () {
5982 return Object.keys( this.flags );
5983 };
5984
5985 /**
5986 * Clear all flags.
5987 *
5988 * @chainable
5989 * @fires flag
5990 */
5991 OO.ui.FlaggedElement.prototype.clearFlags = function () {
5992 var flag, className,
5993 changes = {},
5994 remove = [],
5995 classPrefix = 'oo-ui-flaggedElement-';
5996
5997 for ( flag in this.flags ) {
5998 className = classPrefix + flag;
5999 changes[ flag ] = false;
6000 delete this.flags[ flag ];
6001 remove.push( className );
6002 }
6003
6004 if ( this.$flagged ) {
6005 this.$flagged.removeClass( remove.join( ' ' ) );
6006 }
6007
6008 this.updateThemeClasses();
6009 this.emit( 'flag', changes );
6010
6011 return this;
6012 };
6013
6014 /**
6015 * Add one or more flags.
6016 *
6017 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
6018 * or an object keyed by flag name with a boolean value that indicates whether the flag should
6019 * be added (`true`) or removed (`false`).
6020 * @chainable
6021 * @fires flag
6022 */
6023 OO.ui.FlaggedElement.prototype.setFlags = function ( flags ) {
6024 var i, len, flag, className,
6025 changes = {},
6026 add = [],
6027 remove = [],
6028 classPrefix = 'oo-ui-flaggedElement-';
6029
6030 if ( typeof flags === 'string' ) {
6031 className = classPrefix + flags;
6032 // Set
6033 if ( !this.flags[ flags ] ) {
6034 this.flags[ flags ] = true;
6035 add.push( className );
6036 }
6037 } else if ( Array.isArray( flags ) ) {
6038 for ( i = 0, len = flags.length; i < len; i++ ) {
6039 flag = flags[ i ];
6040 className = classPrefix + flag;
6041 // Set
6042 if ( !this.flags[ flag ] ) {
6043 changes[ flag ] = true;
6044 this.flags[ flag ] = true;
6045 add.push( className );
6046 }
6047 }
6048 } else if ( OO.isPlainObject( flags ) ) {
6049 for ( flag in flags ) {
6050 className = classPrefix + flag;
6051 if ( flags[ flag ] ) {
6052 // Set
6053 if ( !this.flags[ flag ] ) {
6054 changes[ flag ] = true;
6055 this.flags[ flag ] = true;
6056 add.push( className );
6057 }
6058 } else {
6059 // Remove
6060 if ( this.flags[ flag ] ) {
6061 changes[ flag ] = false;
6062 delete this.flags[ flag ];
6063 remove.push( className );
6064 }
6065 }
6066 }
6067 }
6068
6069 if ( this.$flagged ) {
6070 this.$flagged
6071 .addClass( add.join( ' ' ) )
6072 .removeClass( remove.join( ' ' ) );
6073 }
6074
6075 this.updateThemeClasses();
6076 this.emit( 'flag', changes );
6077
6078 return this;
6079 };
6080
6081 /**
6082 * TitledElement is mixed into other classes to provide a `title` attribute.
6083 * Titles are rendered by the browser and are made visible when the user moves
6084 * the mouse over the element. Titles are not visible on touch devices.
6085 *
6086 * @example
6087 * // TitledElement provides a 'title' attribute to the
6088 * // ButtonWidget class
6089 * var button = new OO.ui.ButtonWidget( {
6090 * label: 'Button with Title',
6091 * title: 'I am a button'
6092 * } );
6093 * $( 'body' ).append( button.$element );
6094 *
6095 * @abstract
6096 * @class
6097 *
6098 * @constructor
6099 * @param {Object} [config] Configuration options
6100 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
6101 * If this config is omitted, the title functionality is applied to $element, the
6102 * element created by the class.
6103 * @cfg {string|Function} [title] The title text or a function that returns text. If
6104 * this config is omitted, the value of the {@link #static-title static title} property is used.
6105 */
6106 OO.ui.TitledElement = function OoUiTitledElement( config ) {
6107 // Configuration initialization
6108 config = config || {};
6109
6110 // Properties
6111 this.$titled = null;
6112 this.title = null;
6113
6114 // Initialization
6115 this.setTitle( config.title || this.constructor.static.title );
6116 this.setTitledElement( config.$titled || this.$element );
6117 };
6118
6119 /* Setup */
6120
6121 OO.initClass( OO.ui.TitledElement );
6122
6123 /* Static Properties */
6124
6125 /**
6126 * The title text, a function that returns text, or `null` for no title. The value of the static property
6127 * is overridden if the #title config option is used.
6128 *
6129 * @static
6130 * @inheritable
6131 * @property {string|Function|null}
6132 */
6133 OO.ui.TitledElement.static.title = null;
6134
6135 /* Methods */
6136
6137 /**
6138 * Set the titled element.
6139 *
6140 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
6141 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
6142 *
6143 * @param {jQuery} $titled Element that should use the 'titled' functionality
6144 */
6145 OO.ui.TitledElement.prototype.setTitledElement = function ( $titled ) {
6146 if ( this.$titled ) {
6147 this.$titled.removeAttr( 'title' );
6148 }
6149
6150 this.$titled = $titled;
6151 if ( this.title ) {
6152 this.$titled.attr( 'title', this.title );
6153 }
6154 };
6155
6156 /**
6157 * Set title.
6158 *
6159 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
6160 * @chainable
6161 */
6162 OO.ui.TitledElement.prototype.setTitle = function ( title ) {
6163 title = typeof title === 'string' ? OO.ui.resolveMsg( title ) : null;
6164
6165 if ( this.title !== title ) {
6166 if ( this.$titled ) {
6167 if ( title !== null ) {
6168 this.$titled.attr( 'title', title );
6169 } else {
6170 this.$titled.removeAttr( 'title' );
6171 }
6172 }
6173 this.title = title;
6174 }
6175
6176 return this;
6177 };
6178
6179 /**
6180 * Get title.
6181 *
6182 * @return {string} Title string
6183 */
6184 OO.ui.TitledElement.prototype.getTitle = function () {
6185 return this.title;
6186 };
6187
6188 /**
6189 * Element that can be automatically clipped to visible boundaries.
6190 *
6191 * Whenever the element's natural height changes, you have to call
6192 * #clip to make sure it's still clipping correctly.
6193 *
6194 * @abstract
6195 * @class
6196 *
6197 * @constructor
6198 * @param {Object} [config] Configuration options
6199 * @cfg {jQuery} [$clippable] Nodes to clip, assigned to #$clippable, omit to use #$element
6200 */
6201 OO.ui.ClippableElement = function OoUiClippableElement( config ) {
6202 // Configuration initialization
6203 config = config || {};
6204
6205 // Properties
6206 this.$clippable = null;
6207 this.clipping = false;
6208 this.clippedHorizontally = false;
6209 this.clippedVertically = false;
6210 this.$clippableContainer = null;
6211 this.$clippableScroller = null;
6212 this.$clippableWindow = null;
6213 this.idealWidth = null;
6214 this.idealHeight = null;
6215 this.onClippableContainerScrollHandler = this.clip.bind( this );
6216 this.onClippableWindowResizeHandler = this.clip.bind( this );
6217
6218 // Initialization
6219 this.setClippableElement( config.$clippable || this.$element );
6220 };
6221
6222 /* Methods */
6223
6224 /**
6225 * Set clippable element.
6226 *
6227 * If an element is already set, it will be cleaned up before setting up the new element.
6228 *
6229 * @param {jQuery} $clippable Element to make clippable
6230 */
6231 OO.ui.ClippableElement.prototype.setClippableElement = function ( $clippable ) {
6232 if ( this.$clippable ) {
6233 this.$clippable.removeClass( 'oo-ui-clippableElement-clippable' );
6234 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
6235 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6236 }
6237
6238 this.$clippable = $clippable.addClass( 'oo-ui-clippableElement-clippable' );
6239 this.clip();
6240 };
6241
6242 /**
6243 * Toggle clipping.
6244 *
6245 * Do not turn clipping on until after the element is attached to the DOM and visible.
6246 *
6247 * @param {boolean} [clipping] Enable clipping, omit to toggle
6248 * @chainable
6249 */
6250 OO.ui.ClippableElement.prototype.toggleClipping = function ( clipping ) {
6251 clipping = clipping === undefined ? !this.clipping : !!clipping;
6252
6253 if ( this.clipping !== clipping ) {
6254 this.clipping = clipping;
6255 if ( clipping ) {
6256 this.$clippableContainer = $( this.getClosestScrollableElementContainer() );
6257 // If the clippable container is the root, we have to listen to scroll events and check
6258 // jQuery.scrollTop on the window because of browser inconsistencies
6259 this.$clippableScroller = this.$clippableContainer.is( 'html, body' ) ?
6260 $( OO.ui.Element.static.getWindow( this.$clippableContainer ) ) :
6261 this.$clippableContainer;
6262 this.$clippableScroller.on( 'scroll', this.onClippableContainerScrollHandler );
6263 this.$clippableWindow = $( this.getElementWindow() )
6264 .on( 'resize', this.onClippableWindowResizeHandler );
6265 // Initial clip after visible
6266 this.clip();
6267 } else {
6268 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
6269 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6270
6271 this.$clippableContainer = null;
6272 this.$clippableScroller.off( 'scroll', this.onClippableContainerScrollHandler );
6273 this.$clippableScroller = null;
6274 this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler );
6275 this.$clippableWindow = null;
6276 }
6277 }
6278
6279 return this;
6280 };
6281
6282 /**
6283 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
6284 *
6285 * @return {boolean} Element will be clipped to the visible area
6286 */
6287 OO.ui.ClippableElement.prototype.isClipping = function () {
6288 return this.clipping;
6289 };
6290
6291 /**
6292 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
6293 *
6294 * @return {boolean} Part of the element is being clipped
6295 */
6296 OO.ui.ClippableElement.prototype.isClipped = function () {
6297 return this.clippedHorizontally || this.clippedVertically;
6298 };
6299
6300 /**
6301 * Check if the right of the element is being clipped by the nearest scrollable container.
6302 *
6303 * @return {boolean} Part of the element is being clipped
6304 */
6305 OO.ui.ClippableElement.prototype.isClippedHorizontally = function () {
6306 return this.clippedHorizontally;
6307 };
6308
6309 /**
6310 * Check if the bottom of the element is being clipped by the nearest scrollable container.
6311 *
6312 * @return {boolean} Part of the element is being clipped
6313 */
6314 OO.ui.ClippableElement.prototype.isClippedVertically = function () {
6315 return this.clippedVertically;
6316 };
6317
6318 /**
6319 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
6320 *
6321 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
6322 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
6323 */
6324 OO.ui.ClippableElement.prototype.setIdealSize = function ( width, height ) {
6325 this.idealWidth = width;
6326 this.idealHeight = height;
6327
6328 if ( !this.clipping ) {
6329 // Update dimensions
6330 this.$clippable.css( { width: width, height: height } );
6331 }
6332 // While clipping, idealWidth and idealHeight are not considered
6333 };
6334
6335 /**
6336 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
6337 * the element's natural height changes.
6338 *
6339 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
6340 * overlapped by, the visible area of the nearest scrollable container.
6341 *
6342 * @chainable
6343 */
6344 OO.ui.ClippableElement.prototype.clip = function () {
6345 if ( !this.clipping ) {
6346 // this.$clippableContainer and this.$clippableWindow are null, so the below will fail
6347 return this;
6348 }
6349
6350 var buffer = 7, // Chosen by fair dice roll
6351 cOffset = this.$clippable.offset(),
6352 $container = this.$clippableContainer.is( 'html, body' ) ?
6353 this.$clippableWindow : this.$clippableContainer,
6354 ccOffset = $container.offset() || { top: 0, left: 0 },
6355 ccHeight = $container.innerHeight() - buffer,
6356 ccWidth = $container.innerWidth() - buffer,
6357 cHeight = this.$clippable.outerHeight() + buffer,
6358 cWidth = this.$clippable.outerWidth() + buffer,
6359 scrollTop = this.$clippableScroller.scrollTop(),
6360 scrollLeft = this.$clippableScroller.scrollLeft(),
6361 desiredWidth = cOffset.left < 0 ?
6362 cWidth + cOffset.left :
6363 ( ccOffset.left + scrollLeft + ccWidth ) - cOffset.left,
6364 desiredHeight = cOffset.top < 0 ?
6365 cHeight + cOffset.top :
6366 ( ccOffset.top + scrollTop + ccHeight ) - cOffset.top,
6367 naturalWidth = this.$clippable.prop( 'scrollWidth' ),
6368 naturalHeight = this.$clippable.prop( 'scrollHeight' ),
6369 clipWidth = desiredWidth < naturalWidth,
6370 clipHeight = desiredHeight < naturalHeight;
6371
6372 if ( clipWidth ) {
6373 this.$clippable.css( { overflowX: 'scroll', width: desiredWidth } );
6374 } else {
6375 this.$clippable.css( { width: this.idealWidth || '', overflowX: '' } );
6376 }
6377 if ( clipHeight ) {
6378 this.$clippable.css( { overflowY: 'scroll', height: desiredHeight } );
6379 } else {
6380 this.$clippable.css( { height: this.idealHeight || '', overflowY: '' } );
6381 }
6382
6383 // If we stopped clipping in at least one of the dimensions
6384 if ( !clipWidth || !clipHeight ) {
6385 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6386 }
6387
6388 this.clippedHorizontally = clipWidth;
6389 this.clippedVertically = clipHeight;
6390
6391 return this;
6392 };
6393
6394 /**
6395 * Generic toolbar tool.
6396 *
6397 * @abstract
6398 * @class
6399 * @extends OO.ui.Widget
6400 * @mixins OO.ui.IconElement
6401 * @mixins OO.ui.FlaggedElement
6402 *
6403 * @constructor
6404 * @param {OO.ui.ToolGroup} toolGroup
6405 * @param {Object} [config] Configuration options
6406 * @cfg {string|Function} [title] Title text or a function that returns text
6407 */
6408 OO.ui.Tool = function OoUiTool( toolGroup, config ) {
6409 // Allow passing positional parameters inside the config object
6410 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
6411 config = toolGroup;
6412 toolGroup = config.toolGroup;
6413 }
6414
6415 // Configuration initialization
6416 config = config || {};
6417
6418 // Parent constructor
6419 OO.ui.Tool.super.call( this, config );
6420
6421 // Mixin constructors
6422 OO.ui.IconElement.call( this, config );
6423 OO.ui.FlaggedElement.call( this, config );
6424
6425 // Properties
6426 this.toolGroup = toolGroup;
6427 this.toolbar = this.toolGroup.getToolbar();
6428 this.active = false;
6429 this.$title = $( '<span>' );
6430 this.$accel = $( '<span>' );
6431 this.$link = $( '<a>' );
6432 this.title = null;
6433
6434 // Events
6435 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
6436
6437 // Initialization
6438 this.$title.addClass( 'oo-ui-tool-title' );
6439 this.$accel
6440 .addClass( 'oo-ui-tool-accel' )
6441 .prop( {
6442 // This may need to be changed if the key names are ever localized,
6443 // but for now they are essentially written in English
6444 dir: 'ltr',
6445 lang: 'en'
6446 } );
6447 this.$link
6448 .addClass( 'oo-ui-tool-link' )
6449 .append( this.$icon, this.$title, this.$accel )
6450 .prop( 'tabIndex', 0 )
6451 .attr( 'role', 'button' );
6452 this.$element
6453 .data( 'oo-ui-tool', this )
6454 .addClass(
6455 'oo-ui-tool ' + 'oo-ui-tool-name-' +
6456 this.constructor.static.name.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
6457 )
6458 .append( this.$link );
6459 this.setTitle( config.title || this.constructor.static.title );
6460 };
6461
6462 /* Setup */
6463
6464 OO.inheritClass( OO.ui.Tool, OO.ui.Widget );
6465 OO.mixinClass( OO.ui.Tool, OO.ui.IconElement );
6466 OO.mixinClass( OO.ui.Tool, OO.ui.FlaggedElement );
6467
6468 /* Events */
6469
6470 /**
6471 * @event select
6472 */
6473
6474 /* Static Properties */
6475
6476 /**
6477 * @static
6478 * @inheritdoc
6479 */
6480 OO.ui.Tool.static.tagName = 'span';
6481
6482 /**
6483 * Symbolic name of tool.
6484 *
6485 * @abstract
6486 * @static
6487 * @inheritable
6488 * @property {string}
6489 */
6490 OO.ui.Tool.static.name = '';
6491
6492 /**
6493 * Tool group.
6494 *
6495 * @abstract
6496 * @static
6497 * @inheritable
6498 * @property {string}
6499 */
6500 OO.ui.Tool.static.group = '';
6501
6502 /**
6503 * Tool title.
6504 *
6505 * Title is used as a tooltip when the tool is part of a bar tool group, or a label when the tool
6506 * is part of a list or menu tool group. If a trigger is associated with an action by the same name
6507 * as the tool, a description of its keyboard shortcut for the appropriate platform will be
6508 * appended to the title if the tool is part of a bar tool group.
6509 *
6510 * @abstract
6511 * @static
6512 * @inheritable
6513 * @property {string|Function} Title text or a function that returns text
6514 */
6515 OO.ui.Tool.static.title = '';
6516
6517 /**
6518 * Tool can be automatically added to catch-all groups.
6519 *
6520 * @static
6521 * @inheritable
6522 * @property {boolean}
6523 */
6524 OO.ui.Tool.static.autoAddToCatchall = true;
6525
6526 /**
6527 * Tool can be automatically added to named groups.
6528 *
6529 * @static
6530 * @property {boolean}
6531 * @inheritable
6532 */
6533 OO.ui.Tool.static.autoAddToGroup = true;
6534
6535 /**
6536 * Check if this tool is compatible with given data.
6537 *
6538 * @static
6539 * @inheritable
6540 * @param {Mixed} data Data to check
6541 * @return {boolean} Tool can be used with data
6542 */
6543 OO.ui.Tool.static.isCompatibleWith = function () {
6544 return false;
6545 };
6546
6547 /* Methods */
6548
6549 /**
6550 * Handle the toolbar state being updated.
6551 *
6552 * This is an abstract method that must be overridden in a concrete subclass.
6553 *
6554 * @abstract
6555 */
6556 OO.ui.Tool.prototype.onUpdateState = function () {
6557 throw new Error(
6558 'OO.ui.Tool.onUpdateState not implemented in this subclass:' + this.constructor
6559 );
6560 };
6561
6562 /**
6563 * Handle the tool being selected.
6564 *
6565 * This is an abstract method that must be overridden in a concrete subclass.
6566 *
6567 * @abstract
6568 */
6569 OO.ui.Tool.prototype.onSelect = function () {
6570 throw new Error(
6571 'OO.ui.Tool.onSelect not implemented in this subclass:' + this.constructor
6572 );
6573 };
6574
6575 /**
6576 * Check if the button is active.
6577 *
6578 * @return {boolean} Button is active
6579 */
6580 OO.ui.Tool.prototype.isActive = function () {
6581 return this.active;
6582 };
6583
6584 /**
6585 * Make the button appear active or inactive.
6586 *
6587 * @param {boolean} state Make button appear active
6588 */
6589 OO.ui.Tool.prototype.setActive = function ( state ) {
6590 this.active = !!state;
6591 if ( this.active ) {
6592 this.$element.addClass( 'oo-ui-tool-active' );
6593 } else {
6594 this.$element.removeClass( 'oo-ui-tool-active' );
6595 }
6596 };
6597
6598 /**
6599 * Get the tool title.
6600 *
6601 * @param {string|Function} title Title text or a function that returns text
6602 * @chainable
6603 */
6604 OO.ui.Tool.prototype.setTitle = function ( title ) {
6605 this.title = OO.ui.resolveMsg( title );
6606 this.updateTitle();
6607 return this;
6608 };
6609
6610 /**
6611 * Get the tool title.
6612 *
6613 * @return {string} Title text
6614 */
6615 OO.ui.Tool.prototype.getTitle = function () {
6616 return this.title;
6617 };
6618
6619 /**
6620 * Get the tool's symbolic name.
6621 *
6622 * @return {string} Symbolic name of tool
6623 */
6624 OO.ui.Tool.prototype.getName = function () {
6625 return this.constructor.static.name;
6626 };
6627
6628 /**
6629 * Update the title.
6630 */
6631 OO.ui.Tool.prototype.updateTitle = function () {
6632 var titleTooltips = this.toolGroup.constructor.static.titleTooltips,
6633 accelTooltips = this.toolGroup.constructor.static.accelTooltips,
6634 accel = this.toolbar.getToolAccelerator( this.constructor.static.name ),
6635 tooltipParts = [];
6636
6637 this.$title.text( this.title );
6638 this.$accel.text( accel );
6639
6640 if ( titleTooltips && typeof this.title === 'string' && this.title.length ) {
6641 tooltipParts.push( this.title );
6642 }
6643 if ( accelTooltips && typeof accel === 'string' && accel.length ) {
6644 tooltipParts.push( accel );
6645 }
6646 if ( tooltipParts.length ) {
6647 this.$link.attr( 'title', tooltipParts.join( ' ' ) );
6648 } else {
6649 this.$link.removeAttr( 'title' );
6650 }
6651 };
6652
6653 /**
6654 * Destroy tool.
6655 */
6656 OO.ui.Tool.prototype.destroy = function () {
6657 this.toolbar.disconnect( this );
6658 this.$element.remove();
6659 };
6660
6661 /**
6662 * Collection of tool groups.
6663 *
6664 * @example
6665 * // Basic OOjs UI toolbar example
6666 *
6667 * // Create the toolbar
6668 * var toolFactory = new OO.ui.ToolFactory();
6669 * var toolGroupFactory = new OO.ui.ToolGroupFactory();
6670 * var toolbar = new OO.ui.Toolbar( toolFactory, toolGroupFactory );
6671 *
6672 * // We will be placing status text in this element when tools are used
6673 * var $area = $( '<p>' ).css( 'font-size', '0.8em' ).text( 'Toolbar example' );
6674 *
6675 * // Define the tools that we're going to place in our toolbar
6676 *
6677 * // Create a class inheriting from OO.ui.Tool
6678 * function PictureTool() {
6679 * PictureTool.super.apply( this, arguments );
6680 * };
6681 * OO.inheritClass( PictureTool, OO.ui.Tool );
6682 * // Each tool must have a 'name' (used as an internal identifier, see later) and at least one
6683 * // of 'icon' and 'title' (displayed icon and text).
6684 * PictureTool.static.name = 'picture';
6685 * PictureTool.static.icon = 'picture';
6686 * PictureTool.static.title = 'Insert picture';
6687 * // Defines the action that will happen when this tool is selected (clicked).
6688 * PictureTool.prototype.onSelect = function () {
6689 * $area.text( 'Picture tool clicked!' );
6690 * this.setActive( false );
6691 * };
6692 * // The toolbar can be synchronized with the state of some external stuff, like a text
6693 * // editor's editing area, highlighting the tools (e.g. a 'bold' tool would be shown as active
6694 * // when the text cursor was inside bolded text). Here we simply disable this feature.
6695 * PictureTool.prototype.onUpdateState = function () {
6696 * this.setActive( false );
6697 * };
6698 * // Make this tool available in our toolFactory and thus our toolbar
6699 * toolFactory.register( PictureTool );
6700 *
6701 * // Register two more tools, nothing interesting here
6702 * function SettingsTool() {
6703 * SettingsTool.super.apply( this, arguments );
6704 * };
6705 * OO.inheritClass( SettingsTool, OO.ui.Tool );
6706 * SettingsTool.static.name = 'settings';
6707 * SettingsTool.static.icon = 'settings';
6708 * SettingsTool.static.title = 'Change settings';
6709 * SettingsTool.prototype.onSelect = function () {
6710 * $area.text( 'Settings tool clicked!' );
6711 * this.setActive( false );
6712 * };
6713 * SettingsTool.prototype.onUpdateState = function () {
6714 * this.setActive( false );
6715 * };
6716 * toolFactory.register( SettingsTool );
6717 *
6718 * // Register two more tools, nothing interesting here
6719 * function StuffTool() {
6720 * StuffTool.super.apply( this, arguments );
6721 * };
6722 * OO.inheritClass( StuffTool, OO.ui.Tool );
6723 * StuffTool.static.name = 'stuff';
6724 * StuffTool.static.icon = 'ellipsis';
6725 * StuffTool.static.title = 'More stuff';
6726 * StuffTool.prototype.onSelect = function () {
6727 * $area.text( 'More stuff tool clicked!' );
6728 * this.setActive( false );
6729 * };
6730 * StuffTool.prototype.onUpdateState = function () {
6731 * this.setActive( false );
6732 * };
6733 * toolFactory.register( StuffTool );
6734 *
6735 * // This is a PopupTool. Rather than having a custom 'onSelect' action, it will display a
6736 * // little popup window (a PopupWidget). 'onUpdateState' is also already implemented.
6737 * function HelpTool( toolGroup, config ) {
6738 * OO.ui.PopupTool.call( this, toolGroup, $.extend( { popup: {
6739 * padded: true,
6740 * label: 'Help',
6741 * head: true
6742 * } }, config ) );
6743 * this.popup.$body.append( '<p>I am helpful!</p>' );
6744 * };
6745 * OO.inheritClass( HelpTool, OO.ui.PopupTool );
6746 * HelpTool.static.name = 'help';
6747 * HelpTool.static.icon = 'help';
6748 * HelpTool.static.title = 'Help';
6749 * toolFactory.register( HelpTool );
6750 *
6751 * // Finally define which tools and in what order appear in the toolbar. Each tool may only be
6752 * // used once (but not all defined tools must be used).
6753 * toolbar.setup( [
6754 * {
6755 * // 'bar' tool groups display tools' icons only, side-by-side.
6756 * type: 'bar',
6757 * include: [ 'picture', 'help' ]
6758 * },
6759 * {
6760 * // 'list' tool groups display both the titles and icons, in a dropdown list.
6761 * type: 'list',
6762 * indicator: 'down',
6763 * label: 'More',
6764 * include: [ 'settings', 'stuff' ]
6765 * }
6766 * // Note how the tools themselves are toolgroup-agnostic - the same tool can be displayed
6767 * // either in a 'list' or a 'bar'. There is a 'menu' tool group too, not showcased here.
6768 * ] );
6769 *
6770 * // Create some UI around the toolbar and place it in the document
6771 * var frame = new OO.ui.PanelLayout( {
6772 * expanded: false,
6773 * framed: true
6774 * } );
6775 * var contentFrame = new OO.ui.PanelLayout( {
6776 * expanded: false,
6777 * padded: true
6778 * } );
6779 * frame.$element.append(
6780 * toolbar.$element,
6781 * contentFrame.$element.append( $area )
6782 * );
6783 * $( 'body' ).append( frame.$element );
6784 *
6785 * // Here is where the toolbar is actually built. This must be done after inserting it into the
6786 * // document.
6787 * toolbar.initialize();
6788 * toolbar.emit( 'updateState' );
6789 *
6790 * @class
6791 * @extends OO.ui.Element
6792 * @mixins OO.EventEmitter
6793 * @mixins OO.ui.GroupElement
6794 *
6795 * @constructor
6796 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
6797 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating tool groups
6798 * @param {Object} [config] Configuration options
6799 * @cfg {boolean} [actions] Add an actions section opposite to the tools
6800 * @cfg {boolean} [shadow] Add a shadow below the toolbar
6801 */
6802 OO.ui.Toolbar = function OoUiToolbar( toolFactory, toolGroupFactory, config ) {
6803 // Allow passing positional parameters inside the config object
6804 if ( OO.isPlainObject( toolFactory ) && config === undefined ) {
6805 config = toolFactory;
6806 toolFactory = config.toolFactory;
6807 toolGroupFactory = config.toolGroupFactory;
6808 }
6809
6810 // Configuration initialization
6811 config = config || {};
6812
6813 // Parent constructor
6814 OO.ui.Toolbar.super.call( this, config );
6815
6816 // Mixin constructors
6817 OO.EventEmitter.call( this );
6818 OO.ui.GroupElement.call( this, config );
6819
6820 // Properties
6821 this.toolFactory = toolFactory;
6822 this.toolGroupFactory = toolGroupFactory;
6823 this.groups = [];
6824 this.tools = {};
6825 this.$bar = $( '<div>' );
6826 this.$actions = $( '<div>' );
6827 this.initialized = false;
6828 this.onWindowResizeHandler = this.onWindowResize.bind( this );
6829
6830 // Events
6831 this.$element
6832 .add( this.$bar ).add( this.$group ).add( this.$actions )
6833 .on( 'mousedown', this.onPointerDown.bind( this ) );
6834
6835 // Initialization
6836 this.$group.addClass( 'oo-ui-toolbar-tools' );
6837 if ( config.actions ) {
6838 this.$bar.append( this.$actions.addClass( 'oo-ui-toolbar-actions' ) );
6839 }
6840 this.$bar
6841 .addClass( 'oo-ui-toolbar-bar' )
6842 .append( this.$group, '<div style="clear:both"></div>' );
6843 if ( config.shadow ) {
6844 this.$bar.append( '<div class="oo-ui-toolbar-shadow"></div>' );
6845 }
6846 this.$element.addClass( 'oo-ui-toolbar' ).append( this.$bar );
6847 };
6848
6849 /* Setup */
6850
6851 OO.inheritClass( OO.ui.Toolbar, OO.ui.Element );
6852 OO.mixinClass( OO.ui.Toolbar, OO.EventEmitter );
6853 OO.mixinClass( OO.ui.Toolbar, OO.ui.GroupElement );
6854
6855 /* Methods */
6856
6857 /**
6858 * Get the tool factory.
6859 *
6860 * @return {OO.ui.ToolFactory} Tool factory
6861 */
6862 OO.ui.Toolbar.prototype.getToolFactory = function () {
6863 return this.toolFactory;
6864 };
6865
6866 /**
6867 * Get the tool group factory.
6868 *
6869 * @return {OO.Factory} Tool group factory
6870 */
6871 OO.ui.Toolbar.prototype.getToolGroupFactory = function () {
6872 return this.toolGroupFactory;
6873 };
6874
6875 /**
6876 * Handles mouse down events.
6877 *
6878 * @param {jQuery.Event} e Mouse down event
6879 */
6880 OO.ui.Toolbar.prototype.onPointerDown = function ( e ) {
6881 var $closestWidgetToEvent = $( e.target ).closest( '.oo-ui-widget' ),
6882 $closestWidgetToToolbar = this.$element.closest( '.oo-ui-widget' );
6883 if ( !$closestWidgetToEvent.length || $closestWidgetToEvent[ 0 ] === $closestWidgetToToolbar[ 0 ] ) {
6884 return false;
6885 }
6886 };
6887
6888 /**
6889 * Handle window resize event.
6890 *
6891 * @private
6892 * @param {jQuery.Event} e Window resize event
6893 */
6894 OO.ui.Toolbar.prototype.onWindowResize = function () {
6895 this.$element.toggleClass(
6896 'oo-ui-toolbar-narrow',
6897 this.$bar.width() <= this.narrowThreshold
6898 );
6899 };
6900
6901 /**
6902 * Sets up handles and preloads required information for the toolbar to work.
6903 * This must be called after it is attached to a visible document and before doing anything else.
6904 */
6905 OO.ui.Toolbar.prototype.initialize = function () {
6906 this.initialized = true;
6907 this.narrowThreshold = this.$group.width() + this.$actions.width();
6908 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
6909 this.onWindowResize();
6910 };
6911
6912 /**
6913 * Setup toolbar.
6914 *
6915 * Tools can be specified in the following ways:
6916 *
6917 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
6918 * - All tools in a group: `{ group: 'group-name' }`
6919 * - All tools: `'*'` - Using this will make the group a list with a "More" label by default
6920 *
6921 * @param {Object.<string,Array>} groups List of tool group configurations
6922 * @param {Array|string} [groups.include] Tools to include
6923 * @param {Array|string} [groups.exclude] Tools to exclude
6924 * @param {Array|string} [groups.promote] Tools to promote to the beginning
6925 * @param {Array|string} [groups.demote] Tools to demote to the end
6926 */
6927 OO.ui.Toolbar.prototype.setup = function ( groups ) {
6928 var i, len, type, group,
6929 items = [],
6930 defaultType = 'bar';
6931
6932 // Cleanup previous groups
6933 this.reset();
6934
6935 // Build out new groups
6936 for ( i = 0, len = groups.length; i < len; i++ ) {
6937 group = groups[ i ];
6938 if ( group.include === '*' ) {
6939 // Apply defaults to catch-all groups
6940 if ( group.type === undefined ) {
6941 group.type = 'list';
6942 }
6943 if ( group.label === undefined ) {
6944 group.label = OO.ui.msg( 'ooui-toolbar-more' );
6945 }
6946 }
6947 // Check type has been registered
6948 type = this.getToolGroupFactory().lookup( group.type ) ? group.type : defaultType;
6949 items.push(
6950 this.getToolGroupFactory().create( type, this, group )
6951 );
6952 }
6953 this.addItems( items );
6954 };
6955
6956 /**
6957 * Remove all tools and groups from the toolbar.
6958 */
6959 OO.ui.Toolbar.prototype.reset = function () {
6960 var i, len;
6961
6962 this.groups = [];
6963 this.tools = {};
6964 for ( i = 0, len = this.items.length; i < len; i++ ) {
6965 this.items[ i ].destroy();
6966 }
6967 this.clearItems();
6968 };
6969
6970 /**
6971 * Destroys toolbar, removing event handlers and DOM elements.
6972 *
6973 * Call this whenever you are done using a toolbar.
6974 */
6975 OO.ui.Toolbar.prototype.destroy = function () {
6976 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
6977 this.reset();
6978 this.$element.remove();
6979 };
6980
6981 /**
6982 * Check if tool has not been used yet.
6983 *
6984 * @param {string} name Symbolic name of tool
6985 * @return {boolean} Tool is available
6986 */
6987 OO.ui.Toolbar.prototype.isToolAvailable = function ( name ) {
6988 return !this.tools[ name ];
6989 };
6990
6991 /**
6992 * Prevent tool from being used again.
6993 *
6994 * @param {OO.ui.Tool} tool Tool to reserve
6995 */
6996 OO.ui.Toolbar.prototype.reserveTool = function ( tool ) {
6997 this.tools[ tool.getName() ] = tool;
6998 };
6999
7000 /**
7001 * Allow tool to be used again.
7002 *
7003 * @param {OO.ui.Tool} tool Tool to release
7004 */
7005 OO.ui.Toolbar.prototype.releaseTool = function ( tool ) {
7006 delete this.tools[ tool.getName() ];
7007 };
7008
7009 /**
7010 * Get accelerator label for tool.
7011 *
7012 * This is a stub that should be overridden to provide access to accelerator information.
7013 *
7014 * @param {string} name Symbolic name of tool
7015 * @return {string|undefined} Tool accelerator label if available
7016 */
7017 OO.ui.Toolbar.prototype.getToolAccelerator = function () {
7018 return undefined;
7019 };
7020
7021 /**
7022 * Collection of tools.
7023 *
7024 * Tools can be specified in the following ways:
7025 *
7026 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
7027 * - All tools in a group: `{ group: 'group-name' }`
7028 * - All tools: `'*'`
7029 *
7030 * @abstract
7031 * @class
7032 * @extends OO.ui.Widget
7033 * @mixins OO.ui.GroupElement
7034 *
7035 * @constructor
7036 * @param {OO.ui.Toolbar} toolbar
7037 * @param {Object} [config] Configuration options
7038 * @cfg {Array|string} [include=[]] List of tools to include
7039 * @cfg {Array|string} [exclude=[]] List of tools to exclude
7040 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning
7041 * @cfg {Array|string} [demote=[]] List of tools to demote to the end
7042 */
7043 OO.ui.ToolGroup = function OoUiToolGroup( toolbar, config ) {
7044 // Allow passing positional parameters inside the config object
7045 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
7046 config = toolbar;
7047 toolbar = config.toolbar;
7048 }
7049
7050 // Configuration initialization
7051 config = config || {};
7052
7053 // Parent constructor
7054 OO.ui.ToolGroup.super.call( this, config );
7055
7056 // Mixin constructors
7057 OO.ui.GroupElement.call( this, config );
7058
7059 // Properties
7060 this.toolbar = toolbar;
7061 this.tools = {};
7062 this.pressed = null;
7063 this.autoDisabled = false;
7064 this.include = config.include || [];
7065 this.exclude = config.exclude || [];
7066 this.promote = config.promote || [];
7067 this.demote = config.demote || [];
7068 this.onCapturedMouseUpHandler = this.onCapturedMouseUp.bind( this );
7069
7070 // Events
7071 this.$element.on( {
7072 mousedown: this.onPointerDown.bind( this ),
7073 mouseup: this.onPointerUp.bind( this ),
7074 mouseover: this.onMouseOver.bind( this ),
7075 mouseout: this.onMouseOut.bind( this )
7076 } );
7077 this.toolbar.getToolFactory().connect( this, { register: 'onToolFactoryRegister' } );
7078 this.aggregate( { disable: 'itemDisable' } );
7079 this.connect( this, { itemDisable: 'updateDisabled' } );
7080
7081 // Initialization
7082 this.$group.addClass( 'oo-ui-toolGroup-tools' );
7083 this.$element
7084 .addClass( 'oo-ui-toolGroup' )
7085 .append( this.$group );
7086 this.populate();
7087 };
7088
7089 /* Setup */
7090
7091 OO.inheritClass( OO.ui.ToolGroup, OO.ui.Widget );
7092 OO.mixinClass( OO.ui.ToolGroup, OO.ui.GroupElement );
7093
7094 /* Events */
7095
7096 /**
7097 * @event update
7098 */
7099
7100 /* Static Properties */
7101
7102 /**
7103 * Show labels in tooltips.
7104 *
7105 * @static
7106 * @inheritable
7107 * @property {boolean}
7108 */
7109 OO.ui.ToolGroup.static.titleTooltips = false;
7110
7111 /**
7112 * Show acceleration labels in tooltips.
7113 *
7114 * @static
7115 * @inheritable
7116 * @property {boolean}
7117 */
7118 OO.ui.ToolGroup.static.accelTooltips = false;
7119
7120 /**
7121 * Automatically disable the toolgroup when all tools are disabled
7122 *
7123 * @static
7124 * @inheritable
7125 * @property {boolean}
7126 */
7127 OO.ui.ToolGroup.static.autoDisable = true;
7128
7129 /* Methods */
7130
7131 /**
7132 * @inheritdoc
7133 */
7134 OO.ui.ToolGroup.prototype.isDisabled = function () {
7135 return this.autoDisabled || OO.ui.ToolGroup.super.prototype.isDisabled.apply( this, arguments );
7136 };
7137
7138 /**
7139 * @inheritdoc
7140 */
7141 OO.ui.ToolGroup.prototype.updateDisabled = function () {
7142 var i, item, allDisabled = true;
7143
7144 if ( this.constructor.static.autoDisable ) {
7145 for ( i = this.items.length - 1; i >= 0; i-- ) {
7146 item = this.items[ i ];
7147 if ( !item.isDisabled() ) {
7148 allDisabled = false;
7149 break;
7150 }
7151 }
7152 this.autoDisabled = allDisabled;
7153 }
7154 OO.ui.ToolGroup.super.prototype.updateDisabled.apply( this, arguments );
7155 };
7156
7157 /**
7158 * Handle mouse down events.
7159 *
7160 * @param {jQuery.Event} e Mouse down event
7161 */
7162 OO.ui.ToolGroup.prototype.onPointerDown = function ( e ) {
7163 if ( !this.isDisabled() && e.which === 1 ) {
7164 this.pressed = this.getTargetTool( e );
7165 if ( this.pressed ) {
7166 this.pressed.setActive( true );
7167 this.getElementDocument().addEventListener(
7168 'mouseup', this.onCapturedMouseUpHandler, true
7169 );
7170 }
7171 }
7172 return false;
7173 };
7174
7175 /**
7176 * Handle captured mouse up events.
7177 *
7178 * @param {Event} e Mouse up event
7179 */
7180 OO.ui.ToolGroup.prototype.onCapturedMouseUp = function ( e ) {
7181 this.getElementDocument().removeEventListener( 'mouseup', this.onCapturedMouseUpHandler, true );
7182 // onPointerUp may be called a second time, depending on where the mouse is when the button is
7183 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
7184 this.onPointerUp( e );
7185 };
7186
7187 /**
7188 * Handle mouse up events.
7189 *
7190 * @param {jQuery.Event} e Mouse up event
7191 */
7192 OO.ui.ToolGroup.prototype.onPointerUp = function ( e ) {
7193 var tool = this.getTargetTool( e );
7194
7195 if ( !this.isDisabled() && e.which === 1 && this.pressed && this.pressed === tool ) {
7196 this.pressed.onSelect();
7197 }
7198
7199 this.pressed = null;
7200 return false;
7201 };
7202
7203 /**
7204 * Handle mouse over events.
7205 *
7206 * @param {jQuery.Event} e Mouse over event
7207 */
7208 OO.ui.ToolGroup.prototype.onMouseOver = function ( e ) {
7209 var tool = this.getTargetTool( e );
7210
7211 if ( this.pressed && this.pressed === tool ) {
7212 this.pressed.setActive( true );
7213 }
7214 };
7215
7216 /**
7217 * Handle mouse out events.
7218 *
7219 * @param {jQuery.Event} e Mouse out event
7220 */
7221 OO.ui.ToolGroup.prototype.onMouseOut = function ( e ) {
7222 var tool = this.getTargetTool( e );
7223
7224 if ( this.pressed && this.pressed === tool ) {
7225 this.pressed.setActive( false );
7226 }
7227 };
7228
7229 /**
7230 * Get the closest tool to a jQuery.Event.
7231 *
7232 * Only tool links are considered, which prevents other elements in the tool such as popups from
7233 * triggering tool group interactions.
7234 *
7235 * @private
7236 * @param {jQuery.Event} e
7237 * @return {OO.ui.Tool|null} Tool, `null` if none was found
7238 */
7239 OO.ui.ToolGroup.prototype.getTargetTool = function ( e ) {
7240 var tool,
7241 $item = $( e.target ).closest( '.oo-ui-tool-link' );
7242
7243 if ( $item.length ) {
7244 tool = $item.parent().data( 'oo-ui-tool' );
7245 }
7246
7247 return tool && !tool.isDisabled() ? tool : null;
7248 };
7249
7250 /**
7251 * Handle tool registry register events.
7252 *
7253 * If a tool is registered after the group is created, we must repopulate the list to account for:
7254 *
7255 * - a tool being added that may be included
7256 * - a tool already included being overridden
7257 *
7258 * @param {string} name Symbolic name of tool
7259 */
7260 OO.ui.ToolGroup.prototype.onToolFactoryRegister = function () {
7261 this.populate();
7262 };
7263
7264 /**
7265 * Get the toolbar this group is in.
7266 *
7267 * @return {OO.ui.Toolbar} Toolbar of group
7268 */
7269 OO.ui.ToolGroup.prototype.getToolbar = function () {
7270 return this.toolbar;
7271 };
7272
7273 /**
7274 * Add and remove tools based on configuration.
7275 */
7276 OO.ui.ToolGroup.prototype.populate = function () {
7277 var i, len, name, tool,
7278 toolFactory = this.toolbar.getToolFactory(),
7279 names = {},
7280 add = [],
7281 remove = [],
7282 list = this.toolbar.getToolFactory().getTools(
7283 this.include, this.exclude, this.promote, this.demote
7284 );
7285
7286 // Build a list of needed tools
7287 for ( i = 0, len = list.length; i < len; i++ ) {
7288 name = list[ i ];
7289 if (
7290 // Tool exists
7291 toolFactory.lookup( name ) &&
7292 // Tool is available or is already in this group
7293 ( this.toolbar.isToolAvailable( name ) || this.tools[ name ] )
7294 ) {
7295 // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before
7296 // creating it, but we can't call reserveTool() yet because we haven't created the tool.
7297 this.toolbar.tools[ name ] = true;
7298 tool = this.tools[ name ];
7299 if ( !tool ) {
7300 // Auto-initialize tools on first use
7301 this.tools[ name ] = tool = toolFactory.create( name, this );
7302 tool.updateTitle();
7303 }
7304 this.toolbar.reserveTool( tool );
7305 add.push( tool );
7306 names[ name ] = true;
7307 }
7308 }
7309 // Remove tools that are no longer needed
7310 for ( name in this.tools ) {
7311 if ( !names[ name ] ) {
7312 this.tools[ name ].destroy();
7313 this.toolbar.releaseTool( this.tools[ name ] );
7314 remove.push( this.tools[ name ] );
7315 delete this.tools[ name ];
7316 }
7317 }
7318 if ( remove.length ) {
7319 this.removeItems( remove );
7320 }
7321 // Update emptiness state
7322 if ( add.length ) {
7323 this.$element.removeClass( 'oo-ui-toolGroup-empty' );
7324 } else {
7325 this.$element.addClass( 'oo-ui-toolGroup-empty' );
7326 }
7327 // Re-add tools (moving existing ones to new locations)
7328 this.addItems( add );
7329 // Disabled state may depend on items
7330 this.updateDisabled();
7331 };
7332
7333 /**
7334 * Destroy tool group.
7335 */
7336 OO.ui.ToolGroup.prototype.destroy = function () {
7337 var name;
7338
7339 this.clearItems();
7340 this.toolbar.getToolFactory().disconnect( this );
7341 for ( name in this.tools ) {
7342 this.toolbar.releaseTool( this.tools[ name ] );
7343 this.tools[ name ].disconnect( this ).destroy();
7344 delete this.tools[ name ];
7345 }
7346 this.$element.remove();
7347 };
7348
7349 /**
7350 * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
7351 * consists of a header that contains the dialog title, a body with the message, and a footer that
7352 * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
7353 * of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
7354 *
7355 * There are two basic types of message dialogs, confirmation and alert:
7356 *
7357 * - **confirmation**: the dialog title describes what a progressive action will do and the message provides
7358 * more details about the consequences.
7359 * - **alert**: the dialog title describes which event occurred and the message provides more information
7360 * about why the event occurred.
7361 *
7362 * The MessageDialog class specifies two actions: ‘accept’, the primary
7363 * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
7364 * passing along the selected action.
7365 *
7366 * For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
7367 *
7368 * @example
7369 * // Example: Creating and opening a message dialog window.
7370 * var messageDialog = new OO.ui.MessageDialog();
7371 *
7372 * // Create and append a window manager.
7373 * var windowManager = new OO.ui.WindowManager();
7374 * $( 'body' ).append( windowManager.$element );
7375 * windowManager.addWindows( [ messageDialog ] );
7376 * // Open the window.
7377 * windowManager.openWindow( messageDialog, {
7378 * title: 'Basic message dialog',
7379 * message: 'This is the message'
7380 * } );
7381 *
7382 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
7383 *
7384 * @class
7385 * @extends OO.ui.Dialog
7386 *
7387 * @constructor
7388 * @param {Object} [config] Configuration options
7389 */
7390 OO.ui.MessageDialog = function OoUiMessageDialog( config ) {
7391 // Parent constructor
7392 OO.ui.MessageDialog.super.call( this, config );
7393
7394 // Properties
7395 this.verticalActionLayout = null;
7396
7397 // Initialization
7398 this.$element.addClass( 'oo-ui-messageDialog' );
7399 };
7400
7401 /* Inheritance */
7402
7403 OO.inheritClass( OO.ui.MessageDialog, OO.ui.Dialog );
7404
7405 /* Static Properties */
7406
7407 OO.ui.MessageDialog.static.name = 'message';
7408
7409 OO.ui.MessageDialog.static.size = 'small';
7410
7411 OO.ui.MessageDialog.static.verbose = false;
7412
7413 /**
7414 * Dialog title.
7415 *
7416 * The title of a confirmation dialog describes what a progressive action will do. The
7417 * title of an alert dialog describes which event occurred.
7418 *
7419 * @static
7420 * @inheritable
7421 * @property {jQuery|string|Function|null}
7422 */
7423 OO.ui.MessageDialog.static.title = null;
7424
7425 /**
7426 * The message displayed in the dialog body.
7427 *
7428 * A confirmation message describes the consequences of a progressive action. An alert
7429 * message describes why an event occurred.
7430 *
7431 * @static
7432 * @inheritable
7433 * @property {jQuery|string|Function|null}
7434 */
7435 OO.ui.MessageDialog.static.message = null;
7436
7437 OO.ui.MessageDialog.static.actions = [
7438 { action: 'accept', label: OO.ui.deferMsg( 'ooui-dialog-message-accept' ), flags: 'primary' },
7439 { action: 'reject', label: OO.ui.deferMsg( 'ooui-dialog-message-reject' ), flags: 'safe' }
7440 ];
7441
7442 /* Methods */
7443
7444 /**
7445 * @inheritdoc
7446 */
7447 OO.ui.MessageDialog.prototype.setManager = function ( manager ) {
7448 OO.ui.MessageDialog.super.prototype.setManager.call( this, manager );
7449
7450 // Events
7451 this.manager.connect( this, {
7452 resize: 'onResize'
7453 } );
7454
7455 return this;
7456 };
7457
7458 /**
7459 * @inheritdoc
7460 */
7461 OO.ui.MessageDialog.prototype.onActionResize = function ( action ) {
7462 this.fitActions();
7463 return OO.ui.MessageDialog.super.prototype.onActionResize.call( this, action );
7464 };
7465
7466 /**
7467 * Handle window resized events.
7468 *
7469 * @private
7470 */
7471 OO.ui.MessageDialog.prototype.onResize = function () {
7472 var dialog = this;
7473 dialog.fitActions();
7474 // Wait for CSS transition to finish and do it again :(
7475 setTimeout( function () {
7476 dialog.fitActions();
7477 }, 300 );
7478 };
7479
7480 /**
7481 * Toggle action layout between vertical and horizontal.
7482 *
7483 *
7484 * @private
7485 * @param {boolean} [value] Layout actions vertically, omit to toggle
7486 * @chainable
7487 */
7488 OO.ui.MessageDialog.prototype.toggleVerticalActionLayout = function ( value ) {
7489 value = value === undefined ? !this.verticalActionLayout : !!value;
7490
7491 if ( value !== this.verticalActionLayout ) {
7492 this.verticalActionLayout = value;
7493 this.$actions
7494 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value )
7495 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value );
7496 }
7497
7498 return this;
7499 };
7500
7501 /**
7502 * @inheritdoc
7503 */
7504 OO.ui.MessageDialog.prototype.getActionProcess = function ( action ) {
7505 if ( action ) {
7506 return new OO.ui.Process( function () {
7507 this.close( { action: action } );
7508 }, this );
7509 }
7510 return OO.ui.MessageDialog.super.prototype.getActionProcess.call( this, action );
7511 };
7512
7513 /**
7514 * @inheritdoc
7515 *
7516 * @param {Object} [data] Dialog opening data
7517 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
7518 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
7519 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
7520 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
7521 * action item
7522 */
7523 OO.ui.MessageDialog.prototype.getSetupProcess = function ( data ) {
7524 data = data || {};
7525
7526 // Parent method
7527 return OO.ui.MessageDialog.super.prototype.getSetupProcess.call( this, data )
7528 .next( function () {
7529 this.title.setLabel(
7530 data.title !== undefined ? data.title : this.constructor.static.title
7531 );
7532 this.message.setLabel(
7533 data.message !== undefined ? data.message : this.constructor.static.message
7534 );
7535 this.message.$element.toggleClass(
7536 'oo-ui-messageDialog-message-verbose',
7537 data.verbose !== undefined ? data.verbose : this.constructor.static.verbose
7538 );
7539 }, this );
7540 };
7541
7542 /**
7543 * @inheritdoc
7544 */
7545 OO.ui.MessageDialog.prototype.getBodyHeight = function () {
7546 var bodyHeight, oldOverflow,
7547 $scrollable = this.container.$element;
7548
7549 oldOverflow = $scrollable[ 0 ].style.overflow;
7550 $scrollable[ 0 ].style.overflow = 'hidden';
7551
7552 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
7553
7554 bodyHeight = this.text.$element.outerHeight( true );
7555 $scrollable[ 0 ].style.overflow = oldOverflow;
7556
7557 return bodyHeight;
7558 };
7559
7560 /**
7561 * @inheritdoc
7562 */
7563 OO.ui.MessageDialog.prototype.setDimensions = function ( dim ) {
7564 var $scrollable = this.container.$element;
7565 OO.ui.MessageDialog.super.prototype.setDimensions.call( this, dim );
7566
7567 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
7568 // Need to do it after transition completes (250ms), add 50ms just in case.
7569 setTimeout( function () {
7570 var oldOverflow = $scrollable[ 0 ].style.overflow;
7571 $scrollable[ 0 ].style.overflow = 'hidden';
7572
7573 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
7574
7575 $scrollable[ 0 ].style.overflow = oldOverflow;
7576 }, 300 );
7577
7578 return this;
7579 };
7580
7581 /**
7582 * @inheritdoc
7583 */
7584 OO.ui.MessageDialog.prototype.initialize = function () {
7585 // Parent method
7586 OO.ui.MessageDialog.super.prototype.initialize.call( this );
7587
7588 // Properties
7589 this.$actions = $( '<div>' );
7590 this.container = new OO.ui.PanelLayout( {
7591 scrollable: true, classes: [ 'oo-ui-messageDialog-container' ]
7592 } );
7593 this.text = new OO.ui.PanelLayout( {
7594 padded: true, expanded: false, classes: [ 'oo-ui-messageDialog-text' ]
7595 } );
7596 this.message = new OO.ui.LabelWidget( {
7597 classes: [ 'oo-ui-messageDialog-message' ]
7598 } );
7599
7600 // Initialization
7601 this.title.$element.addClass( 'oo-ui-messageDialog-title' );
7602 this.$content.addClass( 'oo-ui-messageDialog-content' );
7603 this.container.$element.append( this.text.$element );
7604 this.text.$element.append( this.title.$element, this.message.$element );
7605 this.$body.append( this.container.$element );
7606 this.$actions.addClass( 'oo-ui-messageDialog-actions' );
7607 this.$foot.append( this.$actions );
7608 };
7609
7610 /**
7611 * @inheritdoc
7612 */
7613 OO.ui.MessageDialog.prototype.attachActions = function () {
7614 var i, len, other, special, others;
7615
7616 // Parent method
7617 OO.ui.MessageDialog.super.prototype.attachActions.call( this );
7618
7619 special = this.actions.getSpecial();
7620 others = this.actions.getOthers();
7621 if ( special.safe ) {
7622 this.$actions.append( special.safe.$element );
7623 special.safe.toggleFramed( false );
7624 }
7625 if ( others.length ) {
7626 for ( i = 0, len = others.length; i < len; i++ ) {
7627 other = others[ i ];
7628 this.$actions.append( other.$element );
7629 other.toggleFramed( false );
7630 }
7631 }
7632 if ( special.primary ) {
7633 this.$actions.append( special.primary.$element );
7634 special.primary.toggleFramed( false );
7635 }
7636
7637 if ( !this.isOpening() ) {
7638 // If the dialog is currently opening, this will be called automatically soon.
7639 // This also calls #fitActions.
7640 this.updateSize();
7641 }
7642 };
7643
7644 /**
7645 * Fit action actions into columns or rows.
7646 *
7647 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
7648 *
7649 * @private
7650 */
7651 OO.ui.MessageDialog.prototype.fitActions = function () {
7652 var i, len, action,
7653 previous = this.verticalActionLayout,
7654 actions = this.actions.get();
7655
7656 // Detect clipping
7657 this.toggleVerticalActionLayout( false );
7658 for ( i = 0, len = actions.length; i < len; i++ ) {
7659 action = actions[ i ];
7660 if ( action.$element.innerWidth() < action.$label.outerWidth( true ) ) {
7661 this.toggleVerticalActionLayout( true );
7662 break;
7663 }
7664 }
7665
7666 // Move the body out of the way of the foot
7667 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
7668
7669 if ( this.verticalActionLayout !== previous ) {
7670 // We changed the layout, window height might need to be updated.
7671 this.updateSize();
7672 }
7673 };
7674
7675 /**
7676 * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
7677 * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
7678 * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
7679 * relevant. The ProcessDialog class is always extended and customized with the actions and content
7680 * required for each process.
7681 *
7682 * The process dialog box consists of a header that visually represents the ‘working’ state of long
7683 * processes with an animation. The header contains the dialog title as well as
7684 * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
7685 * a ‘primary’ action on the right (e.g., ‘Done’).
7686 *
7687 * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
7688 * Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
7689 *
7690 * @example
7691 * // Example: Creating and opening a process dialog window.
7692 * function MyProcessDialog( config ) {
7693 * MyProcessDialog.super.call( this, config );
7694 * }
7695 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
7696 *
7697 * MyProcessDialog.static.title = 'Process dialog';
7698 * MyProcessDialog.static.actions = [
7699 * { action: 'save', label: 'Done', flags: 'primary' },
7700 * { label: 'Cancel', flags: 'safe' }
7701 * ];
7702 *
7703 * MyProcessDialog.prototype.initialize = function () {
7704 * MyProcessDialog.super.prototype.initialize.apply( this, arguments );
7705 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
7706 * this.content.$element.append( '<p>This is a process dialog window. The header contains the title and two buttons: \'Cancel\' (a safe action) on the left and \'Done\' (a primary action) on the right.</p>' );
7707 * this.$body.append( this.content.$element );
7708 * };
7709 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
7710 * var dialog = this;
7711 * if ( action ) {
7712 * return new OO.ui.Process( function () {
7713 * dialog.close( { action: action } );
7714 * } );
7715 * }
7716 * return MyProcessDialog.super.prototype.getActionProcess.call( this, action );
7717 * };
7718 *
7719 * var windowManager = new OO.ui.WindowManager();
7720 * $( 'body' ).append( windowManager.$element );
7721 *
7722 * var dialog = new MyProcessDialog();
7723 * windowManager.addWindows( [ dialog ] );
7724 * windowManager.openWindow( dialog );
7725 *
7726 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
7727 *
7728 * @abstract
7729 * @class
7730 * @extends OO.ui.Dialog
7731 *
7732 * @constructor
7733 * @param {Object} [config] Configuration options
7734 */
7735 OO.ui.ProcessDialog = function OoUiProcessDialog( config ) {
7736 // Parent constructor
7737 OO.ui.ProcessDialog.super.call( this, config );
7738
7739 // Initialization
7740 this.$element.addClass( 'oo-ui-processDialog' );
7741 };
7742
7743 /* Setup */
7744
7745 OO.inheritClass( OO.ui.ProcessDialog, OO.ui.Dialog );
7746
7747 /* Methods */
7748
7749 /**
7750 * Handle dismiss button click events.
7751 *
7752 * Hides errors.
7753 *
7754 * @private
7755 */
7756 OO.ui.ProcessDialog.prototype.onDismissErrorButtonClick = function () {
7757 this.hideErrors();
7758 };
7759
7760 /**
7761 * Handle retry button click events.
7762 *
7763 * Hides errors and then tries again.
7764 *
7765 * @private
7766 */
7767 OO.ui.ProcessDialog.prototype.onRetryButtonClick = function () {
7768 this.hideErrors();
7769 this.executeAction( this.currentAction );
7770 };
7771
7772 /**
7773 * @inheritdoc
7774 */
7775 OO.ui.ProcessDialog.prototype.onActionResize = function ( action ) {
7776 if ( this.actions.isSpecial( action ) ) {
7777 this.fitLabel();
7778 }
7779 return OO.ui.ProcessDialog.super.prototype.onActionResize.call( this, action );
7780 };
7781
7782 /**
7783 * @inheritdoc
7784 */
7785 OO.ui.ProcessDialog.prototype.initialize = function () {
7786 // Parent method
7787 OO.ui.ProcessDialog.super.prototype.initialize.call( this );
7788
7789 // Properties
7790 this.$navigation = $( '<div>' );
7791 this.$location = $( '<div>' );
7792 this.$safeActions = $( '<div>' );
7793 this.$primaryActions = $( '<div>' );
7794 this.$otherActions = $( '<div>' );
7795 this.dismissButton = new OO.ui.ButtonWidget( {
7796 label: OO.ui.msg( 'ooui-dialog-process-dismiss' )
7797 } );
7798 this.retryButton = new OO.ui.ButtonWidget();
7799 this.$errors = $( '<div>' );
7800 this.$errorsTitle = $( '<div>' );
7801
7802 // Events
7803 this.dismissButton.connect( this, { click: 'onDismissErrorButtonClick' } );
7804 this.retryButton.connect( this, { click: 'onRetryButtonClick' } );
7805
7806 // Initialization
7807 this.title.$element.addClass( 'oo-ui-processDialog-title' );
7808 this.$location
7809 .append( this.title.$element )
7810 .addClass( 'oo-ui-processDialog-location' );
7811 this.$safeActions.addClass( 'oo-ui-processDialog-actions-safe' );
7812 this.$primaryActions.addClass( 'oo-ui-processDialog-actions-primary' );
7813 this.$otherActions.addClass( 'oo-ui-processDialog-actions-other' );
7814 this.$errorsTitle
7815 .addClass( 'oo-ui-processDialog-errors-title' )
7816 .text( OO.ui.msg( 'ooui-dialog-process-error' ) );
7817 this.$errors
7818 .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
7819 .append( this.$errorsTitle, this.dismissButton.$element, this.retryButton.$element );
7820 this.$content
7821 .addClass( 'oo-ui-processDialog-content' )
7822 .append( this.$errors );
7823 this.$navigation
7824 .addClass( 'oo-ui-processDialog-navigation' )
7825 .append( this.$safeActions, this.$location, this.$primaryActions );
7826 this.$head.append( this.$navigation );
7827 this.$foot.append( this.$otherActions );
7828 };
7829
7830 /**
7831 * @inheritdoc
7832 */
7833 OO.ui.ProcessDialog.prototype.getActionWidgets = function ( actions ) {
7834 var i, len, widgets = [];
7835 for ( i = 0, len = actions.length; i < len; i++ ) {
7836 widgets.push(
7837 new OO.ui.ActionWidget( $.extend( { framed: true }, actions[ i ] ) )
7838 );
7839 }
7840 return widgets;
7841 };
7842
7843 /**
7844 * @inheritdoc
7845 */
7846 OO.ui.ProcessDialog.prototype.attachActions = function () {
7847 var i, len, other, special, others;
7848
7849 // Parent method
7850 OO.ui.ProcessDialog.super.prototype.attachActions.call( this );
7851
7852 special = this.actions.getSpecial();
7853 others = this.actions.getOthers();
7854 if ( special.primary ) {
7855 this.$primaryActions.append( special.primary.$element );
7856 }
7857 for ( i = 0, len = others.length; i < len; i++ ) {
7858 other = others[ i ];
7859 this.$otherActions.append( other.$element );
7860 }
7861 if ( special.safe ) {
7862 this.$safeActions.append( special.safe.$element );
7863 }
7864
7865 this.fitLabel();
7866 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
7867 };
7868
7869 /**
7870 * @inheritdoc
7871 */
7872 OO.ui.ProcessDialog.prototype.executeAction = function ( action ) {
7873 var process = this;
7874 return OO.ui.ProcessDialog.super.prototype.executeAction.call( this, action )
7875 .fail( function ( errors ) {
7876 process.showErrors( errors || [] );
7877 } );
7878 };
7879
7880 /**
7881 * Fit label between actions.
7882 *
7883 * @private
7884 * @chainable
7885 */
7886 OO.ui.ProcessDialog.prototype.fitLabel = function () {
7887 var width = Math.max(
7888 this.$safeActions.is( ':visible' ) ? this.$safeActions.width() : 0,
7889 this.$primaryActions.is( ':visible' ) ? this.$primaryActions.width() : 0
7890 );
7891 this.$location.css( { paddingLeft: width, paddingRight: width } );
7892
7893 return this;
7894 };
7895
7896 /**
7897 * Handle errors that occurred during accept or reject processes.
7898 *
7899 * @private
7900 * @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled
7901 */
7902 OO.ui.ProcessDialog.prototype.showErrors = function ( errors ) {
7903 var i, len, $item, actions,
7904 items = [],
7905 abilities = {},
7906 recoverable = true,
7907 warning = false;
7908
7909 if ( errors instanceof OO.ui.Error ) {
7910 errors = [ errors ];
7911 }
7912
7913 for ( i = 0, len = errors.length; i < len; i++ ) {
7914 if ( !errors[ i ].isRecoverable() ) {
7915 recoverable = false;
7916 }
7917 if ( errors[ i ].isWarning() ) {
7918 warning = true;
7919 }
7920 $item = $( '<div>' )
7921 .addClass( 'oo-ui-processDialog-error' )
7922 .append( errors[ i ].getMessage() );
7923 items.push( $item[ 0 ] );
7924 }
7925 this.$errorItems = $( items );
7926 if ( recoverable ) {
7927 abilities[this.currentAction] = true;
7928 // Copy the flags from the first matching action
7929 actions = this.actions.get( { actions: this.currentAction } );
7930 if ( actions.length ) {
7931 this.retryButton.clearFlags().setFlags( actions[0].getFlags() );
7932 }
7933 } else {
7934 abilities[this.currentAction] = false;
7935 this.actions.setAbilities( abilities );
7936 }
7937 if ( warning ) {
7938 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-continue' ) );
7939 } else {
7940 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-retry' ) );
7941 }
7942 this.retryButton.toggle( recoverable );
7943 this.$errorsTitle.after( this.$errorItems );
7944 this.$errors.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
7945 };
7946
7947 /**
7948 * Hide errors.
7949 *
7950 * @private
7951 */
7952 OO.ui.ProcessDialog.prototype.hideErrors = function () {
7953 this.$errors.addClass( 'oo-ui-element-hidden' );
7954 if ( this.$errorItems ) {
7955 this.$errorItems.remove();
7956 this.$errorItems = null;
7957 }
7958 };
7959
7960 /**
7961 * @inheritdoc
7962 */
7963 OO.ui.ProcessDialog.prototype.getTeardownProcess = function ( data ) {
7964 // Parent method
7965 return OO.ui.ProcessDialog.super.prototype.getTeardownProcess.call( this, data )
7966 .first( function () {
7967 // Make sure to hide errors
7968 this.hideErrors();
7969 }, this );
7970 };
7971
7972 /**
7973 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
7974 * which is a widget that is specified by reference before any optional configuration settings.
7975 *
7976 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
7977 *
7978 * - **left**: The label is placed before the field-widget and aligned with the left margin.
7979 * A left-alignment is used for forms with many fields.
7980 * - **right**: The label is placed before the field-widget and aligned to the right margin.
7981 * A right-alignment is used for long but familiar forms which users tab through,
7982 * verifying the current field with a quick glance at the label.
7983 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
7984 * that users fill out from top to bottom.
7985 * - **inline**: The label is placed after the field-widget and aligned to the left.
7986 * An inline-alignment is best used with checkboxes or radio buttons.
7987 *
7988 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
7989 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
7990 *
7991 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
7992 * @class
7993 * @extends OO.ui.Layout
7994 * @mixins OO.ui.LabelElement
7995 *
7996 * @constructor
7997 * @param {OO.ui.Widget} fieldWidget Field widget
7998 * @param {Object} [config] Configuration options
7999 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
8000 * @cfg {string} [help] Help text. When help text is specified, a help icon will appear
8001 * in the upper-right corner of the rendered field.
8002 */
8003 OO.ui.FieldLayout = function OoUiFieldLayout( fieldWidget, config ) {
8004 // Allow passing positional parameters inside the config object
8005 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
8006 config = fieldWidget;
8007 fieldWidget = config.fieldWidget;
8008 }
8009
8010 var hasInputWidget = fieldWidget instanceof OO.ui.InputWidget;
8011
8012 // Configuration initialization
8013 config = $.extend( { align: 'left' }, config );
8014
8015 // Parent constructor
8016 OO.ui.FieldLayout.super.call( this, config );
8017
8018 // Mixin constructors
8019 OO.ui.LabelElement.call( this, config );
8020
8021 // Properties
8022 this.fieldWidget = fieldWidget;
8023 this.$field = $( '<div>' );
8024 this.$body = $( '<' + ( hasInputWidget ? 'label' : 'div' ) + '>' );
8025 this.align = null;
8026 if ( config.help ) {
8027 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
8028 classes: [ 'oo-ui-fieldLayout-help' ],
8029 framed: false,
8030 icon: 'info'
8031 } );
8032
8033 this.popupButtonWidget.getPopup().$body.append(
8034 $( '<div>' )
8035 .text( config.help )
8036 .addClass( 'oo-ui-fieldLayout-help-content' )
8037 );
8038 this.$help = this.popupButtonWidget.$element;
8039 } else {
8040 this.$help = $( [] );
8041 }
8042
8043 // Events
8044 if ( hasInputWidget ) {
8045 this.$label.on( 'click', this.onLabelClick.bind( this ) );
8046 }
8047 this.fieldWidget.connect( this, { disable: 'onFieldDisable' } );
8048
8049 // Initialization
8050 this.$element
8051 .addClass( 'oo-ui-fieldLayout' )
8052 .append( this.$help, this.$body );
8053 this.$body.addClass( 'oo-ui-fieldLayout-body' );
8054 this.$field
8055 .addClass( 'oo-ui-fieldLayout-field' )
8056 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget.isDisabled() )
8057 .append( this.fieldWidget.$element );
8058
8059 this.setAlignment( config.align );
8060 };
8061
8062 /* Setup */
8063
8064 OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
8065 OO.mixinClass( OO.ui.FieldLayout, OO.ui.LabelElement );
8066
8067 /* Methods */
8068
8069 /**
8070 * Handle field disable events.
8071 *
8072 * @private
8073 * @param {boolean} value Field is disabled
8074 */
8075 OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
8076 this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
8077 };
8078
8079 /**
8080 * Handle label mouse click events.
8081 *
8082 * @private
8083 * @param {jQuery.Event} e Mouse click event
8084 */
8085 OO.ui.FieldLayout.prototype.onLabelClick = function () {
8086 this.fieldWidget.simulateLabelClick();
8087 return false;
8088 };
8089
8090 /**
8091 * Get the widget contained by the field.
8092 *
8093 * @return {OO.ui.Widget} Field widget
8094 */
8095 OO.ui.FieldLayout.prototype.getField = function () {
8096 return this.fieldWidget;
8097 };
8098
8099 /**
8100 * Set the field alignment mode.
8101 *
8102 * @private
8103 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
8104 * @chainable
8105 */
8106 OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
8107 if ( value !== this.align ) {
8108 // Default to 'left'
8109 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
8110 value = 'left';
8111 }
8112 // Reorder elements
8113 if ( value === 'inline' ) {
8114 this.$body.append( this.$field, this.$label );
8115 } else {
8116 this.$body.append( this.$label, this.$field );
8117 }
8118 // Set classes. The following classes can be used here:
8119 // * oo-ui-fieldLayout-align-left
8120 // * oo-ui-fieldLayout-align-right
8121 // * oo-ui-fieldLayout-align-top
8122 // * oo-ui-fieldLayout-align-inline
8123 if ( this.align ) {
8124 this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
8125 }
8126 this.$element.addClass( 'oo-ui-fieldLayout-align-' + value );
8127 this.align = value;
8128 }
8129
8130 return this;
8131 };
8132
8133 /**
8134 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
8135 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
8136 * is required and is specified before any optional configuration settings.
8137 *
8138 * Labels can be aligned in one of four ways:
8139 *
8140 * - **left**: The label is placed before the field-widget and aligned with the left margin.
8141 * A left-alignment is used for forms with many fields.
8142 * - **right**: The label is placed before the field-widget and aligned to the right margin.
8143 * A right-alignment is used for long but familiar forms which users tab through,
8144 * verifying the current field with a quick glance at the label.
8145 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
8146 * that users fill out from top to bottom.
8147 * - **inline**: The label is placed after the field-widget and aligned to the left.
8148 * An inline-alignment is best used with checkboxes or radio buttons.
8149 *
8150 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
8151 * text is specified.
8152 *
8153 * @example
8154 * // Example of an ActionFieldLayout
8155 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
8156 * new OO.ui.TextInputWidget( {
8157 * placeholder: 'Field widget'
8158 * } ),
8159 * new OO.ui.ButtonWidget( {
8160 * label: 'Button'
8161 * } ),
8162 * {
8163 * label: 'An ActionFieldLayout. This label is aligned top',
8164 * align: 'top',
8165 * help: 'This is help text'
8166 * }
8167 * );
8168 *
8169 * $( 'body' ).append( actionFieldLayout.$element );
8170 *
8171 *
8172 * @class
8173 * @extends OO.ui.FieldLayout
8174 *
8175 * @constructor
8176 * @param {OO.ui.Widget} fieldWidget Field widget
8177 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
8178 * @param {Object} [config] Configuration options
8179 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
8180 * @cfg {string} [help] Help text. When help text is specified, a help icon will appear in the
8181 * upper-right corner of the rendered field.
8182 */
8183 OO.ui.ActionFieldLayout = function OoUiActionFieldLayout( fieldWidget, buttonWidget, config ) {
8184 // Allow passing positional parameters inside the config object
8185 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
8186 config = fieldWidget;
8187 fieldWidget = config.fieldWidget;
8188 buttonWidget = config.buttonWidget;
8189 }
8190
8191 // Configuration initialization
8192 config = $.extend( { align: 'left' }, config );
8193
8194 // Parent constructor
8195 OO.ui.ActionFieldLayout.super.call( this, fieldWidget, config );
8196
8197 // Properties
8198 this.fieldWidget = fieldWidget;
8199 this.buttonWidget = buttonWidget;
8200 this.$button = $( '<div>' )
8201 .addClass( 'oo-ui-actionFieldLayout-button' )
8202 .append( this.buttonWidget.$element );
8203 this.$input = $( '<div>' )
8204 .addClass( 'oo-ui-actionFieldLayout-input' )
8205 .append( this.fieldWidget.$element );
8206 this.$field
8207 .addClass( 'oo-ui-actionFieldLayout' )
8208 .append( this.$input, this.$button );
8209 };
8210
8211 /* Setup */
8212
8213 OO.inheritClass( OO.ui.ActionFieldLayout, OO.ui.FieldLayout );
8214
8215 /**
8216 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
8217 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
8218 * configured with a label as well. For more information and examples,
8219 * please see the [OOjs UI documentation on MediaWiki][1].
8220 *
8221 * @example
8222 * // Example of a fieldset layout
8223 * var input1 = new OO.ui.TextInputWidget( {
8224 * placeholder: 'A text input field'
8225 * } );
8226 *
8227 * var input2 = new OO.ui.TextInputWidget( {
8228 * placeholder: 'A text input field'
8229 * } );
8230 *
8231 * var fieldset = new OO.ui.FieldsetLayout( {
8232 * label: 'Example of a fieldset layout'
8233 * } );
8234 *
8235 * fieldset.addItems( [
8236 * new OO.ui.FieldLayout( input1, {
8237 * label: 'Field One'
8238 * } ),
8239 * new OO.ui.FieldLayout( input2, {
8240 * label: 'Field Two'
8241 * } )
8242 * ] );
8243 * $( 'body' ).append( fieldset.$element );
8244 *
8245 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
8246 *
8247 * @class
8248 * @extends OO.ui.Layout
8249 * @mixins OO.ui.IconElement
8250 * @mixins OO.ui.LabelElement
8251 * @mixins OO.ui.GroupElement
8252 *
8253 * @constructor
8254 * @param {Object} [config] Configuration options
8255 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
8256 */
8257 OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
8258 // Configuration initialization
8259 config = config || {};
8260
8261 // Parent constructor
8262 OO.ui.FieldsetLayout.super.call( this, config );
8263
8264 // Mixin constructors
8265 OO.ui.IconElement.call( this, config );
8266 OO.ui.LabelElement.call( this, config );
8267 OO.ui.GroupElement.call( this, config );
8268
8269 if ( config.help ) {
8270 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
8271 classes: [ 'oo-ui-fieldsetLayout-help' ],
8272 framed: false,
8273 icon: 'info'
8274 } );
8275
8276 this.popupButtonWidget.getPopup().$body.append(
8277 $( '<div>' )
8278 .text( config.help )
8279 .addClass( 'oo-ui-fieldsetLayout-help-content' )
8280 );
8281 this.$help = this.popupButtonWidget.$element;
8282 } else {
8283 this.$help = $( [] );
8284 }
8285
8286 // Initialization
8287 this.$element
8288 .addClass( 'oo-ui-fieldsetLayout' )
8289 .prepend( this.$help, this.$icon, this.$label, this.$group );
8290 if ( Array.isArray( config.items ) ) {
8291 this.addItems( config.items );
8292 }
8293 };
8294
8295 /* Setup */
8296
8297 OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
8298 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.IconElement );
8299 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.LabelElement );
8300 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.GroupElement );
8301
8302 /**
8303 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
8304 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
8305 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
8306 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
8307 *
8308 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
8309 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
8310 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
8311 * some fancier controls. Some controls have both regular and InputWidget variants, for example
8312 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
8313 * often have simplified APIs to match the capabilities of HTML forms.
8314 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
8315 *
8316 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
8317 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8318 *
8319 * @example
8320 * // Example of a form layout that wraps a fieldset layout
8321 * var input1 = new OO.ui.TextInputWidget( {
8322 * placeholder: 'Username'
8323 * } );
8324 * var input2 = new OO.ui.TextInputWidget( {
8325 * placeholder: 'Password',
8326 * type: 'password'
8327 * } );
8328 * var submit = new OO.ui.ButtonInputWidget( {
8329 * label: 'Submit'
8330 * } );
8331 *
8332 * var fieldset = new OO.ui.FieldsetLayout( {
8333 * label: 'A form layout'
8334 * } );
8335 * fieldset.addItems( [
8336 * new OO.ui.FieldLayout( input1, {
8337 * label: 'Username',
8338 * align: 'top'
8339 * } ),
8340 * new OO.ui.FieldLayout( input2, {
8341 * label: 'Password',
8342 * align: 'top'
8343 * } ),
8344 * new OO.ui.FieldLayout( submit )
8345 * ] );
8346 * var form = new OO.ui.FormLayout( {
8347 * items: [ fieldset ],
8348 * action: '/api/formhandler',
8349 * method: 'get'
8350 * } )
8351 * $( 'body' ).append( form.$element );
8352 *
8353 * @class
8354 * @extends OO.ui.Layout
8355 * @mixins OO.ui.GroupElement
8356 *
8357 * @constructor
8358 * @param {Object} [config] Configuration options
8359 * @cfg {string} [method] HTML form `method` attribute
8360 * @cfg {string} [action] HTML form `action` attribute
8361 * @cfg {string} [enctype] HTML form `enctype` attribute
8362 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
8363 */
8364 OO.ui.FormLayout = function OoUiFormLayout( config ) {
8365 // Configuration initialization
8366 config = config || {};
8367
8368 // Parent constructor
8369 OO.ui.FormLayout.super.call( this, config );
8370
8371 // Mixin constructors
8372 OO.ui.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
8373
8374 // Events
8375 this.$element.on( 'submit', this.onFormSubmit.bind( this ) );
8376
8377 // Initialization
8378 this.$element
8379 .addClass( 'oo-ui-formLayout' )
8380 .attr( {
8381 method: config.method,
8382 action: config.action,
8383 enctype: config.enctype
8384 } );
8385 if ( Array.isArray( config.items ) ) {
8386 this.addItems( config.items );
8387 }
8388 };
8389
8390 /* Setup */
8391
8392 OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout );
8393 OO.mixinClass( OO.ui.FormLayout, OO.ui.GroupElement );
8394
8395 /* Events */
8396
8397 /**
8398 * A 'submit' event is emitted when the form is submitted.
8399 *
8400 * @event submit
8401 */
8402
8403 /* Static Properties */
8404
8405 OO.ui.FormLayout.static.tagName = 'form';
8406
8407 /* Methods */
8408
8409 /**
8410 * Handle form submit events.
8411 *
8412 * @private
8413 * @param {jQuery.Event} e Submit event
8414 * @fires submit
8415 */
8416 OO.ui.FormLayout.prototype.onFormSubmit = function () {
8417 this.emit( 'submit' );
8418 return false;
8419 };
8420
8421 /**
8422 * 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)
8423 * and its size is customized with the #menuSize config. The content area will fill all remaining space.
8424 *
8425 * @example
8426 * var menuLayout = new OO.ui.MenuLayout( {
8427 * position: 'top'
8428 * } ),
8429 * menuPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
8430 * contentPanel = new OO.ui.PanelLayout( { padded: true, expanded: true, scrollable: true } ),
8431 * select = new OO.ui.SelectWidget( {
8432 * items: [
8433 * new OO.ui.OptionWidget( {
8434 * data: 'before',
8435 * label: 'Before',
8436 * } ),
8437 * new OO.ui.OptionWidget( {
8438 * data: 'after',
8439 * label: 'After',
8440 * } ),
8441 * new OO.ui.OptionWidget( {
8442 * data: 'top',
8443 * label: 'Top',
8444 * } ),
8445 * new OO.ui.OptionWidget( {
8446 * data: 'bottom',
8447 * label: 'Bottom',
8448 * } )
8449 * ]
8450 * } ).on( 'select', function ( item ) {
8451 * menuLayout.setMenuPosition( item.getData() );
8452 * } );
8453 *
8454 * menuLayout.$menu.append(
8455 * menuPanel.$element.append( '<b>Menu panel</b>', select.$element )
8456 * );
8457 * menuLayout.$content.append(
8458 * contentPanel.$element.append( '<b>Content panel</b>', '<p>Note that the menu is positioned relative to the content panel: top, bottom, after, before.</p>')
8459 * );
8460 * $( 'body' ).append( menuLayout.$element );
8461 *
8462 * If menu size needs to be overridden, it can be accomplished using CSS similar to the snippet
8463 * below. MenuLayout's CSS will override the appropriate values with 'auto' or '0' to display the
8464 * menu correctly. If `menuPosition` is known beforehand, CSS rules corresponding to other positions
8465 * may be omitted.
8466 *
8467 * .oo-ui-menuLayout-menu {
8468 * height: 200px;
8469 * width: 200px;
8470 * }
8471 * .oo-ui-menuLayout-content {
8472 * top: 200px;
8473 * left: 200px;
8474 * right: 200px;
8475 * bottom: 200px;
8476 * }
8477 *
8478 * @class
8479 * @extends OO.ui.Layout
8480 *
8481 * @constructor
8482 * @param {Object} [config] Configuration options
8483 * @cfg {boolean} [showMenu=true] Show menu
8484 * @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before`
8485 */
8486 OO.ui.MenuLayout = function OoUiMenuLayout( config ) {
8487 // Configuration initialization
8488 config = $.extend( {
8489 showMenu: true,
8490 menuPosition: 'before'
8491 }, config );
8492
8493 // Parent constructor
8494 OO.ui.MenuLayout.super.call( this, config );
8495
8496 /**
8497 * Menu DOM node
8498 *
8499 * @property {jQuery}
8500 */
8501 this.$menu = $( '<div>' );
8502 /**
8503 * Content DOM node
8504 *
8505 * @property {jQuery}
8506 */
8507 this.$content = $( '<div>' );
8508
8509 // Initialization
8510 this.$menu
8511 .addClass( 'oo-ui-menuLayout-menu' );
8512 this.$content.addClass( 'oo-ui-menuLayout-content' );
8513 this.$element
8514 .addClass( 'oo-ui-menuLayout' )
8515 .append( this.$content, this.$menu );
8516 this.setMenuPosition( config.menuPosition );
8517 this.toggleMenu( config.showMenu );
8518 };
8519
8520 /* Setup */
8521
8522 OO.inheritClass( OO.ui.MenuLayout, OO.ui.Layout );
8523
8524 /* Methods */
8525
8526 /**
8527 * Toggle menu.
8528 *
8529 * @param {boolean} showMenu Show menu, omit to toggle
8530 * @chainable
8531 */
8532 OO.ui.MenuLayout.prototype.toggleMenu = function ( showMenu ) {
8533 showMenu = showMenu === undefined ? !this.showMenu : !!showMenu;
8534
8535 if ( this.showMenu !== showMenu ) {
8536 this.showMenu = showMenu;
8537 this.$element
8538 .toggleClass( 'oo-ui-menuLayout-showMenu', this.showMenu )
8539 .toggleClass( 'oo-ui-menuLayout-hideMenu', !this.showMenu );
8540 }
8541
8542 return this;
8543 };
8544
8545 /**
8546 * Check if menu is visible
8547 *
8548 * @return {boolean} Menu is visible
8549 */
8550 OO.ui.MenuLayout.prototype.isMenuVisible = function () {
8551 return this.showMenu;
8552 };
8553
8554 /**
8555 * Set menu position.
8556 *
8557 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
8558 * @throws {Error} If position value is not supported
8559 * @chainable
8560 */
8561 OO.ui.MenuLayout.prototype.setMenuPosition = function ( position ) {
8562 this.$element.removeClass( 'oo-ui-menuLayout-' + this.menuPosition );
8563 this.menuPosition = position;
8564 this.$element.addClass( 'oo-ui-menuLayout-' + position );
8565
8566 return this;
8567 };
8568
8569 /**
8570 * Get menu position.
8571 *
8572 * @return {string} Menu position
8573 */
8574 OO.ui.MenuLayout.prototype.getMenuPosition = function () {
8575 return this.menuPosition;
8576 };
8577
8578 /**
8579 * BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as
8580 * an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate
8581 * through the pages and select which one to display. By default, only one page is
8582 * displayed at a time and the outline is hidden. When a user navigates to a new page,
8583 * the booklet layout automatically focuses on the first focusable element, unless the
8584 * default setting is changed. Optionally, booklets can be configured to show
8585 * {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items.
8586 *
8587 * @example
8588 * // Example of a BookletLayout that contains two PageLayouts.
8589 *
8590 * function PageOneLayout( name, config ) {
8591 * PageOneLayout.super.call( this, name, config );
8592 * this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' );
8593 * }
8594 * OO.inheritClass( PageOneLayout, OO.ui.PageLayout );
8595 * PageOneLayout.prototype.setupOutlineItem = function () {
8596 * this.outlineItem.setLabel( 'Page One' );
8597 * };
8598 *
8599 * function PageTwoLayout( name, config ) {
8600 * PageTwoLayout.super.call( this, name, config );
8601 * this.$element.append( '<p>Second page</p>' );
8602 * }
8603 * OO.inheritClass( PageTwoLayout, OO.ui.PageLayout );
8604 * PageTwoLayout.prototype.setupOutlineItem = function () {
8605 * this.outlineItem.setLabel( 'Page Two' );
8606 * };
8607 *
8608 * var page1 = new PageOneLayout( 'one' ),
8609 * page2 = new PageTwoLayout( 'two' );
8610 *
8611 * var booklet = new OO.ui.BookletLayout( {
8612 * outlined: true
8613 * } );
8614 *
8615 * booklet.addPages ( [ page1, page2 ] );
8616 * $( 'body' ).append( booklet.$element );
8617 *
8618 * @class
8619 * @extends OO.ui.MenuLayout
8620 *
8621 * @constructor
8622 * @param {Object} [config] Configuration options
8623 * @cfg {boolean} [continuous=false] Show all pages, one after another
8624 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed.
8625 * @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet.
8626 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
8627 */
8628 OO.ui.BookletLayout = function OoUiBookletLayout( config ) {
8629 // Configuration initialization
8630 config = config || {};
8631
8632 // Parent constructor
8633 OO.ui.BookletLayout.super.call( this, config );
8634
8635 // Properties
8636 this.currentPageName = null;
8637 this.pages = {};
8638 this.ignoreFocus = false;
8639 this.stackLayout = new OO.ui.StackLayout( { continuous: !!config.continuous } );
8640 this.$content.append( this.stackLayout.$element );
8641 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
8642 this.outlineVisible = false;
8643 this.outlined = !!config.outlined;
8644 if ( this.outlined ) {
8645 this.editable = !!config.editable;
8646 this.outlineControlsWidget = null;
8647 this.outlineSelectWidget = new OO.ui.OutlineSelectWidget();
8648 this.outlinePanel = new OO.ui.PanelLayout( { scrollable: true } );
8649 this.$menu.append( this.outlinePanel.$element );
8650 this.outlineVisible = true;
8651 if ( this.editable ) {
8652 this.outlineControlsWidget = new OO.ui.OutlineControlsWidget(
8653 this.outlineSelectWidget
8654 );
8655 }
8656 }
8657 this.toggleMenu( this.outlined );
8658
8659 // Events
8660 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
8661 if ( this.outlined ) {
8662 this.outlineSelectWidget.connect( this, { select: 'onOutlineSelectWidgetSelect' } );
8663 }
8664 if ( this.autoFocus ) {
8665 // Event 'focus' does not bubble, but 'focusin' does
8666 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
8667 }
8668
8669 // Initialization
8670 this.$element.addClass( 'oo-ui-bookletLayout' );
8671 this.stackLayout.$element.addClass( 'oo-ui-bookletLayout-stackLayout' );
8672 if ( this.outlined ) {
8673 this.outlinePanel.$element
8674 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
8675 .append( this.outlineSelectWidget.$element );
8676 if ( this.editable ) {
8677 this.outlinePanel.$element
8678 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
8679 .append( this.outlineControlsWidget.$element );
8680 }
8681 }
8682 };
8683
8684 /* Setup */
8685
8686 OO.inheritClass( OO.ui.BookletLayout, OO.ui.MenuLayout );
8687
8688 /* Events */
8689
8690 /**
8691 * A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout.
8692 * @event set
8693 * @param {OO.ui.PageLayout} page Current page
8694 */
8695
8696 /**
8697 * An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout.
8698 *
8699 * @event add
8700 * @param {OO.ui.PageLayout[]} page Added pages
8701 * @param {number} index Index pages were added at
8702 */
8703
8704 /**
8705 * A 'remove' event is emitted when pages are {@link #clearPages cleared} or
8706 * {@link #removePages removed} from the booklet.
8707 *
8708 * @event remove
8709 * @param {OO.ui.PageLayout[]} pages Removed pages
8710 */
8711
8712 /* Methods */
8713
8714 /**
8715 * Handle stack layout focus.
8716 *
8717 * @private
8718 * @param {jQuery.Event} e Focusin event
8719 */
8720 OO.ui.BookletLayout.prototype.onStackLayoutFocus = function ( e ) {
8721 var name, $target;
8722
8723 // Find the page that an element was focused within
8724 $target = $( e.target ).closest( '.oo-ui-pageLayout' );
8725 for ( name in this.pages ) {
8726 // Check for page match, exclude current page to find only page changes
8727 if ( this.pages[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentPageName ) {
8728 this.setPage( name );
8729 break;
8730 }
8731 }
8732 };
8733
8734 /**
8735 * Handle stack layout set events.
8736 *
8737 * @private
8738 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
8739 */
8740 OO.ui.BookletLayout.prototype.onStackLayoutSet = function ( page ) {
8741 var layout = this;
8742 if ( page ) {
8743 page.scrollElementIntoView( { complete: function () {
8744 if ( layout.autoFocus ) {
8745 layout.focus();
8746 }
8747 } } );
8748 }
8749 };
8750
8751 /**
8752 * Focus the first input in the current page.
8753 *
8754 * If no page is selected, the first selectable page will be selected.
8755 * If the focus is already in an element on the current page, nothing will happen.
8756 * @param {number} [itemIndex] A specific item to focus on
8757 */
8758 OO.ui.BookletLayout.prototype.focus = function ( itemIndex ) {
8759 var $input, page,
8760 items = this.stackLayout.getItems();
8761
8762 if ( itemIndex !== undefined && items[ itemIndex ] ) {
8763 page = items[ itemIndex ];
8764 } else {
8765 page = this.stackLayout.getCurrentItem();
8766 }
8767
8768 if ( !page && this.outlined ) {
8769 this.selectFirstSelectablePage();
8770 page = this.stackLayout.getCurrentItem();
8771 }
8772 if ( !page ) {
8773 return;
8774 }
8775 // Only change the focus if is not already in the current page
8776 if ( !page.$element.find( ':focus' ).length ) {
8777 $input = page.$element.find( ':input:first' );
8778 if ( $input.length ) {
8779 $input[ 0 ].focus();
8780 }
8781 }
8782 };
8783
8784 /**
8785 * Find the first focusable input in the booklet layout and focus
8786 * on it.
8787 */
8788 OO.ui.BookletLayout.prototype.focusFirstFocusable = function () {
8789 var i, len,
8790 found = false,
8791 items = this.stackLayout.getItems(),
8792 checkAndFocus = function () {
8793 if ( OO.ui.isFocusableElement( $( this ) ) ) {
8794 $( this ).focus();
8795 found = true;
8796 return false;
8797 }
8798 };
8799
8800 for ( i = 0, len = items.length; i < len; i++ ) {
8801 if ( found ) {
8802 break;
8803 }
8804 // Find all potentially focusable elements in the item
8805 // and check if they are focusable
8806 items[i].$element
8807 .find( 'input, select, textarea, button, object' )
8808 /* jshint loopfunc:true */
8809 .each( checkAndFocus );
8810 }
8811 };
8812
8813 /**
8814 * Handle outline widget select events.
8815 *
8816 * @private
8817 * @param {OO.ui.OptionWidget|null} item Selected item
8818 */
8819 OO.ui.BookletLayout.prototype.onOutlineSelectWidgetSelect = function ( item ) {
8820 if ( item ) {
8821 this.setPage( item.getData() );
8822 }
8823 };
8824
8825 /**
8826 * Check if booklet has an outline.
8827 *
8828 * @return {boolean} Booklet has an outline
8829 */
8830 OO.ui.BookletLayout.prototype.isOutlined = function () {
8831 return this.outlined;
8832 };
8833
8834 /**
8835 * Check if booklet has editing controls.
8836 *
8837 * @return {boolean} Booklet is editable
8838 */
8839 OO.ui.BookletLayout.prototype.isEditable = function () {
8840 return this.editable;
8841 };
8842
8843 /**
8844 * Check if booklet has a visible outline.
8845 *
8846 * @return {boolean} Outline is visible
8847 */
8848 OO.ui.BookletLayout.prototype.isOutlineVisible = function () {
8849 return this.outlined && this.outlineVisible;
8850 };
8851
8852 /**
8853 * Hide or show the outline.
8854 *
8855 * @param {boolean} [show] Show outline, omit to invert current state
8856 * @chainable
8857 */
8858 OO.ui.BookletLayout.prototype.toggleOutline = function ( show ) {
8859 if ( this.outlined ) {
8860 show = show === undefined ? !this.outlineVisible : !!show;
8861 this.outlineVisible = show;
8862 this.toggleMenu( show );
8863 }
8864
8865 return this;
8866 };
8867
8868 /**
8869 * Get the page closest to the specified page.
8870 *
8871 * @param {OO.ui.PageLayout} page Page to use as a reference point
8872 * @return {OO.ui.PageLayout|null} Page closest to the specified page
8873 */
8874 OO.ui.BookletLayout.prototype.getClosestPage = function ( page ) {
8875 var next, prev, level,
8876 pages = this.stackLayout.getItems(),
8877 index = $.inArray( page, pages );
8878
8879 if ( index !== -1 ) {
8880 next = pages[ index + 1 ];
8881 prev = pages[ index - 1 ];
8882 // Prefer adjacent pages at the same level
8883 if ( this.outlined ) {
8884 level = this.outlineSelectWidget.getItemFromData( page.getName() ).getLevel();
8885 if (
8886 prev &&
8887 level === this.outlineSelectWidget.getItemFromData( prev.getName() ).getLevel()
8888 ) {
8889 return prev;
8890 }
8891 if (
8892 next &&
8893 level === this.outlineSelectWidget.getItemFromData( next.getName() ).getLevel()
8894 ) {
8895 return next;
8896 }
8897 }
8898 }
8899 return prev || next || null;
8900 };
8901
8902 /**
8903 * Get the outline widget.
8904 *
8905 * If the booklet is not outlined, the method will return `null`.
8906 *
8907 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
8908 */
8909 OO.ui.BookletLayout.prototype.getOutline = function () {
8910 return this.outlineSelectWidget;
8911 };
8912
8913 /**
8914 * Get the outline controls widget.
8915 *
8916 * If the outline is not editable, the method will return `null`.
8917 *
8918 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
8919 */
8920 OO.ui.BookletLayout.prototype.getOutlineControls = function () {
8921 return this.outlineControlsWidget;
8922 };
8923
8924 /**
8925 * Get a page by its symbolic name.
8926 *
8927 * @param {string} name Symbolic name of page
8928 * @return {OO.ui.PageLayout|undefined} Page, if found
8929 */
8930 OO.ui.BookletLayout.prototype.getPage = function ( name ) {
8931 return this.pages[ name ];
8932 };
8933
8934 /**
8935 * Get the current page.
8936 *
8937 * @return {OO.ui.PageLayout|undefined} Current page, if found
8938 */
8939 OO.ui.BookletLayout.prototype.getCurrentPage = function () {
8940 var name = this.getCurrentPageName();
8941 return name ? this.getPage( name ) : undefined;
8942 };
8943
8944 /**
8945 * Get the symbolic name of the current page.
8946 *
8947 * @return {string|null} Symbolic name of the current page
8948 */
8949 OO.ui.BookletLayout.prototype.getCurrentPageName = function () {
8950 return this.currentPageName;
8951 };
8952
8953 /**
8954 * Add pages to the booklet layout
8955 *
8956 * When pages are added with the same names as existing pages, the existing pages will be
8957 * automatically removed before the new pages are added.
8958 *
8959 * @param {OO.ui.PageLayout[]} pages Pages to add
8960 * @param {number} index Index of the insertion point
8961 * @fires add
8962 * @chainable
8963 */
8964 OO.ui.BookletLayout.prototype.addPages = function ( pages, index ) {
8965 var i, len, name, page, item, currentIndex,
8966 stackLayoutPages = this.stackLayout.getItems(),
8967 remove = [],
8968 items = [];
8969
8970 // Remove pages with same names
8971 for ( i = 0, len = pages.length; i < len; i++ ) {
8972 page = pages[ i ];
8973 name = page.getName();
8974
8975 if ( Object.prototype.hasOwnProperty.call( this.pages, name ) ) {
8976 // Correct the insertion index
8977 currentIndex = $.inArray( this.pages[ name ], stackLayoutPages );
8978 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
8979 index--;
8980 }
8981 remove.push( this.pages[ name ] );
8982 }
8983 }
8984 if ( remove.length ) {
8985 this.removePages( remove );
8986 }
8987
8988 // Add new pages
8989 for ( i = 0, len = pages.length; i < len; i++ ) {
8990 page = pages[ i ];
8991 name = page.getName();
8992 this.pages[ page.getName() ] = page;
8993 if ( this.outlined ) {
8994 item = new OO.ui.OutlineOptionWidget( { data: name } );
8995 page.setOutlineItem( item );
8996 items.push( item );
8997 }
8998 }
8999
9000 if ( this.outlined && items.length ) {
9001 this.outlineSelectWidget.addItems( items, index );
9002 this.selectFirstSelectablePage();
9003 }
9004 this.stackLayout.addItems( pages, index );
9005 this.emit( 'add', pages, index );
9006
9007 return this;
9008 };
9009
9010 /**
9011 * Remove the specified pages from the booklet layout.
9012 *
9013 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
9014 *
9015 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
9016 * @fires remove
9017 * @chainable
9018 */
9019 OO.ui.BookletLayout.prototype.removePages = function ( pages ) {
9020 var i, len, name, page,
9021 items = [];
9022
9023 for ( i = 0, len = pages.length; i < len; i++ ) {
9024 page = pages[ i ];
9025 name = page.getName();
9026 delete this.pages[ name ];
9027 if ( this.outlined ) {
9028 items.push( this.outlineSelectWidget.getItemFromData( name ) );
9029 page.setOutlineItem( null );
9030 }
9031 }
9032 if ( this.outlined && items.length ) {
9033 this.outlineSelectWidget.removeItems( items );
9034 this.selectFirstSelectablePage();
9035 }
9036 this.stackLayout.removeItems( pages );
9037 this.emit( 'remove', pages );
9038
9039 return this;
9040 };
9041
9042 /**
9043 * Clear all pages from the booklet layout.
9044 *
9045 * To remove only a subset of pages from the booklet, use the #removePages method.
9046 *
9047 * @fires remove
9048 * @chainable
9049 */
9050 OO.ui.BookletLayout.prototype.clearPages = function () {
9051 var i, len,
9052 pages = this.stackLayout.getItems();
9053
9054 this.pages = {};
9055 this.currentPageName = null;
9056 if ( this.outlined ) {
9057 this.outlineSelectWidget.clearItems();
9058 for ( i = 0, len = pages.length; i < len; i++ ) {
9059 pages[ i ].setOutlineItem( null );
9060 }
9061 }
9062 this.stackLayout.clearItems();
9063
9064 this.emit( 'remove', pages );
9065
9066 return this;
9067 };
9068
9069 /**
9070 * Set the current page by symbolic name.
9071 *
9072 * @fires set
9073 * @param {string} name Symbolic name of page
9074 */
9075 OO.ui.BookletLayout.prototype.setPage = function ( name ) {
9076 var selectedItem,
9077 $focused,
9078 page = this.pages[ name ];
9079
9080 if ( name !== this.currentPageName ) {
9081 if ( this.outlined ) {
9082 selectedItem = this.outlineSelectWidget.getSelectedItem();
9083 if ( selectedItem && selectedItem.getData() !== name ) {
9084 this.outlineSelectWidget.selectItem( this.outlineSelectWidget.getItemFromData( name ) );
9085 }
9086 }
9087 if ( page ) {
9088 if ( this.currentPageName && this.pages[ this.currentPageName ] ) {
9089 this.pages[ this.currentPageName ].setActive( false );
9090 // Blur anything focused if the next page doesn't have anything focusable - this
9091 // is not needed if the next page has something focusable because once it is focused
9092 // this blur happens automatically
9093 if ( this.autoFocus && !page.$element.find( ':input' ).length ) {
9094 $focused = this.pages[ this.currentPageName ].$element.find( ':focus' );
9095 if ( $focused.length ) {
9096 $focused[ 0 ].blur();
9097 }
9098 }
9099 }
9100 this.currentPageName = name;
9101 this.stackLayout.setItem( page );
9102 page.setActive( true );
9103 this.emit( 'set', page );
9104 }
9105 }
9106 };
9107
9108 /**
9109 * Select the first selectable page.
9110 *
9111 * @chainable
9112 */
9113 OO.ui.BookletLayout.prototype.selectFirstSelectablePage = function () {
9114 if ( !this.outlineSelectWidget.getSelectedItem() ) {
9115 this.outlineSelectWidget.selectItem( this.outlineSelectWidget.getFirstSelectableItem() );
9116 }
9117
9118 return this;
9119 };
9120
9121 /**
9122 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
9123 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
9124 *
9125 * @example
9126 * // Example of a panel layout
9127 * var panel = new OO.ui.PanelLayout( {
9128 * expanded: false,
9129 * framed: true,
9130 * padded: true,
9131 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
9132 * } );
9133 * $( 'body' ).append( panel.$element );
9134 *
9135 * @class
9136 * @extends OO.ui.Layout
9137 *
9138 * @constructor
9139 * @param {Object} [config] Configuration options
9140 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
9141 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
9142 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
9143 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
9144 */
9145 OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
9146 // Configuration initialization
9147 config = $.extend( {
9148 scrollable: false,
9149 padded: false,
9150 expanded: true,
9151 framed: false
9152 }, config );
9153
9154 // Parent constructor
9155 OO.ui.PanelLayout.super.call( this, config );
9156
9157 // Initialization
9158 this.$element.addClass( 'oo-ui-panelLayout' );
9159 if ( config.scrollable ) {
9160 this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
9161 }
9162 if ( config.padded ) {
9163 this.$element.addClass( 'oo-ui-panelLayout-padded' );
9164 }
9165 if ( config.expanded ) {
9166 this.$element.addClass( 'oo-ui-panelLayout-expanded' );
9167 }
9168 if ( config.framed ) {
9169 this.$element.addClass( 'oo-ui-panelLayout-framed' );
9170 }
9171 };
9172
9173 /* Setup */
9174
9175 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
9176
9177 /**
9178 * PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display
9179 * from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly,
9180 * rather extended to include the required content and functionality.
9181 *
9182 * Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline
9183 * item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See
9184 * {@link OO.ui.BookletLayout BookletLayout} for an example.
9185 *
9186 * @class
9187 * @extends OO.ui.PanelLayout
9188 *
9189 * @constructor
9190 * @param {string} name Unique symbolic name of page
9191 * @param {Object} [config] Configuration options
9192 */
9193 OO.ui.PageLayout = function OoUiPageLayout( name, config ) {
9194 // Allow passing positional parameters inside the config object
9195 if ( OO.isPlainObject( name ) && config === undefined ) {
9196 config = name;
9197 name = config.name;
9198 }
9199
9200 // Configuration initialization
9201 config = $.extend( { scrollable: true }, config );
9202
9203 // Parent constructor
9204 OO.ui.PageLayout.super.call( this, config );
9205
9206 // Properties
9207 this.name = name;
9208 this.outlineItem = null;
9209 this.active = false;
9210
9211 // Initialization
9212 this.$element.addClass( 'oo-ui-pageLayout' );
9213 };
9214
9215 /* Setup */
9216
9217 OO.inheritClass( OO.ui.PageLayout, OO.ui.PanelLayout );
9218
9219 /* Events */
9220
9221 /**
9222 * An 'active' event is emitted when the page becomes active. Pages become active when they are
9223 * shown in a booklet layout that is configured to display only one page at a time.
9224 *
9225 * @event active
9226 * @param {boolean} active Page is active
9227 */
9228
9229 /* Methods */
9230
9231 /**
9232 * Get the symbolic name of the page.
9233 *
9234 * @return {string} Symbolic name of page
9235 */
9236 OO.ui.PageLayout.prototype.getName = function () {
9237 return this.name;
9238 };
9239
9240 /**
9241 * Check if page is active.
9242 *
9243 * Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display
9244 * only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state.
9245 *
9246 * @return {boolean} Page is active
9247 */
9248 OO.ui.PageLayout.prototype.isActive = function () {
9249 return this.active;
9250 };
9251
9252 /**
9253 * Get outline item.
9254 *
9255 * The outline item allows users to access the page from the booklet's outline
9256 * navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method.
9257 *
9258 * @return {OO.ui.OutlineOptionWidget|null} Outline option widget
9259 */
9260 OO.ui.PageLayout.prototype.getOutlineItem = function () {
9261 return this.outlineItem;
9262 };
9263
9264 /**
9265 * Set or unset the outline item.
9266 *
9267 * Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it,
9268 * or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline
9269 * level), use #setupOutlineItem instead of this method.
9270 *
9271 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear
9272 * @chainable
9273 */
9274 OO.ui.PageLayout.prototype.setOutlineItem = function ( outlineItem ) {
9275 this.outlineItem = outlineItem || null;
9276 if ( outlineItem ) {
9277 this.setupOutlineItem();
9278 }
9279 return this;
9280 };
9281
9282 /**
9283 * Set up the outline item.
9284 *
9285 * Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset
9286 * the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use
9287 * the #setOutlineItem method instead.
9288 *
9289 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up
9290 * @chainable
9291 */
9292 OO.ui.PageLayout.prototype.setupOutlineItem = function () {
9293 return this;
9294 };
9295
9296 /**
9297 * Set the page to its 'active' state.
9298 *
9299 * Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional
9300 * CSS is applied to the outline item to reflect the page's active state. Outside of the booklet
9301 * context, setting the active state on a page does nothing.
9302 *
9303 * @param {boolean} value Page is active
9304 * @fires active
9305 */
9306 OO.ui.PageLayout.prototype.setActive = function ( active ) {
9307 active = !!active;
9308
9309 if ( active !== this.active ) {
9310 this.active = active;
9311 this.$element.toggleClass( 'oo-ui-pageLayout-active', active );
9312 this.emit( 'active', this.active );
9313 }
9314 };
9315
9316 /**
9317 * StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed
9318 * at a time, though the stack layout can also be configured to show all contained panels, one after another,
9319 * by setting the #continuous option to 'true'.
9320 *
9321 * @example
9322 * // A stack layout with two panels, configured to be displayed continously
9323 * var myStack = new OO.ui.StackLayout( {
9324 * items: [
9325 * new OO.ui.PanelLayout( {
9326 * $content: $( '<p>Panel One</p>' ),
9327 * padded: true,
9328 * framed: true
9329 * } ),
9330 * new OO.ui.PanelLayout( {
9331 * $content: $( '<p>Panel Two</p>' ),
9332 * padded: true,
9333 * framed: true
9334 * } )
9335 * ],
9336 * continuous: true
9337 * } );
9338 * $( 'body' ).append( myStack.$element );
9339 *
9340 * @class
9341 * @extends OO.ui.PanelLayout
9342 * @mixins OO.ui.GroupElement
9343 *
9344 * @constructor
9345 * @param {Object} [config] Configuration options
9346 * @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time.
9347 * @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout.
9348 */
9349 OO.ui.StackLayout = function OoUiStackLayout( config ) {
9350 // Configuration initialization
9351 config = $.extend( { scrollable: true }, config );
9352
9353 // Parent constructor
9354 OO.ui.StackLayout.super.call( this, config );
9355
9356 // Mixin constructors
9357 OO.ui.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
9358
9359 // Properties
9360 this.currentItem = null;
9361 this.continuous = !!config.continuous;
9362
9363 // Initialization
9364 this.$element.addClass( 'oo-ui-stackLayout' );
9365 if ( this.continuous ) {
9366 this.$element.addClass( 'oo-ui-stackLayout-continuous' );
9367 }
9368 if ( Array.isArray( config.items ) ) {
9369 this.addItems( config.items );
9370 }
9371 };
9372
9373 /* Setup */
9374
9375 OO.inheritClass( OO.ui.StackLayout, OO.ui.PanelLayout );
9376 OO.mixinClass( OO.ui.StackLayout, OO.ui.GroupElement );
9377
9378 /* Events */
9379
9380 /**
9381 * A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed},
9382 * {@link #clearItems cleared} or {@link #setItem displayed}.
9383 *
9384 * @event set
9385 * @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown
9386 */
9387
9388 /* Methods */
9389
9390 /**
9391 * Get the current panel.
9392 *
9393 * @return {OO.ui.Layout|null}
9394 */
9395 OO.ui.StackLayout.prototype.getCurrentItem = function () {
9396 return this.currentItem;
9397 };
9398
9399 /**
9400 * Unset the current item.
9401 *
9402 * @private
9403 * @param {OO.ui.StackLayout} layout
9404 * @fires set
9405 */
9406 OO.ui.StackLayout.prototype.unsetCurrentItem = function () {
9407 var prevItem = this.currentItem;
9408 if ( prevItem === null ) {
9409 return;
9410 }
9411
9412 this.currentItem = null;
9413 this.emit( 'set', null );
9414 };
9415
9416 /**
9417 * Add panel layouts to the stack layout.
9418 *
9419 * Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different
9420 * insertion point. Adding a panel that is already in the stack will move it to the end of the array or the point specified
9421 * by the index.
9422 *
9423 * @param {OO.ui.Layout[]} items Panels to add
9424 * @param {number} [index] Index of the insertion point
9425 * @chainable
9426 */
9427 OO.ui.StackLayout.prototype.addItems = function ( items, index ) {
9428 // Update the visibility
9429 this.updateHiddenState( items, this.currentItem );
9430
9431 // Mixin method
9432 OO.ui.GroupElement.prototype.addItems.call( this, items, index );
9433
9434 if ( !this.currentItem && items.length ) {
9435 this.setItem( items[ 0 ] );
9436 }
9437
9438 return this;
9439 };
9440
9441 /**
9442 * Remove the specified panels from the stack layout.
9443 *
9444 * Removed panels are detached from the DOM, not removed, so that they may be reused. To remove all panels,
9445 * you may wish to use the #clearItems method instead.
9446 *
9447 * @param {OO.ui.Layout[]} items Panels to remove
9448 * @chainable
9449 * @fires set
9450 */
9451 OO.ui.StackLayout.prototype.removeItems = function ( items ) {
9452 // Mixin method
9453 OO.ui.GroupElement.prototype.removeItems.call( this, items );
9454
9455 if ( $.inArray( this.currentItem, items ) !== -1 ) {
9456 if ( this.items.length ) {
9457 this.setItem( this.items[ 0 ] );
9458 } else {
9459 this.unsetCurrentItem();
9460 }
9461 }
9462
9463 return this;
9464 };
9465
9466 /**
9467 * Clear all panels from the stack layout.
9468 *
9469 * Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only
9470 * a subset of panels, use the #removeItems method.
9471 *
9472 * @chainable
9473 * @fires set
9474 */
9475 OO.ui.StackLayout.prototype.clearItems = function () {
9476 this.unsetCurrentItem();
9477 OO.ui.GroupElement.prototype.clearItems.call( this );
9478
9479 return this;
9480 };
9481
9482 /**
9483 * Show the specified panel.
9484 *
9485 * If another panel is currently displayed, it will be hidden.
9486 *
9487 * @param {OO.ui.Layout} item Panel to show
9488 * @chainable
9489 * @fires set
9490 */
9491 OO.ui.StackLayout.prototype.setItem = function ( item ) {
9492 if ( item !== this.currentItem ) {
9493 this.updateHiddenState( this.items, item );
9494
9495 if ( $.inArray( item, this.items ) !== -1 ) {
9496 this.currentItem = item;
9497 this.emit( 'set', item );
9498 } else {
9499 this.unsetCurrentItem();
9500 }
9501 }
9502
9503 return this;
9504 };
9505
9506 /**
9507 * Update the visibility of all items in case of non-continuous view.
9508 *
9509 * Ensure all items are hidden except for the selected one.
9510 * This method does nothing when the stack is continuous.
9511 *
9512 * @private
9513 * @param {OO.ui.Layout[]} items Item list iterate over
9514 * @param {OO.ui.Layout} [selectedItem] Selected item to show
9515 */
9516 OO.ui.StackLayout.prototype.updateHiddenState = function ( items, selectedItem ) {
9517 var i, len;
9518
9519 if ( !this.continuous ) {
9520 for ( i = 0, len = items.length; i < len; i++ ) {
9521 if ( !selectedItem || selectedItem !== items[ i ] ) {
9522 items[ i ].$element.addClass( 'oo-ui-element-hidden' );
9523 }
9524 }
9525 if ( selectedItem ) {
9526 selectedItem.$element.removeClass( 'oo-ui-element-hidden' );
9527 }
9528 }
9529 };
9530
9531 /**
9532 * Horizontal bar layout of tools as icon buttons.
9533 *
9534 * @class
9535 * @extends OO.ui.ToolGroup
9536 *
9537 * @constructor
9538 * @param {OO.ui.Toolbar} toolbar
9539 * @param {Object} [config] Configuration options
9540 */
9541 OO.ui.BarToolGroup = function OoUiBarToolGroup( toolbar, config ) {
9542 // Allow passing positional parameters inside the config object
9543 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
9544 config = toolbar;
9545 toolbar = config.toolbar;
9546 }
9547
9548 // Parent constructor
9549 OO.ui.BarToolGroup.super.call( this, toolbar, config );
9550
9551 // Initialization
9552 this.$element.addClass( 'oo-ui-barToolGroup' );
9553 };
9554
9555 /* Setup */
9556
9557 OO.inheritClass( OO.ui.BarToolGroup, OO.ui.ToolGroup );
9558
9559 /* Static Properties */
9560
9561 OO.ui.BarToolGroup.static.titleTooltips = true;
9562
9563 OO.ui.BarToolGroup.static.accelTooltips = true;
9564
9565 OO.ui.BarToolGroup.static.name = 'bar';
9566
9567 /**
9568 * Popup list of tools with an icon and optional label.
9569 *
9570 * @abstract
9571 * @class
9572 * @extends OO.ui.ToolGroup
9573 * @mixins OO.ui.IconElement
9574 * @mixins OO.ui.IndicatorElement
9575 * @mixins OO.ui.LabelElement
9576 * @mixins OO.ui.TitledElement
9577 * @mixins OO.ui.ClippableElement
9578 *
9579 * @constructor
9580 * @param {OO.ui.Toolbar} toolbar
9581 * @param {Object} [config] Configuration options
9582 * @cfg {string} [header] Text to display at the top of the pop-up
9583 */
9584 OO.ui.PopupToolGroup = function OoUiPopupToolGroup( toolbar, config ) {
9585 // Allow passing positional parameters inside the config object
9586 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
9587 config = toolbar;
9588 toolbar = config.toolbar;
9589 }
9590
9591 // Configuration initialization
9592 config = config || {};
9593
9594 // Parent constructor
9595 OO.ui.PopupToolGroup.super.call( this, toolbar, config );
9596
9597 // Mixin constructors
9598 OO.ui.IconElement.call( this, config );
9599 OO.ui.IndicatorElement.call( this, config );
9600 OO.ui.LabelElement.call( this, config );
9601 OO.ui.TitledElement.call( this, config );
9602 OO.ui.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
9603
9604 // Properties
9605 this.active = false;
9606 this.dragging = false;
9607 this.onBlurHandler = this.onBlur.bind( this );
9608 this.$handle = $( '<span>' );
9609
9610 // Events
9611 this.$handle.on( {
9612 mousedown: this.onHandlePointerDown.bind( this ),
9613 mouseup: this.onHandlePointerUp.bind( this )
9614 } );
9615
9616 // Initialization
9617 this.$handle
9618 .addClass( 'oo-ui-popupToolGroup-handle' )
9619 .append( this.$icon, this.$label, this.$indicator );
9620 // If the pop-up should have a header, add it to the top of the toolGroup.
9621 // Note: If this feature is useful for other widgets, we could abstract it into an
9622 // OO.ui.HeaderedElement mixin constructor.
9623 if ( config.header !== undefined ) {
9624 this.$group
9625 .prepend( $( '<span>' )
9626 .addClass( 'oo-ui-popupToolGroup-header' )
9627 .text( config.header )
9628 );
9629 }
9630 this.$element
9631 .addClass( 'oo-ui-popupToolGroup' )
9632 .prepend( this.$handle );
9633 };
9634
9635 /* Setup */
9636
9637 OO.inheritClass( OO.ui.PopupToolGroup, OO.ui.ToolGroup );
9638 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.IconElement );
9639 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.IndicatorElement );
9640 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.LabelElement );
9641 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.TitledElement );
9642 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.ClippableElement );
9643
9644 /* Static Properties */
9645
9646 /* Methods */
9647
9648 /**
9649 * @inheritdoc
9650 */
9651 OO.ui.PopupToolGroup.prototype.setDisabled = function () {
9652 // Parent method
9653 OO.ui.PopupToolGroup.super.prototype.setDisabled.apply( this, arguments );
9654
9655 if ( this.isDisabled() && this.isElementAttached() ) {
9656 this.setActive( false );
9657 }
9658 };
9659
9660 /**
9661 * Handle focus being lost.
9662 *
9663 * The event is actually generated from a mouseup, so it is not a normal blur event object.
9664 *
9665 * @param {jQuery.Event} e Mouse up event
9666 */
9667 OO.ui.PopupToolGroup.prototype.onBlur = function ( e ) {
9668 // Only deactivate when clicking outside the dropdown element
9669 if ( $( e.target ).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element[ 0 ] ) {
9670 this.setActive( false );
9671 }
9672 };
9673
9674 /**
9675 * @inheritdoc
9676 */
9677 OO.ui.PopupToolGroup.prototype.onPointerUp = function ( e ) {
9678 // Only close toolgroup when a tool was actually selected
9679 if ( !this.isDisabled() && e.which === 1 && this.pressed && this.pressed === this.getTargetTool( e ) ) {
9680 this.setActive( false );
9681 }
9682 return OO.ui.PopupToolGroup.super.prototype.onPointerUp.call( this, e );
9683 };
9684
9685 /**
9686 * Handle mouse up events.
9687 *
9688 * @param {jQuery.Event} e Mouse up event
9689 */
9690 OO.ui.PopupToolGroup.prototype.onHandlePointerUp = function () {
9691 return false;
9692 };
9693
9694 /**
9695 * Handle mouse down events.
9696 *
9697 * @param {jQuery.Event} e Mouse down event
9698 */
9699 OO.ui.PopupToolGroup.prototype.onHandlePointerDown = function ( e ) {
9700 if ( !this.isDisabled() && e.which === 1 ) {
9701 this.setActive( !this.active );
9702 }
9703 return false;
9704 };
9705
9706 /**
9707 * Switch into active mode.
9708 *
9709 * When active, mouseup events anywhere in the document will trigger deactivation.
9710 */
9711 OO.ui.PopupToolGroup.prototype.setActive = function ( value ) {
9712 value = !!value;
9713 if ( this.active !== value ) {
9714 this.active = value;
9715 if ( value ) {
9716 this.getElementDocument().addEventListener( 'mouseup', this.onBlurHandler, true );
9717
9718 // Try anchoring the popup to the left first
9719 this.$element.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
9720 this.toggleClipping( true );
9721 if ( this.isClippedHorizontally() ) {
9722 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
9723 this.toggleClipping( false );
9724 this.$element
9725 .removeClass( 'oo-ui-popupToolGroup-left' )
9726 .addClass( 'oo-ui-popupToolGroup-right' );
9727 this.toggleClipping( true );
9728 }
9729 } else {
9730 this.getElementDocument().removeEventListener( 'mouseup', this.onBlurHandler, true );
9731 this.$element.removeClass(
9732 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
9733 );
9734 this.toggleClipping( false );
9735 }
9736 }
9737 };
9738
9739 /**
9740 * Drop down list layout of tools as labeled icon buttons.
9741 *
9742 * This layout allows some tools to be collapsible, controlled by a "More" / "Fewer" option at the
9743 * bottom of the main list. These are not automatically positioned at the bottom of the list; you
9744 * may want to use the 'promote' and 'demote' configuration options to achieve this.
9745 *
9746 * @class
9747 * @extends OO.ui.PopupToolGroup
9748 *
9749 * @constructor
9750 * @param {OO.ui.Toolbar} toolbar
9751 * @param {Object} [config] Configuration options
9752 * @cfg {Array} [allowCollapse] List of tools that can be collapsed. Remaining tools will be always
9753 * shown.
9754 * @cfg {Array} [forceExpand] List of tools that *may not* be collapsed. All remaining tools will be
9755 * allowed to be collapsed.
9756 * @cfg {boolean} [expanded=false] Whether the collapsible tools are expanded by default
9757 */
9758 OO.ui.ListToolGroup = function OoUiListToolGroup( toolbar, config ) {
9759 // Allow passing positional parameters inside the config object
9760 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
9761 config = toolbar;
9762 toolbar = config.toolbar;
9763 }
9764
9765 // Configuration initialization
9766 config = config || {};
9767
9768 // Properties (must be set before parent constructor, which calls #populate)
9769 this.allowCollapse = config.allowCollapse;
9770 this.forceExpand = config.forceExpand;
9771 this.expanded = config.expanded !== undefined ? config.expanded : false;
9772 this.collapsibleTools = [];
9773
9774 // Parent constructor
9775 OO.ui.ListToolGroup.super.call( this, toolbar, config );
9776
9777 // Initialization
9778 this.$element.addClass( 'oo-ui-listToolGroup' );
9779 };
9780
9781 /* Setup */
9782
9783 OO.inheritClass( OO.ui.ListToolGroup, OO.ui.PopupToolGroup );
9784
9785 /* Static Properties */
9786
9787 OO.ui.ListToolGroup.static.accelTooltips = true;
9788
9789 OO.ui.ListToolGroup.static.name = 'list';
9790
9791 /* Methods */
9792
9793 /**
9794 * @inheritdoc
9795 */
9796 OO.ui.ListToolGroup.prototype.populate = function () {
9797 var i, len, allowCollapse = [];
9798
9799 OO.ui.ListToolGroup.super.prototype.populate.call( this );
9800
9801 // Update the list of collapsible tools
9802 if ( this.allowCollapse !== undefined ) {
9803 allowCollapse = this.allowCollapse;
9804 } else if ( this.forceExpand !== undefined ) {
9805 allowCollapse = OO.simpleArrayDifference( Object.keys( this.tools ), this.forceExpand );
9806 }
9807
9808 this.collapsibleTools = [];
9809 for ( i = 0, len = allowCollapse.length; i < len; i++ ) {
9810 if ( this.tools[ allowCollapse[ i ] ] !== undefined ) {
9811 this.collapsibleTools.push( this.tools[ allowCollapse[ i ] ] );
9812 }
9813 }
9814
9815 // Keep at the end, even when tools are added
9816 this.$group.append( this.getExpandCollapseTool().$element );
9817
9818 this.getExpandCollapseTool().toggle( this.collapsibleTools.length !== 0 );
9819 this.updateCollapsibleState();
9820 };
9821
9822 OO.ui.ListToolGroup.prototype.getExpandCollapseTool = function () {
9823 if ( this.expandCollapseTool === undefined ) {
9824 var ExpandCollapseTool = function () {
9825 ExpandCollapseTool.super.apply( this, arguments );
9826 };
9827
9828 OO.inheritClass( ExpandCollapseTool, OO.ui.Tool );
9829
9830 ExpandCollapseTool.prototype.onSelect = function () {
9831 this.toolGroup.expanded = !this.toolGroup.expanded;
9832 this.toolGroup.updateCollapsibleState();
9833 this.setActive( false );
9834 };
9835 ExpandCollapseTool.prototype.onUpdateState = function () {
9836 // Do nothing. Tool interface requires an implementation of this function.
9837 };
9838
9839 ExpandCollapseTool.static.name = 'more-fewer';
9840
9841 this.expandCollapseTool = new ExpandCollapseTool( this );
9842 }
9843 return this.expandCollapseTool;
9844 };
9845
9846 /**
9847 * @inheritdoc
9848 */
9849 OO.ui.ListToolGroup.prototype.onPointerUp = function ( e ) {
9850 var ret = OO.ui.ListToolGroup.super.prototype.onPointerUp.call( this, e );
9851
9852 // Do not close the popup when the user wants to show more/fewer tools
9853 if ( $( e.target ).closest( '.oo-ui-tool-name-more-fewer' ).length ) {
9854 // Prevent the popup list from being hidden
9855 this.setActive( true );
9856 }
9857
9858 return ret;
9859 };
9860
9861 OO.ui.ListToolGroup.prototype.updateCollapsibleState = function () {
9862 var i, len;
9863
9864 this.getExpandCollapseTool()
9865 .setIcon( this.expanded ? 'collapse' : 'expand' )
9866 .setTitle( OO.ui.msg( this.expanded ? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
9867
9868 for ( i = 0, len = this.collapsibleTools.length; i < len; i++ ) {
9869 this.collapsibleTools[ i ].toggle( this.expanded );
9870 }
9871 };
9872
9873 /**
9874 * Drop down menu layout of tools as selectable menu items.
9875 *
9876 * @class
9877 * @extends OO.ui.PopupToolGroup
9878 *
9879 * @constructor
9880 * @param {OO.ui.Toolbar} toolbar
9881 * @param {Object} [config] Configuration options
9882 */
9883 OO.ui.MenuToolGroup = function OoUiMenuToolGroup( toolbar, config ) {
9884 // Allow passing positional parameters inside the config object
9885 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
9886 config = toolbar;
9887 toolbar = config.toolbar;
9888 }
9889
9890 // Configuration initialization
9891 config = config || {};
9892
9893 // Parent constructor
9894 OO.ui.MenuToolGroup.super.call( this, toolbar, config );
9895
9896 // Events
9897 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
9898
9899 // Initialization
9900 this.$element.addClass( 'oo-ui-menuToolGroup' );
9901 };
9902
9903 /* Setup */
9904
9905 OO.inheritClass( OO.ui.MenuToolGroup, OO.ui.PopupToolGroup );
9906
9907 /* Static Properties */
9908
9909 OO.ui.MenuToolGroup.static.accelTooltips = true;
9910
9911 OO.ui.MenuToolGroup.static.name = 'menu';
9912
9913 /* Methods */
9914
9915 /**
9916 * Handle the toolbar state being updated.
9917 *
9918 * When the state changes, the title of each active item in the menu will be joined together and
9919 * used as a label for the group. The label will be empty if none of the items are active.
9920 */
9921 OO.ui.MenuToolGroup.prototype.onUpdateState = function () {
9922 var name,
9923 labelTexts = [];
9924
9925 for ( name in this.tools ) {
9926 if ( this.tools[ name ].isActive() ) {
9927 labelTexts.push( this.tools[ name ].getTitle() );
9928 }
9929 }
9930
9931 this.setLabel( labelTexts.join( ', ' ) || ' ' );
9932 };
9933
9934 /**
9935 * Tool that shows a popup when selected.
9936 *
9937 * @abstract
9938 * @class
9939 * @extends OO.ui.Tool
9940 * @mixins OO.ui.PopupElement
9941 *
9942 * @constructor
9943 * @param {OO.ui.ToolGroup} toolGroup
9944 * @param {Object} [config] Configuration options
9945 */
9946 OO.ui.PopupTool = function OoUiPopupTool( toolGroup, config ) {
9947 // Allow passing positional parameters inside the config object
9948 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
9949 config = toolGroup;
9950 toolGroup = config.toolGroup;
9951 }
9952
9953 // Parent constructor
9954 OO.ui.PopupTool.super.call( this, toolGroup, config );
9955
9956 // Mixin constructors
9957 OO.ui.PopupElement.call( this, config );
9958
9959 // Initialization
9960 this.$element
9961 .addClass( 'oo-ui-popupTool' )
9962 .append( this.popup.$element );
9963 };
9964
9965 /* Setup */
9966
9967 OO.inheritClass( OO.ui.PopupTool, OO.ui.Tool );
9968 OO.mixinClass( OO.ui.PopupTool, OO.ui.PopupElement );
9969
9970 /* Methods */
9971
9972 /**
9973 * Handle the tool being selected.
9974 *
9975 * @inheritdoc
9976 */
9977 OO.ui.PopupTool.prototype.onSelect = function () {
9978 if ( !this.isDisabled() ) {
9979 this.popup.toggle();
9980 }
9981 this.setActive( false );
9982 return false;
9983 };
9984
9985 /**
9986 * Handle the toolbar state being updated.
9987 *
9988 * @inheritdoc
9989 */
9990 OO.ui.PopupTool.prototype.onUpdateState = function () {
9991 this.setActive( false );
9992 };
9993
9994 /**
9995 * Tool that has a tool group inside. This is a bad workaround for the lack of proper hierarchical
9996 * menus in toolbars (T74159).
9997 *
9998 * @abstract
9999 * @class
10000 * @extends OO.ui.Tool
10001 *
10002 * @constructor
10003 * @param {OO.ui.ToolGroup} toolGroup
10004 * @param {Object} [config] Configuration options
10005 */
10006 OO.ui.ToolGroupTool = function OoUiToolGroupTool( toolGroup, config ) {
10007 // Allow passing positional parameters inside the config object
10008 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
10009 config = toolGroup;
10010 toolGroup = config.toolGroup;
10011 }
10012
10013 // Parent constructor
10014 OO.ui.ToolGroupTool.super.call( this, toolGroup, config );
10015
10016 // Properties
10017 this.innerToolGroup = this.createGroup( this.constructor.static.groupConfig );
10018
10019 // Initialization
10020 this.$link.remove();
10021 this.$element
10022 .addClass( 'oo-ui-toolGroupTool' )
10023 .append( this.innerToolGroup.$element );
10024 };
10025
10026 /* Setup */
10027
10028 OO.inheritClass( OO.ui.ToolGroupTool, OO.ui.Tool );
10029
10030 /* Static Properties */
10031
10032 /**
10033 * Tool group configuration. See OO.ui.Toolbar#setup for the accepted values.
10034 *
10035 * @property {Object.<string,Array>}
10036 */
10037 OO.ui.ToolGroupTool.static.groupConfig = {};
10038
10039 /* Methods */
10040
10041 /**
10042 * Handle the tool being selected.
10043 *
10044 * @inheritdoc
10045 */
10046 OO.ui.ToolGroupTool.prototype.onSelect = function () {
10047 this.innerToolGroup.setActive( !this.innerToolGroup.active );
10048 return false;
10049 };
10050
10051 /**
10052 * Handle the toolbar state being updated.
10053 *
10054 * @inheritdoc
10055 */
10056 OO.ui.ToolGroupTool.prototype.onUpdateState = function () {
10057 this.setActive( false );
10058 };
10059
10060 /**
10061 * Build a OO.ui.ToolGroup from the configuration.
10062 *
10063 * @param {Object.<string,Array>} group Tool group configuration. See OO.ui.Toolbar#setup for the
10064 * accepted values.
10065 * @return {OO.ui.ListToolGroup}
10066 */
10067 OO.ui.ToolGroupTool.prototype.createGroup = function ( group ) {
10068 if ( group.include === '*' ) {
10069 // Apply defaults to catch-all groups
10070 if ( group.label === undefined ) {
10071 group.label = OO.ui.msg( 'ooui-toolbar-more' );
10072 }
10073 }
10074
10075 return this.toolbar.getToolGroupFactory().create( 'list', this.toolbar, group );
10076 };
10077
10078 /**
10079 * Mixin for OO.ui.Widget subclasses to provide OO.ui.GroupElement.
10080 *
10081 * Use together with OO.ui.ItemWidget to make disabled state inheritable.
10082 *
10083 * @private
10084 * @abstract
10085 * @class
10086 * @extends OO.ui.GroupElement
10087 *
10088 * @constructor
10089 * @param {Object} [config] Configuration options
10090 */
10091 OO.ui.GroupWidget = function OoUiGroupWidget( config ) {
10092 // Parent constructor
10093 OO.ui.GroupWidget.super.call( this, config );
10094 };
10095
10096 /* Setup */
10097
10098 OO.inheritClass( OO.ui.GroupWidget, OO.ui.GroupElement );
10099
10100 /* Methods */
10101
10102 /**
10103 * Set the disabled state of the widget.
10104 *
10105 * This will also update the disabled state of child widgets.
10106 *
10107 * @param {boolean} disabled Disable widget
10108 * @chainable
10109 */
10110 OO.ui.GroupWidget.prototype.setDisabled = function ( disabled ) {
10111 var i, len;
10112
10113 // Parent method
10114 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
10115 OO.ui.Widget.prototype.setDisabled.call( this, disabled );
10116
10117 // During construction, #setDisabled is called before the OO.ui.GroupElement constructor
10118 if ( this.items ) {
10119 for ( i = 0, len = this.items.length; i < len; i++ ) {
10120 this.items[ i ].updateDisabled();
10121 }
10122 }
10123
10124 return this;
10125 };
10126
10127 /**
10128 * Mixin for widgets used as items in widgets that inherit OO.ui.GroupWidget.
10129 *
10130 * Item widgets have a reference to a OO.ui.GroupWidget while they are attached to the group. This
10131 * allows bidirectional communication.
10132 *
10133 * Use together with OO.ui.GroupWidget to make disabled state inheritable.
10134 *
10135 * @private
10136 * @abstract
10137 * @class
10138 *
10139 * @constructor
10140 */
10141 OO.ui.ItemWidget = function OoUiItemWidget() {
10142 //
10143 };
10144
10145 /* Methods */
10146
10147 /**
10148 * Check if widget is disabled.
10149 *
10150 * Checks parent if present, making disabled state inheritable.
10151 *
10152 * @return {boolean} Widget is disabled
10153 */
10154 OO.ui.ItemWidget.prototype.isDisabled = function () {
10155 return this.disabled ||
10156 ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
10157 };
10158
10159 /**
10160 * Set group element is in.
10161 *
10162 * @param {OO.ui.GroupElement|null} group Group element, null if none
10163 * @chainable
10164 */
10165 OO.ui.ItemWidget.prototype.setElementGroup = function ( group ) {
10166 // Parent method
10167 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
10168 OO.ui.Element.prototype.setElementGroup.call( this, group );
10169
10170 // Initialize item disabled states
10171 this.updateDisabled();
10172
10173 return this;
10174 };
10175
10176 /**
10177 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
10178 * Controls include moving items up and down, removing items, and adding different kinds of items.
10179 * ####Currently, this class is only used by {@link OO.ui.BookletLayout BookletLayouts}.####
10180 *
10181 * @class
10182 * @extends OO.ui.Widget
10183 * @mixins OO.ui.GroupElement
10184 * @mixins OO.ui.IconElement
10185 *
10186 * @constructor
10187 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
10188 * @param {Object} [config] Configuration options
10189 * @cfg {Object} [abilities] List of abilties
10190 * @cfg {boolean} [abilities.move=true] Allow moving movable items
10191 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
10192 */
10193 OO.ui.OutlineControlsWidget = function OoUiOutlineControlsWidget( outline, config ) {
10194 // Allow passing positional parameters inside the config object
10195 if ( OO.isPlainObject( outline ) && config === undefined ) {
10196 config = outline;
10197 outline = config.outline;
10198 }
10199
10200 // Configuration initialization
10201 config = $.extend( { icon: 'add' }, config );
10202
10203 // Parent constructor
10204 OO.ui.OutlineControlsWidget.super.call( this, config );
10205
10206 // Mixin constructors
10207 OO.ui.GroupElement.call( this, config );
10208 OO.ui.IconElement.call( this, config );
10209
10210 // Properties
10211 this.outline = outline;
10212 this.$movers = $( '<div>' );
10213 this.upButton = new OO.ui.ButtonWidget( {
10214 framed: false,
10215 icon: 'collapse',
10216 title: OO.ui.msg( 'ooui-outline-control-move-up' )
10217 } );
10218 this.downButton = new OO.ui.ButtonWidget( {
10219 framed: false,
10220 icon: 'expand',
10221 title: OO.ui.msg( 'ooui-outline-control-move-down' )
10222 } );
10223 this.removeButton = new OO.ui.ButtonWidget( {
10224 framed: false,
10225 icon: 'remove',
10226 title: OO.ui.msg( 'ooui-outline-control-remove' )
10227 } );
10228 this.abilities = { move: true, remove: true };
10229
10230 // Events
10231 outline.connect( this, {
10232 select: 'onOutlineChange',
10233 add: 'onOutlineChange',
10234 remove: 'onOutlineChange'
10235 } );
10236 this.upButton.connect( this, { click: [ 'emit', 'move', -1 ] } );
10237 this.downButton.connect( this, { click: [ 'emit', 'move', 1 ] } );
10238 this.removeButton.connect( this, { click: [ 'emit', 'remove' ] } );
10239
10240 // Initialization
10241 this.$element.addClass( 'oo-ui-outlineControlsWidget' );
10242 this.$group.addClass( 'oo-ui-outlineControlsWidget-items' );
10243 this.$movers
10244 .addClass( 'oo-ui-outlineControlsWidget-movers' )
10245 .append( this.removeButton.$element, this.upButton.$element, this.downButton.$element );
10246 this.$element.append( this.$icon, this.$group, this.$movers );
10247 this.setAbilities( config.abilities || {} );
10248 };
10249
10250 /* Setup */
10251
10252 OO.inheritClass( OO.ui.OutlineControlsWidget, OO.ui.Widget );
10253 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.GroupElement );
10254 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.IconElement );
10255
10256 /* Events */
10257
10258 /**
10259 * @event move
10260 * @param {number} places Number of places to move
10261 */
10262
10263 /**
10264 * @event remove
10265 */
10266
10267 /* Methods */
10268
10269 /**
10270 * Set abilities.
10271 *
10272 * @param {Object} abilities List of abilties
10273 * @param {boolean} [abilities.move] Allow moving movable items
10274 * @param {boolean} [abilities.remove] Allow removing removable items
10275 */
10276 OO.ui.OutlineControlsWidget.prototype.setAbilities = function ( abilities ) {
10277 var ability;
10278
10279 for ( ability in this.abilities ) {
10280 if ( abilities[ability] !== undefined ) {
10281 this.abilities[ability] = !!abilities[ability];
10282 }
10283 }
10284
10285 this.onOutlineChange();
10286 };
10287
10288 /**
10289 *
10290 * @private
10291 * Handle outline change events.
10292 */
10293 OO.ui.OutlineControlsWidget.prototype.onOutlineChange = function () {
10294 var i, len, firstMovable, lastMovable,
10295 items = this.outline.getItems(),
10296 selectedItem = this.outline.getSelectedItem(),
10297 movable = this.abilities.move && selectedItem && selectedItem.isMovable(),
10298 removable = this.abilities.remove && selectedItem && selectedItem.isRemovable();
10299
10300 if ( movable ) {
10301 i = -1;
10302 len = items.length;
10303 while ( ++i < len ) {
10304 if ( items[ i ].isMovable() ) {
10305 firstMovable = items[ i ];
10306 break;
10307 }
10308 }
10309 i = len;
10310 while ( i-- ) {
10311 if ( items[ i ].isMovable() ) {
10312 lastMovable = items[ i ];
10313 break;
10314 }
10315 }
10316 }
10317 this.upButton.setDisabled( !movable || selectedItem === firstMovable );
10318 this.downButton.setDisabled( !movable || selectedItem === lastMovable );
10319 this.removeButton.setDisabled( !removable );
10320 };
10321
10322 /**
10323 * ToggleWidget implements basic behavior of widgets with an on/off state.
10324 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
10325 *
10326 * @abstract
10327 * @class
10328 * @extends OO.ui.Widget
10329 *
10330 * @constructor
10331 * @param {Object} [config] Configuration options
10332 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
10333 * By default, the toggle is in the 'off' state.
10334 */
10335 OO.ui.ToggleWidget = function OoUiToggleWidget( config ) {
10336 // Configuration initialization
10337 config = config || {};
10338
10339 // Parent constructor
10340 OO.ui.ToggleWidget.super.call( this, config );
10341
10342 // Properties
10343 this.value = null;
10344
10345 // Initialization
10346 this.$element.addClass( 'oo-ui-toggleWidget' );
10347 this.setValue( !!config.value );
10348 };
10349
10350 /* Setup */
10351
10352 OO.inheritClass( OO.ui.ToggleWidget, OO.ui.Widget );
10353
10354 /* Events */
10355
10356 /**
10357 * @event change
10358 *
10359 * A change event is emitted when the on/off state of the toggle changes.
10360 *
10361 * @param {boolean} value Value representing the new state of the toggle
10362 */
10363
10364 /* Methods */
10365
10366 /**
10367 * Get the value representing the toggle’s state.
10368 *
10369 * @return {boolean} The on/off state of the toggle
10370 */
10371 OO.ui.ToggleWidget.prototype.getValue = function () {
10372 return this.value;
10373 };
10374
10375 /**
10376 * Set the state of the toggle: `true` for 'on', `false' for 'off'.
10377 *
10378 * @param {boolean} value The state of the toggle
10379 * @fires change
10380 * @chainable
10381 */
10382 OO.ui.ToggleWidget.prototype.setValue = function ( value ) {
10383 value = !!value;
10384 if ( this.value !== value ) {
10385 this.value = value;
10386 this.emit( 'change', value );
10387 this.$element.toggleClass( 'oo-ui-toggleWidget-on', value );
10388 this.$element.toggleClass( 'oo-ui-toggleWidget-off', !value );
10389 this.$element.attr( 'aria-checked', value.toString() );
10390 }
10391 return this;
10392 };
10393
10394 /**
10395 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
10396 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
10397 * removed, and cleared from the group.
10398 *
10399 * @example
10400 * // Example: A ButtonGroupWidget with two buttons
10401 * var button1 = new OO.ui.PopupButtonWidget( {
10402 * label: 'Select a category',
10403 * icon: 'menu',
10404 * popup: {
10405 * $content: $( '<p>List of categories...</p>' ),
10406 * padded: true,
10407 * align: 'left'
10408 * }
10409 * } );
10410 * var button2 = new OO.ui.ButtonWidget( {
10411 * label: 'Add item'
10412 * });
10413 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
10414 * items: [button1, button2]
10415 * } );
10416 * $( 'body' ).append( buttonGroup.$element );
10417 *
10418 * @class
10419 * @extends OO.ui.Widget
10420 * @mixins OO.ui.GroupElement
10421 *
10422 * @constructor
10423 * @param {Object} [config] Configuration options
10424 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
10425 */
10426 OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
10427 // Configuration initialization
10428 config = config || {};
10429
10430 // Parent constructor
10431 OO.ui.ButtonGroupWidget.super.call( this, config );
10432
10433 // Mixin constructors
10434 OO.ui.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
10435
10436 // Initialization
10437 this.$element.addClass( 'oo-ui-buttonGroupWidget' );
10438 if ( Array.isArray( config.items ) ) {
10439 this.addItems( config.items );
10440 }
10441 };
10442
10443 /* Setup */
10444
10445 OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
10446 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.GroupElement );
10447
10448 /**
10449 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
10450 * feels, and functionality can be customized via the class’s configuration options
10451 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
10452 * and examples.
10453 *
10454 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
10455 *
10456 * @example
10457 * // A button widget
10458 * var button = new OO.ui.ButtonWidget( {
10459 * label: 'Button with Icon',
10460 * icon: 'remove',
10461 * iconTitle: 'Remove'
10462 * } );
10463 * $( 'body' ).append( button.$element );
10464 *
10465 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
10466 *
10467 * @class
10468 * @extends OO.ui.Widget
10469 * @mixins OO.ui.ButtonElement
10470 * @mixins OO.ui.IconElement
10471 * @mixins OO.ui.IndicatorElement
10472 * @mixins OO.ui.LabelElement
10473 * @mixins OO.ui.TitledElement
10474 * @mixins OO.ui.FlaggedElement
10475 * @mixins OO.ui.TabIndexedElement
10476 *
10477 * @constructor
10478 * @param {Object} [config] Configuration options
10479 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
10480 * @cfg {string} [target] The frame or window in which to open the hyperlink.
10481 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
10482 */
10483 OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
10484 // Configuration initialization
10485 config = config || {};
10486
10487 // Parent constructor
10488 OO.ui.ButtonWidget.super.call( this, config );
10489
10490 // Mixin constructors
10491 OO.ui.ButtonElement.call( this, config );
10492 OO.ui.IconElement.call( this, config );
10493 OO.ui.IndicatorElement.call( this, config );
10494 OO.ui.LabelElement.call( this, config );
10495 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
10496 OO.ui.FlaggedElement.call( this, config );
10497 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
10498
10499 // Properties
10500 this.href = null;
10501 this.target = null;
10502 this.noFollow = false;
10503
10504 // Events
10505 this.connect( this, { disable: 'onDisable' } );
10506
10507 // Initialization
10508 this.$button.append( this.$icon, this.$label, this.$indicator );
10509 this.$element
10510 .addClass( 'oo-ui-buttonWidget' )
10511 .append( this.$button );
10512 this.setHref( config.href );
10513 this.setTarget( config.target );
10514 this.setNoFollow( config.noFollow );
10515 };
10516
10517 /* Setup */
10518
10519 OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
10520 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.ButtonElement );
10521 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.IconElement );
10522 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.IndicatorElement );
10523 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.LabelElement );
10524 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.TitledElement );
10525 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.FlaggedElement );
10526 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.TabIndexedElement );
10527
10528 /* Methods */
10529
10530 /**
10531 * @inheritdoc
10532 */
10533 OO.ui.ButtonWidget.prototype.onMouseDown = function ( e ) {
10534 if ( !this.isDisabled() ) {
10535 // Remove the tab-index while the button is down to prevent the button from stealing focus
10536 this.$button.removeAttr( 'tabindex' );
10537 }
10538
10539 return OO.ui.ButtonElement.prototype.onMouseDown.call( this, e );
10540 };
10541
10542 /**
10543 * @inheritdoc
10544 */
10545 OO.ui.ButtonWidget.prototype.onMouseUp = function ( e ) {
10546 if ( !this.isDisabled() ) {
10547 // Restore the tab-index after the button is up to restore the button's accessibility
10548 this.$button.attr( 'tabindex', this.tabIndex );
10549 }
10550
10551 return OO.ui.ButtonElement.prototype.onMouseUp.call( this, e );
10552 };
10553
10554 /**
10555 * @inheritdoc
10556 */
10557 OO.ui.ButtonWidget.prototype.onClick = function ( e ) {
10558 var ret = OO.ui.ButtonElement.prototype.onClick.call( this, e );
10559 if ( this.href ) {
10560 return true;
10561 }
10562 return ret;
10563 };
10564
10565 /**
10566 * @inheritdoc
10567 */
10568 OO.ui.ButtonWidget.prototype.onKeyPress = function ( e ) {
10569 var ret = OO.ui.ButtonElement.prototype.onKeyPress.call( this, e );
10570 if ( this.href ) {
10571 return true;
10572 }
10573 return ret;
10574 };
10575
10576 /**
10577 * Get hyperlink location.
10578 *
10579 * @return {string} Hyperlink location
10580 */
10581 OO.ui.ButtonWidget.prototype.getHref = function () {
10582 return this.href;
10583 };
10584
10585 /**
10586 * Get hyperlink target.
10587 *
10588 * @return {string} Hyperlink target
10589 */
10590 OO.ui.ButtonWidget.prototype.getTarget = function () {
10591 return this.target;
10592 };
10593
10594 /**
10595 * Get search engine traversal hint.
10596 *
10597 * @return {boolean} Whether search engines should avoid traversing this hyperlink
10598 */
10599 OO.ui.ButtonWidget.prototype.getNoFollow = function () {
10600 return this.noFollow;
10601 };
10602
10603 /**
10604 * Set hyperlink location.
10605 *
10606 * @param {string|null} href Hyperlink location, null to remove
10607 */
10608 OO.ui.ButtonWidget.prototype.setHref = function ( href ) {
10609 href = typeof href === 'string' ? href : null;
10610
10611 if ( href !== this.href ) {
10612 this.href = href;
10613 this.updateHref();
10614 }
10615
10616 return this;
10617 };
10618
10619 /**
10620 * Update the `href` attribute, in case of changes to href or
10621 * disabled state.
10622 *
10623 * @private
10624 * @chainable
10625 */
10626 OO.ui.ButtonWidget.prototype.updateHref = function () {
10627 if ( this.href !== null && !this.isDisabled() ) {
10628 this.$button.attr( 'href', this.href );
10629 } else {
10630 this.$button.removeAttr( 'href' );
10631 }
10632
10633 return this;
10634 };
10635
10636 /**
10637 * Handle disable events.
10638 *
10639 * @private
10640 * @param {boolean} disabled Element is disabled
10641 */
10642 OO.ui.ButtonWidget.prototype.onDisable = function () {
10643 this.updateHref();
10644 };
10645
10646 /**
10647 * Set hyperlink target.
10648 *
10649 * @param {string|null} target Hyperlink target, null to remove
10650 */
10651 OO.ui.ButtonWidget.prototype.setTarget = function ( target ) {
10652 target = typeof target === 'string' ? target : null;
10653
10654 if ( target !== this.target ) {
10655 this.target = target;
10656 if ( target !== null ) {
10657 this.$button.attr( 'target', target );
10658 } else {
10659 this.$button.removeAttr( 'target' );
10660 }
10661 }
10662
10663 return this;
10664 };
10665
10666 /**
10667 * Set search engine traversal hint.
10668 *
10669 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
10670 */
10671 OO.ui.ButtonWidget.prototype.setNoFollow = function ( noFollow ) {
10672 noFollow = typeof noFollow === 'boolean' ? noFollow : true;
10673
10674 if ( noFollow !== this.noFollow ) {
10675 this.noFollow = noFollow;
10676 if ( noFollow ) {
10677 this.$button.attr( 'rel', 'nofollow' );
10678 } else {
10679 this.$button.removeAttr( 'rel' );
10680 }
10681 }
10682
10683 return this;
10684 };
10685
10686 /**
10687 * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
10688 * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
10689 * of the actions.
10690 *
10691 * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
10692 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information
10693 * and examples.
10694 *
10695 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
10696 *
10697 * @class
10698 * @extends OO.ui.ButtonWidget
10699 * @mixins OO.ui.PendingElement
10700 *
10701 * @constructor
10702 * @param {Object} [config] Configuration options
10703 * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
10704 * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
10705 * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
10706 * for more information about setting modes.
10707 * @cfg {boolean} [framed=false] Render the action button with a frame
10708 */
10709 OO.ui.ActionWidget = function OoUiActionWidget( config ) {
10710 // Configuration initialization
10711 config = $.extend( { framed: false }, config );
10712
10713 // Parent constructor
10714 OO.ui.ActionWidget.super.call( this, config );
10715
10716 // Mixin constructors
10717 OO.ui.PendingElement.call( this, config );
10718
10719 // Properties
10720 this.action = config.action || '';
10721 this.modes = config.modes || [];
10722 this.width = 0;
10723 this.height = 0;
10724
10725 // Initialization
10726 this.$element.addClass( 'oo-ui-actionWidget' );
10727 };
10728
10729 /* Setup */
10730
10731 OO.inheritClass( OO.ui.ActionWidget, OO.ui.ButtonWidget );
10732 OO.mixinClass( OO.ui.ActionWidget, OO.ui.PendingElement );
10733
10734 /* Events */
10735
10736 /**
10737 * A resize event is emitted when the size of the widget changes.
10738 *
10739 * @event resize
10740 */
10741
10742 /* Methods */
10743
10744 /**
10745 * Check if the action is configured to be available in the specified `mode`.
10746 *
10747 * @param {string} mode Name of mode
10748 * @return {boolean} The action is configured with the mode
10749 */
10750 OO.ui.ActionWidget.prototype.hasMode = function ( mode ) {
10751 return this.modes.indexOf( mode ) !== -1;
10752 };
10753
10754 /**
10755 * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
10756 *
10757 * @return {string}
10758 */
10759 OO.ui.ActionWidget.prototype.getAction = function () {
10760 return this.action;
10761 };
10762
10763 /**
10764 * Get the symbolic name of the mode or modes for which the action is configured to be available.
10765 *
10766 * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
10767 * Only actions that are configured to be avaiable in the current mode will be visible. All other actions
10768 * are hidden.
10769 *
10770 * @return {string[]}
10771 */
10772 OO.ui.ActionWidget.prototype.getModes = function () {
10773 return this.modes.slice();
10774 };
10775
10776 /**
10777 * Emit a resize event if the size has changed.
10778 *
10779 * @private
10780 * @chainable
10781 */
10782 OO.ui.ActionWidget.prototype.propagateResize = function () {
10783 var width, height;
10784
10785 if ( this.isElementAttached() ) {
10786 width = this.$element.width();
10787 height = this.$element.height();
10788
10789 if ( width !== this.width || height !== this.height ) {
10790 this.width = width;
10791 this.height = height;
10792 this.emit( 'resize' );
10793 }
10794 }
10795
10796 return this;
10797 };
10798
10799 /**
10800 * @inheritdoc
10801 */
10802 OO.ui.ActionWidget.prototype.setIcon = function () {
10803 // Mixin method
10804 OO.ui.IconElement.prototype.setIcon.apply( this, arguments );
10805 this.propagateResize();
10806
10807 return this;
10808 };
10809
10810 /**
10811 * @inheritdoc
10812 */
10813 OO.ui.ActionWidget.prototype.setLabel = function () {
10814 // Mixin method
10815 OO.ui.LabelElement.prototype.setLabel.apply( this, arguments );
10816 this.propagateResize();
10817
10818 return this;
10819 };
10820
10821 /**
10822 * @inheritdoc
10823 */
10824 OO.ui.ActionWidget.prototype.setFlags = function () {
10825 // Mixin method
10826 OO.ui.FlaggedElement.prototype.setFlags.apply( this, arguments );
10827 this.propagateResize();
10828
10829 return this;
10830 };
10831
10832 /**
10833 * @inheritdoc
10834 */
10835 OO.ui.ActionWidget.prototype.clearFlags = function () {
10836 // Mixin method
10837 OO.ui.FlaggedElement.prototype.clearFlags.apply( this, arguments );
10838 this.propagateResize();
10839
10840 return this;
10841 };
10842
10843 /**
10844 * Toggle the visibility of the action button.
10845 *
10846 * @param {boolean} [show] Show button, omit to toggle visibility
10847 * @chainable
10848 */
10849 OO.ui.ActionWidget.prototype.toggle = function () {
10850 // Parent method
10851 OO.ui.ActionWidget.super.prototype.toggle.apply( this, arguments );
10852 this.propagateResize();
10853
10854 return this;
10855 };
10856
10857 /**
10858 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
10859 * which is used to display additional information or options.
10860 *
10861 * @example
10862 * // Example of a popup button.
10863 * var popupButton = new OO.ui.PopupButtonWidget( {
10864 * label: 'Popup button with options',
10865 * icon: 'menu',
10866 * popup: {
10867 * $content: $( '<p>Additional options here.</p>' ),
10868 * padded: true,
10869 * align: 'left'
10870 * }
10871 * } );
10872 * // Append the button to the DOM.
10873 * $( 'body' ).append( popupButton.$element );
10874 *
10875 * @class
10876 * @extends OO.ui.ButtonWidget
10877 * @mixins OO.ui.PopupElement
10878 *
10879 * @constructor
10880 * @param {Object} [config] Configuration options
10881 */
10882 OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
10883 // Parent constructor
10884 OO.ui.PopupButtonWidget.super.call( this, config );
10885
10886 // Mixin constructors
10887 OO.ui.PopupElement.call( this, config );
10888
10889 // Events
10890 this.connect( this, { click: 'onAction' } );
10891
10892 // Initialization
10893 this.$element
10894 .addClass( 'oo-ui-popupButtonWidget' )
10895 .attr( 'aria-haspopup', 'true' )
10896 .append( this.popup.$element );
10897 };
10898
10899 /* Setup */
10900
10901 OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
10902 OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.PopupElement );
10903
10904 /* Methods */
10905
10906 /**
10907 * Handle the button action being triggered.
10908 *
10909 * @private
10910 */
10911 OO.ui.PopupButtonWidget.prototype.onAction = function () {
10912 this.popup.toggle();
10913 };
10914
10915 /**
10916 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
10917 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
10918 * configured with {@link OO.ui.IconElement icons}, {@link OO.ui.IndicatorElement indicators},
10919 * {@link OO.ui.TitledElement titles}, {@link OO.ui.FlaggedElement styling flags},
10920 * and {@link OO.ui.LabelElement labels}. Please see
10921 * the [OOjs UI documentation][1] on MediaWiki for more information.
10922 *
10923 * @example
10924 * // Toggle buttons in the 'off' and 'on' state.
10925 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
10926 * label: 'Toggle Button off'
10927 * } );
10928 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
10929 * label: 'Toggle Button on',
10930 * value: true
10931 * } );
10932 * // Append the buttons to the DOM.
10933 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
10934 *
10935 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
10936 *
10937 * @class
10938 * @extends OO.ui.ToggleWidget
10939 * @mixins OO.ui.ButtonElement
10940 * @mixins OO.ui.IconElement
10941 * @mixins OO.ui.IndicatorElement
10942 * @mixins OO.ui.LabelElement
10943 * @mixins OO.ui.TitledElement
10944 * @mixins OO.ui.FlaggedElement
10945 * @mixins OO.ui.TabIndexedElement
10946 *
10947 * @constructor
10948 * @param {Object} [config] Configuration options
10949 * @cfg {boolean} [value=false] The toggle button’s initial on/off
10950 * state. By default, the button is in the 'off' state.
10951 */
10952 OO.ui.ToggleButtonWidget = function OoUiToggleButtonWidget( config ) {
10953 // Configuration initialization
10954 config = config || {};
10955
10956 // Parent constructor
10957 OO.ui.ToggleButtonWidget.super.call( this, config );
10958
10959 // Mixin constructors
10960 OO.ui.ButtonElement.call( this, config );
10961 OO.ui.IconElement.call( this, config );
10962 OO.ui.IndicatorElement.call( this, config );
10963 OO.ui.LabelElement.call( this, config );
10964 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
10965 OO.ui.FlaggedElement.call( this, config );
10966 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
10967
10968 // Events
10969 this.connect( this, { click: 'onAction' } );
10970
10971 // Initialization
10972 this.$button.append( this.$icon, this.$label, this.$indicator );
10973 this.$element
10974 .addClass( 'oo-ui-toggleButtonWidget' )
10975 .append( this.$button );
10976 };
10977
10978 /* Setup */
10979
10980 OO.inheritClass( OO.ui.ToggleButtonWidget, OO.ui.ToggleWidget );
10981 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.ButtonElement );
10982 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.IconElement );
10983 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.IndicatorElement );
10984 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.LabelElement );
10985 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.TitledElement );
10986 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.FlaggedElement );
10987 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.TabIndexedElement );
10988
10989 /* Methods */
10990
10991 /**
10992 * Handle the button action being triggered.
10993 *
10994 * @private
10995 */
10996 OO.ui.ToggleButtonWidget.prototype.onAction = function () {
10997 this.setValue( !this.value );
10998 };
10999
11000 /**
11001 * @inheritdoc
11002 */
11003 OO.ui.ToggleButtonWidget.prototype.setValue = function ( value ) {
11004 value = !!value;
11005 if ( value !== this.value ) {
11006 // Might be called from parent constructor before ButtonElement constructor
11007 if ( this.$button ) {
11008 this.$button.attr( 'aria-pressed', value.toString() );
11009 }
11010 this.setActive( value );
11011 }
11012
11013 // Parent method
11014 OO.ui.ToggleButtonWidget.super.prototype.setValue.call( this, value );
11015
11016 return this;
11017 };
11018
11019 /**
11020 * @inheritdoc
11021 */
11022 OO.ui.ToggleButtonWidget.prototype.setButtonElement = function ( $button ) {
11023 if ( this.$button ) {
11024 this.$button.removeAttr( 'aria-pressed' );
11025 }
11026 OO.ui.ButtonElement.prototype.setButtonElement.call( this, $button );
11027 this.$button.attr( 'aria-pressed', this.value.toString() );
11028 };
11029
11030 /**
11031 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
11032 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
11033 * users can interact with it.
11034 *
11035 * @example
11036 * // Example: A DropdownWidget with a menu that contains three options
11037 * var dropDown = new OO.ui.DropdownWidget( {
11038 * label: 'Dropdown menu: Select a menu option',
11039 * menu: {
11040 * items: [
11041 * new OO.ui.MenuOptionWidget( {
11042 * data: 'a',
11043 * label: 'First'
11044 * } ),
11045 * new OO.ui.MenuOptionWidget( {
11046 * data: 'b',
11047 * label: 'Second'
11048 * } ),
11049 * new OO.ui.MenuOptionWidget( {
11050 * data: 'c',
11051 * label: 'Third'
11052 * } )
11053 * ]
11054 * }
11055 * } );
11056 *
11057 * $( 'body' ).append( dropDown.$element );
11058 *
11059 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
11060 *
11061 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
11062 *
11063 * @class
11064 * @extends OO.ui.Widget
11065 * @mixins OO.ui.IconElement
11066 * @mixins OO.ui.IndicatorElement
11067 * @mixins OO.ui.LabelElement
11068 * @mixins OO.ui.TitledElement
11069 * @mixins OO.ui.TabIndexedElement
11070 *
11071 * @constructor
11072 * @param {Object} [config] Configuration options
11073 * @cfg {Object} [menu] Configuration options to pass to menu widget
11074 */
11075 OO.ui.DropdownWidget = function OoUiDropdownWidget( config ) {
11076 // Configuration initialization
11077 config = $.extend( { indicator: 'down' }, config );
11078
11079 // Parent constructor
11080 OO.ui.DropdownWidget.super.call( this, config );
11081
11082 // Properties (must be set before TabIndexedElement constructor call)
11083 this.$handle = this.$( '<span>' );
11084
11085 // Mixin constructors
11086 OO.ui.IconElement.call( this, config );
11087 OO.ui.IndicatorElement.call( this, config );
11088 OO.ui.LabelElement.call( this, config );
11089 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
11090 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
11091
11092 // Properties
11093 this.menu = new OO.ui.MenuSelectWidget( $.extend( { widget: this }, config.menu ) );
11094
11095 // Events
11096 this.$handle.on( {
11097 click: this.onClick.bind( this ),
11098 keypress: this.onKeyPress.bind( this )
11099 } );
11100 this.menu.connect( this, { select: 'onMenuSelect' } );
11101
11102 // Initialization
11103 this.$handle
11104 .addClass( 'oo-ui-dropdownWidget-handle' )
11105 .append( this.$icon, this.$label, this.$indicator );
11106 this.$element
11107 .addClass( 'oo-ui-dropdownWidget' )
11108 .append( this.$handle, this.menu.$element );
11109 };
11110
11111 /* Setup */
11112
11113 OO.inheritClass( OO.ui.DropdownWidget, OO.ui.Widget );
11114 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.IconElement );
11115 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.IndicatorElement );
11116 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.LabelElement );
11117 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.TitledElement );
11118 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.TabIndexedElement );
11119
11120 /* Methods */
11121
11122 /**
11123 * Get the menu.
11124 *
11125 * @return {OO.ui.MenuSelectWidget} Menu of widget
11126 */
11127 OO.ui.DropdownWidget.prototype.getMenu = function () {
11128 return this.menu;
11129 };
11130
11131 /**
11132 * Handles menu select events.
11133 *
11134 * @private
11135 * @param {OO.ui.MenuOptionWidget} item Selected menu item
11136 */
11137 OO.ui.DropdownWidget.prototype.onMenuSelect = function ( item ) {
11138 var selectedLabel;
11139
11140 if ( !item ) {
11141 return;
11142 }
11143
11144 selectedLabel = item.getLabel();
11145
11146 // If the label is a DOM element, clone it, because setLabel will append() it
11147 if ( selectedLabel instanceof jQuery ) {
11148 selectedLabel = selectedLabel.clone();
11149 }
11150
11151 this.setLabel( selectedLabel );
11152 };
11153
11154 /**
11155 * Handle mouse click events.
11156 *
11157 * @private
11158 * @param {jQuery.Event} e Mouse click event
11159 */
11160 OO.ui.DropdownWidget.prototype.onClick = function ( e ) {
11161 if ( !this.isDisabled() && e.which === 1 ) {
11162 this.menu.toggle();
11163 }
11164 return false;
11165 };
11166
11167 /**
11168 * Handle key press events.
11169 *
11170 * @private
11171 * @param {jQuery.Event} e Key press event
11172 */
11173 OO.ui.DropdownWidget.prototype.onKeyPress = function ( e ) {
11174 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
11175 this.menu.toggle();
11176 return false;
11177 }
11178 };
11179
11180 /**
11181 * IconWidget is a generic widget for {@link OO.ui.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
11182 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
11183 * for a list of icons included in the library.
11184 *
11185 * @example
11186 * // An icon widget with a label
11187 * var myIcon = new OO.ui.IconWidget( {
11188 * icon: 'help',
11189 * iconTitle: 'Help'
11190 * } );
11191 * // Create a label.
11192 * var iconLabel = new OO.ui.LabelWidget( {
11193 * label: 'Help'
11194 * } );
11195 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
11196 *
11197 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
11198 *
11199 * @class
11200 * @extends OO.ui.Widget
11201 * @mixins OO.ui.IconElement
11202 * @mixins OO.ui.TitledElement
11203 * @mixins OO.ui.FlaggedElement
11204 *
11205 * @constructor
11206 * @param {Object} [config] Configuration options
11207 */
11208 OO.ui.IconWidget = function OoUiIconWidget( config ) {
11209 // Configuration initialization
11210 config = config || {};
11211
11212 // Parent constructor
11213 OO.ui.IconWidget.super.call( this, config );
11214
11215 // Mixin constructors
11216 OO.ui.IconElement.call( this, $.extend( {}, config, { $icon: this.$element } ) );
11217 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
11218 OO.ui.FlaggedElement.call( this, $.extend( {}, config, { $flagged: this.$element } ) );
11219
11220 // Initialization
11221 this.$element.addClass( 'oo-ui-iconWidget' );
11222 };
11223
11224 /* Setup */
11225
11226 OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
11227 OO.mixinClass( OO.ui.IconWidget, OO.ui.IconElement );
11228 OO.mixinClass( OO.ui.IconWidget, OO.ui.TitledElement );
11229 OO.mixinClass( OO.ui.IconWidget, OO.ui.FlaggedElement );
11230
11231 /* Static Properties */
11232
11233 OO.ui.IconWidget.static.tagName = 'span';
11234
11235 /**
11236 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
11237 * attention to the status of an item or to clarify the function of a control. For a list of
11238 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
11239 *
11240 * @example
11241 * // Example of an indicator widget
11242 * var indicator1 = new OO.ui.IndicatorWidget( {
11243 * indicator: 'alert'
11244 * } );
11245 *
11246 * // Create a fieldset layout to add a label
11247 * var fieldset = new OO.ui.FieldsetLayout();
11248 * fieldset.addItems( [
11249 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
11250 * ] );
11251 * $( 'body' ).append( fieldset.$element );
11252 *
11253 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
11254 *
11255 * @class
11256 * @extends OO.ui.Widget
11257 * @mixins OO.ui.IndicatorElement
11258 * @mixins OO.ui.TitledElement
11259 *
11260 * @constructor
11261 * @param {Object} [config] Configuration options
11262 */
11263 OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
11264 // Configuration initialization
11265 config = config || {};
11266
11267 // Parent constructor
11268 OO.ui.IndicatorWidget.super.call( this, config );
11269
11270 // Mixin constructors
11271 OO.ui.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$element } ) );
11272 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
11273
11274 // Initialization
11275 this.$element.addClass( 'oo-ui-indicatorWidget' );
11276 };
11277
11278 /* Setup */
11279
11280 OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
11281 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.IndicatorElement );
11282 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.TitledElement );
11283
11284 /* Static Properties */
11285
11286 OO.ui.IndicatorWidget.static.tagName = 'span';
11287
11288 /**
11289 * InputWidget is the base class for all input widgets, which
11290 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
11291 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
11292 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
11293 *
11294 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11295 *
11296 * @abstract
11297 * @class
11298 * @extends OO.ui.Widget
11299 * @mixins OO.ui.FlaggedElement
11300 * @mixins OO.ui.TabIndexedElement
11301 *
11302 * @constructor
11303 * @param {Object} [config] Configuration options
11304 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
11305 * @cfg {string} [value=''] The value of the input.
11306 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
11307 * before it is accepted.
11308 */
11309 OO.ui.InputWidget = function OoUiInputWidget( config ) {
11310 // Configuration initialization
11311 config = config || {};
11312
11313 // Parent constructor
11314 OO.ui.InputWidget.super.call( this, config );
11315
11316 // Properties
11317 this.$input = this.getInputElement( config );
11318 this.value = '';
11319 this.inputFilter = config.inputFilter;
11320
11321 // Mixin constructors
11322 OO.ui.FlaggedElement.call( this, config );
11323 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
11324
11325 // Events
11326 this.$input.on( 'keydown mouseup cut paste change input select', this.onEdit.bind( this ) );
11327
11328 // Initialization
11329 this.$input
11330 .attr( 'name', config.name )
11331 .prop( 'disabled', this.isDisabled() );
11332 this.$element.addClass( 'oo-ui-inputWidget' ).append( this.$input, $( '<span>' ) );
11333 this.setValue( config.value );
11334 };
11335
11336 /* Setup */
11337
11338 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
11339 OO.mixinClass( OO.ui.InputWidget, OO.ui.FlaggedElement );
11340 OO.mixinClass( OO.ui.InputWidget, OO.ui.TabIndexedElement );
11341
11342 /* Events */
11343
11344 /**
11345 * @event change
11346 *
11347 * A change event is emitted when the value of the input changes.
11348 *
11349 * @param {string} value
11350 */
11351
11352 /* Methods */
11353
11354 /**
11355 * Get input element.
11356 *
11357 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
11358 * different circumstances. The element must have a `value` property (like form elements).
11359 *
11360 * @private
11361 * @param {Object} config Configuration options
11362 * @return {jQuery} Input element
11363 */
11364 OO.ui.InputWidget.prototype.getInputElement = function () {
11365 return $( '<input>' );
11366 };
11367
11368 /**
11369 * Handle potentially value-changing events.
11370 *
11371 * @private
11372 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
11373 */
11374 OO.ui.InputWidget.prototype.onEdit = function () {
11375 var widget = this;
11376 if ( !this.isDisabled() ) {
11377 // Allow the stack to clear so the value will be updated
11378 setTimeout( function () {
11379 widget.setValue( widget.$input.val() );
11380 } );
11381 }
11382 };
11383
11384 /**
11385 * Get the value of the input.
11386 *
11387 * @return {string} Input value
11388 */
11389 OO.ui.InputWidget.prototype.getValue = function () {
11390 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
11391 // it, and we won't know unless they're kind enough to trigger a 'change' event.
11392 var value = this.$input.val();
11393 if ( this.value !== value ) {
11394 this.setValue( value );
11395 }
11396 return this.value;
11397 };
11398
11399 /**
11400 * Set the direction of the input, either RTL (right-to-left) or LTR (left-to-right).
11401 *
11402 * @param {boolean} isRTL
11403 * Direction is right-to-left
11404 */
11405 OO.ui.InputWidget.prototype.setRTL = function ( isRTL ) {
11406 this.$input.prop( 'dir', isRTL ? 'rtl' : 'ltr' );
11407 };
11408
11409 /**
11410 * Set the value of the input.
11411 *
11412 * @param {string} value New value
11413 * @fires change
11414 * @chainable
11415 */
11416 OO.ui.InputWidget.prototype.setValue = function ( value ) {
11417 value = this.cleanUpValue( value );
11418 // Update the DOM if it has changed. Note that with cleanUpValue, it
11419 // is possible for the DOM value to change without this.value changing.
11420 if ( this.$input.val() !== value ) {
11421 this.$input.val( value );
11422 }
11423 if ( this.value !== value ) {
11424 this.value = value;
11425 this.emit( 'change', this.value );
11426 }
11427 return this;
11428 };
11429
11430 /**
11431 * Clean up incoming value.
11432 *
11433 * Ensures value is a string, and converts undefined and null to empty string.
11434 *
11435 * @private
11436 * @param {string} value Original value
11437 * @return {string} Cleaned up value
11438 */
11439 OO.ui.InputWidget.prototype.cleanUpValue = function ( value ) {
11440 if ( value === undefined || value === null ) {
11441 return '';
11442 } else if ( this.inputFilter ) {
11443 return this.inputFilter( String( value ) );
11444 } else {
11445 return String( value );
11446 }
11447 };
11448
11449 /**
11450 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
11451 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
11452 * called directly.
11453 */
11454 OO.ui.InputWidget.prototype.simulateLabelClick = function () {
11455 if ( !this.isDisabled() ) {
11456 if ( this.$input.is( ':checkbox, :radio' ) ) {
11457 this.$input.click();
11458 }
11459 if ( this.$input.is( ':input' ) ) {
11460 this.$input[ 0 ].focus();
11461 }
11462 }
11463 };
11464
11465 /**
11466 * @inheritdoc
11467 */
11468 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
11469 OO.ui.InputWidget.super.prototype.setDisabled.call( this, state );
11470 if ( this.$input ) {
11471 this.$input.prop( 'disabled', this.isDisabled() );
11472 }
11473 return this;
11474 };
11475
11476 /**
11477 * Focus the input.
11478 *
11479 * @chainable
11480 */
11481 OO.ui.InputWidget.prototype.focus = function () {
11482 this.$input[ 0 ].focus();
11483 return this;
11484 };
11485
11486 /**
11487 * Blur the input.
11488 *
11489 * @chainable
11490 */
11491 OO.ui.InputWidget.prototype.blur = function () {
11492 this.$input[ 0 ].blur();
11493 return this;
11494 };
11495
11496 /**
11497 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
11498 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
11499 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
11500 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
11501 * [OOjs UI documentation on MediaWiki] [1] for more information.
11502 *
11503 * @example
11504 * // A ButtonInputWidget rendered as an HTML button, the default.
11505 * var button = new OO.ui.ButtonInputWidget( {
11506 * label: 'Input button',
11507 * icon: 'check',
11508 * value: 'check'
11509 * } );
11510 * $( 'body' ).append( button.$element );
11511 *
11512 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
11513 *
11514 * @class
11515 * @extends OO.ui.InputWidget
11516 * @mixins OO.ui.ButtonElement
11517 * @mixins OO.ui.IconElement
11518 * @mixins OO.ui.IndicatorElement
11519 * @mixins OO.ui.LabelElement
11520 * @mixins OO.ui.TitledElement
11521 *
11522 * @constructor
11523 * @param {Object} [config] Configuration options
11524 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
11525 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
11526 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
11527 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
11528 * be set to `true` when there’s need to support IE6 in a form with multiple buttons.
11529 */
11530 OO.ui.ButtonInputWidget = function OoUiButtonInputWidget( config ) {
11531 // Configuration initialization
11532 config = $.extend( { type: 'button', useInputTag: false }, config );
11533
11534 // Properties (must be set before parent constructor, which calls #setValue)
11535 this.useInputTag = config.useInputTag;
11536
11537 // Parent constructor
11538 OO.ui.ButtonInputWidget.super.call( this, config );
11539
11540 // Mixin constructors
11541 OO.ui.ButtonElement.call( this, $.extend( {}, config, { $button: this.$input } ) );
11542 OO.ui.IconElement.call( this, config );
11543 OO.ui.IndicatorElement.call( this, config );
11544 OO.ui.LabelElement.call( this, config );
11545 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
11546
11547 // Initialization
11548 if ( !config.useInputTag ) {
11549 this.$input.append( this.$icon, this.$label, this.$indicator );
11550 }
11551 this.$element.addClass( 'oo-ui-buttonInputWidget' );
11552 };
11553
11554 /* Setup */
11555
11556 OO.inheritClass( OO.ui.ButtonInputWidget, OO.ui.InputWidget );
11557 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.ButtonElement );
11558 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.IconElement );
11559 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.IndicatorElement );
11560 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.LabelElement );
11561 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.TitledElement );
11562
11563 /* Methods */
11564
11565 /**
11566 * @inheritdoc
11567 * @private
11568 */
11569 OO.ui.ButtonInputWidget.prototype.getInputElement = function ( config ) {
11570 var html = '<' + ( config.useInputTag ? 'input' : 'button' ) + ' type="' + config.type + '">';
11571 return $( html );
11572 };
11573
11574 /**
11575 * Set label value.
11576 *
11577 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
11578 *
11579 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
11580 * text, or `null` for no label
11581 * @chainable
11582 */
11583 OO.ui.ButtonInputWidget.prototype.setLabel = function ( label ) {
11584 OO.ui.LabelElement.prototype.setLabel.call( this, label );
11585
11586 if ( this.useInputTag ) {
11587 if ( typeof label === 'function' ) {
11588 label = OO.ui.resolveMsg( label );
11589 }
11590 if ( label instanceof jQuery ) {
11591 label = label.text();
11592 }
11593 if ( !label ) {
11594 label = '';
11595 }
11596 this.$input.val( label );
11597 }
11598
11599 return this;
11600 };
11601
11602 /**
11603 * Set the value of the input.
11604 *
11605 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
11606 * they do not support {@link #value values}.
11607 *
11608 * @param {string} value New value
11609 * @chainable
11610 */
11611 OO.ui.ButtonInputWidget.prototype.setValue = function ( value ) {
11612 if ( !this.useInputTag ) {
11613 OO.ui.ButtonInputWidget.super.prototype.setValue.call( this, value );
11614 }
11615 return this;
11616 };
11617
11618 /**
11619 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
11620 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
11621 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
11622 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
11623 *
11624 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
11625 *
11626 * @example
11627 * // An example of selected, unselected, and disabled checkbox inputs
11628 * var checkbox1=new OO.ui.CheckboxInputWidget( {
11629 * value: 'a',
11630 * selected: true
11631 * } );
11632 * var checkbox2=new OO.ui.CheckboxInputWidget( {
11633 * value: 'b'
11634 * } );
11635 * var checkbox3=new OO.ui.CheckboxInputWidget( {
11636 * value:'c',
11637 * disabled: true
11638 * } );
11639 * // Create a fieldset layout with fields for each checkbox.
11640 * var fieldset = new OO.ui.FieldsetLayout( {
11641 * label: 'Checkboxes'
11642 * } );
11643 * fieldset.addItems( [
11644 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
11645 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
11646 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
11647 * ] );
11648 * $( 'body' ).append( fieldset.$element );
11649 *
11650 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11651 *
11652 * @class
11653 * @extends OO.ui.InputWidget
11654 *
11655 * @constructor
11656 * @param {Object} [config] Configuration options
11657 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
11658 */
11659 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
11660 // Configuration initialization
11661 config = config || {};
11662
11663 // Parent constructor
11664 OO.ui.CheckboxInputWidget.super.call( this, config );
11665
11666 // Initialization
11667 this.$element.addClass( 'oo-ui-checkboxInputWidget' );
11668 this.setSelected( config.selected !== undefined ? config.selected : false );
11669 };
11670
11671 /* Setup */
11672
11673 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
11674
11675 /* Methods */
11676
11677 /**
11678 * @inheritdoc
11679 * @private
11680 */
11681 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
11682 return $( '<input type="checkbox" />' );
11683 };
11684
11685 /**
11686 * @inheritdoc
11687 */
11688 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
11689 var widget = this;
11690 if ( !this.isDisabled() ) {
11691 // Allow the stack to clear so the value will be updated
11692 setTimeout( function () {
11693 widget.setSelected( widget.$input.prop( 'checked' ) );
11694 } );
11695 }
11696 };
11697
11698 /**
11699 * Set selection state of this checkbox.
11700 *
11701 * @param {boolean} state `true` for selected
11702 * @chainable
11703 */
11704 OO.ui.CheckboxInputWidget.prototype.setSelected = function ( state ) {
11705 state = !!state;
11706 if ( this.selected !== state ) {
11707 this.selected = state;
11708 this.$input.prop( 'checked', this.selected );
11709 this.emit( 'change', this.selected );
11710 }
11711 return this;
11712 };
11713
11714 /**
11715 * Check if this checkbox is selected.
11716 *
11717 * @return {boolean} Checkbox is selected
11718 */
11719 OO.ui.CheckboxInputWidget.prototype.isSelected = function () {
11720 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
11721 // it, and we won't know unless they're kind enough to trigger a 'change' event.
11722 var selected = this.$input.prop( 'checked' );
11723 if ( this.selected !== selected ) {
11724 this.setSelected( selected );
11725 }
11726 return this.selected;
11727 };
11728
11729 /**
11730 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
11731 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
11732 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
11733 * more information about input widgets.
11734 *
11735 * @example
11736 * // Example: A DropdownInputWidget with three options
11737 * var dropDown = new OO.ui.DropdownInputWidget( {
11738 * label: 'Dropdown menu: Select a menu option',
11739 * options: [
11740 * { data: 'a', label: 'First' } ,
11741 * { data: 'b', label: 'Second'} ,
11742 * { data: 'c', label: 'Third' }
11743 * ]
11744 * } );
11745 * $( 'body' ).append( dropDown.$element );
11746 *
11747 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11748 *
11749 * @class
11750 * @extends OO.ui.InputWidget
11751 *
11752 * @constructor
11753 * @param {Object} [config] Configuration options
11754 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
11755 */
11756 OO.ui.DropdownInputWidget = function OoUiDropdownInputWidget( config ) {
11757 // Configuration initialization
11758 config = config || {};
11759
11760 // Properties (must be done before parent constructor which calls #setDisabled)
11761 this.dropdownWidget = new OO.ui.DropdownWidget();
11762
11763 // Parent constructor
11764 OO.ui.DropdownInputWidget.super.call( this, config );
11765
11766 // Events
11767 this.dropdownWidget.getMenu().connect( this, { select: 'onMenuSelect' } );
11768
11769 // Initialization
11770 this.setOptions( config.options || [] );
11771 this.$element
11772 .addClass( 'oo-ui-dropdownInputWidget' )
11773 .append( this.dropdownWidget.$element );
11774 };
11775
11776 /* Setup */
11777
11778 OO.inheritClass( OO.ui.DropdownInputWidget, OO.ui.InputWidget );
11779
11780 /* Methods */
11781
11782 /**
11783 * @inheritdoc
11784 * @private
11785 */
11786 OO.ui.DropdownInputWidget.prototype.getInputElement = function () {
11787 return $( '<input type="hidden">' );
11788 };
11789
11790 /**
11791 * Handles menu select events.
11792 *
11793 * @private
11794 * @param {OO.ui.MenuOptionWidget} item Selected menu item
11795 */
11796 OO.ui.DropdownInputWidget.prototype.onMenuSelect = function ( item ) {
11797 this.setValue( item.getData() );
11798 };
11799
11800 /**
11801 * @inheritdoc
11802 */
11803 OO.ui.DropdownInputWidget.prototype.setValue = function ( value ) {
11804 var item = this.dropdownWidget.getMenu().getItemFromData( value );
11805 if ( item ) {
11806 this.dropdownWidget.getMenu().selectItem( item );
11807 }
11808 OO.ui.DropdownInputWidget.super.prototype.setValue.call( this, value );
11809 return this;
11810 };
11811
11812 /**
11813 * @inheritdoc
11814 */
11815 OO.ui.DropdownInputWidget.prototype.setDisabled = function ( state ) {
11816 this.dropdownWidget.setDisabled( state );
11817 OO.ui.DropdownInputWidget.super.prototype.setDisabled.call( this, state );
11818 return this;
11819 };
11820
11821 /**
11822 * Set the options available for this input.
11823 *
11824 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
11825 * @chainable
11826 */
11827 OO.ui.DropdownInputWidget.prototype.setOptions = function ( options ) {
11828 var value = this.getValue();
11829
11830 // Rebuild the dropdown menu
11831 this.dropdownWidget.getMenu()
11832 .clearItems()
11833 .addItems( options.map( function ( opt ) {
11834 return new OO.ui.MenuOptionWidget( {
11835 data: opt.data,
11836 label: opt.label !== undefined ? opt.label : opt.data
11837 } );
11838 } ) );
11839
11840 // Restore the previous value, or reset to something sensible
11841 if ( this.dropdownWidget.getMenu().getItemFromData( value ) ) {
11842 // Previous value is still available, ensure consistency with the dropdown
11843 this.setValue( value );
11844 } else {
11845 // No longer valid, reset
11846 if ( options.length ) {
11847 this.setValue( options[ 0 ].data );
11848 }
11849 }
11850
11851 return this;
11852 };
11853
11854 /**
11855 * @inheritdoc
11856 */
11857 OO.ui.DropdownInputWidget.prototype.focus = function () {
11858 this.dropdownWidget.getMenu().toggle( true );
11859 return this;
11860 };
11861
11862 /**
11863 * @inheritdoc
11864 */
11865 OO.ui.DropdownInputWidget.prototype.blur = function () {
11866 this.dropdownWidget.getMenu().toggle( false );
11867 return this;
11868 };
11869
11870 /**
11871 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
11872 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
11873 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
11874 * please see the [OOjs UI documentation on MediaWiki][1].
11875 *
11876 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
11877 *
11878 * @example
11879 * // An example of selected, unselected, and disabled radio inputs
11880 * var radio1 = new OO.ui.RadioInputWidget( {
11881 * value: 'a',
11882 * selected: true
11883 * } );
11884 * var radio2 = new OO.ui.RadioInputWidget( {
11885 * value: 'b'
11886 * } );
11887 * var radio3 = new OO.ui.RadioInputWidget( {
11888 * value: 'c',
11889 * disabled: true
11890 * } );
11891 * // Create a fieldset layout with fields for each radio button.
11892 * var fieldset = new OO.ui.FieldsetLayout( {
11893 * label: 'Radio inputs'
11894 * } );
11895 * fieldset.addItems( [
11896 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
11897 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
11898 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
11899 * ] );
11900 * $( 'body' ).append( fieldset.$element );
11901 *
11902 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11903 *
11904 * @class
11905 * @extends OO.ui.InputWidget
11906 *
11907 * @constructor
11908 * @param {Object} [config] Configuration options
11909 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
11910 */
11911 OO.ui.RadioInputWidget = function OoUiRadioInputWidget( config ) {
11912 // Configuration initialization
11913 config = config || {};
11914
11915 // Parent constructor
11916 OO.ui.RadioInputWidget.super.call( this, config );
11917
11918 // Initialization
11919 this.$element.addClass( 'oo-ui-radioInputWidget' );
11920 this.setSelected( config.selected !== undefined ? config.selected : false );
11921 };
11922
11923 /* Setup */
11924
11925 OO.inheritClass( OO.ui.RadioInputWidget, OO.ui.InputWidget );
11926
11927 /* Methods */
11928
11929 /**
11930 * @inheritdoc
11931 * @private
11932 */
11933 OO.ui.RadioInputWidget.prototype.getInputElement = function () {
11934 return $( '<input type="radio" />' );
11935 };
11936
11937 /**
11938 * @inheritdoc
11939 */
11940 OO.ui.RadioInputWidget.prototype.onEdit = function () {
11941 // RadioInputWidget doesn't track its state.
11942 };
11943
11944 /**
11945 * Set selection state of this radio button.
11946 *
11947 * @param {boolean} state `true` for selected
11948 * @chainable
11949 */
11950 OO.ui.RadioInputWidget.prototype.setSelected = function ( state ) {
11951 // RadioInputWidget doesn't track its state.
11952 this.$input.prop( 'checked', state );
11953 return this;
11954 };
11955
11956 /**
11957 * Check if this radio button is selected.
11958 *
11959 * @return {boolean} Radio is selected
11960 */
11961 OO.ui.RadioInputWidget.prototype.isSelected = function () {
11962 return this.$input.prop( 'checked' );
11963 };
11964
11965 /**
11966 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
11967 * size of the field as well as its presentation. In addition, these widgets can be configured
11968 * with {@link OO.ui.IconElement icons}, {@link OO.ui.IndicatorElement indicators}, an optional
11969 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
11970 * which modifies incoming values rather than validating them.
11971 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
11972 *
11973 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
11974 *
11975 * @example
11976 * // Example of a text input widget
11977 * var textInput = new OO.ui.TextInputWidget( {
11978 * value: 'Text input'
11979 * } )
11980 * $( 'body' ).append( textInput.$element );
11981 *
11982 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11983 *
11984 * @class
11985 * @extends OO.ui.InputWidget
11986 * @mixins OO.ui.IconElement
11987 * @mixins OO.ui.IndicatorElement
11988 * @mixins OO.ui.PendingElement
11989 * @mixins OO.ui.LabelElement
11990 *
11991 * @constructor
11992 * @param {Object} [config] Configuration options
11993 * @cfg {string} [type='text'] The value of the HTML `type` attribute
11994 * @cfg {string} [placeholder] Placeholder text
11995 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
11996 * instruct the browser to focus this widget.
11997 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
11998 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
11999 * @cfg {boolean} [multiline=false] Allow multiple lines of text
12000 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
12001 * Use the #maxRows config to specify a maximum number of displayed rows.
12002 * @cfg {boolean} [maxRows=10] Maximum number of rows to display when #autosize is set to true.
12003 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
12004 * the value or placeholder text: `'before'` or `'after'`
12005 * @cfg {boolean} [required=false] Mark the field as required
12006 * @cfg {RegExp|string} [validate] Validation pattern, either a regular expression or the
12007 * symbolic name of a pattern defined by the class: 'non-empty' (the value cannot be an empty string)
12008 * or 'integer' (the value must contain only numbers).
12009 */
12010 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
12011 // Configuration initialization
12012 config = $.extend( {
12013 type: 'text',
12014 labelPosition: 'after',
12015 maxRows: 10
12016 }, config );
12017
12018 // Parent constructor
12019 OO.ui.TextInputWidget.super.call( this, config );
12020
12021 // Mixin constructors
12022 OO.ui.IconElement.call( this, config );
12023 OO.ui.IndicatorElement.call( this, config );
12024 OO.ui.PendingElement.call( this, config );
12025 OO.ui.LabelElement.call( this, config );
12026
12027 // Properties
12028 this.readOnly = false;
12029 this.multiline = !!config.multiline;
12030 this.autosize = !!config.autosize;
12031 this.maxRows = config.maxRows;
12032 this.validate = null;
12033
12034 // Clone for resizing
12035 if ( this.autosize ) {
12036 this.$clone = this.$input
12037 .clone()
12038 .insertAfter( this.$input )
12039 .attr( 'aria-hidden', 'true' )
12040 .addClass( 'oo-ui-element-hidden' );
12041 }
12042
12043 this.setValidation( config.validate );
12044 this.setLabelPosition( config.labelPosition );
12045
12046 // Events
12047 this.$input.on( {
12048 keypress: this.onKeyPress.bind( this ),
12049 blur: this.setValidityFlag.bind( this )
12050 } );
12051 this.$input.one( {
12052 focus: this.onElementAttach.bind( this )
12053 } );
12054 this.$icon.on( 'mousedown', this.onIconMouseDown.bind( this ) );
12055 this.$indicator.on( 'mousedown', this.onIndicatorMouseDown.bind( this ) );
12056 this.on( 'labelChange', this.updatePosition.bind( this ) );
12057
12058 // Initialization
12059 this.$element
12060 .addClass( 'oo-ui-textInputWidget' )
12061 .append( this.$icon, this.$indicator );
12062 this.setReadOnly( !!config.readOnly );
12063 if ( config.placeholder ) {
12064 this.$input.attr( 'placeholder', config.placeholder );
12065 }
12066 if ( config.maxLength !== undefined ) {
12067 this.$input.attr( 'maxlength', config.maxLength );
12068 }
12069 if ( config.autofocus ) {
12070 this.$input.attr( 'autofocus', 'autofocus' );
12071 }
12072 if ( config.required ) {
12073 this.$input.attr( 'required', 'true' );
12074 }
12075 if ( this.label || config.autosize ) {
12076 this.installParentChangeDetector();
12077 }
12078 };
12079
12080 /* Setup */
12081
12082 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
12083 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.IconElement );
12084 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.IndicatorElement );
12085 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.PendingElement );
12086 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.LabelElement );
12087
12088 /* Static properties */
12089
12090 OO.ui.TextInputWidget.static.validationPatterns = {
12091 'non-empty': /.+/,
12092 integer: /^\d+$/
12093 };
12094
12095 /* Events */
12096
12097 /**
12098 * An `enter` event is emitted when the user presses 'enter' inside the text box.
12099 *
12100 * Not emitted if the input is multiline.
12101 *
12102 * @event enter
12103 */
12104
12105 /* Methods */
12106
12107 /**
12108 * Handle icon mouse down events.
12109 *
12110 * @private
12111 * @param {jQuery.Event} e Mouse down event
12112 * @fires icon
12113 */
12114 OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) {
12115 if ( e.which === 1 ) {
12116 this.$input[ 0 ].focus();
12117 return false;
12118 }
12119 };
12120
12121 /**
12122 * Handle indicator mouse down events.
12123 *
12124 * @private
12125 * @param {jQuery.Event} e Mouse down event
12126 * @fires indicator
12127 */
12128 OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
12129 if ( e.which === 1 ) {
12130 this.$input[ 0 ].focus();
12131 return false;
12132 }
12133 };
12134
12135 /**
12136 * Handle key press events.
12137 *
12138 * @private
12139 * @param {jQuery.Event} e Key press event
12140 * @fires enter If enter key is pressed and input is not multiline
12141 */
12142 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
12143 if ( e.which === OO.ui.Keys.ENTER && !this.multiline ) {
12144 this.emit( 'enter', e );
12145 }
12146 };
12147
12148 /**
12149 * Handle element attach events.
12150 *
12151 * @private
12152 * @param {jQuery.Event} e Element attach event
12153 */
12154 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
12155 // Any previously calculated size is now probably invalid if we reattached elsewhere
12156 this.valCache = null;
12157 this.adjustSize();
12158 this.positionLabel();
12159 };
12160
12161 /**
12162 * @inheritdoc
12163 */
12164 OO.ui.TextInputWidget.prototype.onEdit = function () {
12165 this.adjustSize();
12166
12167 // Parent method
12168 return OO.ui.TextInputWidget.super.prototype.onEdit.call( this );
12169 };
12170
12171 /**
12172 * @inheritdoc
12173 */
12174 OO.ui.TextInputWidget.prototype.setValue = function ( value ) {
12175 // Parent method
12176 OO.ui.TextInputWidget.super.prototype.setValue.call( this, value );
12177
12178 this.setValidityFlag();
12179 this.adjustSize();
12180 return this;
12181 };
12182
12183 /**
12184 * Check if the input is {@link #readOnly read-only}.
12185 *
12186 * @return {boolean}
12187 */
12188 OO.ui.TextInputWidget.prototype.isReadOnly = function () {
12189 return this.readOnly;
12190 };
12191
12192 /**
12193 * Set the {@link #readOnly read-only} state of the input.
12194 *
12195 * @param {boolean} state Make input read-only
12196 * @chainable
12197 */
12198 OO.ui.TextInputWidget.prototype.setReadOnly = function ( state ) {
12199 this.readOnly = !!state;
12200 this.$input.prop( 'readOnly', this.readOnly );
12201 return this;
12202 };
12203
12204 /**
12205 * Support function for making #onElementAttach work across browsers.
12206 *
12207 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
12208 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
12209 *
12210 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
12211 * first time that the element gets attached to the documented.
12212 */
12213 OO.ui.TextInputWidget.prototype.installParentChangeDetector = function () {
12214 var mutationObserver, onRemove, topmostNode, fakeParentNode,
12215 MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
12216 widget = this;
12217
12218 if ( MutationObserver ) {
12219 // The new way. If only it wasn't so ugly.
12220
12221 if ( this.$element.closest( 'html' ).length ) {
12222 // Widget is attached already, do nothing. This breaks the functionality of this function when
12223 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
12224 // would require observation of the whole document, which would hurt performance of other,
12225 // more important code.
12226 return;
12227 }
12228
12229 // Find topmost node in the tree
12230 topmostNode = this.$element[0];
12231 while ( topmostNode.parentNode ) {
12232 topmostNode = topmostNode.parentNode;
12233 }
12234
12235 // We have no way to detect the $element being attached somewhere without observing the entire
12236 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
12237 // parent node of $element, and instead detect when $element is removed from it (and thus
12238 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
12239 // doesn't get attached, we end up back here and create the parent.
12240
12241 mutationObserver = new MutationObserver( function ( mutations ) {
12242 var i, j, removedNodes;
12243 for ( i = 0; i < mutations.length; i++ ) {
12244 removedNodes = mutations[ i ].removedNodes;
12245 for ( j = 0; j < removedNodes.length; j++ ) {
12246 if ( removedNodes[ j ] === topmostNode ) {
12247 setTimeout( onRemove, 0 );
12248 return;
12249 }
12250 }
12251 }
12252 } );
12253
12254 onRemove = function () {
12255 // If the node was attached somewhere else, report it
12256 if ( widget.$element.closest( 'html' ).length ) {
12257 widget.onElementAttach();
12258 }
12259 mutationObserver.disconnect();
12260 widget.installParentChangeDetector();
12261 };
12262
12263 // Create a fake parent and observe it
12264 fakeParentNode = $( '<div>' ).append( this.$element )[0];
12265 mutationObserver.observe( fakeParentNode, { childList: true } );
12266 } else {
12267 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
12268 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
12269 this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) );
12270 }
12271 };
12272
12273 /**
12274 * Automatically adjust the size of the text input.
12275 *
12276 * This only affects #multiline inputs that are {@link #autosize autosized}.
12277 *
12278 * @chainable
12279 */
12280 OO.ui.TextInputWidget.prototype.adjustSize = function () {
12281 var scrollHeight, innerHeight, outerHeight, maxInnerHeight, measurementError, idealHeight;
12282
12283 if ( this.multiline && this.autosize && this.$input.val() !== this.valCache ) {
12284 this.$clone
12285 .val( this.$input.val() )
12286 .attr( 'rows', '' )
12287 // Set inline height property to 0 to measure scroll height
12288 .css( 'height', 0 );
12289
12290 this.$clone.removeClass( 'oo-ui-element-hidden' );
12291
12292 this.valCache = this.$input.val();
12293
12294 scrollHeight = this.$clone[ 0 ].scrollHeight;
12295
12296 // Remove inline height property to measure natural heights
12297 this.$clone.css( 'height', '' );
12298 innerHeight = this.$clone.innerHeight();
12299 outerHeight = this.$clone.outerHeight();
12300
12301 // Measure max rows height
12302 this.$clone
12303 .attr( 'rows', this.maxRows )
12304 .css( 'height', 'auto' )
12305 .val( '' );
12306 maxInnerHeight = this.$clone.innerHeight();
12307
12308 // Difference between reported innerHeight and scrollHeight with no scrollbars present
12309 // Equals 1 on Blink-based browsers and 0 everywhere else
12310 measurementError = maxInnerHeight - this.$clone[ 0 ].scrollHeight;
12311 idealHeight = Math.min( maxInnerHeight, scrollHeight + measurementError );
12312
12313 this.$clone.addClass( 'oo-ui-element-hidden' );
12314
12315 // Only apply inline height when expansion beyond natural height is needed
12316 if ( idealHeight > innerHeight ) {
12317 // Use the difference between the inner and outer height as a buffer
12318 this.$input.css( 'height', idealHeight + ( outerHeight - innerHeight ) );
12319 } else {
12320 this.$input.css( 'height', '' );
12321 }
12322 }
12323 return this;
12324 };
12325
12326 /**
12327 * @inheritdoc
12328 * @private
12329 */
12330 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
12331 return config.multiline ? $( '<textarea>' ) : $( '<input type="' + config.type + '" />' );
12332 };
12333
12334 /**
12335 * Check if the input supports multiple lines.
12336 *
12337 * @return {boolean}
12338 */
12339 OO.ui.TextInputWidget.prototype.isMultiline = function () {
12340 return !!this.multiline;
12341 };
12342
12343 /**
12344 * Check if the input automatically adjusts its size.
12345 *
12346 * @return {boolean}
12347 */
12348 OO.ui.TextInputWidget.prototype.isAutosizing = function () {
12349 return !!this.autosize;
12350 };
12351
12352 /**
12353 * Select the entire text of the input.
12354 *
12355 * @chainable
12356 */
12357 OO.ui.TextInputWidget.prototype.select = function () {
12358 this.$input.select();
12359 return this;
12360 };
12361
12362 /**
12363 * Set the validation pattern.
12364 *
12365 * The validation pattern is either a regular expression or the symbolic name of a pattern
12366 * defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
12367 * value must contain only numbers).
12368 *
12369 * @param {RegExp|string|null} validate Regular expression or the symbolic name of a
12370 * pattern (either ‘integer’ or ‘non-empty’) defined by the class.
12371 */
12372 OO.ui.TextInputWidget.prototype.setValidation = function ( validate ) {
12373 if ( validate instanceof RegExp ) {
12374 this.validate = validate;
12375 } else {
12376 this.validate = this.constructor.static.validationPatterns[ validate ] || /.*/;
12377 }
12378 };
12379
12380 /**
12381 * Sets the 'invalid' flag appropriately.
12382 */
12383 OO.ui.TextInputWidget.prototype.setValidityFlag = function () {
12384 var widget = this;
12385 this.isValid().done( function ( valid ) {
12386 widget.setFlags( { invalid: !valid } );
12387 } );
12388 };
12389
12390 /**
12391 * Check if a value is valid.
12392 *
12393 * This method returns a promise that resolves with a boolean `true` if the current value is
12394 * considered valid according to the supplied {@link #validate validation pattern}.
12395 *
12396 * @return {jQuery.Deferred} A promise that resolves to a boolean `true` if the value is valid.
12397 */
12398 OO.ui.TextInputWidget.prototype.isValid = function () {
12399 return $.Deferred().resolve( !!this.getValue().match( this.validate ) ).promise();
12400 };
12401
12402 /**
12403 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
12404 *
12405 * @param {string} labelPosition Label position, 'before' or 'after'
12406 * @chainable
12407 */
12408 OO.ui.TextInputWidget.prototype.setLabelPosition = function ( labelPosition ) {
12409 this.labelPosition = labelPosition;
12410 this.updatePosition();
12411 return this;
12412 };
12413
12414 /**
12415 * Deprecated alias of #setLabelPosition
12416 *
12417 * @deprecated Use setLabelPosition instead.
12418 */
12419 OO.ui.TextInputWidget.prototype.setPosition =
12420 OO.ui.TextInputWidget.prototype.setLabelPosition;
12421
12422 /**
12423 * Update the position of the inline label.
12424 *
12425 * This method is called by #setLabelPosition, and can also be called on its own if
12426 * something causes the label to be mispositioned.
12427 *
12428 *
12429 * @chainable
12430 */
12431 OO.ui.TextInputWidget.prototype.updatePosition = function () {
12432 var after = this.labelPosition === 'after';
12433
12434 this.$element
12435 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label && after )
12436 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label && !after );
12437
12438 if ( this.label ) {
12439 this.positionLabel();
12440 }
12441
12442 return this;
12443 };
12444
12445 /**
12446 * Position the label by setting the correct padding on the input.
12447 *
12448 * @private
12449 * @chainable
12450 */
12451 OO.ui.TextInputWidget.prototype.positionLabel = function () {
12452 // Clear old values
12453 this.$input
12454 // Clear old values if present
12455 .css( {
12456 'padding-right': '',
12457 'padding-left': ''
12458 } );
12459
12460 if ( this.label ) {
12461 this.$element.append( this.$label );
12462 } else {
12463 this.$label.detach();
12464 return;
12465 }
12466
12467 var after = this.labelPosition === 'after',
12468 rtl = this.$element.css( 'direction' ) === 'rtl',
12469 property = after === rtl ? 'padding-left' : 'padding-right';
12470
12471 this.$input.css( property, this.$label.outerWidth( true ) );
12472
12473 return this;
12474 };
12475
12476 /**
12477 * ComboBoxWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
12478 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
12479 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
12480 *
12481 * - by typing a value in the text input field. If the value exactly matches the value of a menu
12482 * option, that option will appear to be selected.
12483 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
12484 * input field.
12485 *
12486 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
12487 *
12488 * @example
12489 * // Example: A ComboBoxWidget.
12490 * var comboBox = new OO.ui.ComboBoxWidget( {
12491 * label: 'ComboBoxWidget',
12492 * input: { value: 'Option One' },
12493 * menu: {
12494 * items: [
12495 * new OO.ui.MenuOptionWidget( {
12496 * data: 'Option 1',
12497 * label: 'Option One'
12498 * } ),
12499 * new OO.ui.MenuOptionWidget( {
12500 * data: 'Option 2',
12501 * label: 'Option Two'
12502 * } ),
12503 * new OO.ui.MenuOptionWidget( {
12504 * data: 'Option 3',
12505 * label: 'Option Three'
12506 * } ),
12507 * new OO.ui.MenuOptionWidget( {
12508 * data: 'Option 4',
12509 * label: 'Option Four'
12510 * } ),
12511 * new OO.ui.MenuOptionWidget( {
12512 * data: 'Option 5',
12513 * label: 'Option Five'
12514 * } )
12515 * ]
12516 * }
12517 * } );
12518 * $( 'body' ).append( comboBox.$element );
12519 *
12520 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
12521 *
12522 * @class
12523 * @extends OO.ui.Widget
12524 * @mixins OO.ui.TabIndexedElement
12525 *
12526 * @constructor
12527 * @param {Object} [config] Configuration options
12528 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
12529 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
12530 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
12531 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
12532 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
12533 */
12534 OO.ui.ComboBoxWidget = function OoUiComboBoxWidget( config ) {
12535 // Configuration initialization
12536 config = config || {};
12537
12538 // Parent constructor
12539 OO.ui.ComboBoxWidget.super.call( this, config );
12540
12541 // Properties (must be set before TabIndexedElement constructor call)
12542 this.$indicator = this.$( '<span>' );
12543
12544 // Mixin constructors
12545 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$indicator } ) );
12546
12547 // Properties
12548 this.$overlay = config.$overlay || this.$element;
12549 this.input = new OO.ui.TextInputWidget( $.extend(
12550 {
12551 indicator: 'down',
12552 $indicator: this.$indicator,
12553 disabled: this.isDisabled()
12554 },
12555 config.input
12556 ) );
12557 this.input.$input.eq( 0 ).attr( {
12558 role: 'combobox',
12559 'aria-autocomplete': 'list'
12560 } );
12561 this.menu = new OO.ui.TextInputMenuSelectWidget( this.input, $.extend(
12562 {
12563 widget: this,
12564 input: this.input,
12565 disabled: this.isDisabled()
12566 },
12567 config.menu
12568 ) );
12569
12570 // Events
12571 this.$indicator.on( {
12572 click: this.onClick.bind( this ),
12573 keypress: this.onKeyPress.bind( this )
12574 } );
12575 this.input.connect( this, {
12576 change: 'onInputChange',
12577 enter: 'onInputEnter'
12578 } );
12579 this.menu.connect( this, {
12580 choose: 'onMenuChoose',
12581 add: 'onMenuItemsChange',
12582 remove: 'onMenuItemsChange'
12583 } );
12584
12585 // Initialization
12586 this.$element.addClass( 'oo-ui-comboBoxWidget' ).append( this.input.$element );
12587 this.$overlay.append( this.menu.$element );
12588 this.onMenuItemsChange();
12589 };
12590
12591 /* Setup */
12592
12593 OO.inheritClass( OO.ui.ComboBoxWidget, OO.ui.Widget );
12594 OO.mixinClass( OO.ui.ComboBoxWidget, OO.ui.TabIndexedElement );
12595
12596 /* Methods */
12597
12598 /**
12599 * Get the combobox's menu.
12600 * @return {OO.ui.TextInputMenuSelectWidget} Menu widget
12601 */
12602 OO.ui.ComboBoxWidget.prototype.getMenu = function () {
12603 return this.menu;
12604 };
12605
12606 /**
12607 * Handle input change events.
12608 *
12609 * @private
12610 * @param {string} value New value
12611 */
12612 OO.ui.ComboBoxWidget.prototype.onInputChange = function ( value ) {
12613 var match = this.menu.getItemFromData( value );
12614
12615 this.menu.selectItem( match );
12616 if ( this.menu.getHighlightedItem() ) {
12617 this.menu.highlightItem( match );
12618 }
12619
12620 if ( !this.isDisabled() ) {
12621 this.menu.toggle( true );
12622 }
12623 };
12624
12625 /**
12626 * Handle mouse click events.
12627 *
12628 *
12629 * @private
12630 * @param {jQuery.Event} e Mouse click event
12631 */
12632 OO.ui.ComboBoxWidget.prototype.onClick = function ( e ) {
12633 if ( !this.isDisabled() && e.which === 1 ) {
12634 this.menu.toggle();
12635 this.input.$input[ 0 ].focus();
12636 }
12637 return false;
12638 };
12639
12640 /**
12641 * Handle key press events.
12642 *
12643 *
12644 * @private
12645 * @param {jQuery.Event} e Key press event
12646 */
12647 OO.ui.ComboBoxWidget.prototype.onKeyPress = function ( e ) {
12648 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
12649 this.menu.toggle();
12650 this.input.$input[ 0 ].focus();
12651 return false;
12652 }
12653 };
12654
12655 /**
12656 * Handle input enter events.
12657 *
12658 * @private
12659 */
12660 OO.ui.ComboBoxWidget.prototype.onInputEnter = function () {
12661 if ( !this.isDisabled() ) {
12662 this.menu.toggle( false );
12663 }
12664 };
12665
12666 /**
12667 * Handle menu choose events.
12668 *
12669 * @private
12670 * @param {OO.ui.OptionWidget} item Chosen item
12671 */
12672 OO.ui.ComboBoxWidget.prototype.onMenuChoose = function ( item ) {
12673 this.input.setValue( item.getData() );
12674 };
12675
12676 /**
12677 * Handle menu item change events.
12678 *
12679 * @private
12680 */
12681 OO.ui.ComboBoxWidget.prototype.onMenuItemsChange = function () {
12682 var match = this.menu.getItemFromData( this.input.getValue() );
12683 this.menu.selectItem( match );
12684 if ( this.menu.getHighlightedItem() ) {
12685 this.menu.highlightItem( match );
12686 }
12687 this.$element.toggleClass( 'oo-ui-comboBoxWidget-empty', this.menu.isEmpty() );
12688 };
12689
12690 /**
12691 * @inheritdoc
12692 */
12693 OO.ui.ComboBoxWidget.prototype.setDisabled = function ( disabled ) {
12694 // Parent method
12695 OO.ui.ComboBoxWidget.super.prototype.setDisabled.call( this, disabled );
12696
12697 if ( this.input ) {
12698 this.input.setDisabled( this.isDisabled() );
12699 }
12700 if ( this.menu ) {
12701 this.menu.setDisabled( this.isDisabled() );
12702 }
12703
12704 return this;
12705 };
12706
12707 /**
12708 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
12709 * be configured with a `label` option that is set to a string, a label node, or a function:
12710 *
12711 * - String: a plaintext string
12712 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
12713 * label that includes a link or special styling, such as a gray color or additional graphical elements.
12714 * - Function: a function that will produce a string in the future. Functions are used
12715 * in cases where the value of the label is not currently defined.
12716 *
12717 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
12718 * will come into focus when the label is clicked.
12719 *
12720 * @example
12721 * // Examples of LabelWidgets
12722 * var label1 = new OO.ui.LabelWidget( {
12723 * label: 'plaintext label'
12724 * } );
12725 * var label2 = new OO.ui.LabelWidget( {
12726 * label: $( '<a href="default.html">jQuery label</a>' )
12727 * } );
12728 * // Create a fieldset layout with fields for each example
12729 * var fieldset = new OO.ui.FieldsetLayout();
12730 * fieldset.addItems( [
12731 * new OO.ui.FieldLayout( label1 ),
12732 * new OO.ui.FieldLayout( label2 )
12733 * ] );
12734 * $( 'body' ).append( fieldset.$element );
12735 *
12736 *
12737 * @class
12738 * @extends OO.ui.Widget
12739 * @mixins OO.ui.LabelElement
12740 *
12741 * @constructor
12742 * @param {Object} [config] Configuration options
12743 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
12744 * Clicking the label will focus the specified input field.
12745 */
12746 OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
12747 // Configuration initialization
12748 config = config || {};
12749
12750 // Parent constructor
12751 OO.ui.LabelWidget.super.call( this, config );
12752
12753 // Mixin constructors
12754 OO.ui.LabelElement.call( this, $.extend( {}, config, { $label: this.$element } ) );
12755 OO.ui.TitledElement.call( this, config );
12756
12757 // Properties
12758 this.input = config.input;
12759
12760 // Events
12761 if ( this.input instanceof OO.ui.InputWidget ) {
12762 this.$element.on( 'click', this.onClick.bind( this ) );
12763 }
12764
12765 // Initialization
12766 this.$element.addClass( 'oo-ui-labelWidget' );
12767 };
12768
12769 /* Setup */
12770
12771 OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
12772 OO.mixinClass( OO.ui.LabelWidget, OO.ui.LabelElement );
12773 OO.mixinClass( OO.ui.LabelWidget, OO.ui.TitledElement );
12774
12775 /* Static Properties */
12776
12777 OO.ui.LabelWidget.static.tagName = 'span';
12778
12779 /* Methods */
12780
12781 /**
12782 * Handles label mouse click events.
12783 *
12784 * @private
12785 * @param {jQuery.Event} e Mouse click event
12786 */
12787 OO.ui.LabelWidget.prototype.onClick = function () {
12788 this.input.simulateLabelClick();
12789 return false;
12790 };
12791
12792 /**
12793 * OptionWidgets are special elements that can be selected and configured with data. The
12794 * data is often unique for each option, but it does not have to be. OptionWidgets are used
12795 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
12796 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
12797 *
12798 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
12799 *
12800 * @class
12801 * @extends OO.ui.Widget
12802 * @mixins OO.ui.LabelElement
12803 * @mixins OO.ui.FlaggedElement
12804 *
12805 * @constructor
12806 * @param {Object} [config] Configuration options
12807 */
12808 OO.ui.OptionWidget = function OoUiOptionWidget( config ) {
12809 // Configuration initialization
12810 config = config || {};
12811
12812 // Parent constructor
12813 OO.ui.OptionWidget.super.call( this, config );
12814
12815 // Mixin constructors
12816 OO.ui.ItemWidget.call( this );
12817 OO.ui.LabelElement.call( this, config );
12818 OO.ui.FlaggedElement.call( this, config );
12819
12820 // Properties
12821 this.selected = false;
12822 this.highlighted = false;
12823 this.pressed = false;
12824
12825 // Initialization
12826 this.$element
12827 .data( 'oo-ui-optionWidget', this )
12828 .attr( 'role', 'option' )
12829 .addClass( 'oo-ui-optionWidget' )
12830 .append( this.$label );
12831 };
12832
12833 /* Setup */
12834
12835 OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
12836 OO.mixinClass( OO.ui.OptionWidget, OO.ui.ItemWidget );
12837 OO.mixinClass( OO.ui.OptionWidget, OO.ui.LabelElement );
12838 OO.mixinClass( OO.ui.OptionWidget, OO.ui.FlaggedElement );
12839
12840 /* Static Properties */
12841
12842 OO.ui.OptionWidget.static.selectable = true;
12843
12844 OO.ui.OptionWidget.static.highlightable = true;
12845
12846 OO.ui.OptionWidget.static.pressable = true;
12847
12848 OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
12849
12850 /* Methods */
12851
12852 /**
12853 * Check if the option can be selected.
12854 *
12855 * @return {boolean} Item is selectable
12856 */
12857 OO.ui.OptionWidget.prototype.isSelectable = function () {
12858 return this.constructor.static.selectable && !this.isDisabled();
12859 };
12860
12861 /**
12862 * Check if the option can be highlighted. A highlight indicates that the option
12863 * may be selected when a user presses enter or clicks. Disabled items cannot
12864 * be highlighted.
12865 *
12866 * @return {boolean} Item is highlightable
12867 */
12868 OO.ui.OptionWidget.prototype.isHighlightable = function () {
12869 return this.constructor.static.highlightable && !this.isDisabled();
12870 };
12871
12872 /**
12873 * Check if the option can be pressed. The pressed state occurs when a user mouses
12874 * down on an item, but has not yet let go of the mouse.
12875 *
12876 * @return {boolean} Item is pressable
12877 */
12878 OO.ui.OptionWidget.prototype.isPressable = function () {
12879 return this.constructor.static.pressable && !this.isDisabled();
12880 };
12881
12882 /**
12883 * Check if the option is selected.
12884 *
12885 * @return {boolean} Item is selected
12886 */
12887 OO.ui.OptionWidget.prototype.isSelected = function () {
12888 return this.selected;
12889 };
12890
12891 /**
12892 * Check if the option is highlighted. A highlight indicates that the
12893 * item may be selected when a user presses enter or clicks.
12894 *
12895 * @return {boolean} Item is highlighted
12896 */
12897 OO.ui.OptionWidget.prototype.isHighlighted = function () {
12898 return this.highlighted;
12899 };
12900
12901 /**
12902 * Check if the option is pressed. The pressed state occurs when a user mouses
12903 * down on an item, but has not yet let go of the mouse. The item may appear
12904 * selected, but it will not be selected until the user releases the mouse.
12905 *
12906 * @return {boolean} Item is pressed
12907 */
12908 OO.ui.OptionWidget.prototype.isPressed = function () {
12909 return this.pressed;
12910 };
12911
12912 /**
12913 * Set the option’s selected state. In general, all modifications to the selection
12914 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
12915 * method instead of this method.
12916 *
12917 * @param {boolean} [state=false] Select option
12918 * @chainable
12919 */
12920 OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
12921 if ( this.constructor.static.selectable ) {
12922 this.selected = !!state;
12923 this.$element
12924 .toggleClass( 'oo-ui-optionWidget-selected', state )
12925 .attr( 'aria-selected', state.toString() );
12926 if ( state && this.constructor.static.scrollIntoViewOnSelect ) {
12927 this.scrollElementIntoView();
12928 }
12929 this.updateThemeClasses();
12930 }
12931 return this;
12932 };
12933
12934 /**
12935 * Set the option’s highlighted state. In general, all programmatic
12936 * modifications to the highlight should be handled by the
12937 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
12938 * method instead of this method.
12939 *
12940 * @param {boolean} [state=false] Highlight option
12941 * @chainable
12942 */
12943 OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
12944 if ( this.constructor.static.highlightable ) {
12945 this.highlighted = !!state;
12946 this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state );
12947 this.updateThemeClasses();
12948 }
12949 return this;
12950 };
12951
12952 /**
12953 * Set the option’s pressed state. In general, all
12954 * programmatic modifications to the pressed state should be handled by the
12955 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
12956 * method instead of this method.
12957 *
12958 * @param {boolean} [state=false] Press option
12959 * @chainable
12960 */
12961 OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
12962 if ( this.constructor.static.pressable ) {
12963 this.pressed = !!state;
12964 this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state );
12965 this.updateThemeClasses();
12966 }
12967 return this;
12968 };
12969
12970 /**
12971 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
12972 * with an {@link OO.ui.IconElement icon} and/or {@link OO.ui.IndicatorElement indicator}.
12973 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
12974 * options. For more information about options and selects, please see the
12975 * [OOjs UI documentation on MediaWiki][1].
12976 *
12977 * @example
12978 * // Decorated options in a select widget
12979 * var select = new OO.ui.SelectWidget( {
12980 * items: [
12981 * new OO.ui.DecoratedOptionWidget( {
12982 * data: 'a',
12983 * label: 'Option with icon',
12984 * icon: 'help'
12985 * } ),
12986 * new OO.ui.DecoratedOptionWidget( {
12987 * data: 'b',
12988 * label: 'Option with indicator',
12989 * indicator: 'next'
12990 * } )
12991 * ]
12992 * } );
12993 * $( 'body' ).append( select.$element );
12994 *
12995 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
12996 *
12997 * @class
12998 * @extends OO.ui.OptionWidget
12999 * @mixins OO.ui.IconElement
13000 * @mixins OO.ui.IndicatorElement
13001 *
13002 * @constructor
13003 * @param {Object} [config] Configuration options
13004 */
13005 OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( config ) {
13006 // Parent constructor
13007 OO.ui.DecoratedOptionWidget.super.call( this, config );
13008
13009 // Mixin constructors
13010 OO.ui.IconElement.call( this, config );
13011 OO.ui.IndicatorElement.call( this, config );
13012
13013 // Initialization
13014 this.$element
13015 .addClass( 'oo-ui-decoratedOptionWidget' )
13016 .prepend( this.$icon )
13017 .append( this.$indicator );
13018 };
13019
13020 /* Setup */
13021
13022 OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget );
13023 OO.mixinClass( OO.ui.OptionWidget, OO.ui.IconElement );
13024 OO.mixinClass( OO.ui.OptionWidget, OO.ui.IndicatorElement );
13025
13026 /**
13027 * ButtonOptionWidget is a special type of {@link OO.ui.ButtonElement button element} that
13028 * can be selected and configured with data. The class is
13029 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
13030 * [OOjs UI documentation on MediaWiki] [1] for more information.
13031 *
13032 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
13033 *
13034 * @class
13035 * @extends OO.ui.DecoratedOptionWidget
13036 * @mixins OO.ui.ButtonElement
13037 * @mixins OO.ui.TabIndexedElement
13038 *
13039 * @constructor
13040 * @param {Object} [config] Configuration options
13041 */
13042 OO.ui.ButtonOptionWidget = function OoUiButtonOptionWidget( config ) {
13043 // Configuration initialization
13044 config = $.extend( { tabIndex: -1 }, config );
13045
13046 // Parent constructor
13047 OO.ui.ButtonOptionWidget.super.call( this, config );
13048
13049 // Mixin constructors
13050 OO.ui.ButtonElement.call( this, config );
13051 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
13052
13053 // Initialization
13054 this.$element.addClass( 'oo-ui-buttonOptionWidget' );
13055 this.$button.append( this.$element.contents() );
13056 this.$element.append( this.$button );
13057 };
13058
13059 /* Setup */
13060
13061 OO.inheritClass( OO.ui.ButtonOptionWidget, OO.ui.DecoratedOptionWidget );
13062 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.ButtonElement );
13063 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.TabIndexedElement );
13064
13065 /* Static Properties */
13066
13067 // Allow button mouse down events to pass through so they can be handled by the parent select widget
13068 OO.ui.ButtonOptionWidget.static.cancelButtonMouseDownEvents = false;
13069
13070 OO.ui.ButtonOptionWidget.static.highlightable = false;
13071
13072 /* Methods */
13073
13074 /**
13075 * @inheritdoc
13076 */
13077 OO.ui.ButtonOptionWidget.prototype.setSelected = function ( state ) {
13078 OO.ui.ButtonOptionWidget.super.prototype.setSelected.call( this, state );
13079
13080 if ( this.constructor.static.selectable ) {
13081 this.setActive( state );
13082 }
13083
13084 return this;
13085 };
13086
13087 /**
13088 * RadioOptionWidget is an option widget that looks like a radio button.
13089 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
13090 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
13091 *
13092 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
13093 *
13094 * @class
13095 * @extends OO.ui.OptionWidget
13096 *
13097 * @constructor
13098 * @param {Object} [config] Configuration options
13099 */
13100 OO.ui.RadioOptionWidget = function OoUiRadioOptionWidget( config ) {
13101 // Configuration initialization
13102 config = config || {};
13103
13104 // Properties (must be done before parent constructor which calls #setDisabled)
13105 this.radio = new OO.ui.RadioInputWidget( { value: config.data, tabIndex: -1 } );
13106
13107 // Parent constructor
13108 OO.ui.RadioOptionWidget.super.call( this, config );
13109
13110 // Initialization
13111 this.$element
13112 .addClass( 'oo-ui-radioOptionWidget' )
13113 .prepend( this.radio.$element );
13114 };
13115
13116 /* Setup */
13117
13118 OO.inheritClass( OO.ui.RadioOptionWidget, OO.ui.OptionWidget );
13119
13120 /* Static Properties */
13121
13122 OO.ui.RadioOptionWidget.static.highlightable = false;
13123
13124 OO.ui.RadioOptionWidget.static.scrollIntoViewOnSelect = true;
13125
13126 OO.ui.RadioOptionWidget.static.pressable = false;
13127
13128 OO.ui.RadioOptionWidget.static.tagName = 'label';
13129
13130 /* Methods */
13131
13132 /**
13133 * @inheritdoc
13134 */
13135 OO.ui.RadioOptionWidget.prototype.setSelected = function ( state ) {
13136 OO.ui.RadioOptionWidget.super.prototype.setSelected.call( this, state );
13137
13138 this.radio.setSelected( state );
13139
13140 return this;
13141 };
13142
13143 /**
13144 * @inheritdoc
13145 */
13146 OO.ui.RadioOptionWidget.prototype.setDisabled = function ( disabled ) {
13147 OO.ui.RadioOptionWidget.super.prototype.setDisabled.call( this, disabled );
13148
13149 this.radio.setDisabled( this.isDisabled() );
13150
13151 return this;
13152 };
13153
13154 /**
13155 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
13156 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
13157 * the [OOjs UI documentation on MediaWiki] [1] for more information.
13158 *
13159 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
13160 *
13161 * @class
13162 * @extends OO.ui.DecoratedOptionWidget
13163 *
13164 * @constructor
13165 * @param {Object} [config] Configuration options
13166 */
13167 OO.ui.MenuOptionWidget = function OoUiMenuOptionWidget( config ) {
13168 // Configuration initialization
13169 config = $.extend( { icon: 'check' }, config );
13170
13171 // Parent constructor
13172 OO.ui.MenuOptionWidget.super.call( this, config );
13173
13174 // Initialization
13175 this.$element
13176 .attr( 'role', 'menuitem' )
13177 .addClass( 'oo-ui-menuOptionWidget' );
13178 };
13179
13180 /* Setup */
13181
13182 OO.inheritClass( OO.ui.MenuOptionWidget, OO.ui.DecoratedOptionWidget );
13183
13184 /* Static Properties */
13185
13186 OO.ui.MenuOptionWidget.static.scrollIntoViewOnSelect = true;
13187
13188 /**
13189 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
13190 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
13191 *
13192 * @example
13193 * var myDropdown = new OO.ui.DropdownWidget( {
13194 * menu: {
13195 * items: [
13196 * new OO.ui.MenuSectionOptionWidget( {
13197 * label: 'Dogs'
13198 * } ),
13199 * new OO.ui.MenuOptionWidget( {
13200 * data: 'corgi',
13201 * label: 'Welsh Corgi'
13202 * } ),
13203 * new OO.ui.MenuOptionWidget( {
13204 * data: 'poodle',
13205 * label: 'Standard Poodle'
13206 * } ),
13207 * new OO.ui.MenuSectionOptionWidget( {
13208 * label: 'Cats'
13209 * } ),
13210 * new OO.ui.MenuOptionWidget( {
13211 * data: 'lion',
13212 * label: 'Lion'
13213 * } )
13214 * ]
13215 * }
13216 * } );
13217 * $( 'body' ).append( myDropdown.$element );
13218 *
13219 *
13220 * @class
13221 * @extends OO.ui.DecoratedOptionWidget
13222 *
13223 * @constructor
13224 * @param {Object} [config] Configuration options
13225 */
13226 OO.ui.MenuSectionOptionWidget = function OoUiMenuSectionOptionWidget( config ) {
13227 // Parent constructor
13228 OO.ui.MenuSectionOptionWidget.super.call( this, config );
13229
13230 // Initialization
13231 this.$element.addClass( 'oo-ui-menuSectionOptionWidget' );
13232 };
13233
13234 /* Setup */
13235
13236 OO.inheritClass( OO.ui.MenuSectionOptionWidget, OO.ui.DecoratedOptionWidget );
13237
13238 /* Static Properties */
13239
13240 OO.ui.MenuSectionOptionWidget.static.selectable = false;
13241
13242 OO.ui.MenuSectionOptionWidget.static.highlightable = false;
13243
13244 /**
13245 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
13246 *
13247 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
13248 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
13249 * for an example.
13250 *
13251 * @class
13252 * @extends OO.ui.DecoratedOptionWidget
13253 *
13254 * @constructor
13255 * @param {Object} [config] Configuration options
13256 * @cfg {number} [level] Indentation level
13257 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
13258 */
13259 OO.ui.OutlineOptionWidget = function OoUiOutlineOptionWidget( config ) {
13260 // Configuration initialization
13261 config = config || {};
13262
13263 // Parent constructor
13264 OO.ui.OutlineOptionWidget.super.call( this, config );
13265
13266 // Properties
13267 this.level = 0;
13268 this.movable = !!config.movable;
13269 this.removable = !!config.removable;
13270
13271 // Initialization
13272 this.$element.addClass( 'oo-ui-outlineOptionWidget' );
13273 this.setLevel( config.level );
13274 };
13275
13276 /* Setup */
13277
13278 OO.inheritClass( OO.ui.OutlineOptionWidget, OO.ui.DecoratedOptionWidget );
13279
13280 /* Static Properties */
13281
13282 OO.ui.OutlineOptionWidget.static.highlightable = false;
13283
13284 OO.ui.OutlineOptionWidget.static.scrollIntoViewOnSelect = true;
13285
13286 OO.ui.OutlineOptionWidget.static.levelClass = 'oo-ui-outlineOptionWidget-level-';
13287
13288 OO.ui.OutlineOptionWidget.static.levels = 3;
13289
13290 /* Methods */
13291
13292 /**
13293 * Check if item is movable.
13294 *
13295 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
13296 *
13297 * @return {boolean} Item is movable
13298 */
13299 OO.ui.OutlineOptionWidget.prototype.isMovable = function () {
13300 return this.movable;
13301 };
13302
13303 /**
13304 * Check if item is removable.
13305 *
13306 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
13307 *
13308 * @return {boolean} Item is removable
13309 */
13310 OO.ui.OutlineOptionWidget.prototype.isRemovable = function () {
13311 return this.removable;
13312 };
13313
13314 /**
13315 * Get indentation level.
13316 *
13317 * @return {number} Indentation level
13318 */
13319 OO.ui.OutlineOptionWidget.prototype.getLevel = function () {
13320 return this.level;
13321 };
13322
13323 /**
13324 * Set movability.
13325 *
13326 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
13327 *
13328 * @param {boolean} movable Item is movable
13329 * @chainable
13330 */
13331 OO.ui.OutlineOptionWidget.prototype.setMovable = function ( movable ) {
13332 this.movable = !!movable;
13333 this.updateThemeClasses();
13334 return this;
13335 };
13336
13337 /**
13338 * Set removability.
13339 *
13340 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
13341 *
13342 * @param {boolean} movable Item is removable
13343 * @chainable
13344 */
13345 OO.ui.OutlineOptionWidget.prototype.setRemovable = function ( removable ) {
13346 this.removable = !!removable;
13347 this.updateThemeClasses();
13348 return this;
13349 };
13350
13351 /**
13352 * Set indentation level.
13353 *
13354 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
13355 * @chainable
13356 */
13357 OO.ui.OutlineOptionWidget.prototype.setLevel = function ( level ) {
13358 var levels = this.constructor.static.levels,
13359 levelClass = this.constructor.static.levelClass,
13360 i = levels;
13361
13362 this.level = level ? Math.max( 0, Math.min( levels - 1, level ) ) : 0;
13363 while ( i-- ) {
13364 if ( this.level === i ) {
13365 this.$element.addClass( levelClass + i );
13366 } else {
13367 this.$element.removeClass( levelClass + i );
13368 }
13369 }
13370 this.updateThemeClasses();
13371
13372 return this;
13373 };
13374
13375 /**
13376 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
13377 * By default, each popup has an anchor that points toward its origin.
13378 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
13379 *
13380 * @example
13381 * // A popup widget.
13382 * var popup = new OO.ui.PopupWidget( {
13383 * $content: $( '<p>Hi there!</p>' ),
13384 * padded: true,
13385 * width: 300
13386 * } );
13387 *
13388 * $( 'body' ).append( popup.$element );
13389 * // To display the popup, toggle the visibility to 'true'.
13390 * popup.toggle( true );
13391 *
13392 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
13393 *
13394 * @class
13395 * @extends OO.ui.Widget
13396 * @mixins OO.ui.LabelElement
13397 *
13398 * @constructor
13399 * @param {Object} [config] Configuration options
13400 * @cfg {number} [width=320] Width of popup in pixels
13401 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
13402 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
13403 * @cfg {string} [align='center'] Alignment of the popup: `center`, `left`, or `right`.
13404 * If the popup is right-aligned, the right edge of the popup is aligned to the anchor.
13405 * For left-aligned popups, the left edge is aligned to the anchor.
13406 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
13407 * See the [OOjs UI docs on MediaWiki][3] for an example.
13408 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
13409 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
13410 * @cfg {jQuery} [$content] Content to append to the popup's body
13411 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
13412 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
13413 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
13414 * for an example.
13415 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
13416 * @cfg {boolean} [head] Show a popup header that contains a #label (if specified) and close
13417 * button.
13418 * @cfg {boolean} [padded] Add padding to the popup's body
13419 */
13420 OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
13421 // Configuration initialization
13422 config = config || {};
13423
13424 // Parent constructor
13425 OO.ui.PopupWidget.super.call( this, config );
13426
13427 // Properties (must be set before ClippableElement constructor call)
13428 this.$body = $( '<div>' );
13429
13430 // Mixin constructors
13431 OO.ui.LabelElement.call( this, config );
13432 OO.ui.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$body } ) );
13433
13434 // Properties
13435 this.$popup = $( '<div>' );
13436 this.$head = $( '<div>' );
13437 this.$anchor = $( '<div>' );
13438 // If undefined, will be computed lazily in updateDimensions()
13439 this.$container = config.$container;
13440 this.containerPadding = config.containerPadding !== undefined ? config.containerPadding : 10;
13441 this.autoClose = !!config.autoClose;
13442 this.$autoCloseIgnore = config.$autoCloseIgnore;
13443 this.transitionTimeout = null;
13444 this.anchor = null;
13445 this.width = config.width !== undefined ? config.width : 320;
13446 this.height = config.height !== undefined ? config.height : null;
13447 this.align = config.align || 'center';
13448 this.closeButton = new OO.ui.ButtonWidget( { framed: false, icon: 'close' } );
13449 this.onMouseDownHandler = this.onMouseDown.bind( this );
13450 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
13451
13452 // Events
13453 this.closeButton.connect( this, { click: 'onCloseButtonClick' } );
13454
13455 // Initialization
13456 this.toggleAnchor( config.anchor === undefined || config.anchor );
13457 this.$body.addClass( 'oo-ui-popupWidget-body' );
13458 this.$anchor.addClass( 'oo-ui-popupWidget-anchor' );
13459 this.$head
13460 .addClass( 'oo-ui-popupWidget-head' )
13461 .append( this.$label, this.closeButton.$element );
13462 if ( !config.head ) {
13463 this.$head.addClass( 'oo-ui-element-hidden' );
13464 }
13465 this.$popup
13466 .addClass( 'oo-ui-popupWidget-popup' )
13467 .append( this.$head, this.$body );
13468 this.$element
13469 .addClass( 'oo-ui-popupWidget' )
13470 .append( this.$popup, this.$anchor );
13471 // Move content, which was added to #$element by OO.ui.Widget, to the body
13472 if ( config.$content instanceof jQuery ) {
13473 this.$body.append( config.$content );
13474 }
13475 if ( config.padded ) {
13476 this.$body.addClass( 'oo-ui-popupWidget-body-padded' );
13477 }
13478
13479 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
13480 // that reference properties not initialized at that time of parent class construction
13481 // TODO: Find a better way to handle post-constructor setup
13482 this.visible = false;
13483 this.$element.addClass( 'oo-ui-element-hidden' );
13484 };
13485
13486 /* Setup */
13487
13488 OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
13489 OO.mixinClass( OO.ui.PopupWidget, OO.ui.LabelElement );
13490 OO.mixinClass( OO.ui.PopupWidget, OO.ui.ClippableElement );
13491
13492 /* Methods */
13493
13494 /**
13495 * Handles mouse down events.
13496 *
13497 * @private
13498 * @param {MouseEvent} e Mouse down event
13499 */
13500 OO.ui.PopupWidget.prototype.onMouseDown = function ( e ) {
13501 if (
13502 this.isVisible() &&
13503 !$.contains( this.$element[ 0 ], e.target ) &&
13504 ( !this.$autoCloseIgnore || !this.$autoCloseIgnore.has( e.target ).length )
13505 ) {
13506 this.toggle( false );
13507 }
13508 };
13509
13510 /**
13511 * Bind mouse down listener.
13512 *
13513 * @private
13514 */
13515 OO.ui.PopupWidget.prototype.bindMouseDownListener = function () {
13516 // Capture clicks outside popup
13517 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler, true );
13518 };
13519
13520 /**
13521 * Handles close button click events.
13522 *
13523 * @private
13524 */
13525 OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
13526 if ( this.isVisible() ) {
13527 this.toggle( false );
13528 }
13529 };
13530
13531 /**
13532 * Unbind mouse down listener.
13533 *
13534 * @private
13535 */
13536 OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () {
13537 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler, true );
13538 };
13539
13540 /**
13541 * Handles key down events.
13542 *
13543 * @private
13544 * @param {KeyboardEvent} e Key down event
13545 */
13546 OO.ui.PopupWidget.prototype.onDocumentKeyDown = function ( e ) {
13547 if (
13548 e.which === OO.ui.Keys.ESCAPE &&
13549 this.isVisible()
13550 ) {
13551 this.toggle( false );
13552 e.preventDefault();
13553 e.stopPropagation();
13554 }
13555 };
13556
13557 /**
13558 * Bind key down listener.
13559 *
13560 * @private
13561 */
13562 OO.ui.PopupWidget.prototype.bindKeyDownListener = function () {
13563 this.getElementWindow().addEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
13564 };
13565
13566 /**
13567 * Unbind key down listener.
13568 *
13569 * @private
13570 */
13571 OO.ui.PopupWidget.prototype.unbindKeyDownListener = function () {
13572 this.getElementWindow().removeEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
13573 };
13574
13575 /**
13576 * Show, hide, or toggle the visibility of the anchor.
13577 *
13578 * @param {boolean} [show] Show anchor, omit to toggle
13579 */
13580 OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) {
13581 show = show === undefined ? !this.anchored : !!show;
13582
13583 if ( this.anchored !== show ) {
13584 if ( show ) {
13585 this.$element.addClass( 'oo-ui-popupWidget-anchored' );
13586 } else {
13587 this.$element.removeClass( 'oo-ui-popupWidget-anchored' );
13588 }
13589 this.anchored = show;
13590 }
13591 };
13592
13593 /**
13594 * Check if the anchor is visible.
13595 *
13596 * @return {boolean} Anchor is visible
13597 */
13598 OO.ui.PopupWidget.prototype.hasAnchor = function () {
13599 return this.anchor;
13600 };
13601
13602 /**
13603 * @inheritdoc
13604 */
13605 OO.ui.PopupWidget.prototype.toggle = function ( show ) {
13606 show = show === undefined ? !this.isVisible() : !!show;
13607
13608 var change = show !== this.isVisible();
13609
13610 // Parent method
13611 OO.ui.PopupWidget.super.prototype.toggle.call( this, show );
13612
13613 if ( change ) {
13614 if ( show ) {
13615 if ( this.autoClose ) {
13616 this.bindMouseDownListener();
13617 this.bindKeyDownListener();
13618 }
13619 this.updateDimensions();
13620 this.toggleClipping( true );
13621 } else {
13622 this.toggleClipping( false );
13623 if ( this.autoClose ) {
13624 this.unbindMouseDownListener();
13625 this.unbindKeyDownListener();
13626 }
13627 }
13628 }
13629
13630 return this;
13631 };
13632
13633 /**
13634 * Set the size of the popup.
13635 *
13636 * Changing the size may also change the popup's position depending on the alignment.
13637 *
13638 * @param {number} width Width in pixels
13639 * @param {number} height Height in pixels
13640 * @param {boolean} [transition=false] Use a smooth transition
13641 * @chainable
13642 */
13643 OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) {
13644 this.width = width;
13645 this.height = height !== undefined ? height : null;
13646 if ( this.isVisible() ) {
13647 this.updateDimensions( transition );
13648 }
13649 };
13650
13651 /**
13652 * Update the size and position.
13653 *
13654 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
13655 * be called automatically.
13656 *
13657 * @param {boolean} [transition=false] Use a smooth transition
13658 * @chainable
13659 */
13660 OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) {
13661 var popupOffset, originOffset, containerLeft, containerWidth, containerRight,
13662 popupLeft, popupRight, overlapLeft, overlapRight, anchorWidth,
13663 widget = this;
13664
13665 if ( !this.$container ) {
13666 // Lazy-initialize $container if not specified in constructor
13667 this.$container = $( this.getClosestScrollableElementContainer() );
13668 }
13669
13670 // Set height and width before measuring things, since it might cause our measurements
13671 // to change (e.g. due to scrollbars appearing or disappearing)
13672 this.$popup.css( {
13673 width: this.width,
13674 height: this.height !== null ? this.height : 'auto'
13675 } );
13676
13677 // Compute initial popupOffset based on alignment
13678 popupOffset = this.width * ( { left: 0, center: -0.5, right: -1 } )[ this.align ];
13679
13680 // Figure out if this will cause the popup to go beyond the edge of the container
13681 originOffset = this.$element.offset().left;
13682 containerLeft = this.$container.offset().left;
13683 containerWidth = this.$container.innerWidth();
13684 containerRight = containerLeft + containerWidth;
13685 popupLeft = popupOffset - this.containerPadding;
13686 popupRight = popupOffset + this.containerPadding + this.width + this.containerPadding;
13687 overlapLeft = ( originOffset + popupLeft ) - containerLeft;
13688 overlapRight = containerRight - ( originOffset + popupRight );
13689
13690 // Adjust offset to make the popup not go beyond the edge, if needed
13691 if ( overlapRight < 0 ) {
13692 popupOffset += overlapRight;
13693 } else if ( overlapLeft < 0 ) {
13694 popupOffset -= overlapLeft;
13695 }
13696
13697 // Adjust offset to avoid anchor being rendered too close to the edge
13698 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
13699 // TODO: Find a measurement that works for CSS anchors and image anchors
13700 anchorWidth = this.$anchor[ 0 ].scrollWidth * 2;
13701 if ( popupOffset + this.width < anchorWidth ) {
13702 popupOffset = anchorWidth - this.width;
13703 } else if ( -popupOffset < anchorWidth ) {
13704 popupOffset = -anchorWidth;
13705 }
13706
13707 // Prevent transition from being interrupted
13708 clearTimeout( this.transitionTimeout );
13709 if ( transition ) {
13710 // Enable transition
13711 this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
13712 }
13713
13714 // Position body relative to anchor
13715 this.$popup.css( 'margin-left', popupOffset );
13716
13717 if ( transition ) {
13718 // Prevent transitioning after transition is complete
13719 this.transitionTimeout = setTimeout( function () {
13720 widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
13721 }, 200 );
13722 } else {
13723 // Prevent transitioning immediately
13724 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
13725 }
13726
13727 // Reevaluate clipping state since we've relocated and resized the popup
13728 this.clip();
13729
13730 return this;
13731 };
13732
13733 /**
13734 * Progress bars visually display the status of an operation, such as a download,
13735 * and can be either determinate or indeterminate:
13736 *
13737 * - **determinate** process bars show the percent of an operation that is complete.
13738 *
13739 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
13740 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
13741 * not use percentages.
13742 *
13743 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
13744 *
13745 * @example
13746 * // Examples of determinate and indeterminate progress bars.
13747 * var progressBar1 = new OO.ui.ProgressBarWidget( {
13748 * progress: 33
13749 * } );
13750 * var progressBar2 = new OO.ui.ProgressBarWidget();
13751 *
13752 * // Create a FieldsetLayout to layout progress bars
13753 * var fieldset = new OO.ui.FieldsetLayout;
13754 * fieldset.addItems( [
13755 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
13756 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
13757 * ] );
13758 * $( 'body' ).append( fieldset.$element );
13759 *
13760 * @class
13761 * @extends OO.ui.Widget
13762 *
13763 * @constructor
13764 * @param {Object} [config] Configuration options
13765 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
13766 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
13767 * By default, the progress bar is indeterminate.
13768 */
13769 OO.ui.ProgressBarWidget = function OoUiProgressBarWidget( config ) {
13770 // Configuration initialization
13771 config = config || {};
13772
13773 // Parent constructor
13774 OO.ui.ProgressBarWidget.super.call( this, config );
13775
13776 // Properties
13777 this.$bar = $( '<div>' );
13778 this.progress = null;
13779
13780 // Initialization
13781 this.setProgress( config.progress !== undefined ? config.progress : false );
13782 this.$bar.addClass( 'oo-ui-progressBarWidget-bar' );
13783 this.$element
13784 .attr( {
13785 role: 'progressbar',
13786 'aria-valuemin': 0,
13787 'aria-valuemax': 100
13788 } )
13789 .addClass( 'oo-ui-progressBarWidget' )
13790 .append( this.$bar );
13791 };
13792
13793 /* Setup */
13794
13795 OO.inheritClass( OO.ui.ProgressBarWidget, OO.ui.Widget );
13796
13797 /* Static Properties */
13798
13799 OO.ui.ProgressBarWidget.static.tagName = 'div';
13800
13801 /* Methods */
13802
13803 /**
13804 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
13805 *
13806 * @return {number|boolean} Progress percent
13807 */
13808 OO.ui.ProgressBarWidget.prototype.getProgress = function () {
13809 return this.progress;
13810 };
13811
13812 /**
13813 * Set the percent of the process completed or `false` for an indeterminate process.
13814 *
13815 * @param {number|boolean} progress Progress percent or `false` for indeterminate
13816 */
13817 OO.ui.ProgressBarWidget.prototype.setProgress = function ( progress ) {
13818 this.progress = progress;
13819
13820 if ( progress !== false ) {
13821 this.$bar.css( 'width', this.progress + '%' );
13822 this.$element.attr( 'aria-valuenow', this.progress );
13823 } else {
13824 this.$bar.css( 'width', '' );
13825 this.$element.removeAttr( 'aria-valuenow' );
13826 }
13827 this.$element.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress );
13828 };
13829
13830 /**
13831 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
13832 * and a {@link OO.ui.TextInputMenuSelectWidget menu} of search results, which is displayed beneath the query
13833 * field. Unlike {@link OO.ui.LookupElement lookup menus}, search result menus are always visible to the user.
13834 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
13835 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
13836 *
13837 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
13838 * the [OOjs UI demos][1] for an example.
13839 *
13840 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
13841 *
13842 * @class
13843 * @extends OO.ui.Widget
13844 *
13845 * @constructor
13846 * @param {Object} [config] Configuration options
13847 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
13848 * @cfg {string} [value] Initial query value
13849 */
13850 OO.ui.SearchWidget = function OoUiSearchWidget( config ) {
13851 // Configuration initialization
13852 config = config || {};
13853
13854 // Parent constructor
13855 OO.ui.SearchWidget.super.call( this, config );
13856
13857 // Properties
13858 this.query = new OO.ui.TextInputWidget( {
13859 icon: 'search',
13860 placeholder: config.placeholder,
13861 value: config.value
13862 } );
13863 this.results = new OO.ui.SelectWidget();
13864 this.$query = $( '<div>' );
13865 this.$results = $( '<div>' );
13866
13867 // Events
13868 this.query.connect( this, {
13869 change: 'onQueryChange',
13870 enter: 'onQueryEnter'
13871 } );
13872 this.results.connect( this, {
13873 highlight: 'onResultsHighlight',
13874 select: 'onResultsSelect'
13875 } );
13876 this.query.$input.on( 'keydown', this.onQueryKeydown.bind( this ) );
13877
13878 // Initialization
13879 this.$query
13880 .addClass( 'oo-ui-searchWidget-query' )
13881 .append( this.query.$element );
13882 this.$results
13883 .addClass( 'oo-ui-searchWidget-results' )
13884 .append( this.results.$element );
13885 this.$element
13886 .addClass( 'oo-ui-searchWidget' )
13887 .append( this.$results, this.$query );
13888 };
13889
13890 /* Setup */
13891
13892 OO.inheritClass( OO.ui.SearchWidget, OO.ui.Widget );
13893
13894 /* Events */
13895
13896 /**
13897 * A 'highlight' event is emitted when an item is highlighted. The highlight indicates which
13898 * item will be selected. When a user mouses over a menu item, it is highlighted. If a search
13899 * string is typed into the query field instead, the first menu item that matches the query
13900 * will be highlighted.
13901
13902 * @event highlight
13903 * @deprecated Connect straight to getResults() events instead
13904 * @param {Object|null} item Item data or null if no item is highlighted
13905 */
13906
13907 /**
13908 * A 'select' event is emitted when an item is selected. A menu item is selected when it is clicked,
13909 * or when a user types a search query, a menu result is highlighted, and the user presses enter.
13910 *
13911 * @event select
13912 * @deprecated Connect straight to getResults() events instead
13913 * @param {Object|null} item Item data or null if no item is selected
13914 */
13915
13916 /* Methods */
13917
13918 /**
13919 * Handle query key down events.
13920 *
13921 * @private
13922 * @param {jQuery.Event} e Key down event
13923 */
13924 OO.ui.SearchWidget.prototype.onQueryKeydown = function ( e ) {
13925 var highlightedItem, nextItem,
13926 dir = e.which === OO.ui.Keys.DOWN ? 1 : ( e.which === OO.ui.Keys.UP ? -1 : 0 );
13927
13928 if ( dir ) {
13929 highlightedItem = this.results.getHighlightedItem();
13930 if ( !highlightedItem ) {
13931 highlightedItem = this.results.getSelectedItem();
13932 }
13933 nextItem = this.results.getRelativeSelectableItem( highlightedItem, dir );
13934 this.results.highlightItem( nextItem );
13935 nextItem.scrollElementIntoView();
13936 }
13937 };
13938
13939 /**
13940 * Handle select widget select events.
13941 *
13942 * Clears existing results. Subclasses should repopulate items according to new query.
13943 *
13944 * @private
13945 * @param {string} value New value
13946 */
13947 OO.ui.SearchWidget.prototype.onQueryChange = function () {
13948 // Reset
13949 this.results.clearItems();
13950 };
13951
13952 /**
13953 * Handle select widget enter key events.
13954 *
13955 * Selects highlighted item.
13956 *
13957 * @private
13958 * @param {string} value New value
13959 */
13960 OO.ui.SearchWidget.prototype.onQueryEnter = function () {
13961 // Reset
13962 this.results.selectItem( this.results.getHighlightedItem() );
13963 };
13964
13965 /**
13966 * Handle select widget highlight events.
13967 *
13968 * @private
13969 * @deprecated Connect straight to getResults() events instead
13970 * @param {OO.ui.OptionWidget} item Highlighted item
13971 * @fires highlight
13972 */
13973 OO.ui.SearchWidget.prototype.onResultsHighlight = function ( item ) {
13974 this.emit( 'highlight', item ? item.getData() : null );
13975 };
13976
13977 /**
13978 * Handle select widget select events.
13979 *
13980 * @private
13981 * @deprecated Connect straight to getResults() events instead
13982 * @param {OO.ui.OptionWidget} item Selected item
13983 * @fires select
13984 */
13985 OO.ui.SearchWidget.prototype.onResultsSelect = function ( item ) {
13986 this.emit( 'select', item ? item.getData() : null );
13987 };
13988
13989 /**
13990 * Get the query input.
13991 *
13992 * @return {OO.ui.TextInputWidget} Query input
13993 */
13994 OO.ui.SearchWidget.prototype.getQuery = function () {
13995 return this.query;
13996 };
13997
13998 /**
13999 * Get the search results menu.
14000 *
14001 * @return {OO.ui.SelectWidget} Menu of search results
14002 */
14003 OO.ui.SearchWidget.prototype.getResults = function () {
14004 return this.results;
14005 };
14006
14007 /**
14008 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
14009 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
14010 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
14011 * menu selects}.
14012 *
14013 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
14014 * information, please see the [OOjs UI documentation on MediaWiki][1].
14015 *
14016 * @example
14017 * // Example of a select widget with three options
14018 * var select = new OO.ui.SelectWidget( {
14019 * items: [
14020 * new OO.ui.OptionWidget( {
14021 * data: 'a',
14022 * label: 'Option One',
14023 * } ),
14024 * new OO.ui.OptionWidget( {
14025 * data: 'b',
14026 * label: 'Option Two',
14027 * } ),
14028 * new OO.ui.OptionWidget( {
14029 * data: 'c',
14030 * label: 'Option Three',
14031 * } )
14032 * ]
14033 * } );
14034 * $( 'body' ).append( select.$element );
14035 *
14036 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14037 *
14038 * @class
14039 * @extends OO.ui.Widget
14040 * @mixins OO.ui.GroupElement
14041 *
14042 * @constructor
14043 * @param {Object} [config] Configuration options
14044 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
14045 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
14046 * the [OOjs UI documentation on MediaWiki] [2] for examples.
14047 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14048 */
14049 OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
14050 // Configuration initialization
14051 config = config || {};
14052
14053 // Parent constructor
14054 OO.ui.SelectWidget.super.call( this, config );
14055
14056 // Mixin constructors
14057 OO.ui.GroupWidget.call( this, $.extend( {}, config, { $group: this.$element } ) );
14058
14059 // Properties
14060 this.pressed = false;
14061 this.selecting = null;
14062 this.onMouseUpHandler = this.onMouseUp.bind( this );
14063 this.onMouseMoveHandler = this.onMouseMove.bind( this );
14064 this.onKeyDownHandler = this.onKeyDown.bind( this );
14065
14066 // Events
14067 this.$element.on( {
14068 mousedown: this.onMouseDown.bind( this ),
14069 mouseover: this.onMouseOver.bind( this ),
14070 mouseleave: this.onMouseLeave.bind( this )
14071 } );
14072
14073 // Initialization
14074 this.$element
14075 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
14076 .attr( 'role', 'listbox' );
14077 if ( Array.isArray( config.items ) ) {
14078 this.addItems( config.items );
14079 }
14080 };
14081
14082 /* Setup */
14083
14084 OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
14085
14086 // Need to mixin base class as well
14087 OO.mixinClass( OO.ui.SelectWidget, OO.ui.GroupElement );
14088 OO.mixinClass( OO.ui.SelectWidget, OO.ui.GroupWidget );
14089
14090 /* Events */
14091
14092 /**
14093 * @event highlight
14094 *
14095 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
14096 *
14097 * @param {OO.ui.OptionWidget|null} item Highlighted item
14098 */
14099
14100 /**
14101 * @event press
14102 *
14103 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
14104 * pressed state of an option.
14105 *
14106 * @param {OO.ui.OptionWidget|null} item Pressed item
14107 */
14108
14109 /**
14110 * @event select
14111 *
14112 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
14113 *
14114 * @param {OO.ui.OptionWidget|null} item Selected item
14115 */
14116
14117 /**
14118 * @event choose
14119 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
14120 * @param {OO.ui.OptionWidget} item Chosen item
14121 */
14122
14123 /**
14124 * @event add
14125 *
14126 * An `add` event is emitted when options are added to the select with the #addItems method.
14127 *
14128 * @param {OO.ui.OptionWidget[]} items Added items
14129 * @param {number} index Index of insertion point
14130 */
14131
14132 /**
14133 * @event remove
14134 *
14135 * A `remove` event is emitted when options are removed from the select with the #clearItems
14136 * or #removeItems methods.
14137 *
14138 * @param {OO.ui.OptionWidget[]} items Removed items
14139 */
14140
14141 /* Methods */
14142
14143 /**
14144 * Handle mouse down events.
14145 *
14146 * @private
14147 * @param {jQuery.Event} e Mouse down event
14148 */
14149 OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
14150 var item;
14151
14152 if ( !this.isDisabled() && e.which === 1 ) {
14153 this.togglePressed( true );
14154 item = this.getTargetItem( e );
14155 if ( item && item.isSelectable() ) {
14156 this.pressItem( item );
14157 this.selecting = item;
14158 this.getElementDocument().addEventListener(
14159 'mouseup',
14160 this.onMouseUpHandler,
14161 true
14162 );
14163 this.getElementDocument().addEventListener(
14164 'mousemove',
14165 this.onMouseMoveHandler,
14166 true
14167 );
14168 }
14169 }
14170 return false;
14171 };
14172
14173 /**
14174 * Handle mouse up events.
14175 *
14176 * @private
14177 * @param {jQuery.Event} e Mouse up event
14178 */
14179 OO.ui.SelectWidget.prototype.onMouseUp = function ( e ) {
14180 var item;
14181
14182 this.togglePressed( false );
14183 if ( !this.selecting ) {
14184 item = this.getTargetItem( e );
14185 if ( item && item.isSelectable() ) {
14186 this.selecting = item;
14187 }
14188 }
14189 if ( !this.isDisabled() && e.which === 1 && this.selecting ) {
14190 this.pressItem( null );
14191 this.chooseItem( this.selecting );
14192 this.selecting = null;
14193 }
14194
14195 this.getElementDocument().removeEventListener(
14196 'mouseup',
14197 this.onMouseUpHandler,
14198 true
14199 );
14200 this.getElementDocument().removeEventListener(
14201 'mousemove',
14202 this.onMouseMoveHandler,
14203 true
14204 );
14205
14206 return false;
14207 };
14208
14209 /**
14210 * Handle mouse move events.
14211 *
14212 * @private
14213 * @param {jQuery.Event} e Mouse move event
14214 */
14215 OO.ui.SelectWidget.prototype.onMouseMove = function ( e ) {
14216 var item;
14217
14218 if ( !this.isDisabled() && this.pressed ) {
14219 item = this.getTargetItem( e );
14220 if ( item && item !== this.selecting && item.isSelectable() ) {
14221 this.pressItem( item );
14222 this.selecting = item;
14223 }
14224 }
14225 return false;
14226 };
14227
14228 /**
14229 * Handle mouse over events.
14230 *
14231 * @private
14232 * @param {jQuery.Event} e Mouse over event
14233 */
14234 OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
14235 var item;
14236
14237 if ( !this.isDisabled() ) {
14238 item = this.getTargetItem( e );
14239 this.highlightItem( item && item.isHighlightable() ? item : null );
14240 }
14241 return false;
14242 };
14243
14244 /**
14245 * Handle mouse leave events.
14246 *
14247 * @private
14248 * @param {jQuery.Event} e Mouse over event
14249 */
14250 OO.ui.SelectWidget.prototype.onMouseLeave = function () {
14251 if ( !this.isDisabled() ) {
14252 this.highlightItem( null );
14253 }
14254 return false;
14255 };
14256
14257 /**
14258 * Handle key down events.
14259 *
14260 * @protected
14261 * @param {jQuery.Event} e Key down event
14262 */
14263 OO.ui.SelectWidget.prototype.onKeyDown = function ( e ) {
14264 var nextItem,
14265 handled = false,
14266 currentItem = this.getHighlightedItem() || this.getSelectedItem();
14267
14268 if ( !this.isDisabled() && this.isVisible() ) {
14269 switch ( e.keyCode ) {
14270 case OO.ui.Keys.ENTER:
14271 if ( currentItem && currentItem.constructor.static.highlightable ) {
14272 // Was only highlighted, now let's select it. No-op if already selected.
14273 this.chooseItem( currentItem );
14274 handled = true;
14275 }
14276 break;
14277 case OO.ui.Keys.UP:
14278 case OO.ui.Keys.LEFT:
14279 nextItem = this.getRelativeSelectableItem( currentItem, -1 );
14280 handled = true;
14281 break;
14282 case OO.ui.Keys.DOWN:
14283 case OO.ui.Keys.RIGHT:
14284 nextItem = this.getRelativeSelectableItem( currentItem, 1 );
14285 handled = true;
14286 break;
14287 case OO.ui.Keys.ESCAPE:
14288 case OO.ui.Keys.TAB:
14289 if ( currentItem && currentItem.constructor.static.highlightable ) {
14290 currentItem.setHighlighted( false );
14291 }
14292 this.unbindKeyDownListener();
14293 // Don't prevent tabbing away / defocusing
14294 handled = false;
14295 break;
14296 }
14297
14298 if ( nextItem ) {
14299 if ( nextItem.constructor.static.highlightable ) {
14300 this.highlightItem( nextItem );
14301 } else {
14302 this.chooseItem( nextItem );
14303 }
14304 nextItem.scrollElementIntoView();
14305 }
14306
14307 if ( handled ) {
14308 // Can't just return false, because e is not always a jQuery event
14309 e.preventDefault();
14310 e.stopPropagation();
14311 }
14312 }
14313 };
14314
14315 /**
14316 * Bind key down listener.
14317 *
14318 * @protected
14319 */
14320 OO.ui.SelectWidget.prototype.bindKeyDownListener = function () {
14321 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler, true );
14322 };
14323
14324 /**
14325 * Unbind key down listener.
14326 *
14327 * @protected
14328 */
14329 OO.ui.SelectWidget.prototype.unbindKeyDownListener = function () {
14330 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler, true );
14331 };
14332
14333 /**
14334 * Get the closest item to a jQuery.Event.
14335 *
14336 * @private
14337 * @param {jQuery.Event} e
14338 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
14339 */
14340 OO.ui.SelectWidget.prototype.getTargetItem = function ( e ) {
14341 return $( e.target ).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
14342 };
14343
14344 /**
14345 * Get selected item.
14346 *
14347 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
14348 */
14349 OO.ui.SelectWidget.prototype.getSelectedItem = function () {
14350 var i, len;
14351
14352 for ( i = 0, len = this.items.length; i < len; i++ ) {
14353 if ( this.items[ i ].isSelected() ) {
14354 return this.items[ i ];
14355 }
14356 }
14357 return null;
14358 };
14359
14360 /**
14361 * Get highlighted item.
14362 *
14363 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
14364 */
14365 OO.ui.SelectWidget.prototype.getHighlightedItem = function () {
14366 var i, len;
14367
14368 for ( i = 0, len = this.items.length; i < len; i++ ) {
14369 if ( this.items[ i ].isHighlighted() ) {
14370 return this.items[ i ];
14371 }
14372 }
14373 return null;
14374 };
14375
14376 /**
14377 * Toggle pressed state.
14378 *
14379 * Press is a state that occurs when a user mouses down on an item, but
14380 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
14381 * until the user releases the mouse.
14382 *
14383 * @param {boolean} pressed An option is being pressed
14384 */
14385 OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
14386 if ( pressed === undefined ) {
14387 pressed = !this.pressed;
14388 }
14389 if ( pressed !== this.pressed ) {
14390 this.$element
14391 .toggleClass( 'oo-ui-selectWidget-pressed', pressed )
14392 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed );
14393 this.pressed = pressed;
14394 }
14395 };
14396
14397 /**
14398 * Highlight an option. If the `item` param is omitted, no options will be highlighted
14399 * and any existing highlight will be removed. The highlight is mutually exclusive.
14400 *
14401 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
14402 * @fires highlight
14403 * @chainable
14404 */
14405 OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
14406 var i, len, highlighted,
14407 changed = false;
14408
14409 for ( i = 0, len = this.items.length; i < len; i++ ) {
14410 highlighted = this.items[ i ] === item;
14411 if ( this.items[ i ].isHighlighted() !== highlighted ) {
14412 this.items[ i ].setHighlighted( highlighted );
14413 changed = true;
14414 }
14415 }
14416 if ( changed ) {
14417 this.emit( 'highlight', item );
14418 }
14419
14420 return this;
14421 };
14422
14423 /**
14424 * Programmatically select an option by its reference. If the `item` parameter is omitted,
14425 * all options will be deselected.
14426 *
14427 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
14428 * @fires select
14429 * @chainable
14430 */
14431 OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
14432 var i, len, selected,
14433 changed = false;
14434
14435 for ( i = 0, len = this.items.length; i < len; i++ ) {
14436 selected = this.items[ i ] === item;
14437 if ( this.items[ i ].isSelected() !== selected ) {
14438 this.items[ i ].setSelected( selected );
14439 changed = true;
14440 }
14441 }
14442 if ( changed ) {
14443 this.emit( 'select', item );
14444 }
14445
14446 return this;
14447 };
14448
14449 /**
14450 * Press an item.
14451 *
14452 * Press is a state that occurs when a user mouses down on an item, but has not
14453 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
14454 * releases the mouse.
14455 *
14456 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
14457 * @fires press
14458 * @chainable
14459 */
14460 OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
14461 var i, len, pressed,
14462 changed = false;
14463
14464 for ( i = 0, len = this.items.length; i < len; i++ ) {
14465 pressed = this.items[ i ] === item;
14466 if ( this.items[ i ].isPressed() !== pressed ) {
14467 this.items[ i ].setPressed( pressed );
14468 changed = true;
14469 }
14470 }
14471 if ( changed ) {
14472 this.emit( 'press', item );
14473 }
14474
14475 return this;
14476 };
14477
14478 /**
14479 * Choose an item.
14480 *
14481 * Note that ‘choose’ should never be modified programmatically. A user can choose
14482 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
14483 * use the #selectItem method.
14484 *
14485 * This method is identical to #selectItem, but may vary in subclasses that take additional action
14486 * when users choose an item with the keyboard or mouse.
14487 *
14488 * @param {OO.ui.OptionWidget} item Item to choose
14489 * @fires choose
14490 * @chainable
14491 */
14492 OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
14493 this.selectItem( item );
14494 this.emit( 'choose', item );
14495
14496 return this;
14497 };
14498
14499 /**
14500 * Get an option by its position relative to the specified item (or to the start of the option array,
14501 * if item is `null`). The direction in which to search through the option array is specified with a
14502 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
14503 * `null` if there are no options in the array.
14504 *
14505 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
14506 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
14507 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
14508 */
14509 OO.ui.SelectWidget.prototype.getRelativeSelectableItem = function ( item, direction ) {
14510 var currentIndex, nextIndex, i,
14511 increase = direction > 0 ? 1 : -1,
14512 len = this.items.length;
14513
14514 if ( item instanceof OO.ui.OptionWidget ) {
14515 currentIndex = $.inArray( item, this.items );
14516 nextIndex = ( currentIndex + increase + len ) % len;
14517 } else {
14518 // If no item is selected and moving forward, start at the beginning.
14519 // If moving backward, start at the end.
14520 nextIndex = direction > 0 ? 0 : len - 1;
14521 }
14522
14523 for ( i = 0; i < len; i++ ) {
14524 item = this.items[ nextIndex ];
14525 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
14526 return item;
14527 }
14528 nextIndex = ( nextIndex + increase + len ) % len;
14529 }
14530 return null;
14531 };
14532
14533 /**
14534 * Get the next selectable item or `null` if there are no selectable items.
14535 * Disabled options and menu-section markers and breaks are not selectable.
14536 *
14537 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
14538 */
14539 OO.ui.SelectWidget.prototype.getFirstSelectableItem = function () {
14540 var i, len, item;
14541
14542 for ( i = 0, len = this.items.length; i < len; i++ ) {
14543 item = this.items[ i ];
14544 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
14545 return item;
14546 }
14547 }
14548
14549 return null;
14550 };
14551
14552 /**
14553 * Add an array of options to the select. Optionally, an index number can be used to
14554 * specify an insertion point.
14555 *
14556 * @param {OO.ui.OptionWidget[]} items Items to add
14557 * @param {number} [index] Index to insert items after
14558 * @fires add
14559 * @chainable
14560 */
14561 OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
14562 // Mixin method
14563 OO.ui.GroupWidget.prototype.addItems.call( this, items, index );
14564
14565 // Always provide an index, even if it was omitted
14566 this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
14567
14568 return this;
14569 };
14570
14571 /**
14572 * Remove the specified array of options from the select. Options will be detached
14573 * from the DOM, not removed, so they can be reused later. To remove all options from
14574 * the select, you may wish to use the #clearItems method instead.
14575 *
14576 * @param {OO.ui.OptionWidget[]} items Items to remove
14577 * @fires remove
14578 * @chainable
14579 */
14580 OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
14581 var i, len, item;
14582
14583 // Deselect items being removed
14584 for ( i = 0, len = items.length; i < len; i++ ) {
14585 item = items[ i ];
14586 if ( item.isSelected() ) {
14587 this.selectItem( null );
14588 }
14589 }
14590
14591 // Mixin method
14592 OO.ui.GroupWidget.prototype.removeItems.call( this, items );
14593
14594 this.emit( 'remove', items );
14595
14596 return this;
14597 };
14598
14599 /**
14600 * Clear all options from the select. Options will be detached from the DOM, not removed,
14601 * so that they can be reused later. To remove a subset of options from the select, use
14602 * the #removeItems method.
14603 *
14604 * @fires remove
14605 * @chainable
14606 */
14607 OO.ui.SelectWidget.prototype.clearItems = function () {
14608 var items = this.items.slice();
14609
14610 // Mixin method
14611 OO.ui.GroupWidget.prototype.clearItems.call( this );
14612
14613 // Clear selection
14614 this.selectItem( null );
14615
14616 this.emit( 'remove', items );
14617
14618 return this;
14619 };
14620
14621 /**
14622 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
14623 * button options and is used together with
14624 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
14625 * highlighting, choosing, and selecting mutually exclusive options. Please see
14626 * the [OOjs UI documentation on MediaWiki] [1] for more information.
14627 *
14628 * @example
14629 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
14630 * var option1 = new OO.ui.ButtonOptionWidget( {
14631 * data: 1,
14632 * label: 'Option 1',
14633 * title: 'Button option 1'
14634 * } );
14635 *
14636 * var option2 = new OO.ui.ButtonOptionWidget( {
14637 * data: 2,
14638 * label: 'Option 2',
14639 * title: 'Button option 2'
14640 * } );
14641 *
14642 * var option3 = new OO.ui.ButtonOptionWidget( {
14643 * data: 3,
14644 * label: 'Option 3',
14645 * title: 'Button option 3'
14646 * } );
14647 *
14648 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
14649 * items: [ option1, option2, option3 ]
14650 * } );
14651 * $( 'body' ).append( buttonSelect.$element );
14652 *
14653 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14654 *
14655 * @class
14656 * @extends OO.ui.SelectWidget
14657 * @mixins OO.ui.TabIndexedElement
14658 *
14659 * @constructor
14660 * @param {Object} [config] Configuration options
14661 */
14662 OO.ui.ButtonSelectWidget = function OoUiButtonSelectWidget( config ) {
14663 // Parent constructor
14664 OO.ui.ButtonSelectWidget.super.call( this, config );
14665
14666 // Mixin constructors
14667 OO.ui.TabIndexedElement.call( this, config );
14668
14669 // Events
14670 this.$element.on( {
14671 focus: this.bindKeyDownListener.bind( this ),
14672 blur: this.unbindKeyDownListener.bind( this )
14673 } );
14674
14675 // Initialization
14676 this.$element.addClass( 'oo-ui-buttonSelectWidget' );
14677 };
14678
14679 /* Setup */
14680
14681 OO.inheritClass( OO.ui.ButtonSelectWidget, OO.ui.SelectWidget );
14682 OO.mixinClass( OO.ui.ButtonSelectWidget, OO.ui.TabIndexedElement );
14683
14684 /**
14685 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
14686 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
14687 * an interface for adding, removing and selecting options.
14688 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
14689 *
14690 * @example
14691 * // A RadioSelectWidget with RadioOptions.
14692 * var option1 = new OO.ui.RadioOptionWidget( {
14693 * data: 'a',
14694 * label: 'Selected radio option'
14695 * } );
14696 *
14697 * var option2 = new OO.ui.RadioOptionWidget( {
14698 * data: 'b',
14699 * label: 'Unselected radio option'
14700 * } );
14701 *
14702 * var radioSelect=new OO.ui.RadioSelectWidget( {
14703 * items: [ option1, option2 ]
14704 * } );
14705 *
14706 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
14707 * radioSelect.selectItem( option1 );
14708 *
14709 * $( 'body' ).append( radioSelect.$element );
14710 *
14711 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14712
14713 *
14714 * @class
14715 * @extends OO.ui.SelectWidget
14716 * @mixins OO.ui.TabIndexedElement
14717 *
14718 * @constructor
14719 * @param {Object} [config] Configuration options
14720 */
14721 OO.ui.RadioSelectWidget = function OoUiRadioSelectWidget( config ) {
14722 // Parent constructor
14723 OO.ui.RadioSelectWidget.super.call( this, config );
14724
14725 // Mixin constructors
14726 OO.ui.TabIndexedElement.call( this, config );
14727
14728 // Events
14729 this.$element.on( {
14730 focus: this.bindKeyDownListener.bind( this ),
14731 blur: this.unbindKeyDownListener.bind( this )
14732 } );
14733
14734 // Initialization
14735 this.$element.addClass( 'oo-ui-radioSelectWidget' );
14736 };
14737
14738 /* Setup */
14739
14740 OO.inheritClass( OO.ui.RadioSelectWidget, OO.ui.SelectWidget );
14741 OO.mixinClass( OO.ui.RadioSelectWidget, OO.ui.TabIndexedElement );
14742
14743 /**
14744 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
14745 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
14746 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxWidget ComboBoxWidget},
14747 * and {@link OO.ui.LookupElement LookupElement} for examples of widgets that contain menus.
14748 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
14749 * and customized to be opened, closed, and displayed as needed.
14750 *
14751 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
14752 * mouse outside the menu.
14753 *
14754 * Menus also have support for keyboard interaction:
14755 *
14756 * - Enter/Return key: choose and select a menu option
14757 * - Up-arrow key: highlight the previous menu option
14758 * - Down-arrow key: highlight the next menu option
14759 * - Esc key: hide the menu
14760 *
14761 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
14762 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14763 *
14764 * @class
14765 * @extends OO.ui.SelectWidget
14766 * @mixins OO.ui.ClippableElement
14767 *
14768 * @constructor
14769 * @param {Object} [config] Configuration options
14770 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
14771 * the text the user types. This config is used by {@link OO.ui.ComboBoxWidget ComboBoxWidget}
14772 * and {@link OO.ui.LookupElement LookupElement}
14773 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu’s active state. If the user clicks the mouse
14774 * anywhere on the page outside of this widget, the menu is hidden.
14775 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
14776 */
14777 OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) {
14778 // Configuration initialization
14779 config = config || {};
14780
14781 // Parent constructor
14782 OO.ui.MenuSelectWidget.super.call( this, config );
14783
14784 // Mixin constructors
14785 OO.ui.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
14786
14787 // Properties
14788 this.newItems = null;
14789 this.autoHide = config.autoHide === undefined || !!config.autoHide;
14790 this.$input = config.input ? config.input.$input : null;
14791 this.$widget = config.widget ? config.widget.$element : null;
14792 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
14793
14794 // Initialization
14795 this.$element
14796 .addClass( 'oo-ui-menuSelectWidget' )
14797 .attr( 'role', 'menu' );
14798
14799 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
14800 // that reference properties not initialized at that time of parent class construction
14801 // TODO: Find a better way to handle post-constructor setup
14802 this.visible = false;
14803 this.$element.addClass( 'oo-ui-element-hidden' );
14804 };
14805
14806 /* Setup */
14807
14808 OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget );
14809 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.ClippableElement );
14810
14811 /* Methods */
14812
14813 /**
14814 * Handles document mouse down events.
14815 *
14816 * @protected
14817 * @param {jQuery.Event} e Key down event
14818 */
14819 OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) {
14820 if (
14821 !OO.ui.contains( this.$element[ 0 ], e.target, true ) &&
14822 ( !this.$widget || !OO.ui.contains( this.$widget[ 0 ], e.target, true ) )
14823 ) {
14824 this.toggle( false );
14825 }
14826 };
14827
14828 /**
14829 * @inheritdoc
14830 */
14831 OO.ui.MenuSelectWidget.prototype.onKeyDown = function ( e ) {
14832 var currentItem = this.getHighlightedItem() || this.getSelectedItem();
14833
14834 if ( !this.isDisabled() && this.isVisible() ) {
14835 switch ( e.keyCode ) {
14836 case OO.ui.Keys.LEFT:
14837 case OO.ui.Keys.RIGHT:
14838 // Do nothing if a text field is associated, arrow keys will be handled natively
14839 if ( !this.$input ) {
14840 OO.ui.MenuSelectWidget.super.prototype.onKeyDown.call( this, e );
14841 }
14842 break;
14843 case OO.ui.Keys.ESCAPE:
14844 case OO.ui.Keys.TAB:
14845 if ( currentItem ) {
14846 currentItem.setHighlighted( false );
14847 }
14848 this.toggle( false );
14849 // Don't prevent tabbing away, prevent defocusing
14850 if ( e.keyCode === OO.ui.Keys.ESCAPE ) {
14851 e.preventDefault();
14852 e.stopPropagation();
14853 }
14854 break;
14855 default:
14856 OO.ui.MenuSelectWidget.super.prototype.onKeyDown.call( this, e );
14857 return;
14858 }
14859 }
14860 };
14861
14862 /**
14863 * @inheritdoc
14864 */
14865 OO.ui.MenuSelectWidget.prototype.bindKeyDownListener = function () {
14866 if ( this.$input ) {
14867 this.$input.on( 'keydown', this.onKeyDownHandler );
14868 } else {
14869 OO.ui.MenuSelectWidget.super.prototype.bindKeyDownListener.call( this );
14870 }
14871 };
14872
14873 /**
14874 * @inheritdoc
14875 */
14876 OO.ui.MenuSelectWidget.prototype.unbindKeyDownListener = function () {
14877 if ( this.$input ) {
14878 this.$input.off( 'keydown', this.onKeyDownHandler );
14879 } else {
14880 OO.ui.MenuSelectWidget.super.prototype.unbindKeyDownListener.call( this );
14881 }
14882 };
14883
14884 /**
14885 * Choose an item.
14886 *
14887 * When a user chooses an item, the menu is closed.
14888 *
14889 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
14890 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
14891 * @param {OO.ui.OptionWidget} item Item to choose
14892 * @chainable
14893 */
14894 OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) {
14895 OO.ui.MenuSelectWidget.super.prototype.chooseItem.call( this, item );
14896 this.toggle( false );
14897 return this;
14898 };
14899
14900 /**
14901 * @inheritdoc
14902 */
14903 OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) {
14904 var i, len, item;
14905
14906 // Parent method
14907 OO.ui.MenuSelectWidget.super.prototype.addItems.call( this, items, index );
14908
14909 // Auto-initialize
14910 if ( !this.newItems ) {
14911 this.newItems = [];
14912 }
14913
14914 for ( i = 0, len = items.length; i < len; i++ ) {
14915 item = items[ i ];
14916 if ( this.isVisible() ) {
14917 // Defer fitting label until item has been attached
14918 item.fitLabel();
14919 } else {
14920 this.newItems.push( item );
14921 }
14922 }
14923
14924 // Reevaluate clipping
14925 this.clip();
14926
14927 return this;
14928 };
14929
14930 /**
14931 * @inheritdoc
14932 */
14933 OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) {
14934 // Parent method
14935 OO.ui.MenuSelectWidget.super.prototype.removeItems.call( this, items );
14936
14937 // Reevaluate clipping
14938 this.clip();
14939
14940 return this;
14941 };
14942
14943 /**
14944 * @inheritdoc
14945 */
14946 OO.ui.MenuSelectWidget.prototype.clearItems = function () {
14947 // Parent method
14948 OO.ui.MenuSelectWidget.super.prototype.clearItems.call( this );
14949
14950 // Reevaluate clipping
14951 this.clip();
14952
14953 return this;
14954 };
14955
14956 /**
14957 * @inheritdoc
14958 */
14959 OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) {
14960 visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length;
14961
14962 var i, len,
14963 change = visible !== this.isVisible();
14964
14965 // Parent method
14966 OO.ui.MenuSelectWidget.super.prototype.toggle.call( this, visible );
14967
14968 if ( change ) {
14969 if ( visible ) {
14970 this.bindKeyDownListener();
14971
14972 if ( this.newItems && this.newItems.length ) {
14973 for ( i = 0, len = this.newItems.length; i < len; i++ ) {
14974 this.newItems[ i ].fitLabel();
14975 }
14976 this.newItems = null;
14977 }
14978 this.toggleClipping( true );
14979
14980 // Auto-hide
14981 if ( this.autoHide ) {
14982 this.getElementDocument().addEventListener(
14983 'mousedown', this.onDocumentMouseDownHandler, true
14984 );
14985 }
14986 } else {
14987 this.unbindKeyDownListener();
14988 this.getElementDocument().removeEventListener(
14989 'mousedown', this.onDocumentMouseDownHandler, true
14990 );
14991 this.toggleClipping( false );
14992 }
14993 }
14994
14995 return this;
14996 };
14997
14998 /**
14999 * TextInputMenuSelectWidget is a menu that is specially designed to be positioned beneath
15000 * a {@link OO.ui.TextInputWidget text input} field. The menu's position is automatically
15001 * calculated and maintained when the menu is toggled or the window is resized.
15002 * See OO.ui.ComboBoxWidget for an example of a widget that uses this class.
15003 *
15004 * @class
15005 * @extends OO.ui.MenuSelectWidget
15006 *
15007 * @constructor
15008 * @param {OO.ui.TextInputWidget} inputWidget Text input widget to provide menu for
15009 * @param {Object} [config] Configuration options
15010 * @cfg {jQuery} [$container=input.$element] Element to render menu under
15011 */
15012 OO.ui.TextInputMenuSelectWidget = function OoUiTextInputMenuSelectWidget( inputWidget, config ) {
15013 // Allow passing positional parameters inside the config object
15014 if ( OO.isPlainObject( inputWidget ) && config === undefined ) {
15015 config = inputWidget;
15016 inputWidget = config.inputWidget;
15017 }
15018
15019 // Configuration initialization
15020 config = config || {};
15021
15022 // Parent constructor
15023 OO.ui.TextInputMenuSelectWidget.super.call( this, config );
15024
15025 // Properties
15026 this.inputWidget = inputWidget;
15027 this.$container = config.$container || this.inputWidget.$element;
15028 this.onWindowResizeHandler = this.onWindowResize.bind( this );
15029
15030 // Initialization
15031 this.$element.addClass( 'oo-ui-textInputMenuSelectWidget' );
15032 };
15033
15034 /* Setup */
15035
15036 OO.inheritClass( OO.ui.TextInputMenuSelectWidget, OO.ui.MenuSelectWidget );
15037
15038 /* Methods */
15039
15040 /**
15041 * Handle window resize event.
15042 *
15043 * @private
15044 * @param {jQuery.Event} e Window resize event
15045 */
15046 OO.ui.TextInputMenuSelectWidget.prototype.onWindowResize = function () {
15047 this.position();
15048 };
15049
15050 /**
15051 * @inheritdoc
15052 */
15053 OO.ui.TextInputMenuSelectWidget.prototype.toggle = function ( visible ) {
15054 visible = visible === undefined ? !this.isVisible() : !!visible;
15055
15056 var change = visible !== this.isVisible();
15057
15058 if ( change && visible ) {
15059 // Make sure the width is set before the parent method runs.
15060 // After this we have to call this.position(); again to actually
15061 // position ourselves correctly.
15062 this.position();
15063 }
15064
15065 // Parent method
15066 OO.ui.TextInputMenuSelectWidget.super.prototype.toggle.call( this, visible );
15067
15068 if ( change ) {
15069 if ( this.isVisible() ) {
15070 this.position();
15071 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
15072 } else {
15073 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
15074 }
15075 }
15076
15077 return this;
15078 };
15079
15080 /**
15081 * Position the menu.
15082 *
15083 * @private
15084 * @chainable
15085 */
15086 OO.ui.TextInputMenuSelectWidget.prototype.position = function () {
15087 var $container = this.$container,
15088 pos = OO.ui.Element.static.getRelativePosition( $container, this.$element.offsetParent() );
15089
15090 // Position under input
15091 pos.top += $container.height();
15092 this.$element.css( pos );
15093
15094 // Set width
15095 this.setIdealSize( $container.width() );
15096 // We updated the position, so re-evaluate the clipping state
15097 this.clip();
15098
15099 return this;
15100 };
15101
15102 /**
15103 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
15104 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
15105 *
15106 * ####Currently, this class is only used by {@link OO.ui.BookletLayout BookletLayouts}.####
15107 *
15108 * @class
15109 * @extends OO.ui.SelectWidget
15110 * @mixins OO.ui.TabIndexedElement
15111 *
15112 * @constructor
15113 * @param {Object} [config] Configuration options
15114 */
15115 OO.ui.OutlineSelectWidget = function OoUiOutlineSelectWidget( config ) {
15116 // Parent constructor
15117 OO.ui.OutlineSelectWidget.super.call( this, config );
15118
15119 // Mixin constructors
15120 OO.ui.TabIndexedElement.call( this, config );
15121
15122 // Events
15123 this.$element.on( {
15124 focus: this.bindKeyDownListener.bind( this ),
15125 blur: this.unbindKeyDownListener.bind( this )
15126 } );
15127
15128 // Initialization
15129 this.$element.addClass( 'oo-ui-outlineSelectWidget' );
15130 };
15131
15132 /* Setup */
15133
15134 OO.inheritClass( OO.ui.OutlineSelectWidget, OO.ui.SelectWidget );
15135 OO.mixinClass( OO.ui.OutlineSelectWidget, OO.ui.TabIndexedElement );
15136
15137 /**
15138 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
15139 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
15140 * visually by a slider in the leftmost position.
15141 *
15142 * @example
15143 * // Toggle switches in the 'off' and 'on' position.
15144 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
15145 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
15146 * value: true
15147 * } );
15148 *
15149 * // Create a FieldsetLayout to layout and label switches
15150 * var fieldset = new OO.ui.FieldsetLayout( {
15151 * label: 'Toggle switches'
15152 * } );
15153 * fieldset.addItems( [
15154 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
15155 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
15156 * ] );
15157 * $( 'body' ).append( fieldset.$element );
15158 *
15159 * @class
15160 * @extends OO.ui.ToggleWidget
15161 * @mixins OO.ui.TabIndexedElement
15162 *
15163 * @constructor
15164 * @param {Object} [config] Configuration options
15165 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
15166 * By default, the toggle switch is in the 'off' position.
15167 */
15168 OO.ui.ToggleSwitchWidget = function OoUiToggleSwitchWidget( config ) {
15169 // Parent constructor
15170 OO.ui.ToggleSwitchWidget.super.call( this, config );
15171
15172 // Mixin constructors
15173 OO.ui.TabIndexedElement.call( this, config );
15174
15175 // Properties
15176 this.dragging = false;
15177 this.dragStart = null;
15178 this.sliding = false;
15179 this.$glow = $( '<span>' );
15180 this.$grip = $( '<span>' );
15181
15182 // Events
15183 this.$element.on( {
15184 click: this.onClick.bind( this ),
15185 keypress: this.onKeyPress.bind( this )
15186 } );
15187
15188 // Initialization
15189 this.$glow.addClass( 'oo-ui-toggleSwitchWidget-glow' );
15190 this.$grip.addClass( 'oo-ui-toggleSwitchWidget-grip' );
15191 this.$element
15192 .addClass( 'oo-ui-toggleSwitchWidget' )
15193 .attr( 'role', 'checkbox' )
15194 .append( this.$glow, this.$grip );
15195 };
15196
15197 /* Setup */
15198
15199 OO.inheritClass( OO.ui.ToggleSwitchWidget, OO.ui.ToggleWidget );
15200 OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.TabIndexedElement );
15201
15202 /* Methods */
15203
15204 /**
15205 * Handle mouse click events.
15206 *
15207 * @private
15208 * @param {jQuery.Event} e Mouse click event
15209 */
15210 OO.ui.ToggleSwitchWidget.prototype.onClick = function ( e ) {
15211 if ( !this.isDisabled() && e.which === 1 ) {
15212 this.setValue( !this.value );
15213 }
15214 return false;
15215 };
15216
15217 /**
15218 * Handle key press events.
15219 *
15220 * @private
15221 * @param {jQuery.Event} e Key press event
15222 */
15223 OO.ui.ToggleSwitchWidget.prototype.onKeyPress = function ( e ) {
15224 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
15225 this.setValue( !this.value );
15226 return false;
15227 }
15228 };
15229
15230 }( OO ) );